SPB Git

Repository Public

WaveformViews.swift 9.0 KB 169 lines swift

1// ORIX DJ2// File: App/Sources/Features/Waveforms/WaveformViews.swift3// Description: SwiftUI wrappers of the waveform displays: the scrolling Metal waveform (scrub, zoom) and the4//              full-track overview (seek, cue and loop markers).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import MetalKit9import ORIXDJCore10import SwiftUI1112/// Scrolling, zoomable waveform of one deck. Drag to scrub, scroll or pinch to zoom.13struct ScrollingWaveform: View {14    @Environment(AppModel.self) private var model15    @Environment(AppSettings.self) private var settings16    var deck: Int17    @State private var dragOrigin: Double?18    @State private var zoomOrigin: Double?1920    var body: some View {21        let status = model.decks[deck]22        GeometryReader { geo in23            MetalWaveform(deck: deck, engine: model.engine, palette: settings.palette, secondsVisible: settings.waveformZoom, color: ORIX.deck(deck))24                .gesture(DragGesture(minimumDistance: 2).onChanged { g in25                    // Scrubbing moves the real playhead.26                    guard status.track != nil else { return }27                    if dragOrigin == nil { dragOrigin = status.position }28                    let secondsPerPoint = settings.waveformZoom / max(1, Double(geo.size.width))29                    model.engine.seek(deck: deck, seconds: max(0, (dragOrigin ?? 0) - Double(g.translation.width) * secondsPerPoint))30                }.onEnded { _ in dragOrigin = nil })31                .gesture(MagnifyGesture().onChanged { g in32                    if zoomOrigin == nil { zoomOrigin = settings.waveformZoom }33                    settings.waveformZoom = min(32, max(1, (zoomOrigin ?? 6) / Double(g.magnification)))34                }.onEnded { _ in zoomOrigin = nil })35                .overlay(alignment: .bottomTrailing) {36                    HStack(spacing: 2) {37                        Button { settings.waveformZoom = min(32, settings.waveformZoom * 1.5) } label: { Image(systemName: "minus.magnifyingglass") }.accessibilityLabel("Zoom out")38                        Button { settings.waveformZoom = max(1, settings.waveformZoom / 1.5) } label: { Image(systemName: "plus.magnifyingglass") }.accessibilityLabel("Zoom in")39                    }40                    .buttonStyle(.plain).font(.system(size: 11)).foregroundStyle(Color.white.opacity(0.75))41                    .padding(4)42                }43                .overlay {44                    if status.track == nil {45                        Text(model.loadProgress[deck] != nil ? "Loading…" : "Drop a track here, or load one from the library")46                            .font(.system(size: 12)).foregroundStyle(Color.white.opacity(0.55))47                    } else if status.track?.waveform == nil {48                        Text("No waveform: the track has not been analysed").font(.system(size: 12)).foregroundStyle(Color.white.opacity(0.55))49                    }50                }51        }52        .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))53        .accessibilityElement(children: .contain)54        .accessibilityLabel(Text("Waveform, deck \(deckLetters[deck])"))55        .accessibilityValue(status.track == nil ? Text("empty") : Text(verbatim: "\(formatTime(status.position, tenths: false)) of \(formatTime(status.track?.duration ?? 0, tenths: false))"))56        .accessibilityIdentifier("waveform-\(deckLetters[deck])")57    }58}5960private struct MetalWaveform: NSViewRepresentable {61    var deck: Int62    var engine: DJEngine63    var palette: WaveformPalette64    var secondsVisible: Double65    var color: Color6667    func makeCoordinator() -> WaveformRenderer { WaveformRenderer(deck: deck, engine: engine) }6869    func makeNSView(context: Context) -> MTKView {70        let view = MTKView(frame: .zero, device: WaveformRenderer.device)71        view.colorPixelFormat = .bgra8Unorm72        view.clearColor = MTLClearColor(red: 0.02, green: 0.027, blue: 0.055, alpha: 1)73        view.preferredFramesPerSecond = 6074        view.enableSetNeedsDisplay = false75        view.isPaused = false76        view.delegate = context.coordinator77        view.layer?.isOpaque = true78        return view79    }8081    func updateNSView(_ view: MTKView, context: Context) {82        let r = context.coordinator83        r.palette = palette; r.secondsVisible = secondsVisible84        if let c = NSColor(color).usingColorSpace(.sRGB) { r.deckColor = SIMD4(Float(c.redComponent), Float(c.greenComponent), Float(c.blueComponent), 1) }85    }86}8788/// Whole-track overview with playhead, cue points and loop. Click or drag to seek.89struct OverviewWaveform: View {90    @Environment(AppModel.self) private var model91    @Environment(AppSettings.self) private var settings92    var deck: Int93    @State private var cache = OverviewCache()9495    var body: some View {96        let status = model.decks[deck]97        GeometryReader { geo in98            let duration = max(0.001, status.track?.duration ?? 0)99            Canvas { context, size in100                context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(ORIX.Palette.waveformWell))101                guard let track = status.track else { return }102                let paths = cache.paths(for: track, size: size)103                let bands = settings.palette.bands104                context.fill(paths.low, with: .color(Color(hex: bands.low)))105                context.fill(paths.mid, with: .color(Color(hex: bands.mid)))106                context.fill(paths.high, with: .color(Color(hex: bands.high)))107                func x(_ seconds: Double) -> CGFloat { size.width * CGFloat(seconds / duration) }108                // Played part.109                context.fill(Path(CGRect(x: 0, y: 0, width: x(status.position), height: size.height)), with: .color(Color.black.opacity(0.45)))110                if let loop = status.loop {111                    context.fill(Path(CGRect(x: x(loop.start), y: 0, width: max(1, x(loop.end) - x(loop.start)), height: size.height)), with: .color(ORIX.deck(deck).opacity(loop.active ? 0.35 : 0.15)))112                }113                context.fill(Path(CGRect(x: x(status.cuePoint) - 0.5, y: 0, width: 1.5, height: size.height)), with: .color(Color(hex: 0xFF9F0A)))114                for (i, h) in status.hotcues.enumerated() {115                    guard let h else { continue }116                    context.fill(Path(CGRect(x: x(h) - 0.5, y: 0, width: 1.5, height: size.height * 0.5)), with: .color(ORIX.hotCueColors[i % 8]))117                }118                context.fill(Path(CGRect(x: x(status.position) - 1, y: 0, width: 2, height: size.height)), with: .color(.white))119            }120            .contentShape(Rectangle())121            .gesture(DragGesture(minimumDistance: 0).onChanged { g in122                guard status.track != nil else { return }123                model.engine.seek(deck: deck, seconds: duration * Double(min(1, max(0, g.location.x / max(1, geo.size.width)))))124            })125        }126        .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))127        .accessibilityElement(children: .ignore)128        .accessibilityLabel(Text("Track overview, deck \(deckLetters[deck])"))129        .accessibilityValue(Text(verbatim: "\(Int((status.position / max(0.001, status.track?.duration ?? 1)) * 100)) %"))130        .accessibilityAdjustableAction { direction in131            guard let d = status.track?.duration else { return }132            let step = d / 50133            model.engine.seek(deck: deck, seconds: min(d, max(0, status.position + (direction == .increment ? step : -step))))134        }135        .accessibilityIdentifier("overview-\(deckLetters[deck])")136    }137}138139/// Band outlines of the overview, rebuilt only when the track or the size changes.140@MainActor141final class OverviewCache {142    private var track: LoadedTrack?143    private var size = CGSize.zero144    private var columns = 0145    private var stored = (low: Path(), mid: Path(), high: Path())146147    func paths(for track: LoadedTrack, size: CGSize) -> (low: Path, mid: Path, high: Path) {148        let count = track.waveform?.count ?? 0149        if track == self.track, size == self.size, count == columns { return stored }150        self.track = track; self.size = size; columns = count151        guard let wave = track.waveform, count > 0, size.width >= 2 else { stored = (Path(), Path(), Path()); return stored }152        let n = Int(size.width)153        let overview = wave.overview(columns: n)154        func outline(_ values: [UInt8], _ scale: CGFloat) -> Path {155            var p = Path()156            let mid = size.height / 2157            let step = size.width / CGFloat(max(1, values.count))158            p.move(to: CGPoint(x: 0, y: mid))159            for (i, v) in values.enumerated() { p.addLine(to: CGPoint(x: CGFloat(i) * step, y: mid - CGFloat(v) / 255 * mid * scale)) }160            p.addLine(to: CGPoint(x: size.width, y: mid))161            for (i, v) in values.enumerated().reversed() { p.addLine(to: CGPoint(x: CGFloat(i) * step, y: mid + CGFloat(v) / 255 * mid * scale)) }162            p.closeSubpath()163            return p164        }165        stored = (outline(overview.low, 0.94), outline(overview.mid, 0.8), outline(overview.high, 0.66))166        return stored167    }168}169
Files main
Menu

Theme