Repository Public
1// ORIX DJ2// File: App/Sources/Features/Library/LibraryInspector.swift3// Description: Inspector of the selected track: artwork, metadata, tags, rating, file facts, analysis results with4// their confidence, the three-band waveform overview, cue list and play history.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import ORIXDJCore10import SwiftUI1112struct LibraryInspector: View {13 @Environment(AppModel.self) private var model14 @Environment(AppSettings.self) private var settings15 var controller: LibraryController16 @State private var newTag = ""1718 private struct Key: Equatable { var id: Int64?; var version: Int?; var plays: Int?; var revision: Int }1920 var body: some View {21 let track = controller.primaryTrack22 Group {23 if let track {24 ScrollView { content(track).padding(ORIX.Space.sm) }25 } else {26 EmptyState(symbol: "info.circle", title: controller.selection.count > 1 ? "\(controller.selection.count) tracks selected" : "No track selected",27 message: controller.selection.count > 1 ? "Use the context menu to rate, tag or file them together." : "Select a track to see its analysis, waveform, cues and play history.")28 }29 }30 .frame(maxWidth: .infinity, maxHeight: .infinity)31 .background(ORIX.Palette.surface)32 .task(id: Key(id: track?.id, version: track?.analysisVersion, plays: track?.playCount, revision: model.libraryRevision)) {33 await controller.loadInspector(for: track, session: model.session)34 }35 .accessibilityElement(children: .contain).accessibilityIdentifier("library-inspector")36 }3738 @ViewBuilder private func content(_ track: Track) -> some View {39 let data = controller.inspector?.trackID == track.id ? controller.inspector : nil40 VStack(alignment: .leading, spacing: ORIX.Space.sm) {41 HStack(alignment: .top, spacing: ORIX.Space.sm) {42 artwork(data?.artwork)43 VStack(alignment: .leading, spacing: 3) {44 Text(verbatim: track.title.isEmpty ? track.url.lastPathComponent : track.title).font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(2)45 Text(verbatim: track.artist.isEmpty ? "–" : track.artist).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)46 if !track.album.isEmpty { Text(verbatim: track.album).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1) }47 HStack(spacing: 8) {48 RatingStars(rating: track.rating, size: 12) { controller.setRating([track.id], $0, model: model) }49 Button { controller.setFavorite([track.id], !track.favorite, model: model) } label: {50 Image(systemName: track.favorite ? "heart.fill" : "heart").font(.system(size: 13))51 .foregroundStyle(track.favorite ? ORIX.Palette.accent : ORIX.Palette.textTertiary)52 }53 .buttonStyle(.plain)54 .accessibilityLabel("Favourite").accessibilityValue(track.favorite ? Text("on") : Text("off"))55 .accessibilityIdentifier("library-inspector-favourite")56 }57 .padding(.top, 2)58 }59 }6061 if track.missing {62 Label("The audio file is missing. It may have been moved, renamed or be on a disk that is not connected.", systemImage: "exclamationmark.triangle.fill")63 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).fixedSize(horizontal: false, vertical: true)64 }6566 // Waveform overview.67 SectionLabel("Waveform")68 Group {69 if let w = data?.waveform, w.count > 0 {70 LibraryWaveformOverview(summary: w, duration: track.duration, cues: track.cues, bands: settings.palette.bands)71 } else {72 Text(track.isAnalysed ? "Loading…" : "Available after analysis.").font(.system(size: 11)).foregroundStyle(Color(hex: 0xA3AAC2))73 .frame(maxWidth: .infinity, maxHeight: .infinity)74 }75 }76 .frame(height: 64)77 .background(ORIX.Palette.waveformWell, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))78 .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))79 .accessibilityIdentifier("library-inspector-waveform")8081 // Analysis.82 SectionLabel("Analysis")83 if track.isAnalysed {84 Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 5) {85 fact("Tempo", "\(LibraryFormat.bpm(track.bpm)) BPM", detail: track.bpmConfidence.map { String(localized: "confidence \(LibraryFormat.percent($0))") })86 fact("Key", [track.camelot, LibraryKeyNames.musicalName(camelot: track.camelot) ?? track.key].compactMap { $0 }.joined(separator: " · ").ifEmpty("–"),87 detail: track.keyConfidence.map { String(localized: "confidence \(LibraryFormat.percent($0))") })88 fact("Loudness", LibraryFormat.decibels(track.loudnessLUFS, unit: "LUFS"), detail: track.peakDBFS.map { String(localized: "peak \(LibraryFormat.decibels($0, unit: "dBFS"))") })89 fact("Suggested gain", LibraryFormat.decibels(track.gainDB), detail: String(localized: "towards \(Int(AnalysisResult.targetLUFS)) LUFS"))90 }91 } else {92 Text("Not analysed yet. The background analysis measures tempo, key and loudness; loading the track on a deck analyses it at once.")93 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)94 }9596 // Tags.97 SectionLabel("Tags")98 LibraryTagFlow(tags: track.tags) { tag in controller.setTags([track.id], track.tags.filter { $0 != tag }, model: model) }99 HStack(spacing: 6) {100 TextField("Add a tag", text: $newTag).textFieldStyle(.roundedBorder).controlSize(.small)101 .onSubmit { addTag(track) }102 .accessibilityLabel("New tag").accessibilityIdentifier("library-inspector-tag-field")103 Button("Add") { addTag(track) }.controlSize(.small).disabled(newTag.trimmingCharacters(in: .whitespaces).isEmpty)104 .accessibilityIdentifier("library-inspector-tag-add")105 }106107 // Cues.108 SectionLabel("Cues")109 let cues = track.cues.sorted { $0.seconds < $1.seconds }110 if cues.isEmpty {111 Text("No cue stored. Cues set on a deck are saved with the track.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)112 } else {113 VStack(alignment: .leading, spacing: 3) {114 ForEach(cues, id: \.index) { cue in115 HStack(spacing: 6) {116 Text(verbatim: cue.index < 0 ? "CUE" : "\(cue.index + 1)").font(.system(size: 9, weight: .heavy, design: .rounded))117 .foregroundStyle(Color.black.opacity(0.88)).frame(width: 28, height: 15)118 .background(cue.index < 0 ? ORIX.Palette.textSecondary : ORIX.hotCueColors[cue.index % ORIX.hotCueColors.count], in: RoundedRectangle(cornerRadius: 3))119 Text(verbatim: formatTime(cue.seconds)).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)120 Text(cue.index < 0 ? "Main cue" : "Hot cue").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)121 }122 .accessibilityElement(children: .combine)123 }124 }125 }126127 // File.128 SectionLabel("File")129 Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 5) {130 fact("Format", fileFormat(track))131 fact("Length", formatTime(track.duration, tenths: false), detail: LibraryFormat.fileSize(track.fileSize))132 if !track.genre.isEmpty { fact("Genre", track.genre, detail: track.year > 0 ? "\(track.year)" : nil) }133 fact("Added", track.dateAdded.formatted(LibraryFormat.day))134 if let names = data?.crateNames, !names.isEmpty { fact("Crates", names.joined(separator: ", ")) }135 }136 Text(verbatim: track.path).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textTertiary)137 .lineLimit(4).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)138 Button { controller.showInFinder([track.id]) } label: { Label("Show in Finder", systemImage: "folder") }139 .controlSize(.small).disabled(track.missing).accessibilityIdentifier("library-inspector-finder")140141 // History.142 SectionLabel("Play history")143 if let plays = data?.plays, !plays.isEmpty {144 VStack(alignment: .leading, spacing: 3) {145 Text(track.playCount == 1 ? "Played once" : "Played \(track.playCount) times").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)146 ForEach(plays) { p in147 HStack(spacing: 6) {148 if let d = deckLetters.firstIndex(of: p.deck) { DeckBadge(index: d, size: 14) }149 Text(verbatim: p.playedAt.formatted(LibraryFormat.dayTime)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)150 }151 .accessibilityElement(children: .combine)152 }153 }154 } else {155 Text(track.playCount > 0 ? "Played \(track.playCount) times." : "Never played.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)156 }157 }158 .frame(maxWidth: .infinity, alignment: .leading)159 }160161 private func addTag(_ track: Track) {162 let added = LibraryController.parseTags(newTag)163 guard !added.isEmpty else { return }164 var tags = track.tags165 for t in added where !tags.contains(where: { $0.caseInsensitiveCompare(t) == .orderedSame }) { tags.append(t) }166 controller.setTags([track.id], tags, model: model)167 newTag = ""168 }169170 private func fileFormat(_ t: Track) -> String {171 var parts = [t.format.uppercased()]172 if t.sampleRate > 0 { parts.append(String(format: "%.1f kHz", t.sampleRate / 1000)) }173 if t.channels > 0 { parts.append(t.channels == 1 ? String(localized: "mono") : (t.channels == 2 ? String(localized: "stereo") : "\(t.channels) ch")) }174 if t.bitRate > 0 { parts.append("\(t.bitRate / 1000) kbps") }175 return parts.joined(separator: " · ")176 }177178 private func fact(_ label: LocalizedStringKey, _ value: String, detail: String? = nil) -> some View {179 GridRow(alignment: .firstTextBaseline) {180 Text(label).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).gridColumnAlignment(.leading)181 VStack(alignment: .leading, spacing: 1) {182 Text(verbatim: value).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)183 if let detail { Text(verbatim: detail).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary) }184 }185 }186 .accessibilityElement(children: .combine)187 }188189 private func artwork(_ data: Data?) -> some View {190 Group {191 if let data, let image = NSImage(data: data) {192 Image(nsImage: image).resizable().aspectRatio(contentMode: .fill).accessibilityLabel("Artwork")193 } else {194 ZStack {195 ORIX.Palette.well196 Image(systemName: "music.note").font(.system(size: 24, weight: .light)).foregroundStyle(ORIX.Palette.textTertiary)197 }198 .accessibilityLabel("No artwork in this file")199 }200 }201 .frame(width: 76, height: 76)202 .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))203 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline))204 }205}206207private extension String {208 func ifEmpty(_ fallback: String) -> String { isEmpty ? fallback : self }209}210211/// Removable tag chips that wrap.212struct LibraryTagFlow: View {213 var tags: [String]214 var onRemove: (String) -> Void215216 var body: some View {217 if tags.isEmpty {218 Text("No tags.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)219 } else {220 LibraryFlowLayout(spacing: 5) {221 ForEach(tags, id: \.self) { tag in222 HStack(spacing: 3) {223 Text(verbatim: tag).font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)224 Button { onRemove(tag) } label: { Image(systemName: "xmark").font(.system(size: 7, weight: .bold)).frame(width: 12, height: 12).contentShape(Rectangle()) }225 .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary)226 .accessibilityLabel(Text("Remove tag \(tag)"))227 }228 .padding(.leading, 7).padding(.trailing, 4).frame(height: 20)229 .background(ORIX.Palette.surfaceRaised, in: Capsule())230 .overlay(Capsule().strokeBorder(ORIX.Palette.hairline))231 }232 }233 }234 }235}236237struct LibraryFlowLayout: Layout {238 var spacing: CGFloat = 6239240 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {241 arrange(width: proposal.width ?? 260, subviews: subviews).size242 }243244 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {245 let result = arrange(width: bounds.width, subviews: subviews)246 for (i, p) in result.points.enumerated() { subviews[i].place(at: CGPoint(x: bounds.minX + p.x, y: bounds.minY + p.y), proposal: .unspecified) }247 }248249 private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, points: [CGPoint]) {250 var x: CGFloat = 0, y: CGFloat = 0, line: CGFloat = 0, points: [CGPoint] = []251 for s in subviews {252 let size = s.sizeThatFits(.unspecified)253 if x > 0, x + size.width > width { x = 0; y += line + spacing; line = 0 }254 points.append(CGPoint(x: x, y: y))255 x += size.width + spacing; line = max(line, size.height)256 }257 return (CGSize(width: width, height: y + line), points)258 }259}260261/// Whole-track overview: three bands (low behind, high in front) mirrored around the centre line, with cue marks.262struct LibraryWaveformOverview: View {263 var summary: WaveformSummary264 var duration: Double265 var cues: [CuePoint] = []266 var bands: (low: UInt32, mid: UInt32, high: UInt32)267268 var body: some View {269 Canvas(rendersAsynchronously: true) { context, size in270 let columns = max(1, Int(size.width))271 let s = summary.overview(columns: columns)272 let n = s.count273 guard n > 0 else { return }274 let mid = size.height / 2, step = size.width / CGFloat(n)275 func path(_ values: [UInt8], scale: CGFloat) -> Path {276 var p = Path()277 guard values.count == n else { return p }278 for i in 0 ..< n {279 let h = max(0.5, CGFloat(values[i]) / 255 * mid * scale)280 p.addRect(CGRect(x: CGFloat(i) * step, y: mid - h, width: max(1, step), height: h * 2))281 }282 return p283 }284 context.fill(path(s.low, scale: 0.98), with: .color(Color(hex: bands.low)))285 context.fill(path(s.mid, scale: 0.72), with: .color(Color(hex: bands.mid, opacity: 0.92)))286 context.fill(path(s.high, scale: 0.46), with: .color(Color(hex: bands.high, opacity: 0.95)))287 if duration > 0 {288 for cue in cues where cue.seconds >= 0 && cue.seconds <= duration {289 let x = CGFloat(cue.seconds / duration) * size.width290 let color = cue.index < 0 ? Color.white : ORIX.hotCueColors[cue.index % ORIX.hotCueColors.count]291 context.fill(Path(CGRect(x: x, y: 0, width: 1.5, height: size.height)), with: .color(color))292 var flag = Path(); flag.move(to: CGPoint(x: x, y: 0)); flag.addLine(to: CGPoint(x: x + 6, y: 0)); flag.addLine(to: CGPoint(x: x, y: 6)); flag.closeSubpath()293 context.fill(flag, with: .color(color))294 }295 }296 }297 .accessibilityElement(children: .ignore)298 .accessibilityLabel("Waveform overview")299 .accessibilityValue(Text("\(formatTime(duration, tenths: false)) long, \(cues.count) cues"))300 }301}302