SPB Git

Repository Public

AutoDJView.swift 26.0 KB 441 lines swift

1// ORIX DJ2// File: App/Sources/Features/AutoDJ/AutoDJView.swift3// Description: Auto DJ: queue builder with the real play order and the tempo / key relation of each pair, settings,4//              start and stop, live status, and the exact ORIX Script of the next transition.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct AutoDJView: View {12    @Environment(AppModel.self) private var model13    @State private var controller = AutoDJController()14    @State private var appliedLaunch = false1516    private struct ReloadKey: Equatable { var revision: Int; var source: AutoDJSource; var selection: Set<Int64> }1718    var body: some View {19        VStack(spacing: 0) {20            header21            Divider().overlay(ORIX.Palette.hairline)22            HStack(alignment: .top, spacing: ORIX.Space.sm) {23                queuePanel24                ScrollView {25                    VStack(spacing: ORIX.Space.sm) {26                        AutoDJStatusPanel(controller: controller)27                        settingsPanel28                        AutoDJScriptPanel(controller: controller)29                    }30                }31                .frame(width: 470)32            }33            .padding(ORIX.Space.sm)34        }35        .background(ORIX.Palette.canvas)36        .task(id: ReloadKey(revision: model.libraryRevision, source: controller.source, selection: controller.source == .selection ? model.selectedTrackIDs : [])) {37            if controller.loaded { try? await Task.sleep(nanoseconds: 200_000_000) }38            guard !Task.isCancelled else { return }39            await controller.reload(model: model)40            applyLaunchOptions()41        }42        .task(id: model.autoDJ.queue) { await controller.loadRemaining(ids: model.autoDJ.queue, library: model.library) }43        .onAppear {44            controller.settings = model.session.autoDJConfiguration45            if !model.selectedTrackIDs.isEmpty, !controller.loaded { controller.source = .selection }46        }47        .accessibilityElement(children: .contain).accessibilityIdentifier("autodj-root")48    }4950    private func applyLaunchOptions() {51        #if DEBUG52        // -ORIXAutoDJStart YES: start Auto DJ on the default queue once it is loaded (screenshots of the live status).53        guard !appliedLaunch, controller.loaded, !controller.manual.isEmpty else { return }54        appliedLaunch = true55        if UserDefaults.standard.bool(forKey: "ORIXAutoDJStart") {56            Task { try? await Task.sleep(nanoseconds: 4_000_000_000); controller.start(model: model) }57        }58        #endif59    }6061    // MARK: Header6263    private var header: some View {64        HStack(spacing: ORIX.Space.sm) {65            VStack(alignment: .leading, spacing: 2) {66                Text("Auto DJ").font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary)67                Text("Deterministic and local: the order comes from the analysed tempo and key, and every transition is an ORIX Script you can read below. Auto DJ does not use Claude or the network.")68                    .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)69                    .accessibilityIdentifier("autodj-statement")70            }71            Spacer(minLength: ORIX.Space.md)72            if model.autoDJ.enabled {73                Button { controller.stop(model: model) } label: {74                    Label("Stop Auto DJ", systemImage: "stop.fill").font(.system(size: 13, weight: .semibold)).padding(.horizontal, 6).frame(height: 26)75                }76                .buttonStyle(.borderedProminent).tint(ORIX.Palette.danger)77                .help("Stops Auto DJ. The deck that is playing keeps playing.")78                .accessibilityIdentifier("autodj-stop")79            } else {80                Button { controller.start(model: model) } label: {81                    Label("Start Auto DJ", systemImage: "play.fill").font(.system(size: 13, weight: .semibold)).padding(.horizontal, 6).frame(height: 26)82                }83                .buttonStyle(.borderedProminent).tint(ORIX.Palette.accent)84                .disabled(controller.manual.isEmpty)85                .help(controller.manual.isEmpty ? "The queue is empty." : "Auto DJ uses decks A and B.")86                .accessibilityIdentifier("autodj-start")87            }88        }89        .padding(.horizontal, ORIX.Space.md).padding(.vertical, ORIX.Space.xs)90        .background(ORIX.Palette.surface)91    }9293    // MARK: Queue9495    private var sourceTitle: String {96        switch controller.source {97        case .selection: String(localized: "Library selection (\(model.selectedTrackIDs.count))")98        case .allTracks: String(localized: "All Tracks")99        case let .playlist(id): controller.playlists.first { $0.id == id }?.name ?? String(localized: "Playlist")100        case let .crate(id): controller.crates.first { $0.id == id }?.name ?? String(localized: "Crate")101        case let .smartCrate(id): controller.smartCrates.first { $0.id == id }?.name ?? String(localized: "Smart Crate")102        }103    }104105    private var queuePanel: some View {106        let order = controller.playOrder107        let smart = controller.settings.smartOrder && controller.manual.count > 2108        return Panel(padding: 0) {109            VStack(spacing: 0) {110                HStack(spacing: ORIX.Space.xs) {111                    SectionLabel("Queue from")112                    Menu {113                        Button { controller.source = .selection } label: { Text("Current Library Selection (\(model.selectedTrackIDs.count))") }114                        Button("All Tracks") { controller.source = .allTracks }115                        if !controller.playlists.isEmpty {116                            Section("Playlists") { ForEach(controller.playlists) { p in Button { controller.source = .playlist(p.id) } label: { Text(verbatim: p.name) } } }117                        }118                        if !controller.crates.isEmpty {119                            Section("Crates") { ForEach(controller.crates) { c in Button { controller.source = .crate(c.id) } label: { Text(verbatim: c.name) } } }120                        }121                        if !controller.smartCrates.isEmpty {122                            Section("Smart Crates") { ForEach(controller.smartCrates) { c in Button { controller.source = .smartCrate(c.id) } label: { Text(verbatim: c.name) } } }123                        }124                    } label: { Text(verbatim: sourceTitle).font(.system(size: 12, weight: .semibold)) }125                        .menuStyle(.borderlessButton).fixedSize()126                        .accessibilityLabel("Queue source").accessibilityValue(Text(verbatim: sourceTitle))127                        .accessibilityIdentifier("autodj-source")128                    Spacer()129                    if controller.hasRemovals {130                        Button("Restore Removed") { Task { await controller.restoreRemoved(model: model) } }.controlSize(.small)131                            .accessibilityIdentifier("autodj-restore")132                    }133                    Text(summary(order)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)134                        .accessibilityIdentifier("autodj-queue-count")135                }136                .padding(.horizontal, ORIX.Space.sm).frame(height: 38)137                Divider().overlay(ORIX.Palette.hairline)138                Label {139                    Text(smart ? "Smart ordering is on: after the first track, Auto DJ picks at each step the remaining track with the smallest tempo and key change. Turn it off to arrange the queue by hand."140                        : "Played in this order. Drag rows or use the arrows to arrange the queue.")141                } icon: { Image(systemName: smart ? "wand.and.stars" : "hand.draw") }142                    .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)143                    .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .leading)144                    .background(ORIX.Palette.surfaceRaised.opacity(0.5))145                Divider().overlay(ORIX.Palette.hairline)146                if order.isEmpty {147                    EmptyState(symbol: "list.bullet.indent", title: "The queue is empty",148                               message: controller.source == .selection ? "Select tracks in the Library, or choose a playlist, a crate or a smart crate as the source." : "This source has no playable track. Choose another source.")149                } else {150                    List {151                        ForEach(Array(order.enumerated()), id: \.element.id) { index, track in152                            AutoDJQueueRow(index: index, track: track, next: index + 1 < order.count ? order[index + 1] : nil, smart: smart, count: order.count, controller: controller)153                                .listRowInsets(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8))154                                .listRowSeparatorTint(ORIX.Palette.hairline)155                                .listRowBackground(Color.clear)156                        }157                        .onMove(perform: smart ? nil : { controller.move(from: $0, to: $1) })158                    }159                    .listStyle(.plain).scrollContentBackground(.hidden)160                    .accessibilityIdentifier("autodj-queue")161                }162            }163        }164        .frame(maxWidth: .infinity, maxHeight: .infinity)165    }166167    private func summary(_ order: [Track]) -> String {168        let total = order.reduce(0.0) { $0 + $1.duration }169        let n = order.count170        return (n == 1 ? String(localized: "1 track") : String(localized: "\(n) tracks")) + " · " + formatTime(total, tenths: false)171    }172173    // MARK: Settings174175    private func setting<T>(_ keyPath: WritableKeyPath<AutoDJSettings, T>) -> Binding<T> {176        Binding(get: { controller.settings[keyPath: keyPath] }, set: { v in177            var s = controller.settings; s[keyPath: keyPath] = v178            controller.apply(settings: s, session: model.session)179        })180    }181182    private var settingsPanel: some View {183        Panel {184            VStack(alignment: .leading, spacing: ORIX.Space.xs) {185                SectionLabel("Transition")186                Picker("Style", selection: setting(\.style)) {187                    ForEach(AutoDJStyle.allCases) { style in Text(verbatim: style.displayName).tag(style) }188                }189                .labelsHidden().accessibilityLabel("Transition style").accessibilityIdentifier("autodj-style")190                Text(controller.settings.style.sentence).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)191                HStack {192                    Text("Length").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary)193                    Spacer()194                    Picker("Length", selection: setting(\.bars)) {195                        ForEach([2, 4, 8, 16, 32], id: \.self) { b in Text("\(b) bars").tag(b) }196                    }197                    .labelsHidden().fixedSize().disabled(controller.settings.style == .cut)198                    .accessibilityLabel("Transition length").accessibilityIdentifier("autodj-bars")199                }200                Divider().overlay(ORIX.Palette.hairline)201                toggle("Smart order", "Reorders the queue so neighbours are close in tempo and compatible in key.", setting(\.smartOrder), id: "autodj-smart-order")202                toggle("Sync the incoming deck", "Matches the tempo and phase of the new track to the one that is playing.", setting(\.sync), id: "autodj-sync")203                toggle("Auto gain", "Applies each track's analysed gain so tracks play at a similar loudness.", setting(\.autoGain), id: "autodj-auto-gain")204                HStack {205                    VStack(alignment: .leading, spacing: 1) {206                        Text("Largest tempo change").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary)207                        Text("Used by smart ordering; larger steps are avoided and flagged.").font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)208                    }209                    Spacer()210                    Stepper(value: setting(\.maxTempoChange), in: 1 ... 20, step: 1) {211                        Text(verbatim: String(format: "%.0f %%", controller.settings.maxTempoChange)).font(ORIX.Typeface.value).frame(width: 40, alignment: .trailing)212                    }213                    .accessibilityLabel("Largest tempo change").accessibilityValue(Text(verbatim: String(format: "%.0f percent", controller.settings.maxTempoChange)))214                    .accessibilityIdentifier("autodj-max-tempo")215                }216            }217            .frame(maxWidth: .infinity, alignment: .leading)218        }219        .accessibilityElement(children: .contain).accessibilityIdentifier("autodj-settings")220    }221222    private func toggle(_ title: LocalizedStringKey, _ detail: LocalizedStringKey, _ binding: Binding<Bool>, id: String) -> some View {223        Toggle(isOn: binding) {224            VStack(alignment: .leading, spacing: 1) {225                Text(title).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary)226                Text(detail).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)227            }228            .frame(maxWidth: .infinity, alignment: .leading)229        }230        .toggleStyle(.switch).controlSize(.small)231        .accessibilityIdentifier(id)232    }233234}235236/// Live status. Its own view so the 30 Hz deck refresh does not redraw the queue.237private struct AutoDJStatusPanel: View {238    @Environment(AppModel.self) private var model239    var controller: AutoDJController240241    var body: some View {242        let s = model.autoDJ243        return Panel {244            VStack(alignment: .leading, spacing: ORIX.Space.xs) {245                HStack {246                    SectionLabel("Live status")247                    Spacer()248                    HStack(spacing: 5) {249                        Image(systemName: s.enabled ? "arrow.triangle.2.circlepath" : "pause.circle").font(.system(size: 11, weight: .semibold))250                        Text(verbatim: s.state).font(.system(size: 12, weight: .semibold))251                    }252                    .foregroundStyle(s.enabled ? ORIX.Palette.accentSecondary : ORIX.Palette.textSecondary)253                    .accessibilityElement(children: .combine)254                    .accessibilityLabel("Auto DJ state").accessibilityValue(Text(verbatim: s.state))255                    .accessibilityIdentifier("autodj-state")256                }257                Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 6) {258                    GridRow {259                        Text("Playing deck").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)260                        if s.enabled, let d = s.currentDeck {261                            HStack(spacing: 6) {262                                DeckBadge(index: d, size: 16)263                                Text(verbatim: model.decks[d].track?.title ?? "–").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)264                                if model.decks[d].track != nil { Text(verbatim: "-" + formatTime(model.decks[d].remaining, tenths: false)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary) }265                            }266                        } else { Text(verbatim: "–").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textTertiary) }267                    }268                    GridRow {269                        Text("Next track").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)270                        Text(verbatim: s.enabled && !s.nextTitle.isEmpty ? s.nextTitle : "–").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)271                            .accessibilityIdentifier("autodj-next")272                    }273                    GridRow {274                        Text("Transitions done").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)275                        Text(verbatim: "\(s.transitions)").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)276                            .accessibilityIdentifier("autodj-transitions")277                    }278                    GridRow(alignment: .top) {279                        Text("Still queued").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)280                        VStack(alignment: .leading, spacing: 2) {281                            Text(verbatim: "\(s.queue.count)").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)282                                .accessibilityIdentifier("autodj-remaining")283                            if s.enabled, !controller.remaining.isEmpty {284                                Text(verbatim: controller.remaining.prefix(4).map(\.title).joined(separator: " → ") + (controller.remaining.count > 4 ? " …" : ""))285                                    .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2)286                            }287                        }288                    }289                }290                if !s.enabled, model.decks[0].playing || model.decks[1].playing {291                    let d = model.decks[0].playing ? 0 : 1292                    Text("Deck \(deckLetters[d]) is playing: Auto DJ keeps it and mixes into the first track of the queue on deck \(deckLetters[1 - d]).")293                        .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)294                }295            }296            .frame(maxWidth: .infinity, alignment: .leading)297        }298        .accessibilityElement(children: .contain).accessibilityIdentifier("autodj-status")299    }300}301302private struct AutoDJScriptPanel: View {303    @Environment(AppModel.self) private var model304    var controller: AutoDJController305306    private struct Direction: Equatable { var from: Int }307308    var body: some View {309        let s = model.autoDJ310        let current = s.enabled ? (s.currentDeck ?? 0) : (model.decks[1].playing && !model.decks[0].playing ? 1 : 0)311        let from = deckLetters[current], to = deckLetters[1 - current]312        let source = AutoDJPlanner.transitionScript(from: from, to: to, settings: controller.settings)313        return Panel {314            VStack(alignment: .leading, spacing: ORIX.Space.xs) {315                HStack {316                    SectionLabel("Next transition script")317                    Text(verbatim: "\(from) → \(to)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)318                    Spacer()319                    Button { model.openInEditor(name: "Auto DJ \(from) to \(to)", source: source) } label: { Label("Open in Editor", systemImage: "chevron.left.forwardslash.chevron.right") }320                        .controlSize(.small).accessibilityIdentifier("autodj-open-editor")321                }322                Text("Auto DJ compiles and runs exactly this text when the playing track nears its end.")323                    .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)324                AutoDJScriptText(source: source).accessibilityIdentifier("autodj-script")325                if !s.lastScript.isEmpty {326                    DisclosureGroup {327                        AutoDJScriptText(source: s.lastScript).accessibilityIdentifier("autodj-last-script")328                        HStack {329                            Spacer()330                            Button { model.openInEditor(name: "Auto DJ last transition", source: s.lastScript) } label: { Label("Open in Editor", systemImage: "chevron.left.forwardslash.chevron.right") }331                                .controlSize(.small).accessibilityIdentifier("autodj-open-last")332                        }333                    } label: { Text("Last script run").font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary) }334                } else {335                    Text("No transition has run yet in this session.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)336                }337            }338            .frame(maxWidth: .infinity, alignment: .leading)339        }340    }341}342343/// One queue line: position, track, tempo, key, and how the next track follows it.344private struct AutoDJQueueRow: View {345    var index: Int346    var track: Track347    var next: Track?348    var smart: Bool349    var count: Int350    var controller: AutoDJController351352    var body: some View {353        HStack(spacing: ORIX.Space.xs) {354            Text(verbatim: "\(index + 1)").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 22, alignment: .trailing)355            VStack(alignment: .leading, spacing: 1) {356                Text(verbatim: track.title).font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)357                Text(verbatim: track.artist.isEmpty ? "–" : track.artist).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)358            }359            .frame(minWidth: 110, maxWidth: .infinity, alignment: .leading)360            Text(verbatim: LibraryFormat.bpm(track.bpm)).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).frame(width: 46, alignment: .trailing)361                .accessibilityLabel("Tempo").accessibilityValue(Text(verbatim: LibraryFormat.bpm(track.bpm)))362            Text(verbatim: track.camelot ?? "–").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).frame(width: 32, alignment: .leading)363                .help(Text(verbatim: LibraryKeyNames.musicalName(camelot: track.camelot) ?? ""))364                .accessibilityLabel("Key").accessibilityValue(Text(verbatim: LibraryKeyNames.musicalName(camelot: track.camelot) ?? "unknown"))365            Text(verbatim: formatTime(track.duration, tenths: false)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 36, alignment: .trailing)366            Group {367                if let next {368                    let step = controller.step(from: track, to: next)369                    HStack(spacing: 4) {370                        Image(systemName: step.symbol).font(.system(size: 10, weight: .semibold)).foregroundStyle(step.tint)371                        Text(verbatim: "\(step.tempoWords) · \(step.keyWords)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)372                    }373                    .help(step.overLimit ? "Into the next track. The tempo change is above the limit set on the right." : "Tempo change and key relation into the next track.")374                    .accessibilityElement(children: .ignore)375                    .accessibilityLabel("Into the next track")376                    .accessibilityValue(Text(verbatim: "tempo change \(step.tempoWords), \(step.keyWords)" + (step.overLimit ? ", above the limit" : "")))377                } else {378                    Text("last track").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)379                }380            }381            .frame(width: 196, alignment: .leading)382            HStack(spacing: 2) {383                if smart {384                    rowButton("arrow.up.to.line", "Play first", disabled: index == 0) { controller.playFirst(track.id) }385                } else {386                    rowButton("chevron.up", "Move up", disabled: index == 0) { controller.move(track.id, by: -1) }387                    rowButton("chevron.down", "Move down", disabled: index == count - 1) { controller.move(track.id, by: 1) }388                }389                rowButton("xmark", "Remove from the queue", disabled: false) { controller.remove(track.id) }390            }391            .frame(width: 70, alignment: .trailing)392        }393        .frame(height: 38)394        .accessibilityElement(children: .contain)395        .accessibilityIdentifier("autodj-row-\(index)")396    }397398    private func rowButton(_ symbol: String, _ label: LocalizedStringKey, disabled: Bool, action: @escaping () -> Void) -> some View {399        Button(action: action) { Image(systemName: symbol).font(.system(size: 10, weight: .semibold)).frame(width: 20, height: 20).contentShape(Rectangle()) }400            .buttonStyle(.plain).foregroundStyle(disabled ? ORIX.Palette.textTertiary.opacity(0.4) : ORIX.Palette.textSecondary).disabled(disabled)401            .help(label).accessibilityLabel(label)402    }403}404405/// Read-only ORIX Script with the language's own token classes.406struct AutoDJScriptText: View {407    var source: String408409    var body: some View {410        ScrollView(.horizontal) {411            Text(Self.highlighted(source)).font(.system(size: 11.5, design: .monospaced)).lineSpacing(2)412                .textSelection(.enabled).padding(ORIX.Space.xs).fixedSize(horizontal: true, vertical: true)413        }414        .frame(maxWidth: .infinity, alignment: .leading)415        .background(ORIX.Palette.well, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))416        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline))417        .accessibilityLabel("ORIX Script").accessibilityValue(Text(verbatim: source))418    }419420    static func highlighted(_ source: String) -> AttributedString {421        let text = NSMutableAttributedString(string: source)422        let full = NSRange(location: 0, length: text.length)423        var out = AttributedString(source)424        out.foregroundColor = ORIX.Palette.textPrimary425        for span in Lexer.highlight(source) {426            let range = NSRange(location: span.range.lowerBound, length: span.range.count)427            guard NSIntersectionRange(range, full).length == range.length, let r = Range(range, in: out) else { continue }428            switch span.tokenClass {429            case .keyword: out[r].foregroundColor = ORIX.Palette.accent430            case .root: out[r].foregroundColor = ORIX.Palette.accentSecondary431            case .number: out[r].foregroundColor = ORIX.Palette.warning432            case .string: out[r].foregroundColor = ORIX.Palette.success433            case .comment: out[r].foregroundColor = ORIX.Palette.textTertiary434            case .symbol: out[r].foregroundColor = ORIX.Palette.textSecondary435            case .identifier: out[r].foregroundColor = ORIX.Palette.textPrimary436            }437        }438        return out439    }440}441
Files main
Menu

Theme