SPB Git

Repository Public

MIDIMappingProfile.swift 9.8 KB 237 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Sources/ORIXMIDI/MIDIMappingProfile.swift10// Description      : A named set of mappings for one controller: JSON coding,11//                    validation, file import/export.12// Module           : ORIXMIDI13// Repository       : https://git.spboucher.ai/orix-dj14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091/// A problem found by `MIDIMappingProfile.validate()`. None of them makes the engine unsafe;92/// they describe mappings that cannot work or are probably mistakes.93public enum MIDIMappingProfileIssue: Sendable, Equatable {94    /// Two or more mappings use the same control with the same device scope. The engine fires all of them.95    case duplicateControl(control: MIDIControlID, deviceUniqueID: Int32?, mappingIDs: [UUID])96    case duplicateMappingID(UUID)97    case emptyTarget(mappingID: UUID)98    /// Channel above 15 or note/controller number above 127: no message can ever match.99    case invalidControl(mappingID: UUID)100    /// `minValue`/`maxValue` not finite or outside `0...1`.101    case invalidRange(mappingID: UUID)102    /// Relative mapping whose sensitivity is not a finite, non-zero number.103    case invalidSensitivity(mappingID: UUID)104    /// Relative mode on something other than a CC, or a button mode on pitch bend: the mapping never fires.105    case incompatibleMode(mappingID: UUID)106    case unsupportedFormatVersion(Int)107}108109public enum MIDIMappingProfileError: Error, Sendable, Equatable {110    /// The file was written by a newer ORIX DJ.111    case unsupportedFormatVersion(Int)112}113114public struct MIDIMappingProfile: Codable, Sendable, Identifiable, Equatable {115    public static let currentFormatVersion = 1116    /// Suggested file extension for exported profiles (the content is plain JSON).117    public static let fileExtension = "orixmidi"118119    public var id: UUID120    public var name: String121    /// Substring of the controller's name this profile was made for (for auto-selection in the UI); may be empty.122    public var controllerNameHint: String123    public var mappings: [MIDIMapping]124    public var formatVersion: Int125126    public init(127        id: UUID = UUID(),128        name: String,129        controllerNameHint: String = "",130        mappings: [MIDIMapping] = [],131        formatVersion: Int = MIDIMappingProfile.currentFormatVersion132    ) {133        self.id = id134        self.name = name135        self.controllerNameHint = controllerNameHint136        self.mappings = mappings137        self.formatVersion = formatVersion138    }139140    private enum CodingKeys: String, CodingKey {141        case id, name, controllerNameHint, mappings, formatVersion142    }143144    public init(from decoder: Decoder) throws {145        let c = try decoder.container(keyedBy: CodingKeys.self)146        id = try c.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()147        name = try c.decode(String.self, forKey: .name)148        controllerNameHint = try c.decodeIfPresent(String.self, forKey: .controllerNameHint) ?? ""149        mappings = try c.decodeIfPresent([MIDIMapping].self, forKey: .mappings) ?? []150        formatVersion = try c.decodeIfPresent(Int.self, forKey: .formatVersion) ?? 1151    }152153    // MARK: JSON154155    /// Stable, human-readable JSON (sorted keys, pretty printed).156    public func jsonData() throws -> Data {157        let encoder = JSONEncoder()158        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]159        return try encoder.encode(self)160    }161162    /// Decodes a profile; throws `MIDIMappingProfileError.unsupportedFormatVersion` for files from a newer format.163    public init(jsonData: Data) throws {164        let profile = try JSONDecoder().decode(MIDIMappingProfile.self, from: jsonData)165        guard (1...Self.currentFormatVersion).contains(profile.formatVersion) else {166            throw MIDIMappingProfileError.unsupportedFormatVersion(profile.formatVersion)167        }168        self = profile169    }170171    // MARK: Files172173    public func write(to url: URL) throws {174        try jsonData().write(to: url, options: .atomic)175    }176177    public init(contentsOf url: URL) throws {178        try self.init(jsonData: Data(contentsOf: url))179    }180181    // MARK: Validation182183    /// Returns every issue found, in mapping order; an empty array means the profile is clean.184    ///185    /// Duplicate detection compares control **and** device scope exactly: a device-specific mapping and an186    /// any-device mapping on the same control are not reported (that is a legitimate override pattern,187    /// although both fire for that device).188    public func validate() -> [MIDIMappingProfileIssue] {189        var issues: [MIDIMappingProfileIssue] = []190        if !(1...Self.currentFormatVersion).contains(formatVersion) {191            issues.append(.unsupportedFormatVersion(formatVersion))192        }193194        struct Scope: Hashable {195            var control: MIDIControlID196            var device: Int32?197        }198        var byScope: [Scope: [UUID]] = [:]199        var scopeOrder: [Scope] = []200        var seenIDs = Set<UUID>()201        var reportedIDs = Set<UUID>()202203        for m in mappings {204            if !seenIDs.insert(m.id).inserted, reportedIDs.insert(m.id).inserted {205                issues.append(.duplicateMappingID(m.id))206            }207            if m.target.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {208                issues.append(.emptyTarget(mappingID: m.id))209            }210            if m.control.channel > 15 || m.control.number > 127 {211                issues.append(.invalidControl(mappingID: m.id))212            }213            let rangeOK = m.minValue.isFinite && m.maxValue.isFinite214                && (0...1).contains(m.minValue) && (0...1).contains(m.maxValue)215            if !rangeOK { issues.append(.invalidRange(mappingID: m.id)) }216            switch m.mode {217            case .relative:218                if m.control.kind != .controlChange { issues.append(.incompatibleMode(mappingID: m.id)) }219                if !m.sensitivity.isFinite || m.sensitivity == 0 { issues.append(.invalidSensitivity(mappingID: m.id)) }220            case .toggle, .trigger, .momentary:221                if m.control.kind == .pitchBend { issues.append(.incompatibleMode(mappingID: m.id)) }222            case .absolute:223                break224            }225            let scope = Scope(control: m.control, device: m.deviceUniqueID)226            if byScope[scope] == nil { scopeOrder.append(scope) }227            byScope[scope, default: []].append(m.id)228        }229        for scope in scopeOrder {230            if let ids = byScope[scope], ids.count > 1 {231                issues.append(.duplicateControl(control: scope.control, deviceUniqueID: scope.device, mappingIDs: ids))232            }233        }234        return issues235    }236}237
Files main
Menu

Theme