SPB Git

Repository Public

GeneralSettingsTabs.swift 21.6 KB 366 lines swift

1// ORIX DJ2// File: App/Sources/Features/Settings/GeneralSettingsTabs.swift3// Description: Settings → Mixer, Library, Appearance, Automation and About.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDJCore8import SwiftUI910// MARK: - Mixer1112struct MixerSettingsTab: View {13    @Environment(AppModel.self) private var model14    @Environment(AppSettings.self) private var settings1516    private func curveTitle(_ c: String) -> LocalizedStringKey {17        switch c {18        case "smooth": "Smooth"19        case "linear": "Linear"20        case "cut": "Cut"21        default: LocalizedStringKey(c)22        }23    }2425    var body: some View {26        @Bindable var settings = settings27        SettingsPage {28            SettingsCard(title: "Channel EQ") {29                SettingsRow(title: "EQ bands", detail: "Three bands (low, mid, high) or four (low, low-mid, high-mid, high) on every channel.", divider: false) {30                    Picker("EQ bands", selection: Binding(get: { settings.fourBandEQ ? 4 : 3 }, set: { settings.fourBandEQ = $0 == 4; model.set(.mixer("eqBands"), .number(Double($0))) })) {31                        Text("3-band").tag(3)32                        Text("4-band").tag(4)33                    }34                    .pickerStyle(.segmented).labelsHidden().frame(width: 200, alignment: .trailing)35                    .accessibilityLabel("EQ bands").accessibilityIdentifier("settings-mixer-eq")36                }37            }38            SettingsCard(title: "Crossfader") {39                SettingsRow(title: "Curve", detail: "Smooth is a constant-power blend; Linear keeps both sides at full level in the centre; Cut keeps each side at full level until the last 5 % of the travel, for scratching.", divider: false) {40                    Picker("Crossfader curve", selection: Binding(get: { model.value(.mixer("curve"))?.stringValue ?? "smooth" }, set: { model.set(.mixer("curve"), .string($0)) })) {41                        ForEach(ScriptSchema.crossfaderCurves, id: \.self) { Text(curveTitle($0)).tag($0) }42                    }43                    .pickerStyle(.segmented).labelsHidden().frame(width: 260, alignment: .trailing)44                    .accessibilityLabel("Crossfader curve").accessibilityIdentifier("settings-mixer-curve")45                }46            }47            SettingsCard(title: "Master limiter") {48                SettingsRow(title: "Limiter", detail: "Holds the master output below full scale.") {49                    Toggle("Master limiter", isOn: Binding(get: { model.flag(.mixer("master.limiter")) }, set: { model.set(.mixer("master.limiter"), .bool($0)) }))50                        .labelsHidden().toggleStyle(.switch)51                        .accessibilityLabel("Master limiter").accessibilityIdentifier("settings-mixer-limiter")52                }53                HStack(spacing: ORIX.Space.md) {54                    let reduction = Double(model.render.limiterReductionDB)55                    SettingsReadout(label: "Gain reduction now", value: String(format: "%.1f dB", reduction), tint: reduction < -0.05 ? ORIX.Palette.warning : ORIX.Palette.textPrimary)56                    SettingsReadout(label: "State", value: model.flag(.mixer("master.limiter")) ? (reduction < -0.05 ? String(localized: "Limiting") : String(localized: "On, idle")) : String(localized: "Off"))57                    Spacer()58                }59                .padding(.horizontal, 14).padding(.vertical, 10)60                Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)61                SettingsNote("The limiter changes the sound when it engages: it turns the master down for as long as the mix would exceed full scale. Its indicator shows that gain reduction in decibels. With the limiter off, levels above full scale clip.")62            }63            SettingsCard(title: "Decks at start-up") {64                SettingsRow(title: "Deck count", detail: "How many decks the Studio shows.") {65                    Picker("Deck count", selection: Binding(get: { settings.deckCount }, set: { settings.deckCount = $0; model.deckCountShown = $0 })) {66                        Text("2 decks").tag(2)67                        Text("4 decks").tag(4)68                    }69                    .pickerStyle(.segmented).labelsHidden().frame(width: 200, alignment: .trailing)70                    .accessibilityLabel("Deck count").accessibilityIdentifier("settings-mixer-decks")71                }72                SettingsRow(title: "Deck mode", detail: "The layout of each deck.", divider: false) {73                    Picker("Deck mode", selection: Binding(get: { settings.deckMode }, set: { settings.deckMode = $0; model.deckMode = $0 })) {74                        ForEach(DeckMode.allCases) { Text($0.title).tag($0) }75                    }76                    .labelsHidden().frame(width: 200, alignment: .trailing)77                    .accessibilityLabel("Deck mode").accessibilityIdentifier("settings-mixer-deck-mode")78                }79            }80        }81        .accessibilityIdentifier("settings-mixer")82    }83}8485// MARK: - Library8687struct LibrarySettingsTab: View {88    @Environment(AppModel.self) private var model89    @State private var trackCount: Int?90    @State private var pendingCount: Int?9192    private func reveal(_ url: URL) {93        if FileManager.default.fileExists(atPath: url.path) { NSWorkspace.shared.activateFileViewerSelecting([url]) }94        else { NSWorkspace.shared.activateFileViewerSelecting([url.deletingLastPathComponent()]) }95    }9697    private func location(_ title: LocalizedStringKey, _ url: URL, id: String, divider: Bool = true) -> some View {98        SettingsRow(title: title, divider: divider) {99            HStack(spacing: 8) {100                Text(verbatim: (url.path as NSString).abbreviatingWithTildeInPath).font(.system(size: 11, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary)101                    .lineLimit(1).truncationMode(.middle).frame(maxWidth: 360, alignment: .trailing).textSelection(.enabled)102                Button("Reveal in Finder") { reveal(url) }.controlSize(.small).accessibilityIdentifier("settings-library-reveal-\(id)")103            }104        }105    }106107    var body: some View {108        let dirs = model.session.directories109        SettingsPage {110            SettingsCard(title: "Storage") {111                location("Library database", dirs.libraryDatabase, id: "database")112                location("Recordings", dirs.recordings, id: "recordings")113                location("Demo tracks", dirs.demoTracks, id: "demo", divider: false)114            }115            SettingsCard(title: "Tracks") {116                HStack(spacing: ORIX.Space.md) {117                    SettingsReadout(label: "Tracks in the library", value: trackCount.map { "\($0)" } ?? "–")118                    SettingsReadout(label: "Not analysed yet", value: pendingCount.map { "\($0)" } ?? "–")119                    Spacer()120                }121                .padding(.horizontal, 14).padding(.vertical, 10)122                .accessibilityIdentifier("settings-library-counts")123                Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)124                SettingsRow(title: "Analysis", detail: "Finds tempo, beat grid, key, loudness and the waveform of each track. One track at a time, in the background.") {125                    if let a = model.analysis {126                        VStack(alignment: .trailing, spacing: 4) {127                            HStack(spacing: 8) {128                                ProgressView(value: Double(a.completed), total: Double(max(1, a.total))).frame(width: 140)129                                    .accessibilityLabel("Analysis progress").accessibilityValue(Text("\(a.completed) of \(a.total)"))130                                Button("Cancel") { model.session.cancelAnalysis(); model.refreshNow() }.controlSize(.small).accessibilityIdentifier("settings-library-analyse-cancel")131                            }132                            Text(verbatim: "\(a.completed + 1) / \(a.total) · \(a.currentTitle)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).frame(maxWidth: 260, alignment: .trailing)133                            if a.failures > 0 { Text("\(a.failures) could not be analysed").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.warning) }134                        }135                    } else {136                        Button("Analyse Unanalysed Tracks") { model.session.analyzePending(); model.refreshNow() }137                            .disabled(pendingCount == 0)138                            .accessibilityIdentifier("settings-library-analyse")139                    }140                }141                SettingsRow(title: "Demo tracks", detail: "Six short tracks synthesised by ORIX DJ itself, to try the decks without importing music.", divider: false) {142                    Button("Install Demo Tracks") { model.installDemoTracks() }.accessibilityIdentifier("settings-library-demo")143                }144            }145            SettingsCard(title: "Your files") {146                SettingsNote("ORIX DJ never modifies or copies your original audio files. It reads them where they are and keeps its own data (analysis, cues, playlists, history) in the library database.", symbol: "lock.shield")147            }148        }149        .task(id: "\(model.libraryRevision)-\(model.analysis?.completed ?? -1)") { count() }150        .accessibilityIdentifier("settings-library")151    }152153    private func count() {154        trackCount = try? model.library.count()155        var q = TrackQuery(); q.scope = .unanalysed156        pendingCount = try? model.library.count(query: q)157    }158}159160// MARK: - Appearance161162struct AppearanceSettingsTab: View {163    @Environment(AppModel.self) private var model164    @Environment(AppSettings.self) private var settings165166    private func note(_ p: WaveformPalette) -> LocalizedStringKey? {167        switch p {168        case .colorBlindSafe: "Blue, orange and yellow stay distinct with the common forms of colour-vision deficiency (protanopia, deuteranopia, tritanopia)."169        case .mono: "Bands are told apart by brightness only."170        default: nil171        }172    }173174    var body: some View {175        @Bindable var settings = settings176        SettingsPage {177            SettingsCard(title: "Appearance") {178                SettingsRow(title: "Theme", detail: "System follows the appearance chosen in macOS.", divider: model.options.appearance != nil) {179                    Picker("Theme", selection: $settings.appearance) {180                        Text("System").tag("system")181                        Text("Dark").tag("dark")182                        Text("Light").tag("light")183                    }184                    .pickerStyle(.segmented).labelsHidden().frame(width: 260, alignment: .trailing)185                    .accessibilityLabel("Theme").accessibilityIdentifier("settings-appearance-theme")186                }187                if model.options.appearance != nil {188                    SettingsNote("This instance was launched with a fixed appearance, which takes precedence until it is restarted without that option.")189                }190            }191            SettingsCard(title: "Waveform colours") {192                ForEach(Array(WaveformPalette.allCases.enumerated()), id: \.element) { i, p in193                    let selected = settings.palette == p194                    Button { settings.palette = p } label: {195                        HStack(spacing: ORIX.Space.sm) {196                            Image(systemName: selected ? "largecircle.fill.circle" : "circle").font(.system(size: 14)).foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textTertiary)197                            PaletteSwatch(palette: p)198                            VStack(alignment: .leading, spacing: 2) {199                                Text(p.title).font(.system(size: 13, weight: selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary)200                                if let n = note(p) { Text(n).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true).multilineTextAlignment(.leading) }201                            }202                            Spacer()203                        }204                        .padding(.horizontal, 14).padding(.vertical, 9).contentShape(Rectangle())205                    }206                    .buttonStyle(.plain)207                    .accessibilityAddTraits(selected ? [.isSelected] : [])208                    .accessibilityValue(selected ? Text("selected") : Text("not selected"))209                    .accessibilityIdentifier("settings-appearance-palette-\(p.rawValue)")210                    if i < WaveformPalette.allCases.count - 1 { Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14) }211                }212            }213            SettingsCard(title: "Waveform zoom") {214                SettingsRow(title: "Default zoom", detail: "How many seconds of the track the scrolling waveform shows.", divider: false) {215                    HStack(spacing: 10) {216                        Slider(value: $settings.waveformZoom, in: 2 ... 30, step: 1).frame(width: 220)217                            .accessibilityLabel("Default waveform zoom").accessibilityValue(Text("\(Int(settings.waveformZoom)) seconds"))218                            .accessibilityIdentifier("settings-appearance-zoom")219                        Text(verbatim: "\(Int(settings.waveformZoom)) s").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).frame(width: 36, alignment: .trailing)220                    }221                }222            }223        }224        .accessibilityIdentifier("settings-appearance")225    }226}227228/// Low, mid and high band colours of a palette on the waveform background, labelled so colour is not the only cue.229private struct PaletteSwatch: View {230    var palette: WaveformPalette231232    var body: some View {233        let b = palette.bands234        HStack(spacing: 3) {235            ForEach(Array([(b.low, "L"), (b.mid, "M"), (b.high, "H")].enumerated()), id: \.offset) { _, band in236                Text(verbatim: band.1).font(.system(size: 9, weight: .heavy)).foregroundStyle(Color.black.opacity(0.8))237                    .frame(width: 22, height: 20)238                    .background(Color(hex: band.0), in: RoundedRectangle(cornerRadius: 3))239            }240        }241        .padding(4)242        .background(ORIX.Palette.waveformWell, in: RoundedRectangle(cornerRadius: 6))243        .accessibilityElement(children: .ignore)244        .accessibilityLabel("Low, mid and high band colours")245    }246}247248// MARK: - Automation249250struct AutomationSettingsTab: View {251    @Environment(AppModel.self) private var model252    @State private var lookaheadMS = 30.0253    /// The engine's own value, read the first time the tab opens (before the user can have changed it here).254    @MainActor private static var launchDefaultMS: Double?255256    private var limits: [(LocalizedStringKey, String)] {257        let r = RuntimeLimits()258        return [259            ("Script size", "\(CompileLimits.maxSourceBytes / 1024) KB"),260            ("Statements per script", "\(CompileLimits.maxStatements)"),261            ("Iterations of one loop", "\(CompileLimits.maxLoopIterations)"),262            ("Array length", "\(CompileLimits.maxArrayLength)"),263            ("Shortest every period", "1/\(Int((1 / CompileLimits.minEveryPeriodBeats).rounded())) beat"),264            ("Event handlers per automation", "\(CompileLimits.maxHandlers)"),265            ("Operations without a wait", "\(r.maxOperationsPerStep)"),266            ("Operations over the life of an automation", "\(r.maxTotalOperations)"),267            ("Scheduled blocks at once", "\(r.maxTasks)"),268            ("Ramps at once", "\(r.maxRamps)"),269            ("Commands per beat (ramps excluded)", "\(r.maxCommandsPerBeat)"),270            ("Pending event-handler runs", "\(r.maxPendingHandlerTasks)"),271            ("Longest wait or ramp", "\(Int(r.maxSpanBeats)) beats"),272            ("Function call depth", "\(r.maxCallDepth)"),273        ]274    }275276    var body: some View {277        SettingsPage {278            SettingsCard(title: "ORIX Script") {279                SettingsRow(title: "Language version", detail: "Scripts are saved as plain text with the .\(ORIXScriptLanguage.fileExtension) extension.") {280                    Text(verbatim: ORIXScriptLanguage.version).font(ORIX.Typeface.readout(15)).foregroundStyle(ORIX.Palette.textPrimary)281                        .accessibilityIdentifier("settings-automation-version")282                }283                SettingsRow(title: "Look-ahead", detail: "How far ahead of the clock automations are evaluated, so their commands land on exact samples. A longer look-ahead tolerates a busier system; a shorter one reacts sooner to events. The default is 30 ms.", divider: false) {284                    HStack(spacing: 10) {285                        Slider(value: $lookaheadMS, in: 5 ... 50, step: 1)286                            .frame(width: 200)287                            .accessibilityLabel("Scheduler look-ahead").accessibilityValue(Text("\(Int(lookaheadMS)) milliseconds"))288                            .accessibilityIdentifier("settings-automation-lookahead")289                        Text(verbatim: "\(Int(lookaheadMS)) ms").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).frame(width: 44, alignment: .trailing)290                    }291                }292            }293            SettingsCard(title: "Security model") {294                SettingsNote("Scripts have no access to files, the network or the shell: they can only read and set the deck, mixer and effect controls of ORIX DJ.", symbol: "lock.shield")295                Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)296                SettingsNote("Scripts run on the automation scheduler, never on the audio thread, so a slow script cannot interrupt the sound.", symbol: "waveform.path")297                Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)298                SettingsNote("A script that fails or exceeds a limit is cancelled, and the effects it switched on are bypassed.", symbol: "hand.raised")299            }300            SettingsCard(title: "Language limits (fixed)") {301                ForEach(Array(limits.enumerated()), id: \.offset) { i, row in302                    HStack {303                        Text(row.0).font(.system(size: 12.5)).foregroundStyle(ORIX.Palette.textPrimary)304                        Spacer()305                        Text(verbatim: row.1).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary)306                    }307                    .padding(.horizontal, 14).padding(.vertical, 6)308                    .accessibilityElement(children: .combine)309                    if i < limits.count - 1 { Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14) }310                }311            }312            .accessibilityIdentifier("settings-automation-limits")313        }314        .onAppear {315            let current = (model.host.lookaheadSeconds * 1000).rounded()316            if Self.launchDefaultMS == nil { Self.launchDefaultMS = current }317            lookaheadMS = min(50, max(5, current))318        }319        .onChange(of: lookaheadMS) { _, v in model.host.lookaheadSeconds = v / 1000; model.settings.lookaheadMillis = v }320        .accessibilityIdentifier("settings-automation")321    }322}323324// MARK: - About325326struct AboutSettingsTab: View {327    private func info(_ key: String) -> String { Bundle.main.object(forInfoDictionaryKey: key) as? String ?? "" }328329    var body: some View {330        SettingsPage {331            HStack(spacing: ORIX.Space.md) {332                Image(nsImage: NSApp.applicationIconImage).resizable().frame(width: 84, height: 84).accessibilityHidden(true)333                VStack(alignment: .leading, spacing: 4) {334                    Text(verbatim: info("CFBundleDisplayName").isEmpty ? info("CFBundleName") : info("CFBundleDisplayName"))335                        .font(.system(size: 26, weight: .bold, design: .rounded)).foregroundStyle(ORIX.Palette.textPrimary)336                    Text("Version \(info("CFBundleShortVersionString")) (build \(info("CFBundleVersion")))")337                        .font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled)338                        .accessibilityIdentifier("settings-about-version")339                    Text(verbatim: info("NSHumanReadableCopyright")).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textTertiary)340                }341                Spacer()342            }343            .padding(.bottom, 4)344            SettingsCard(title: "Privacy") {345                SettingsNote("All audio processing happens on this Mac. ORIX DJ needs no account and sends no audio anywhere.", symbol: "lock.shield")346                Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)347                SettingsNote("The only network feature is Claude Studio, which is optional and uses your own Anthropic API key.", symbol: "sparkles")348            }349            SettingsCard(title: "Links") {350                SettingsRow(title: "ORIX apps") {351                    Link(destination: URL(string: "https://orix.spboucher.ai")!) { Text(verbatim: "orix.spboucher.ai") }.accessibilityIdentifier("settings-about-link-orix")352                }353                SettingsRow(title: "Source repositories", divider: false) {354                    Link(destination: URL(string: "https://git.spboucher.ai")!) { Text(verbatim: "git.spboucher.ai") }.accessibilityIdentifier("settings-about-link-git")355                }356            }357            SettingsCard(title: "Components") {358                SettingsRow(title: "ORIX Script", detail: "The automation language built into ORIX DJ.", divider: false) {359                    Text(verbatim: ORIXScriptLanguage.version).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary)360                }361            }362        }363        .accessibilityIdentifier("settings-about")364    }365}366
Files main
Menu

Theme