removed unwanted bar now with waveforms, major updates
This commit is contained in:
+233
-53
@@ -19,6 +19,26 @@ enum DJMix {
|
||||
}
|
||||
}
|
||||
|
||||
struct DJGraphicEQSettings: Codable, Equatable {
|
||||
var enabled = false
|
||||
var preset = "Flat"
|
||||
var gains = [Double](repeating:0,count:10)
|
||||
static let presets: [(String,[Double])] = [
|
||||
("Flat",[0,0,0,0,0,0,0,0,0,0]),
|
||||
("Rock",[4,3,2,0,-2,-1,1,3,4,3]),
|
||||
("Pop",[-1,1,3,4,2,0,-1,-1,1,2]),
|
||||
("Jazz",[3,2,1,1,-1,-1,0,2,3,3]),
|
||||
("Vocal",[-4,-3,-2,0,2,4,4,2,0,-2]),
|
||||
("Bass Boost",[6,5,4,2,0,0,0,0,0,0]),
|
||||
("Treble Boost",[0,0,0,0,0,1,2,3,4,5])
|
||||
]
|
||||
var sanitized: Self {
|
||||
var value = self
|
||||
value.gains = (0..<10).map { gains.indices.contains($0) && gains[$0].isFinite ? min(12,max(-12,gains[$0])) : 0 }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
struct DJPreferences: Codable, Equatable {
|
||||
var autoPlayOnLoad = false
|
||||
var resetEQOnLoad = false
|
||||
@@ -67,16 +87,17 @@ struct DJPreferences: Codable, Equatable {
|
||||
player.defineLoop(start:start,end:min(player.duration,start+length))
|
||||
}
|
||||
}
|
||||
var master: Double = 0.8 { didSet { updateLevel() } }
|
||||
var crossWeight: Double = 1 { didSet { updateLevel() } }
|
||||
var master: Double = 0.8 { didSet { if master != oldValue { updateLevel() } } }
|
||||
var crossWeight: Double = 1 { didSet { if crossWeight != oldValue { updateLevel() } } }
|
||||
private var taps = [Double]()
|
||||
init(_ letter: String,waveformCache: URL? = nil) { self.letter = letter;player = Player(waveformCacheDirectory:waveformCache,persistsMix:false);player.audibleScrubbing = true;player.autoFade = false;updateLevel() }
|
||||
func updateLevel() { player.volume = min(1,max(0,level * master * crossWeight)) }
|
||||
func updateLevel() { let value = min(1,max(0,level * master * crossWeight));if player.volume != value { player.volume = value } }
|
||||
func load(_ song: Song) throws {
|
||||
var audioOnly = song;audioOnly.cdg = nil
|
||||
do { try player.load(audioOnly,startPlaying:false) } catch { self.song = nil;throw error }
|
||||
self.song = song;bpmConfirmed = false;bpmEstimated = false;bpm = 120;taps = [];loadTrackInfo(song)
|
||||
}
|
||||
func updateTrackMetadata(_ song: Song) { self.song = song;player.title = song.title }
|
||||
func unload() { infoTask?.cancel();analysisTask?.cancel();player.stop();song = nil;bpmConfirmed = false;artwork = nil;analysingBPM = false }
|
||||
private func loadTrackInfo(_ song: Song) {
|
||||
infoTask?.cancel();analysisTask?.cancel();artwork = nil;analysingBPM = true
|
||||
@@ -151,6 +172,23 @@ struct DJAudioDevice: Identifiable, Equatable {
|
||||
}
|
||||
|
||||
@MainActor final class DJSystem: ObservableObject {
|
||||
@Published var namesBusy = false
|
||||
private var graphicSaveTask: Task<Void,Never>?
|
||||
@Published var graphicEQ = DJGraphicEQSettings() { didSet {
|
||||
applyGraphicEQ()
|
||||
graphicSaveTask?.cancel()
|
||||
let url = root.appendingPathComponent("DJGraphicEQ.json"),value = graphicEQ.sanitized
|
||||
graphicSaveTask = Task { @MainActor in
|
||||
do { try await Task.sleep(nanoseconds:200_000_000);try JSONEncoder().encode(value).write(to:url,options:.atomic) } catch { }
|
||||
}
|
||||
} }
|
||||
private func applyGraphicEQ() {
|
||||
for player in [a.player,b.player,preview] { player.applyGraphicEQ(graphicEQ.sanitized.gains,enabled:graphicEQ.enabled) }
|
||||
}
|
||||
func chooseGraphicPreset(_ name: String) {
|
||||
guard let gains = DJGraphicEQSettings.presets.first(where:{$0.0 == name})?.1 else { return }
|
||||
graphicEQ = .init(enabled:true,preset:name,gains:gains)
|
||||
}
|
||||
@Published private(set) var waveformJob: WaveformJobProgress?
|
||||
@Published private(set) var generatingWaveforms = false
|
||||
private var waveformTask: Task<Void,Never>?
|
||||
@@ -161,7 +199,7 @@ struct DJAudioDevice: Identifiable, Equatable {
|
||||
let cache = root.appendingPathComponent("Waveforms")
|
||||
generatingWaveforms = true;waveformJob = .init(total:tracks.count)
|
||||
waveformTask = Task.detached(priority:.utility) { [weak self] in
|
||||
let result = WaveformBatch.run(songs:tracks,locations:[],cache:cache,force:force,cancelled:{Task.isCancelled}) { update in
|
||||
let result = await WaveformBatch.runConcurrent(songs:tracks,locations:[],cache:cache,force:force) { update in
|
||||
Task { @MainActor [weak self] in self?.waveformJob = update }
|
||||
}
|
||||
await MainActor.run { [weak self] in
|
||||
@@ -229,6 +267,8 @@ struct DJAudioDevice: Identifiable, Equatable {
|
||||
perform {
|
||||
try FileManager.default.createDirectory(at:root,withIntermediateDirectories:true)
|
||||
library = try Library(url:root.appendingPathComponent("Library.sqlite"));try refresh()
|
||||
if let data = try? Data(contentsOf:root.appendingPathComponent("DJGraphicEQ.json")),let saved = try? JSONDecoder().decode(DJGraphicEQSettings.self,from:data) { graphicEQ = saved.sanitized }
|
||||
applyGraphicEQ()
|
||||
favourites = Set((try library?.setting("DJ.Favourites.v1") ?? "").split(separator:",").compactMap{Int64($0)})
|
||||
if let data = try? Data(contentsOf:root.appendingPathComponent("DJSettings.json")),let saved = try? JSONDecoder().decode(DJPreferences.self,from:data) { settings = saved.sanitized }
|
||||
if let data = try? Data(contentsOf:root.appendingPathComponent("DJAudioRouting.json")),let saved = try? JSONDecoder().decode(DJAudioRouting.self,from:data) { applyRouting(saved) }
|
||||
@@ -746,14 +786,23 @@ private enum DJStyle {
|
||||
|
||||
/// Observe user scrolling, rather than row appearance (List preloads offscreen rows).
|
||||
private struct DJLibraryPageScroll: NSViewRepresentable {
|
||||
var page: Int
|
||||
let next: () -> Void
|
||||
func makeNSView(context: Context) -> Observer { Observer() }
|
||||
func updateNSView(_ view: Observer,context: Context) { view.next = next;view.attach() }
|
||||
func updateNSView(_ view: Observer,context: Context) { view.next = next;view.attach();view.setPage(page) }
|
||||
final class Observer: NSView {
|
||||
var next: (() -> Void)?
|
||||
private weak var scroll: NSScrollView?
|
||||
private var observation: NSObjectProtocol?
|
||||
private var endObservation: NSObjectProtocol?
|
||||
private var currentPage = 0
|
||||
func setPage(_ page: Int) {
|
||||
guard page != currentPage else { return };currentPage = page
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let scroll = self?.scroll else { return }
|
||||
scroll.contentView.scroll(to:.zero);scroll.reflectScrolledClipView(scroll.contentView);self?.lastY = 0
|
||||
}
|
||||
}
|
||||
private var advanced = false
|
||||
private var lastY: CGFloat = 0
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow();DispatchQueue.main.async { [weak self] in self?.attach() } }
|
||||
@@ -801,8 +850,27 @@ private struct DJQueueButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
private struct DJLibrarySnapshot<Content: View>: View, Equatable {
|
||||
let revision: UUID
|
||||
let selection: Set<Int64>
|
||||
let selected: Int64?
|
||||
let page: Int
|
||||
let busy: Bool
|
||||
let font: Double
|
||||
let height: Double
|
||||
@ViewBuilder let content: () -> Content
|
||||
static func == (lhs: Self,rhs: Self) -> Bool {
|
||||
lhs.revision == rhs.revision && lhs.selection == rhs.selection && lhs.selected == rhs.selected && lhs.page == rhs.page && lhs.busy == rhs.busy && lhs.font == rhs.font && lhs.height == rhs.height
|
||||
}
|
||||
var body: some View { content() }
|
||||
}
|
||||
|
||||
struct DJConsole: View {
|
||||
@ObservedObject var system: DJSystem
|
||||
@State private var reinterpreting = false
|
||||
@State private var reinterpretIDs = Set<Int64>()
|
||||
@State private var editingTrack: Song?
|
||||
@State private var graphicEQVisible = false
|
||||
@State private var waveformDetails = false
|
||||
@State private var favouritesOnly = false
|
||||
@State private var queueVisible = false
|
||||
@@ -815,10 +883,14 @@ struct DJConsole: View {
|
||||
@State private var playlistName = ""
|
||||
@State private var renaming = false
|
||||
@State private var page = 0
|
||||
private var songs: [Song] {
|
||||
@State private var libraryRevision = UUID()
|
||||
@State private var filteredTracks = [Song]()
|
||||
private var songs: [Song] { filteredTracks }
|
||||
private func updateFilteredTracks() {
|
||||
libraryRevision = UUID()
|
||||
let all = system.songs.filter{!$0.audio.hasPrefix("showscreen:") && (!favouritesOnly || system.favourites.contains($0.id)) && SongSearch.matches($0,query:query)}
|
||||
if playlist != nil { let lookup = Dictionary(uniqueKeysWithValues:all.map{($0.id,$0)});return playlistIDs.compactMap{lookup[$0]} }
|
||||
return all
|
||||
if playlist != nil { let lookup = Dictionary(uniqueKeysWithValues:all.map{($0.id,$0)});filteredTracks = playlistIDs.compactMap{lookup[$0]} }
|
||||
else { filteredTracks = all }
|
||||
}
|
||||
private var selectedTracks: [Song] { songs.filter { selection.contains($0.id) } }
|
||||
private func selectTrack(_ id: Int64) {
|
||||
@@ -840,7 +912,7 @@ struct DJConsole: View {
|
||||
VStack(spacing:10) {
|
||||
header
|
||||
DJContinuousConsole(system:system,loadA:{loadSelected("A")},loadB:{loadSelected("B")}).fixedSize(horizontal:false,vertical:true)
|
||||
browser.frame(maxWidth:.infinity,maxHeight:.infinity)
|
||||
DJLibrarySnapshot(revision:libraryRevision,selection:selection,selected:selected,page:page,busy:system.generatingWaveforms || system.importing,font:system.settings.libraryFont,height:system.settings.libraryRowHeight) { browser }.equatable().frame(maxWidth:.infinity,maxHeight:.infinity)
|
||||
if let progress = system.importProgress {
|
||||
HStack {
|
||||
Text(progress.current).lineLimit(1);Text("\(progress.completed)/\(progress.total)").monospacedDigit()
|
||||
@@ -862,6 +934,9 @@ struct DJConsole: View {
|
||||
.interactiveDismissDisabled(system.importing)
|
||||
}
|
||||
}
|
||||
.sheet(isPresented:$reinterpreting) { ReinterpretNamesSheet(model:system,ids:reinterpretIDs) }
|
||||
.sheet(item:$editingTrack) { DJTrackMetadataDialog(system:system,song:$0) }
|
||||
.sheet(isPresented:$graphicEQVisible) { DJGraphicEQDialog(system:system) }
|
||||
.sheet(isPresented:$system.cueEditing) { DJCueEditor(system:system) }
|
||||
.sheet(isPresented:Binding(get:{system.loopEditor != nil},set:{if !$0 { system.loopEditor = nil }})) { let deck = system.channel(system.loopEditor ?? "A");DJLoopEditor(player:deck.player,letter:deck.letter) }
|
||||
.sheet(isPresented:Binding(get:{system.waveformJob != nil},set:{if !$0 { system.dismissWaveforms() }})) {
|
||||
@@ -893,12 +968,13 @@ struct DJConsole: View {
|
||||
.alert("DJ workstation",isPresented:Binding(get:{system.error != nil},set:{if !$0 { system.error = nil }})) { Button("OK") { system.error = nil } } message: { Text(system.error ?? "") }
|
||||
.onAppear { refreshPlaylist();connectMIDI() }
|
||||
.onChange(of:selected) { _ in connectMIDI() }
|
||||
.onChange(of:selection) { ids in if selected == nil || !ids.contains(selected!) { selected = songs.first(where:{ids.contains($0.id)})?.id };connectMIDI() }
|
||||
.onChange(of:selection) { ids in if selected == nil || !ids.contains(selected!) { selected = songs.first(where:{ids.contains($0.id)})?.id } }
|
||||
.onChange(of:playlist) { _ in refreshPlaylist();page = 0;selected = nil;selection = [] }
|
||||
.onChange(of:system.songs) { _ in refreshPlaylist();connectMIDI() }
|
||||
.onChange(of:system.playlists) { _ in if let playlist,!system.playlists.contains(where:{$0.id == playlist}) { self.playlist = nil };refreshPlaylist() }
|
||||
.onChange(of:query) { _ in page = 0 }
|
||||
.onChange(of:favouritesOnly) { _ in page = 0 }
|
||||
.onChange(of:query) { _ in updateFilteredTracks();page = 0 }
|
||||
.onChange(of:favouritesOnly) { _ in updateFilteredTracks();page = 0 }
|
||||
.onChange(of:system.favourites) { _ in updateFilteredTracks() }
|
||||
}
|
||||
private var header: some View {
|
||||
HStack {
|
||||
@@ -906,6 +982,7 @@ struct DJConsole: View {
|
||||
Text("DJ WORKSTATION").font(.system(size:12,weight:.bold,design:.rounded))
|
||||
Text("TWO DECKS").font(.system(size:9,weight:.medium)).foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Button { graphicEQVisible = true } label: { Label("Equaliser",systemImage:"slider.vertical.3") }.tint(system.graphicEQ.enabled ? .cyan : .accentColor)
|
||||
DJQueueButton(automix:system.automix,open:{queueVisible = true})
|
||||
if system.previewDeck != nil { Button("Stop headphone preview") { system.stopPreview() }.tint(.green) }
|
||||
}.controlSize(.small)
|
||||
@@ -923,7 +1000,7 @@ struct DJConsole: View {
|
||||
} label: { Image(systemName:"folder.badge.plus") }.frame(width:25)
|
||||
Button { favouritesOnly.toggle() } label: { Label("Favourites",systemImage:favouritesOnly ? "star.fill" : "star") }.foregroundStyle(favouritesOnly ? Color.yellow : Color.secondary).help("Show favourite tracks only")
|
||||
Spacer(minLength:12)
|
||||
TextField("Search DJ music",text:$query).textFieldStyle(.roundedBorder).controlSize(.regular).frame(maxWidth:260)
|
||||
StudioSearchField(placeholder:"Search music",text:$query).frame(maxWidth:260)
|
||||
Button { system.automix.enqueue(selectedTracks) } label: { Image(systemName:"text.badge.plus") }.help("Add selected tracks to the DJ queue").disabled(selectedTracks.isEmpty)
|
||||
Text("\(selection.count) selected").font(.caption).foregroundStyle(.secondary)
|
||||
Button("Import Files / Folder…") { importMedia() }
|
||||
@@ -933,23 +1010,34 @@ struct DJConsole: View {
|
||||
Button { page = min(pages-1,page+1) } label: { Image(systemName:"chevron.right") }.disabled(page >= pages-1)
|
||||
}.controlSize(.small)
|
||||
ScrollViewReader { reader in
|
||||
List(selection:$selection) {
|
||||
ForEach(visible) { song in
|
||||
HStack(spacing:8) {
|
||||
Button { system.toggleFavourite(song.id) } label: { GoldStar(filled:system.favourites.contains(song.id),size:15) }.buttonStyle(.plain).accessibilityLabel(system.favourites.contains(song.id) ? "Remove \(song.title) from favourites" : "Favourite \(song.title)")
|
||||
DJLibraryDragTitle(title:song.title,reference:system.dragReference(song.id),fontSize:system.settings.libraryFont,select:{selectTrack(song.id)},doubleClick:{system.loadFromLibraryDoubleClick(song)},selectAll:{selectAllTracks()}).frame(maxWidth:.infinity,alignment:.leading)
|
||||
Text(song.artist).font(.system(size:10)).foregroundStyle(.secondary).lineLimit(1).frame(width:130,alignment:.leading)
|
||||
Text(DJStyle.stamp(song.duration)).font(.system(size:10).monospacedDigit()).foregroundStyle(.secondary).frame(width:35)
|
||||
Button { system.automix.enqueue([song]) } label: { Image(systemName:"plus") }.accessibilityLabel("Add \(song.title) to DJ queue")
|
||||
Table(visible,selection:$selection) {
|
||||
TableColumn("Favourite") { song in
|
||||
Button { system.toggleFavourite(song.id) } label: { GoldStar(filled:system.favourites.contains(song.id),size:15) }.buttonStyle(.plain).accessibilityLabel(system.favourites.contains(song.id) ? "Remove \(song.title) from favourites" : "Favourite \(song.title)")
|
||||
}.width(55)
|
||||
TableColumn("Title") { song in
|
||||
DJLibraryDragTitle(title:song.title,reference:system.dragReference(song.id),fontSize:system.settings.libraryFont,select:{selectTrack(song.id)},doubleClick:{system.loadFromLibraryDoubleClick(song)},selectAll:{selectAllTracks()})
|
||||
.frame(maxWidth:.infinity,alignment:.leading).frame(minHeight:system.settings.libraryRowHeight)
|
||||
}.width(min:180,ideal:400,max:1600)
|
||||
TableColumn("Artist") { song in Text(song.artist).lineLimit(1).help(song.artist) }.width(min:100,ideal:200,max:800)
|
||||
TableColumn("Album") { song in Text(song.album).lineLimit(1).foregroundStyle(.secondary).help(song.album) }.width(min:90,ideal:180,max:800)
|
||||
TableColumn("Time") { song in Text(DJStyle.stamp(song.duration)).monospacedDigit().foregroundStyle(.secondary) }.width(min:45,ideal:60,max:100)
|
||||
TableColumn("Rating") { song in
|
||||
GoldRating(rating:Binding(get:{song.rating},set:{value in system.perform { try system.library?.rate(song.id,value);try system.refresh() } }))
|
||||
}.width(min:95,ideal:105,max:140)
|
||||
TableColumn("Load") { song in
|
||||
HStack(spacing:7) {
|
||||
Button("A") { system.load(song,into:"A") }.tint(DJStyle.a).accessibilityLabel("Load \(song.title) into A")
|
||||
Button("B") { system.load(song,into:"B") }.tint(DJStyle.b).accessibilityLabel("Load \(song.title) into B")
|
||||
}.padding(.vertical,max(0,(system.settings.libraryRowHeight-24)/2)).tag(song.id).id(song.id).buttonStyle(.bordered).controlSize(.mini)
|
||||
.contextMenu { playlistMenu(song) }
|
||||
}
|
||||
if visible.isEmpty { Text("Import music or choose another playlist.").font(.caption).foregroundStyle(.secondary) }
|
||||
}.listStyle(.inset).scrollContentBackground(.hidden).background(DJStyle.panel,in:RoundedRectangle(cornerRadius:6))
|
||||
}.buttonStyle(.bordered).controlSize(.small)
|
||||
}.width(90)
|
||||
}.font(.system(size:system.settings.libraryFont))
|
||||
.contextMenu(forSelectionType:Int64.self) { ids in
|
||||
if let song = songs.first(where:{ids.contains($0.id)}) { playlistMenu(song) }
|
||||
else { Button("Select All Songs") { selectAllTracks() } }
|
||||
}
|
||||
.scrollContentBackground(.hidden).background(DJStyle.panel,in:RoundedRectangle(cornerRadius:8))
|
||||
.onCommand(#selector(NSResponder.selectAll(_:))) { selectAllTracks() }
|
||||
.background(DJLibraryPageScroll { if page < pages-1 { page += 1 } })
|
||||
.background(DJLibraryPageScroll(page:page) { if page < pages-1 { page += 1 } })
|
||||
.onChange(of:page) { _ in
|
||||
selected = visible.first?.id;selection = Set(visible.first.map{[$0.id]} ?? [])
|
||||
if let first = visible.first?.id { DispatchQueue.main.async { reader.scrollTo(first,anchor:.top) } }
|
||||
@@ -958,6 +1046,10 @@ struct DJConsole: View {
|
||||
}
|
||||
}
|
||||
@ViewBuilder private func playlistMenu(_ song: Song) -> some View {
|
||||
Button("Song Info / Artist…") { editingTrack = song }
|
||||
Button("Reinterpret Selected Names…") { reinterpretIDs = Set(contextTracks(song).map(\.id));reinterpreting = true }.disabled(system.namesBusy)
|
||||
Button("Undo Last Name Reinterpretation") { Task { do { try await system.undoNameChanges() } catch { system.error = error.localizedDescription } } }.disabled(system.namesBusy)
|
||||
Divider()
|
||||
Button("Load into Deck A") { system.load(song,into:"A") }
|
||||
Button("Load into Deck B") { system.load(song,into:"B") }
|
||||
Divider()
|
||||
@@ -993,7 +1085,7 @@ struct DJConsole: View {
|
||||
}.padding(24).frame(width:360)
|
||||
}
|
||||
private func loadSelected(_ deck: String) { if let selectedSong { system.load(selectedSong,into:deck) } else { system.status = "Select a DJ library track, then Load \(deck), or drag a DJ library track onto the deck." } }
|
||||
private func refreshPlaylist() { playlistIDs = playlist.flatMap{try? system.library?.playlistSongIDs($0)} ?? [] }
|
||||
private func refreshPlaylist() { playlistIDs = playlist.flatMap{try? system.library?.playlistSongIDs($0)} ?? [];updateFilteredTracks() }
|
||||
private func connectMIDI() {
|
||||
system.midi.currentValue = { [weak system] action in
|
||||
guard let system else { return nil }
|
||||
@@ -1061,6 +1153,7 @@ private struct DJDeckSurfaces {
|
||||
DJHardwareFader(value:$deck.level,label:"Deck \(deck.letter) level",vertical:true).frame(width:44,height:94)
|
||||
}
|
||||
Text("LEVEL").font(.system(size:8,weight:.semibold)).foregroundStyle(.secondary)
|
||||
Button { player.vocalReductionEnabled.toggle() } label: { Image(systemName:player.vocalReductionEnabled ? "mic.slash.fill" : "mic.fill") }.buttonStyle(.plain).foregroundStyle(player.vocalReductionEnabled ? color : .secondary).help("Centre vocal reduction: reduces centred stereo audio, including some instruments; mono tracks pass through").accessibilityLabel("Deck \(deck.letter) centre vocal reduction").accessibilityValue(player.vocalReductionEnabled ? "On" : "Off")
|
||||
}
|
||||
}.frame(width:110)
|
||||
}
|
||||
@@ -1092,36 +1185,59 @@ struct DJKnob: View {
|
||||
.accessibilityAdjustableAction { direction in let step = (range.upperBound-range.lowerBound)/100;value = min(range.upperBound,max(range.lowerBound,value+(direction == .increment ? step : -step))) }
|
||||
}
|
||||
}
|
||||
private struct DJPlatter: View {
|
||||
@ObservedObject var player: Player
|
||||
private struct DJPlatter: NSViewRepresentable {
|
||||
let player: Player
|
||||
let letter: String
|
||||
let color: Color
|
||||
var markerEnabled = true
|
||||
@State private var lastAngle: Double?
|
||||
var body: some View {
|
||||
TimelineView(.animation(minimumInterval:1.0/60,paused:!player.playing)) { _ in
|
||||
let displayTime = player.displayTime
|
||||
GeometryReader { geometry in
|
||||
ZStack {
|
||||
Circle().fill(Color.black.opacity(0.55)).overlay { Circle().stroke(color.opacity(0.4),lineWidth:3) }
|
||||
ForEach([0.70,0.80,0.90],id:\.self) { scale in Circle().stroke(.white.opacity(0.06),lineWidth:1).scaleEffect(scale) }
|
||||
ZStack {
|
||||
Circle().fill(color.opacity(0.15)).frame(width:53,height:53)
|
||||
Text(letter).font(.system(size:25,weight:.bold,design:.rounded)).foregroundStyle(color)
|
||||
if markerEnabled {
|
||||
Rectangle().fill(color).frame(width:5,height:26).offset(y:-geometry.size.height*0.37)
|
||||
Circle().fill(.white).frame(width:5,height:5).offset(y:-geometry.size.height*0.45)
|
||||
}
|
||||
}.rotationEffect(.degrees(displayTime*200))
|
||||
}.contentShape(Circle())
|
||||
.gesture(DragGesture(minimumDistance:2).onChanged { drag in
|
||||
let angle = atan2(Double(drag.location.y-geometry.size.height/2),Double(drag.location.x-geometry.size.width/2))
|
||||
if let previous = lastAngle { var delta = angle-previous;if delta > .pi { delta -= 2 * .pi };if delta < -.pi { delta += 2 * .pi };player.jog(delta / (2 * .pi) * 2) }
|
||||
lastAngle = angle
|
||||
}.onEnded{_ in lastAngle = nil})
|
||||
}.accessibilityLabel("Deck \(letter) jog platter").accessibilityValue(player.playing ? "Rotating" : "Paused").help("Drag around the platter to jog (2 seconds per turn). Rotation follows source playback time.")
|
||||
func makeNSView(context: Context) -> DJPlatterView { DJPlatterView() }
|
||||
func updateNSView(_ view: DJPlatterView,context: Context) {
|
||||
view.player = player;view.colour = NSColor(color);view.marker = markerEnabled;view.needsDisplay = true
|
||||
view.setAccessibilityElement(true);view.setAccessibilityLabel("Deck \(letter) jog platter")
|
||||
view.toolTip = "Drag around the platter to scrub (2 seconds per turn)"
|
||||
}
|
||||
static func dismantleNSView(_ view: DJPlatterView,coordinator: ()) { view.stopClock() }
|
||||
}
|
||||
private final class DJPlatterView: NSView {
|
||||
weak var player: Player?
|
||||
var colour = NSColor.systemCyan
|
||||
var marker = true
|
||||
private var clock: AnyObject?
|
||||
private var timer: Timer?
|
||||
private var angle: Double?
|
||||
override var isFlipped: Bool { true }
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
func stopClock() { timer?.invalidate();timer = nil;if #available(macOS 14,* ) { (clock as? CADisplayLink)?.invalidate() };clock = nil }
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow();stopClock();guard window != nil else { return }
|
||||
if #available(macOS 14,*) {
|
||||
let link = displayLink(target:self,selector:#selector(frameTick));link.preferredFrameRateRange = CAFrameRateRange(minimum:30,maximum:60,preferred:60);link.add(to:.main,forMode:.common);clock = link
|
||||
} else {
|
||||
let tick = Timer(timeInterval:1/60,repeats:true) { [weak self] _ in self?.frameTick() };RunLoop.main.add(tick,forMode:.common);timer = tick
|
||||
}
|
||||
}
|
||||
@objc private func frameTick() { if player?.playing == true,!isHiddenOrHasHiddenAncestor { needsDisplay = true } }
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
guard let context = NSGraphicsContext.current?.cgContext else { return }
|
||||
let side = min(bounds.width,bounds.height),centre = CGPoint(x:bounds.midX,y:bounds.midY)
|
||||
let disc = CGRect(x:centre.x-side/2+2,y:centre.y-side/2+2,width:side-4,height:side-4)
|
||||
context.setFillColor(NSColor.black.withAlphaComponent(0.55).cgColor);context.fillEllipse(in:disc)
|
||||
context.setStrokeColor(colour.withAlphaComponent(0.4).cgColor);context.setLineWidth(3);context.strokeEllipse(in:disc)
|
||||
context.setStrokeColor(NSColor.white.withAlphaComponent(0.06).cgColor);context.setLineWidth(1)
|
||||
for scale in [0.70,0.80,0.90] { let radius = side*scale/2;context.strokeEllipse(in:CGRect(x:centre.x-radius,y:centre.y-radius,width:radius*2,height:radius*2)) }
|
||||
guard marker else { return }
|
||||
context.translateBy(x:centre.x,y:centre.y);context.rotate(by:(player?.displayTime ?? 0)*200 * .pi/180)
|
||||
context.setFillColor(colour.cgColor);context.fill(CGRect(x:-2.5,y:-side*0.37-13,width:5,height:26))
|
||||
context.setFillColor(NSColor.white.cgColor);context.fillEllipse(in:CGRect(x:-2.5,y:-side*0.45-2.5,width:5,height:5))
|
||||
}
|
||||
override func mouseDown(with event: NSEvent) { let p = convert(event.locationInWindow,from:nil);angle = atan2(p.y-bounds.midY,p.x-bounds.midX) }
|
||||
override func mouseDragged(with event: NSEvent) {
|
||||
let p = convert(event.locationInWindow,from:nil),next = atan2(p.y-bounds.midY,p.x-bounds.midX)
|
||||
if let angle,let player { var delta = next-angle;if delta > .pi { delta -= 2 * .pi };if delta < -.pi { delta += 2 * .pi };player.scrub(to:player.time+delta / .pi) }
|
||||
angle = next;needsDisplay = true
|
||||
}
|
||||
override func mouseUp(with event: NSEvent) { angle = nil;player?.endScrubbing() }
|
||||
deinit { timer?.invalidate();if #available(macOS 14,*) { (clock as? CADisplayLink)?.invalidate() } }
|
||||
}
|
||||
struct DJWaveform: View {
|
||||
@State private var frozenStart: Double?
|
||||
@@ -1619,12 +1735,15 @@ enum DJBPM {
|
||||
return (60*rate/Double(bestLag)*10).rounded()/10
|
||||
}
|
||||
static func analyse(_ url: URL,cancelled: () -> Bool = { false }) throws -> Double? {
|
||||
try WaveformWorkload.shared.acquire(cancelled:cancelled)
|
||||
defer { WaveformWorkload.shared.release() }
|
||||
let file = try AVAudioFile(forReading:url),format = file.processingFormat
|
||||
guard let buffer = AVAudioPCMBuffer(pcmFormat:format,frameCapacity:16384),format.channelCount > 0 else { return nil }
|
||||
let hop = max(1,Int(format.sampleRate/200)),limit = Int64(format.sampleRate*90)
|
||||
var envelope = [Double](),sum = 0.0,count = 0
|
||||
while file.framePosition < min(file.length,limit) {
|
||||
if cancelled() { throw CancellationError() }
|
||||
if WaveformWorkload.shared.playbackActive { Thread.sleep(forTimeInterval:0.001) }
|
||||
try file.read(into:buffer)
|
||||
guard buffer.frameLength > 0,let channels = buffer.floatChannelData else { break }
|
||||
for i in 0..<Int(buffer.frameLength) {
|
||||
@@ -1813,3 +1932,64 @@ enum DJWaveMarkers {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DJGraphicEQDialog: View {
|
||||
@ObservedObject var system: DJSystem
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
private let labels = ["31","62","125","250","500","1k","2k","4k","8k","16k"]
|
||||
var body: some View {
|
||||
VStack(alignment:.leading,spacing:22) {
|
||||
Label("DJ Graphic Equaliser",systemImage:"slider.vertical.3").font(.title2.bold()).foregroundStyle(DJStyle.a)
|
||||
Text("Shared by both decks and all tracks. Your deck EQ controls remain independent.").font(.callout).foregroundStyle(.secondary)
|
||||
HStack {
|
||||
Toggle("Enabled",isOn:$system.graphicEQ.enabled).toggleStyle(.switch)
|
||||
Spacer()
|
||||
Picker("Preset",selection:Binding(get:{system.graphicEQ.preset},set:{system.chooseGraphicPreset($0)})) {
|
||||
ForEach(DJGraphicEQSettings.presets.map(\.0),id:\.self) { Text($0).tag($0) }
|
||||
if system.graphicEQ.preset == "Custom" { Text("Custom").tag("Custom") }
|
||||
}.frame(width:230)
|
||||
Button("Reset") { system.chooseGraphicPreset("Flat") }
|
||||
}
|
||||
HStack(alignment:.top,spacing:14) {
|
||||
ForEach(0..<10,id:\.self) { index in
|
||||
VStack(spacing:9) {
|
||||
Text(String(format:"%+.0f",system.graphicEQ.gains[index])).font(.caption.monospacedDigit()).foregroundStyle(DJStyle.a)
|
||||
DJHardwareFader(value:Binding(get:{(system.graphicEQ.gains[index]+12)/24},set:{ value in
|
||||
var next = system.graphicEQ;next.gains[index] = value*24-12;next.preset = "Custom";system.graphicEQ = next
|
||||
}),label:"Graphic EQ \(labels[index]) hertz",vertical:true).frame(width:40,height:150)
|
||||
Text(labels[index]).font(.caption)
|
||||
}
|
||||
}
|
||||
}.padding(18).background(DJStyle.panel,in:RoundedRectangle(cornerRadius:12))
|
||||
HStack { Text("±12 dB · Changes apply immediately · Saved automatically").font(.caption).foregroundStyle(.secondary);Spacer();Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) }
|
||||
}.padding(26).frame(width:660).background(DJStyle.background).preferredColorScheme(.dark)
|
||||
}
|
||||
}
|
||||
|
||||
private struct DJTrackMetadataDialog: View {
|
||||
@ObservedObject var system: DJSystem
|
||||
let song: Song
|
||||
@State private var title = ""
|
||||
@State private var artist = ""
|
||||
@State private var album = ""
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
var body: some View {
|
||||
VStack(alignment:.leading,spacing:18) {
|
||||
Text("DJ Song Info").font(.title2.bold())
|
||||
TextField("Title",text:$title).textFieldStyle(.roundedBorder)
|
||||
TextField("Artist",text:$artist).textFieldStyle(.roundedBorder)
|
||||
TextField("Album",text:$album).textFieldStyle(.roundedBorder)
|
||||
Text("Changes update your DJ library; the original file is kept.").font(.caption).foregroundStyle(.secondary)
|
||||
HStack { Spacer();Button("Cancel") { dismiss() };Button("Save") {
|
||||
system.perform {
|
||||
try system.library?.updateMetadata(song:song.id,title:title,artist:artist,album:album,label:song.label,rating:song.rating)
|
||||
try system.refresh()
|
||||
if let updated = system.songs.first(where:{$0.id == song.id}) {
|
||||
for deck in [system.a,system.b] where deck.song?.id == song.id { deck.updateTrackMetadata(updated) }
|
||||
}
|
||||
dismiss()
|
||||
}
|
||||
}.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).disabled(title.trimmingCharacters(in:.whitespacesAndNewlines).isEmpty) }
|
||||
}.padding(26).frame(width:480).onAppear { title = song.title;artist = song.artist;album = song.album }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user