SPB Git

Repository Public

EffectsView.swift 11.6 KB 191 lines swift

1// ORIX DJ2// File: App/Sources/Features/Effects/EffectsView.swift3// Description: The effects rack: one modular chain per channel and one for the master. Add, remove, reorder, bypass,4//              tweak every parameter, and save or load whole chains. The catalogue comes from the DSP layer.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct EffectsView: View {12    @Environment(AppModel.self) private var model13    @State private var chains: [LibraryDocument] = []14    @State private var saveName = ""15    @State private var showingSave = false1617    private var rack: Int? { model.selectedRack }1819    var body: some View {20        let slots = currentSlots21        VStack(alignment: .leading, spacing: ORIX.Space.sm) {22            HStack(spacing: 6) {23                rackButton(nil, title: "Master")24                ForEach(0 ..< deckCount, id: \.self) { d in rackButton(d, title: "Deck \(deckLetters[d])") }25                Spacer()26                Menu {27                    ForEach(EffectCategory.allCases, id: \.self) { category in28                        Section(category.rawValue.capitalized) {29                            ForEach(EffectCatalog.all.filter { $0.category == category }, id: \.kind) { d in30                                Button(d.displayName) { add(d.kind) }.disabled(slots.contains { $0.kind == d.kind })31                            }32                        }33                    }34                } label: { Label("Add Effect", systemImage: "plus") }35                    .menuStyle(.borderlessButton).fixedSize()36                    .disabled(slots.count >= rackSlotCount)37                    .accessibilityIdentifier("effects-add")38                Menu {39                    Button("Save Chain…") { saveName = ""; showingSave = true }.disabled(slots.isEmpty)40                    if !chains.isEmpty {41                        Section("Load") { ForEach(chains) { doc in Button(doc.name) { load(doc) } } }42                        Section("Delete") { ForEach(chains) { doc in Button(doc.name, role: .destructive) { try? model.library.deleteDocument(id: doc.id); reload() } } }43                    }44                } label: { Label("Chains", systemImage: "square.stack.3d.up") }45                    .menuStyle(.borderlessButton).fixedSize()46                Button { model.engine.bypassAllEffects(); model.show(notice: "Every effect bypassed") } label: { Label("Bypass All", systemImage: "power") }47                    .help("Switch every effect in every rack off.")48            }49            Text(rack == nil ? "Master rack: after the crossfader, before the master level and limiter." : "Channel rack: after the EQ and filter, before the fader and the headphone cue.")50                .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)51            if slots.isEmpty {52                EmptyState(symbol: "slider.horizontal.3", title: "This rack is empty", message: "Add an effect to build a chain. A rack holds up to eight effects, one of each kind. Scripts address them as fx.<name> on the master and deck.X.fx.<name> on a channel.")53            } else {54                ScrollView(.horizontal) {55                    HStack(alignment: .top, spacing: 0) {56                        FlowTerminal(text: rack == nil ? "Mix" : "Deck \(deckLetters[rack!])")57                        ForEach(Array(slots.enumerated()), id: \.element.kind) { index, slot in58                            FlowArrow()59                            EffectModule(rack: rack, index: index, slot: slot, count: slots.count)60                        }61                        FlowArrow()62                        FlowTerminal(text: rack == nil ? "Master" : "Fader")63                    }64                    .padding(.vertical, 4)65                }66                .scrollIndicators(.visible)67            }68            Spacer(minLength: 0)69        }70        .padding(ORIX.Space.md)71        .task { reload() }72        .alert("Save effect chain", isPresented: $showingSave) {73            TextField("Name", text: $saveName)74            Button("Save") { save() }75            Button("Cancel", role: .cancel) {}76        } message: { Text("The chain keeps the order, settings and on/off state of every effect in this rack.") }77        .accessibilityElement(children: .contain).accessibilityIdentifier("effects-rack")78    }7980    private var currentSlots: [EffectSlotStatus] { _ = model.pulse; return model.engine.rackStatus(rack) }8182    private func rackButton(_ r: Int?, title: LocalizedStringKey) -> some View {83        let selected = model.selectedRack == r84        let active = model.engine.rackStatus(r).filter(\.enabled).count85        return Button { model.selectedRack = r } label: {86            HStack(spacing: 5) {87                if let r { DeckBadge(index: r, size: 16) }88                Text(title).font(.system(size: 12, weight: selected ? .semibold : .regular))89                if active > 0 { Text(verbatim: "\(active) on").font(.system(size: 9, weight: .bold)).padding(.horizontal, 4).background(ORIX.Palette.accent.opacity(0.25), in: Capsule()) }90            }91            .padding(.horizontal, 10).frame(height: 28)92            .foregroundStyle(selected ? ORIX.Palette.textPrimary : ORIX.Palette.textSecondary)93            .background(selected ? ORIX.Palette.surfaceRaised : ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))94            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(selected ? ORIX.Palette.accent : ORIX.Palette.hairline))95        }96        .buttonStyle(.plain)97        .accessibilityAddTraits(selected ? [.isSelected] : [])98    }99100    private func add(_ kind: EffectKind) {101        if model.engine.insertEffect(kind, rack: rack) < 0 { model.show(notice: "The rack is full (\(rackSlotCount) effects).") }102    }103104    private func reload() { chains = (try? model.library.documents(kind: DocumentKind.effectChainPreset)) ?? [] }105106    private func save() {107        let name = saveName.trimmingCharacters(in: .whitespaces)108        guard !name.isEmpty, let data = try? JSONEncoder().encode(EffectChain(name: name, slots: model.engine.rackStatus(rack))) else { return }109        do { _ = try model.library.saveDocument(kind: DocumentKind.effectChainPreset, name: name, json: String(decoding: data, as: UTF8.self)); reload(); model.show(notice: "Chain \"\(name)\" saved") }110        catch { model.show(notice: error.localizedDescription) }111    }112113    private func load(_ doc: LibraryDocument) {114        guard let chain = try? JSONDecoder().decode(EffectChain.self, from: Data(doc.json.utf8)) else { model.show(notice: "This chain could not be read."); return }115        model.engine.applyChain(chain, rack: rack)116    }117}118119private struct FlowArrow: View {120    var body: some View {121        Image(systemName: "arrow.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 26).padding(.top, 60).accessibilityHidden(true)122    }123}124125private struct FlowTerminal: View {126    var text: String127    var body: some View {128        Text(verbatim: text).font(.system(size: 10, weight: .bold)).foregroundStyle(ORIX.Palette.textSecondary)129            .padding(.horizontal, 8).frame(height: 24).overlay(Capsule().strokeBorder(ORIX.Palette.hairline)).padding(.top, 54)130    }131}132133private struct EffectModule: View {134    @Environment(AppModel.self) private var model135    var rack: Int?136    var index: Int137    var slot: EffectSlotStatus138    var count: Int139140    var body: some View {141        let d = EffectCatalog.descriptor(slot.kind)142        let tint = slot.enabled ? ORIX.Palette.accent : ORIX.Palette.textTertiary143        VStack(alignment: .leading, spacing: 8) {144            HStack(spacing: 6) {145                Button { model.engine.setEffectEnabled(rack: rack, slot: index, !slot.enabled) } label: {146                    Image(systemName: "power").font(.system(size: 11, weight: .bold)).frame(width: 24, height: 24)147                        .foregroundStyle(slot.enabled ? ORIX.Palette.onTint : ORIX.Palette.textSecondary)148                        .background(slot.enabled ? AnyShapeStyle(ORIX.Palette.accent) : AnyShapeStyle(ORIX.Palette.surfaceRaised), in: Circle())149                }150                .buttonStyle(.plain)151                .accessibilityLabel(Text("\(d.displayName) power")).accessibilityValue(slot.enabled ? Text("on") : Text("off"))152                .accessibilityIdentifier("effect-power-\(slot.kind.rawValue)")153                VStack(alignment: .leading, spacing: 0) {154                    Text(verbatim: d.displayName).font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)155                    Text(slot.enabled ? "On" : "Bypassed").font(.system(size: 9, weight: .semibold)).foregroundStyle(tint)156                }157                Spacer(minLength: 8)158                Button { model.engine.moveEffect(rack: rack, from: index, to: index - 1) } label: { Image(systemName: "chevron.left") }.disabled(index == 0).accessibilityLabel("Move earlier in the chain")159                Button { model.engine.moveEffect(rack: rack, from: index, to: index + 1) } label: { Image(systemName: "chevron.right") }.disabled(index == count - 1).accessibilityLabel("Move later in the chain")160                Button { model.engine.removeEffect(rack: rack, slot: index) } label: { Image(systemName: "xmark") }.accessibilityLabel("Remove the effect")161            }162            .buttonStyle(.borderless).font(.system(size: 10, weight: .semibold))163            Text(verbatim: d.summary).font(.system(size: 10)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).frame(height: 26, alignment: .topLeading)164            HStack(alignment: .top, spacing: 6) {165                Knob(label: "Mix", value: Double(slot.mix), display: String(format: "%.0f %%", slot.mix * 100), tint: tint, size: 36,166                     onChange: { model.engine.setEffectMix(rack: rack, slot: index, Float($0)) }, onReset: { model.engine.setEffectMix(rack: rack, slot: index, d.defaultMix) })167                ForEach(Array(d.params.enumerated()), id: \.element.id) { p, spec in168                    let address = ParamAddress.fx(slot.kind, deck: rack, spec.id)169                    if spec.unit == .toggle {170                        VStack(spacing: 3) {171                            ToggleChip(title: LocalizedStringKey(spec.name), symbol: nil, isOn: slot.values[p] >= 0.5, tint: tint) { model.engine.setEffectParameter(rack: rack, slot: index, index: p, value: slot.values[p] >= 0.5 ? 0 : 1) }172                        }.frame(height: 36)173                    } else {174                        Knob(label: LocalizedStringKey(spec.name), value: model.position(address), display: model.display(address), tint: tint, bipolar: spec.min < 0, size: 36,175                             onChange: { model.setPosition(address, $0) }, onReset: { model.engine.setEffectParameter(rack: rack, slot: index, index: p, value: spec.defaultValue) })176                            .help(Text(verbatim: spec.doc))177                    }178                }179            }180            Text(verbatim: (rack.map { "deck.\(deckLetters[$0])." } ?? "") + "fx.\(slot.kind.rawValue)").font(.system(size: 9, design: .monospaced)).foregroundStyle(ORIX.Palette.textTertiary)181                .help("The path scripts and the console use for this effect.")182        }183        .padding(10)184        .frame(minWidth: 190)185        .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous))186        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous).strokeBorder(slot.enabled ? ORIX.Palette.accent.opacity(0.7) : ORIX.Palette.hairline))187        .accessibilityElement(children: .contain)188        .accessibilityLabel(Text(verbatim: d.displayName))189    }190}191
Files main
Menu

Theme