SPB Git

Repository Public

DeckView.swift 23.3 KB 362 lines swift

1// ORIX DJ2// File: App/Sources/Features/Decks/DeckView.swift3// Description: One deck: track header, waveforms, transport, tempo and key, loops, beat jump, hot cues, beat-grid4//              tools. Four layouts (standard, vinyl, performance, minimal). Every control drives the engine.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct DeckView: View {12    @Environment(AppModel.self) private var model13    var deck: Int14    var mode: DeckMode15    /// Tighter layout used when four decks share the window.16    var compact = false17    @State private var dropTargeted = false1819    private var status: DeckStatus { model.decks[deck] }20    private var tint: Color { ORIX.deck(deck) }21    private var letter: String { deckLetters[deck] }2223    var body: some View {24        VStack(alignment: .leading, spacing: compact ? 6 : 8) {25            DeckHeader(deck: deck, compact: compact)26            HStack(spacing: 8) {27                if mode == .vinyl, !compact { Platter(deck: deck).frame(width: 118, height: 118) }28                VStack(spacing: 4) {29                    ScrollingWaveform(deck: deck).frame(height: mode == .minimal ? (compact ? 90 : 150) : (compact ? 60 : 96))30                    OverviewWaveform(deck: deck).frame(height: compact ? 20 : 30)31                }32            }33            TransportRow(deck: deck, compact: compact)34            if mode != .minimal {35                LoopRow(deck: deck, compact: compact)36                if mode == .performance, !compact { HotCuePads(deck: deck, large: true) } else { HotCuePads(deck: deck, large: false) }37                if !compact || mode == .performance { GridRow(deck: deck, showsTransportExtras: !(mode == .performance && !compact)) }38            }39        }40        .padding(compact ? 8 : 10)41        .frame(maxWidth: .infinity, alignment: .leading)42        .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous))43        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous).strokeBorder(dropTargeted ? tint : (status.isMaster ? tint.opacity(0.55) : ORIX.Palette.hairline), lineWidth: dropTargeted ? 2 : 1))44        .dropDestination(for: String.self) { items, _ in45            // Rows dragged from the library carry "orix-track:<id>".46            guard let id = items.compactMap({ $0.hasPrefix("orix-track:") ? Int64($0.dropFirst(11)) : nil }).first else { return false }47            model.load(trackID: id, deck: deck)48            return true49        } isTargeted: { dropTargeted = $0 }50        .accessibilityElement(children: .contain)51        .accessibilityLabel(Text("Deck \(letter)"))52        .accessibilityIdentifier("deck-\(letter)")53    }54}5556private struct DeckHeader: View {57    @Environment(AppModel.self) private var model58    var deck: Int59    var compact: Bool6061    var body: some View {62        let s = model.decks[deck]63        let tint = ORIX.deck(deck)64        HStack(alignment: .center, spacing: 8) {65            DeckBadge(index: deck, size: compact ? 20 : 24)66            VStack(alignment: .leading, spacing: 1) {67                if let t = s.track {68                    Text(verbatim: t.title).font(.system(size: compact ? 12 : 14, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)69                    Text(verbatim: t.artist.isEmpty ? " " : t.artist).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)70                } else if let p = model.loadProgress[deck] {71                    Text("Loading…").font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)72                    ProgressView(value: p).frame(maxWidth: 160).accessibilityLabel(Text("Loading deck \(deckLetters[deck])"))73                } else {74                    Text("Empty").font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)75                    Text("Load a track from the library").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)76                }77            }78            Spacer(minLength: 6)79            if s.isMaster {80                Label("Master", systemImage: "crown.fill").font(.system(size: 9, weight: .bold)).labelStyle(.titleAndIcon)81                    .padding(.horizontal, 6).frame(height: 18).foregroundStyle(tint).overlay(Capsule().strokeBorder(tint))82                    .help("This deck drives the master clock.")83            }84            if let key = s.track?.key {85                VStack(spacing: 0) {86                    Text(verbatim: key.transposed(semitones: Int(s.keyShift.rounded())).camelot).font(ORIX.Typeface.readout(compact ? 13 : 15)).foregroundStyle(ORIX.Palette.textPrimary)87                    Text(verbatim: key.transposed(semitones: Int(s.keyShift.rounded())).shortName).font(.system(size: 9, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)88                }89                .help("Estimated key (confidence \(Int(key.confidence * 100)) %). Estimates can be wrong; trust your ears.")90                .accessibilityElement(children: .ignore).accessibilityLabel("Key").accessibilityValue(Text(verbatim: key.name))91            }92            VStack(alignment: .trailing, spacing: 0) {93                Text(verbatim: formatBPM(s.bpm)).font(ORIX.Typeface.readout(compact ? 17 : 22)).foregroundStyle(tint)94                Text(s.trackBPM > 0 ? LocalizedStringKey(String(format: "%+.2f %%", (s.rate - 1) * 100)) : "no tempo").font(.system(size: 9, weight: .semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary)95            }96            .frame(minWidth: compact ? 52 : 64, alignment: .trailing)97            .accessibilityElement(children: .ignore).accessibilityLabel("Tempo").accessibilityValue(Text(verbatim: "\(formatBPM(s.bpm)) BPM"))98            VStack(alignment: .trailing, spacing: 0) {99                Text(verbatim: formatTime(s.position)).font(ORIX.Typeface.readout(compact ? 13 : 15)).foregroundStyle(ORIX.Palette.textPrimary)100                Text(verbatim: "-" + formatTime(s.remaining / max(0.05, s.rate))).font(.system(size: 10, weight: .medium).monospacedDigit())101                    .foregroundStyle(s.playing && s.remaining / max(0.05, s.rate) < 30 ? ORIX.Palette.warning : ORIX.Palette.textTertiary)102            }103            .frame(minWidth: compact ? 58 : 66, alignment: .trailing)104            .accessibilityElement(children: .ignore).accessibilityLabel("Time").accessibilityValue(Text(verbatim: "\(formatTime(s.position, tenths: false)) elapsed, \(formatTime(s.remaining, tenths: false)) remaining"))105        }106    }107}108109private struct TransportRow: View {110    @Environment(AppModel.self) private var model111    var deck: Int112    var compact: Bool113114    var body: some View {115        let s = model.decks[deck]116        let tint = ORIX.deck(deck)117        let letter = deckLetters[deck]118        FlowLayout(spacing: 6, lineSpacing: 6) {119            Button { model.engine.cue(deck: deck) } label: {120                Text("CUE").font(.system(size: 12, weight: .heavy)).frame(width: compact ? 44 : 52, height: compact ? 30 : 36)121                    .foregroundStyle(ORIX.Palette.cue)122                    .background(ORIX.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))123                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.cue.opacity(0.7)))124            }125            .buttonStyle(.plain).disabled(s.track == nil)126            .help("Return to the cue point and pause. Option-click stores the current position as the cue point.")127            .simultaneousGesture(TapGesture().modifiers(.option).onEnded { model.engine.setCue(deck: deck); model.persistCues(deck) })128            .contextMenu { Button("Set Cue Point Here") { model.engine.setCue(deck: deck); model.persistCues(deck) } }129            .accessibilityAction(named: "Set Cue Point Here") { model.engine.setCue(deck: deck); model.persistCues(deck) }130            .accessibilityLabel(Text("Cue, deck \(letter)")).accessibilityIdentifier("cue-\(letter)")131132            Button { if s.playing { model.engine.pause(deck: deck) } else { model.play(deck) } } label: {133                Image(systemName: s.playing ? "pause.fill" : "play.fill").font(.system(size: 15, weight: .bold)).frame(width: compact ? 52 : 64, height: compact ? 30 : 36)134                    .foregroundStyle(s.playing ? ORIX.Palette.onTint : tint)135                    .background(s.playing ? AnyShapeStyle(tint) : AnyShapeStyle(ORIX.Palette.surfaceRaised), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))136                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(tint))137            }138            .buttonStyle(.plain).disabled(s.track == nil)139            .accessibilityLabel(Text(s.playing ? "Pause deck \(letter)" : "Play deck \(letter)")).accessibilityIdentifier("play-\(letter)")140141            ToggleChip(title: "SYNC", symbol: nil, isOn: s.sync, tint: tint) { model.toggle(.deck(deck, "sync")) }142                .help("Follow the tempo and beat phase of the master deck.").accessibilityIdentifier("sync-\(letter)")143            ToggleChip(title: "MSTR", symbol: "crown.fill", isOn: s.isMaster, tint: tint) { model.engine.setMasterDeck(s.isMaster ? nil : deck) }144                .help("Make this deck the master clock while it plays.").accessibilityLabel("Master clock")145            // Tempo.146            VStack(spacing: 1) {147                Fader(label: "Tempo", value: min(1, max(0, 0.5 + (s.rate - 1) / (2 * ControlTargets.tempoRange))), display: String(format: "%+.2f %%", (s.rate - 1) * 100),148                      tint: tint, horizontal: true, centreDetent: true,149                      onChange: { model.setTempo(deck: deck, percent: ($0 - 0.5) * 2 * ControlTargets.tempoRange * 100) }, onReset: { model.setTempo(deck: deck, percent: 0) })150                    .frame(width: compact ? 104 : 128, height: 22)151                    .accessibilityIdentifier("tempo-\(letter)")152                Text("TEMPO ±8 %").font(.system(size: 8, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)153            }154            ToggleChip(title: "KEY LOCK", symbol: "lock.fill", isOn: s.keylock, tint: tint) { model.toggle(.deck(deck, "keylock")) }155                .help("Keep the musical key when the tempo changes (time stretching).").accessibilityIdentifier("keylock-\(letter)")156            if !compact {157                HStack(spacing: 2) {158                    PadButton(title: "", symbol: "minus", minWidth: 22, height: 24) { model.set(.deck(deck, "keyShift"), .number(max(-12, s.keyShift - 1))) }.accessibilityLabel("Key down one semitone")159                    Text(verbatim: s.keyShift == 0 ? "0 st" : String(format: "%+.0f st", s.keyShift)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 36)160                        .onTapGesture(count: 2) { model.set(.deck(deck, "keyShift"), .number(0)) }161                    PadButton(title: "", symbol: "plus", minWidth: 22, height: 24) { model.set(.deck(deck, "keyShift"), .number(min(12, s.keyShift + 1))) }.accessibilityLabel("Key up one semitone")162                }163                .help("Key shift in semitones, independent of tempo.")164            }165        }166    }167}168169private struct LoopRow: View {170    @Environment(AppModel.self) private var model171    var deck: Int172    var compact: Bool173174    var body: some View {175        let s = model.decks[deck]176        let tint = ORIX.deck(deck)177        let activeBeats: Double? = {178            guard let loop = s.loop, loop.active, s.trackBPM > 0 else { return nil }179            return (loop.end - loop.start) * s.trackBPM / 60180        }()181        FlowLayout(spacing: 4, lineSpacing: 4) {182            SectionLabel("Loop").fixedSize().frame(height: 26)183            PadButton(title: String(localized: "IN"), minWidth: 28) { model.engine.loopIn(deck: deck) }.accessibilityLabel("Loop in")184            PadButton(title: String(localized: "OUT"), minWidth: 32) { if let e = model.engine.loopOut(deck: deck) { model.show(notice: e) } }.accessibilityLabel("Loop out")185            ForEach(compact ? [1.0, 2, 4, 8] : [0.25, 0.5, 1, 2, 4, 8, 16], id: \.self) { beats in186                let on = activeBeats.map { abs($0 - beats) < 0.01 } ?? false187                PadButton(title: ParamScale.beatLabel(beats), tint: tint, filled: on, minWidth: 26) {188                    if on { model.engine.loopExit(deck: deck) } else if let e = model.engine.loop(deck: deck, beats: beats) { model.show(notice: e) }189                }190                .accessibilityLabel(Text("Loop \(ParamScale.beatLabel(beats)) beats")).accessibilityAddTraits(on ? [.isSelected] : [])191            }192            PadButton(title: "", symbol: "divide", minWidth: 24) { model.engine.scaleLoop(deck: deck, by: 0.5) }.accessibilityLabel("Halve loop")193            PadButton(title: "×2", minWidth: 24) { model.engine.scaleLoop(deck: deck, by: 2) }.accessibilityLabel("Double loop")194            PadButton(title: (s.loop?.active ?? false) ? String(localized: "EXIT") : String(localized: "RELOOP"), tint: (s.loop?.active ?? false) ? tint : ORIX.Palette.textPrimary, minWidth: 48) {195                if s.loop?.active ?? false { model.engine.loopExit(deck: deck) } else if let e = model.engine.reloop(deck: deck) { model.show(notice: e) }196            }197            SectionLabel("Jump").frame(height: 26).padding(.leading, 6)198            ForEach(compact ? [-4.0, 4] : [-4.0, -1, 1, 4], id: \.self) { beats in199                PadButton(title: (beats > 0 ? "+" : "") + String(Int(beats)), minWidth: 26) { model.engine.jump(deck: deck, beats: beats) }200                    .accessibilityLabel(Text("Jump \(Int(beats)) beats"))201            }202        }203        .disabled(s.track == nil)204    }205}206207private struct HotCuePads: View {208    @Environment(AppModel.self) private var model209    var deck: Int210    var large: Bool211212    var body: some View {213        let s = model.decks[deck]214        let grid = large ? Array(repeating: GridItem(.flexible(), spacing: 6), count: 4) : Array(repeating: GridItem(.flexible(), spacing: 4), count: 8)215        HStack(alignment: .top, spacing: 6) {216            LazyVGrid(columns: grid, spacing: large ? 6 : 4) {217                ForEach(0 ..< ScriptSchema.hotCueCount, id: \.self) { i in218                    let set = s.hotcues.indices.contains(i) && s.hotcues[i] != nil219                    Button {220                        if NSEvent.modifierFlags.contains(.option) { model.engine.clearHotcue(deck: deck, index: i) }221                        else if set { if let e = model.engine.hotcue(deck: deck, index: i) { model.show(notice: e) } }222                        else { model.engine.setHotcue(deck: deck, index: i) }223                        model.persistCues(deck)224                    } label: {225                        VStack(spacing: 0) {226                            Text(verbatim: "\(i + 1)").font(.system(size: large ? 15 : 11, weight: .heavy, design: .rounded))227                            if large || set { Text(verbatim: set ? formatTime(s.hotcues[i] ?? 0, tenths: false) : "–").font(.system(size: 9).monospacedDigit()) }228                        }229                        .frame(maxWidth: .infinity, minHeight: large ? 46 : 28)230                        .foregroundStyle(set ? Color.black.opacity(0.88) : ORIX.Palette.textTertiary)231                        .background(set ? AnyShapeStyle(ORIX.hotCueColors[i]) : AnyShapeStyle(ORIX.Palette.surfaceRaised), in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))232                        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous).strokeBorder(set ? .clear : ORIX.Palette.hairline))233                    }234                    .buttonStyle(.plain)235                    .help(set ? "Jump to hot cue \(i + 1). Option-click clears it." : "Store the playhead in hot cue \(i + 1).")236                    .contextMenu {237                        Button("Store the Playhead Here") { model.engine.setHotcue(deck: deck, index: i); model.persistCues(deck) }238                        Button("Clear") { model.engine.clearHotcue(deck: deck, index: i); model.persistCues(deck) }.disabled(!set)239                    }240                    .accessibilityAction(named: "Clear") { model.engine.clearHotcue(deck: deck, index: i); model.persistCues(deck) }241                    .accessibilityLabel(Text("Hot cue \(i + 1), deck \(deckLetters[deck])"))242                    .accessibilityValue(set ? Text(verbatim: formatTime(s.hotcues[i] ?? 0, tenths: false)) : Text("empty"))243                    .accessibilityIdentifier("hotcue-\(deckLetters[deck])-\(i + 1)")244                }245            }246            VStack(spacing: 4) {247                ToggleChip(title: "QUANT", symbol: nil, isOn: s.quantize, tint: ORIX.deck(deck)) { model.toggle(.deck(deck, "quantize")) }248                    .help("Snap cues, loops and jumps to the beat grid.")249                if large {250                    ToggleChip(title: "REV", symbol: nil, isOn: s.reverse, tint: ORIX.deck(deck)) { model.toggle(.deck(deck, "reverse")) }251                    PadButton(title: String(localized: "BRAKE"), minWidth: 50) { model.engine.brake(deck: deck, seconds: 60 / max(60, model.clock.bpm)) }252                }253            }254        }255        .disabled(s.track == nil)256    }257}258259/// Beat-grid tools: the analysis can be wrong, so the grid is always adjustable by hand.260private struct GridRow: View {261    @Environment(AppModel.self) private var model262    var deck: Int263    /// Reverse and brake live on the pad section in performance mode.264    var showsTransportExtras = true265    @State private var taps: [Date] = []266267    var body: some View {268        let s = model.decks[deck]269        FlowLayout(spacing: 4, lineSpacing: 4) {270            SectionLabel("Grid").fixedSize().frame(height: 26)271            if let grid = s.track?.grid {272                PadButton(title: "", symbol: "chevron.left", minWidth: 22) { shift(grid, -0.005) }.accessibilityLabel("Move grid 5 milliseconds earlier")273                PadButton(title: "", symbol: "chevron.right", minWidth: 22) { shift(grid, 0.005) }.accessibilityLabel("Move grid 5 milliseconds later")274                PadButton(title: "÷2", minWidth: 26) { model.session.setGrid(deck: deck, BeatGrid(bpm: grid.bpm / 2, firstBeatSeconds: grid.firstBeatSeconds, downbeatIndex: 0)) }.accessibilityLabel("Halve the tempo")275                PadButton(title: "×2", minWidth: 26) { model.session.setGrid(deck: deck, BeatGrid(bpm: grid.bpm * 2, firstBeatSeconds: grid.firstBeatSeconds, downbeatIndex: grid.downbeatIndex)) }.accessibilityLabel("Double the tempo")276                PadButton(title: String(localized: "BEAT HERE"), minWidth: 62) {277                    let beat = 60 / grid.bpm278                    model.session.setGrid(deck: deck, BeatGrid(bpm: grid.bpm, firstBeatSeconds: s.position.truncatingRemainder(dividingBy: beat), downbeatIndex: grid.downbeatIndex))279                }.help("Move the grid so a beat falls on the playhead.")280                PadButton(title: String(localized: "BAR HERE"), minWidth: 58) {281                    let index = Int((grid.beat(at: s.position)).rounded()) % 4282                    model.session.setGrid(deck: deck, BeatGrid(bpm: grid.bpm, firstBeatSeconds: grid.firstBeatSeconds, downbeatIndex: (index + 4) % 4))283                }.help("Mark the nearest beat as the first beat of a bar.")284            }285            PadButton(title: String(localized: "TAP"), minWidth: 36) { tap() }.help("Tap four or more beats to set the tempo by hand.")286            if let t = s.track {287                Text(t.grid == nil ? "No tempo detected" : "\(String(format: "%.2f", t.grid?.bpm ?? 0)) BPM · confidence \(Int(t.bpmConfidence * 100)) %")288                    .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).frame(height: 26)289            }290            if showsTransportExtras {291                ToggleChip(title: "REV", symbol: nil, isOn: s.reverse, tint: ORIX.deck(deck)) { model.toggle(.deck(deck, "reverse")) }.help("Play backwards.")292                PadButton(title: String(localized: "BRAKE"), minWidth: 46) { model.engine.brake(deck: deck, seconds: 60 / max(60, model.clock.bpm)) }.help("Tape stop over one beat.")293            }294        }295        .disabled(s.track == nil)296    }297298    private func shift(_ grid: BeatGrid, _ seconds: Double) {299        let beat = 60 / grid.bpm300        var first = (grid.firstBeatSeconds + seconds).truncatingRemainder(dividingBy: beat)301        if first < 0 { first += beat }302        model.session.setGrid(deck: deck, BeatGrid(bpm: grid.bpm, firstBeatSeconds: first, downbeatIndex: grid.downbeatIndex))303    }304305    private func tap() {306        let now = Date()307        if let last = taps.last, now.timeIntervalSince(last) > 2.5 { taps.removeAll() }308        taps.append(now)309        if taps.count > 12 { taps.removeFirst() }310        guard taps.count >= 4 else { return }311        let interval = now.timeIntervalSince(taps[0]) / Double(taps.count - 1)312        let bpm = 60 / interval313        guard bpm > 40, bpm < 300 else { return }314        let s = model.decks[deck]315        // Convert from heard tempo to the track's own tempo, and put a beat on the last tap.316        let trackBPM = bpm / max(0.05, s.rate)317        model.session.setGrid(deck: deck, BeatGrid(bpm: trackBPM, firstBeatSeconds: s.position.truncatingRemainder(dividingBy: 60 / trackBPM), downbeatIndex: 0))318    }319}320321/// Vinyl-inspired platter. It turns at 33⅓ rpm of track time; dragging it moves the real playhead.322private struct Platter: View {323    @Environment(AppModel.self) private var model324    var deck: Int325    @State private var lastAngle: Double?326327    var body: some View {328        let s = model.decks[deck]329        let angle = s.position * (100.0 / 3 / 60) * 360330        GeometryReader { geo in331            let centre = CGPoint(x: geo.size.width / 2, y: geo.size.height / 2)332            ZStack {333                Circle().fill(ORIX.Palette.well)334                ForEach(0 ..< 5, id: \.self) { i in Circle().strokeBorder(ORIX.Palette.hairline.opacity(0.7), lineWidth: 1).padding(CGFloat(8 + i * 8)) }335                Circle().fill(ORIX.deck(deck).opacity(0.9)).padding(geo.size.width * 0.32)336                Text(verbatim: deckLetters[deck]).font(.system(size: 16, weight: .heavy, design: .rounded)).foregroundStyle(Color.black.opacity(0.85))337                // Position marker.338                Capsule().fill(Color.white).frame(width: 3, height: geo.size.height * 0.2).offset(y: -geo.size.height * 0.38).rotationEffect(.degrees(angle))339            }340            .contentShape(Circle())341            .gesture(DragGesture(minimumDistance: 1).onChanged { g in342                guard s.track != nil else { return }343                let a = atan2(Double(g.location.y - centre.y), Double(g.location.x - centre.x))344                if let last = lastAngle {345                    var d = a - last346                    if d > .pi { d -= 2 * .pi } else if d < -.pi { d += 2 * .pi }347                    // One turn is 1.8 seconds of audio, as on a 33⅓ rpm record.348                    model.engine.seek(deck: deck, seconds: max(0, model.engine.deckStatus(deck).position + d / (2 * .pi) * 1.8))349                }350                lastAngle = a351            }.onEnded { _ in lastAngle = nil })352        }353        .accessibilityElement(children: .ignore)354        .accessibilityLabel(Text("Platter, deck \(deckLetters[deck])"))355        .accessibilityValue(Text(verbatim: formatTime(s.position, tenths: false)))356        .accessibilityAdjustableAction { direction in357            model.engine.seek(deck: deck, seconds: max(0, s.position + (direction == .increment ? 0.25 : -0.25)))358        }359        .help("Drag to move through the track. One turn is 1.8 seconds.")360    }361}362
Files main
Menu

Theme