SPB Git

Repository Public

MIDIController.swift 18.7 KB 452 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : App/Sources/Features/MIDI/MIDIController.swift10// Description      : State of the MIDI screen: the live message monitor (fed11//                    from CoreMIDI's thread through a small buffer), MIDI12//                    Learn, and the mapping-profile editor (new, duplicate,13//                    rename, delete, save, activate, import, export).14// Module           : Features15// Repository       : https://git.spboucher.ai/orix-dj16// Created          : 2026-11-2117// Last Modified    : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AppKit92import ORIXDJCore93import SwiftUI94import UniformTypeIdentifiers9596struct MIDIMonitorEvent: Identifiable, Equatable, Sendable {97    var id: UInt6498    var device: String99    var message: MIDIMessage100    var hostTime: UInt64101}102103/// Collects messages on CoreMIDI's thread; the main actor drains it a few times per second.104final class MIDIMonitorBuffer: @unchecked Sendable {105    private let lock = NSLock()106    private var pending: [MIDIMonitorEvent] = []107    private var counter: UInt64 = 0108109    func append(device: MIDIDeviceInfo, message: MIDIMessage, hostTime: UInt64) {110        lock.lock()111        counter += 1112        pending.append(MIDIMonitorEvent(id: counter, device: device.name, message: message, hostTime: hostTime))113        if pending.count > 400 { pending.removeFirst(pending.count - 400) }114        lock.unlock()115    }116117    func drain() -> [MIDIMonitorEvent] {118        lock.lock(); defer { lock.unlock() }119        let out = pending120        pending.removeAll(keepingCapacity: true)121        return out122    }123}124125enum MIDILearnTarget: Equatable {126    case mapping(UUID)127    case newMapping128}129130enum MIDIText {131    static let noteNames = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"]132133    /// Middle C (note 60) is written C3, the convention of most DJ and controller software.134    static func note(_ number: UInt8) -> String { "\(noteNames[Int(number) % 12])\(Int(number) / 12 - 2)" }135136    /// "CC 7 ch 1", "Note C2 ch 10", "Pitch bend ch 1".137    static func control(_ c: MIDIControlID) -> String {138        switch c.kind {139        case .controlChange: "CC \(c.number) ch \(c.channel + 1)"140        case .note: "Note \(note(c.number)) ch \(c.channel + 1)"141        case .pitchBend: "Pitch bend ch \(c.channel + 1)"142        }143    }144145    static func type(_ m: MIDIMessage) -> String {146        switch m {147        case .noteOn: String(localized: "Note on")148        case .noteOff: String(localized: "Note off")149        case .controlChange: String(localized: "Control change")150        case .pitchBend: String(localized: "Pitch bend")151        case .programChange: String(localized: "Program change")152        }153    }154155    static func number(_ m: MIDIMessage) -> String {156        switch m {157        case let .noteOn(_, n, _), let .noteOff(_, n, _): "\(note(n)) (\(n))"158        case let .controlChange(_, n, _): "\(n)"159        case .pitchBend: "–"160        case let .programChange(_, p): "\(p)"161        }162    }163164    static func value(_ m: MIDIMessage) -> String {165        switch m {166        case let .noteOn(_, _, v), let .noteOff(_, _, v): "\(v)"167        case let .controlChange(_, _, v): "\(v)"168        case let .pitchBend(_, v): "\(Int(v) - 8192)"169        case .programChange: "–"170        }171    }172173    static func issue(_ issue: MIDIMappingProfileIssue) -> (mapping: [UUID], text: String) {174        switch issue {175        case let .duplicateControl(control, _, ids): (ids, String(localized: "\(MIDIText.control(control)) is used by \(ids.count) mappings: all of them fire together."))176        case let .duplicateMappingID(id): ([id], String(localized: "Two mappings share the same identifier."))177        case let .emptyTarget(id): ([id], String(localized: "No target chosen."))178        case let .invalidControl(id): ([id], String(localized: "The channel or number is out of range: no message can match."))179        case let .invalidRange(id): ([id], String(localized: "Minimum and maximum must be between 0 and 100 %."))180        case let .invalidSensitivity(id): ([id], String(localized: "The sensitivity of a relative encoder cannot be zero."))181        case let .incompatibleMode(id): ([id], String(localized: "This mode cannot work with this kind of control (relative needs a CC; buttons cannot use pitch bend)."))182        case let .unsupportedFormatVersion(v): ([], String(localized: "The profile uses format version \(v), which this version does not support."))183        }184    }185}186187extension MIDIMappingMode {188    var title: LocalizedStringKey {189        switch self {190        case .absolute: "Absolute"191        case .relative: "Relative"192        case .toggle: "Toggle"193        case .trigger: "Trigger"194        case .momentary: "Momentary"195        }196    }197}198199extension MIDIRelativeEncoding {200    var title: LocalizedStringKey {201        switch self {202        case .twosComplement: "Two's complement"203        case .signedBit: "Signed bit"204        case .binaryOffset: "Offset 64"205        }206    }207}208209@MainActor @Observable210final class MIDIController {211    // Monitor.212    var events: [MIDIMonitorEvent] = []213    var paused = false214    var monitorStart = MIDIManager.currentHostTime()215216    // Profiles.217    var profiles: [MIDIMappingProfile] = []218    var activeName: String?219    /// Working copy of the selected profile.220    var draft: MIDIMappingProfile?221    /// Name under which the draft is stored (nil for a profile that was never saved).222    var storedName: String?223    var dirty = false224    var renameText: String?225    var deleteRequested = false226227    // Learn.228    var learning: MIDILearnTarget?229    var learned: MIDILearnResult?230    var pendingTarget = ""231232    @ObservationIgnored let buffer = MIDIMonitorBuffer()233    @ObservationIgnored private var pump: Task<Void, Never>?234235    // MARK: Monitor236237    /// Installs the message monitor (`onMessage` is not used by the session or the app model) and starts draining it.238    func attach(model: AppModel) {239        let buffer = buffer240        model.session.midi.onMessage = { device, message, hostTime in buffer.append(device: device, message: message, hostTime: hostTime) }241        pump?.cancel()242        pump = Task { [weak self] in243            while !Task.isCancelled {244                try? await Task.sleep(nanoseconds: 80_000_000)245                guard let self else { return }246                let batch = self.buffer.drain()247                if !batch.isEmpty, !self.paused {248                    var next = self.events + batch249                    if next.count > 200 { next.removeFirst(next.count - 200) }250                    self.events = next251                }252            }253        }254        reloadProfiles(model: model, keepDraft: draft != nil)255    }256257    func detach(model: AppModel) {258        pump?.cancel(); pump = nil259        model.session.midi.onMessage = nil260        cancelLearn(model: model)261    }262263    func clearMonitor() { events.removeAll(); monitorStart = MIDIManager.currentHostTime() }264265    func seconds(_ event: MIDIMonitorEvent) -> Double {266        let a = MIDIManager.nanoseconds(fromHostTime: event.hostTime), b = MIDIManager.nanoseconds(fromHostTime: monitorStart)267        return a >= b ? Double(a - b) / 1e9 : 0268    }269270    // MARK: Profiles271272    func reloadProfiles(model: AppModel, keepDraft: Bool = false) {273        profiles = model.session.midiProfiles().sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }274        activeName = model.session.midi.activeProfile?.name275        if keepDraft, draft != nil { return }276        if let name = storedName ?? activeName, let p = profiles.first(where: { $0.name == name }) { select(p) }277        else if let first = profiles.first { select(first) } else { draft = nil; storedName = nil; dirty = false }278    }279280    func select(_ profile: MIDIMappingProfile) { draft = profile; storedName = profile.name; dirty = false }281282    private func uniqueName(_ base: String) -> String {283        var name = base; var n = 2284        while profiles.contains(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) { name = "\(base) \(n)"; n += 1 }285        return name286    }287288    func newProfile(model: AppModel) {289        let hint = model.midiSources.first?.name ?? ""290        let profile = MIDIMappingProfile(name: uniqueName(String(localized: "New Profile")), controllerNameHint: hint)291        persist(profile, activate: false, model: model)292    }293294    func duplicate(model: AppModel) {295        guard var copy = draft else { return }296        copy.id = UUID(); copy.name = uniqueName(String(localized: "\(copy.name) copy"))297        copy.mappings = copy.mappings.map { var m = $0; m.id = UUID(); return m }298        persist(copy, activate: false, model: model)299    }300301    private func persist(_ profile: MIDIMappingProfile, activate: Bool, model: AppModel) {302        do {303            try model.session.saveMIDIProfile(profile, activate: activate)304            storedName = profile.name; draft = profile; dirty = false305            reloadProfiles(model: model, keepDraft: true)306        } catch { model.show(notice: error.localizedDescription) }307    }308309    func save(model: AppModel) {310        guard let draft else { return }311        persist(draft, activate: draft.name == activeName, model: model)312        model.show(notice: String(localized: "Saved MIDI profile \"\(draft.name)\""))313    }314315    func activate(model: AppModel) {316        guard let draft else { return }317        persist(draft, activate: true, model: model)318    }319320    func deactivate(model: AppModel) {321        model.session.midi.activeProfile = nil322        try? model.library.setSetting("midi.activeProfile", value: nil)323        activeName = nil324    }325326    func commitRename(model: AppModel) {327        guard var profile = draft, let text = renameText?.trimmingCharacters(in: .whitespaces) else { return }328        renameText = nil329        guard !text.isEmpty, text != profile.name else { return }330        if profiles.contains(where: { $0.name.caseInsensitiveCompare(text) == .orderedSame && $0.name != storedName }) {331            model.show(notice: String(localized: "A MIDI profile named \"\(text)\" already exists.")); return332        }333        let old = storedName334        let wasActive = old != nil && old == activeName335        profile.name = text336        do {337            try model.session.saveMIDIProfile(profile, activate: wasActive)338            if let old, old != text { _ = try model.library.deleteDocument(kind: DocumentKind.midiMapping, name: old) }339            storedName = text; draft = profile; dirty = false340            reloadProfiles(model: model, keepDraft: true)341        } catch { model.show(notice: error.localizedDescription) }342    }343344    func deleteProfile(model: AppModel) {345        guard let name = storedName else { return }346        if name == activeName { deactivate(model: model) }347        _ = try? model.library.deleteDocument(kind: DocumentKind.midiMapping, name: name)348        draft = nil; storedName = nil; dirty = false349        reloadProfiles(model: model)350    }351352    var profileType: UTType { UTType(filenameExtension: MIDIMappingProfile.fileExtension) ?? .json }353354    func importProfile(model: AppModel) {355        let panel = NSOpenPanel()356        panel.allowedContentTypes = [profileType, .json]357        panel.message = String(localized: "Choose an ORIX DJ MIDI profile (.orixmidi).")358        guard panel.runModal() == .OK, let url = panel.url else { return }359        do {360            var profile = try MIDIMappingProfile(contentsOf: url)361            profile.name = uniqueName(profile.name.isEmpty ? url.deletingPathExtension().lastPathComponent : profile.name)362            persist(profile, activate: false, model: model)363            let issues = profile.validate().count364            model.show(notice: issues == 0 ? String(localized: "Imported \"\(profile.name)\"") : String(localized: "Imported \"\(profile.name)\" with \(issues) issues to review"))365        } catch MIDIMappingProfileError.unsupportedFormatVersion(let v) {366            model.show(notice: String(localized: "This profile was written by a newer ORIX DJ (format \(v))."))367        } catch { model.show(notice: String(localized: "The file is not a valid MIDI profile: \(error.localizedDescription)")) }368    }369370    func exportProfile(model: AppModel) {371        guard let draft else { return }372        let panel = NSSavePanel()373        panel.allowedContentTypes = [profileType]374        panel.nameFieldStringValue = draft.name + "." + MIDIMappingProfile.fileExtension375        guard panel.runModal() == .OK, let url = panel.url else { return }376        do { try draft.write(to: url); model.show(notice: String(localized: "Exported \"\(draft.name)\"")) } catch { model.show(notice: error.localizedDescription) }377    }378379    // MARK: Mapping edits380381    func update(_ id: UUID, _ change: (inout MIDIMapping) -> Void) {382        guard let i = draft?.mappings.firstIndex(where: { $0.id == id }) else { return }383        change(&draft!.mappings[i]); dirty = true384    }385386    func removeMapping(_ id: UUID) { draft?.mappings.removeAll { $0.id == id }; dirty = true }387388    /// Mode that suits a target kind and a control kind.389    static func defaultMode(target: ControlTarget?, control: MIDIControlID) -> MIDIMappingMode {390        switch target?.kind {391        case .toggle: control.kind == .pitchBend ? .absolute : .toggle392        case .trigger: control.kind == .pitchBend ? .absolute : .trigger393        default: .absolute394        }395    }396397    func setTarget(_ id: UUID, target: String) {398        update(id) { m in399            let oldKind = ControlTargets.target(m.target)?.kind400            m.target = target401            let kind = ControlTargets.target(target)?.kind402            if oldKind != kind { m.mode = Self.defaultMode(target: ControlTargets.target(target), control: m.control) }403        }404    }405406    // MARK: Learn407408    func beginLearn(_ target: MIDILearnTarget, model: AppModel) {409        learning = target; learned = nil410        model.session.midi.beginLearn { [weak self] result in411            Task { @MainActor in self?.finishLearn(result) }412        }413    }414415    func cancelLearn(model: AppModel) {416        if learning != nil { model.session.midi.cancelLearn() }417        learning = nil; learned = nil418    }419420    private func finishLearn(_ result: MIDILearnResult) {421        guard let target = learning else { return }422        switch target {423        case let .mapping(id):424            update(id) { m in425                m.control = result.control426                if m.mode == .relative, result.control.kind != .controlChange { m.mode = .absolute }427                if result.control.kind == .pitchBend, m.mode != .absolute { m.mode = .absolute }428            }429            learning = nil430        case .newMapping:431            learned = result432            if pendingTarget.isEmpty { pendingTarget = ControlTargets.all.first?.id ?? "" }433        }434    }435436    /// True when the values seen during learning look like an endless encoder (only small steps around 0 or 64).437    static func looksRelative(_ r: MIDILearnResult) -> Bool {438        guard r.control.kind == .controlChange, r.messageCount >= 2 else { return false }439        let lo = Int(r.minRawValue), hi = Int(r.maxRawValue)440        return (lo >= 1 && hi <= 5) || (lo >= 123 && hi <= 127) || (lo >= 61 && hi <= 67 && lo != hi) || (lo <= 3 && hi >= 125)441    }442443    func addLearned() {444        guard let result = learned, draft != nil, let target = ControlTargets.target(pendingTarget) else { return }445        var mode = Self.defaultMode(target: target, control: result.control)446        if target.kind == .value, Self.looksRelative(result) { mode = .relative }447        draft?.mappings.append(MIDIMapping(control: result.control, target: target.id, mode: mode, softTakeover: mode == .absolute && target.kind == .value && result.control.kind != .note))448        dirty = true449        learning = nil; learned = nil450    }451}452
Files main
Menu

Theme