Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX DJ9// File : App/Sources/Features/MIDI/MIDIView.swift10// Description : MIDI: connected devices with hot-plug, live monitor of11// incoming messages, statistics, and the mapping editor of12// the active profile with MIDI Learn, validation, import and13// 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 ORIXDJCore92import SwiftUI9394struct MIDIView: View {95 @Environment(AppModel.self) private var model96 @State private var controller = MIDIController()9798 var body: some View {99 HStack(alignment: .top, spacing: ORIX.Space.sm) {100 VStack(spacing: ORIX.Space.sm) {101 MIDIDevicesPanel()102 MIDIMonitorPanel(controller: controller)103 }104 .frame(width: 400)105 MIDIMappingPanel(controller: controller)106 }107 .padding(ORIX.Space.sm)108 .background(ORIX.Palette.canvas)109 .onAppear {110 controller.attach(model: model)111 #if DEBUG112 MIDIDemo.runIfRequested(model: model, controller: controller)113 #endif114 }115 .onDisappear { controller.detach(model: model) }116 .accessibilityElement(children: .contain).accessibilityIdentifier("midi-root")117 }118}119120// MARK: - Devices121122private struct MIDIDevicesPanel: View {123 @Environment(AppModel.self) private var model124125 var body: some View {126 // `midiStats` is refreshed five times per second by the app model, which keeps the destination list (read127 // straight from the manager) in step with hot-plug changes.128 let stats = model.midiStats129 let sources = model.midiSources130 let destinations = model.session.midi.destinations131 let connected = Set(model.session.midi.connectedSources.map(\.uniqueID))132 Panel {133 VStack(alignment: .leading, spacing: ORIX.Space.xs) {134 HStack {135 SectionLabel("Devices")136 Spacer()137 Button { model.session.midi.rescan(); model.refreshNow() } label: { Label("Rescan", systemImage: "arrow.clockwise") }138 .controlSize(.small).help("Devices appear and disappear on their own; this re-reads the list now.")139 .accessibilityIdentifier("midi-rescan")140 }141 if sources.isEmpty, destinations.isEmpty {142 VStack(alignment: .leading, spacing: 6) {143 Label("No MIDI device is connected", systemImage: "cable.connector.slash").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)144 Text("Plug a class-compliant controller in: it appears here by itself. ORIX DJ ships no ready-made controller profiles: you map your own controls with MIDI Learn. So far ORIX DJ has been tested with CoreMIDI virtual endpoints only, not with specific hardware.")145 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)146 }147 .accessibilityElement(children: .combine)148 .accessibilityIdentifier("midi-no-device")149 } else {150 if !sources.isEmpty {151 Text("Inputs (controller to ORIX DJ)").font(.system(size: 10.5, weight: .medium)).foregroundStyle(ORIX.Palette.textTertiary)152 ForEach(sources) { d in deviceRow(d, listening: connected.contains(d.uniqueID)) }153 }154 if !destinations.isEmpty {155 Text("Outputs (ORIX DJ to controller)").font(.system(size: 10.5, weight: .medium)).foregroundStyle(ORIX.Palette.textTertiary).padding(.top, 2)156 ForEach(destinations) { d in deviceRow(d, listening: false) }157 }158 Text("Tested with CoreMIDI virtual endpoints only. Controllers are mapped by you with MIDI Learn; no hardware-specific behaviour is claimed.")159 .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)160 .accessibilityIdentifier("midi-honesty")161 }162 Divider().overlay(ORIX.Palette.hairline)163 HStack(spacing: ORIX.Space.md) {164 stat("Received", "\(stats.messagesReceived)", id: "midi-stat-received")165 stat("Ignored", "\(stats.messagesDropped)", id: "midi-stat-dropped")166 .help("Messages ORIX DJ does not use: SysEx, clock, aftertouch, MIDI 2.0 words.")167 stat("Actions sent", "\(stats.targetEventsEmitted)", id: "midi-stat-actions")168 .help("Control events produced by the active profile.")169 Spacer()170 Button("Reset") { model.session.midi.resetStatistics(); model.refreshNow() }.controlSize(.small)171 .accessibilityIdentifier("midi-stat-reset")172 }173 }174 .frame(maxWidth: .infinity, alignment: .leading)175 }176 .accessibilityElement(children: .contain).accessibilityIdentifier("midi-devices")177 }178179 private func stat(_ label: LocalizedStringKey, _ value: String, id: String) -> some View {180 VStack(alignment: .leading, spacing: 1) {181 Text(label).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)182 Text(verbatim: value).font(ORIX.Typeface.readout(15)).foregroundStyle(ORIX.Palette.textPrimary)183 }184 .accessibilityElement(children: .combine)185 .accessibilityIdentifier(id)186 }187188 private func deviceRow(_ d: MIDIDeviceInfo, listening: Bool) -> some View {189 HStack(spacing: 8) {190 Image(systemName: d.kind == .source ? "arrow.down.to.line" : "arrow.up.to.line").font(.system(size: 11, weight: .semibold))191 .foregroundStyle(d.isOnline ? ORIX.Palette.accentSecondary : ORIX.Palette.textTertiary).frame(width: 16)192 VStack(alignment: .leading, spacing: 1) {193 Text(verbatim: d.name.isEmpty ? "Unnamed" : d.name).font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)194 Text(verbatim: [d.manufacturer, d.model].filter { !$0.isEmpty }.joined(separator: " · ").isEmpty ? "–" : [d.manufacturer, d.model].filter { !$0.isEmpty }.joined(separator: " · "))195 .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)196 }197 Spacer()198 if d.isVirtual { chip("virtual", symbol: "app.dashed") }199 if listening { chip("listening", symbol: "ear") }200 chip(d.isOnline ? "online" : "offline", symbol: d.isOnline ? "checkmark.circle" : "xmark.circle", tint: d.isOnline ? ORIX.Palette.success : ORIX.Palette.warning)201 }202 .padding(.vertical, 2)203 .accessibilityElement(children: .combine)204 .accessibilityIdentifier("midi-device-\(d.uniqueID)")205 }206207 private func chip(_ text: LocalizedStringKey, symbol: String, tint: Color = ORIX.Palette.textSecondary) -> some View {208 HStack(spacing: 3) {209 Image(systemName: symbol).font(.system(size: 8, weight: .bold))210 Text(text).font(.system(size: 10, weight: .medium))211 }212 .foregroundStyle(tint).padding(.horizontal, 6).frame(height: 17)213 .overlay(Capsule().strokeBorder(ORIX.Palette.hairline))214 }215}216217// MARK: - Monitor218219private struct MIDIMonitorPanel: View {220 var controller: MIDIController221222 var body: some View {223 Panel(padding: 0) {224 VStack(spacing: 0) {225 HStack(spacing: ORIX.Space.xs) {226 SectionLabel("Incoming messages")227 Text("last \(controller.events.count) of 200").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)228 Spacer()229 ToggleChip(title: controller.paused ? "Paused" : "Pause", symbol: controller.paused ? "play.fill" : "pause.fill", isOn: controller.paused, tint: ORIX.Palette.warning) { controller.paused.toggle() }230 .accessibilityLabel("Pause the monitor").accessibilityIdentifier("midi-monitor-pause")231 Button("Clear") { controller.clearMonitor() }.controlSize(.small).accessibilityIdentifier("midi-monitor-clear")232 }233 .padding(.horizontal, ORIX.Space.sm).frame(height: 36)234 Divider().overlay(ORIX.Palette.hairline)235 HStack(spacing: 0) {236 column("Time", 54, .trailing); column("Device", nil, .leading); column("Type", 96, .leading)237 column("Ch", 26, .trailing); column("Number", 70, .trailing); column("Value", 48, .trailing)238 }239 .padding(.horizontal, ORIX.Space.sm).frame(height: 22).background(ORIX.Palette.surfaceRaised.opacity(0.5))240 Divider().overlay(ORIX.Palette.hairline)241 if controller.events.isEmpty {242 EmptyState(symbol: "waveform.path", title: "Nothing received yet", message: "Move a fader or press a pad on a connected controller: each message is listed here as it arrives.")243 } else {244 ScrollViewReader { proxy in245 ScrollView {246 LazyVStack(spacing: 0) {247 ForEach(controller.events) { e in248 HStack(spacing: 0) {249 cell(String(format: "%.3f", controller.seconds(e)), 54, .trailing, ORIX.Palette.textTertiary)250 cell(e.device, nil, .leading, ORIX.Palette.textSecondary)251 cell(MIDIText.type(e.message), 96, .leading, ORIX.Palette.textPrimary)252 cell("\(e.message.channel + 1)", 26, .trailing, ORIX.Palette.textSecondary)253 cell(MIDIText.number(e.message), 70, .trailing, ORIX.Palette.textPrimary)254 cell(MIDIText.value(e.message), 48, .trailing, ORIX.Palette.textPrimary)255 }256 .padding(.horizontal, ORIX.Space.sm).frame(height: 20)257 .accessibilityElement(children: .combine)258 .id(e.id)259 }260 }261 }262 .onChange(of: controller.events.last?.id) { _, last in if let last { proxy.scrollTo(last, anchor: .bottom) } }263 .onAppear { if let last = controller.events.last?.id { proxy.scrollTo(last, anchor: .bottom) } }264 }265 .accessibilityIdentifier("midi-monitor-list")266 }267 }268 }269 .frame(maxHeight: .infinity)270 .accessibilityElement(children: .contain).accessibilityIdentifier("midi-monitor")271 }272273 private func column(_ title: LocalizedStringKey, _ width: CGFloat?, _ alignment: Alignment) -> some View {274 Text(title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textTertiary).textCase(.uppercase)275 .frame(width: width, alignment: alignment).frame(maxWidth: width == nil ? .infinity : nil, alignment: alignment).padding(.leading, alignment == .leading ? 8 : 0)276 }277278 private func cell(_ text: String, _ width: CGFloat?, _ alignment: Alignment, _ color: Color) -> some View {279 Text(verbatim: text).font(.system(size: 11, design: .monospaced)).foregroundStyle(color).lineLimit(1)280 .frame(width: width, alignment: alignment).frame(maxWidth: width == nil ? .infinity : nil, alignment: alignment).padding(.leading, alignment == .leading ? 8 : 0)281 }282}283284// MARK: - Mapping editor285286private struct MIDIMappingPanel: View {287 @Environment(AppModel.self) private var model288 var controller: MIDIController289290 var body: some View {291 @Bindable var controller = controller292 Panel(padding: 0) {293 VStack(spacing: 0) {294 profileBar295 Divider().overlay(ORIX.Palette.hairline)296 if let draft = controller.draft {297 learnBar(draft)298 Divider().overlay(ORIX.Palette.hairline)299 mappingList(draft)300 } else {301 EmptyState(symbol: "slider.horizontal.2.square", title: "No MIDI profile yet",302 message: "A profile is a set of mappings between the controls of one controller and ORIX DJ. Create one, then use MIDI Learn to add mappings.",303 actionTitle: "New Profile") { controller.newProfile(model: model) }304 }305 }306 }307 .frame(maxWidth: .infinity, maxHeight: .infinity)308 .alert("Rename Profile", isPresented: Binding(get: { controller.renameText != nil }, set: { if !$0 { controller.renameText = nil } })) {309 TextField("Name", text: Binding(get: { controller.renameText ?? "" }, set: { controller.renameText = $0 })).accessibilityIdentifier("midi-rename-field")310 Button("Cancel", role: .cancel) { controller.renameText = nil }311 Button("Rename") { controller.commitRename(model: model) }.keyboardShortcut(.defaultAction)312 }313 .confirmationDialog("Delete this MIDI profile?", isPresented: $controller.deleteRequested) {314 Button("Delete", role: .destructive) { controller.deleteProfile(model: model) }315 Button("Cancel", role: .cancel) {}316 } message: { Text("The mappings of \"\(controller.draft?.name ?? "")\" are removed from the library. Exported files are not touched.") }317 .accessibilityElement(children: .contain).accessibilityIdentifier("midi-mappings")318 }319320 private var profileBar: some View {321 let isActive = controller.draft != nil && controller.storedName == controller.activeName322 return HStack(spacing: ORIX.Space.xs) {323 SectionLabel("Profile")324 Menu {325 ForEach(controller.profiles) { p in326 Button { controller.select(p) } label: {327 if p.name == controller.activeName { Label { Text(verbatim: p.name) } icon: { Image(systemName: "checkmark") } } else { Text(verbatim: p.name) }328 }329 }330 if controller.profiles.isEmpty { Text("No saved profile") }331 } label: { Text(verbatim: controller.draft?.name ?? String(localized: "None")).font(.system(size: 12, weight: .semibold)) }332 .menuStyle(.borderlessButton).fixedSize().disabled(controller.dirty)333 .help(controller.dirty ? "Save or revert the changes before switching profile." : "Choose the profile to edit.")334 .accessibilityLabel("Profile").accessibilityValue(Text(verbatim: controller.draft?.name ?? "none"))335 .accessibilityIdentifier("midi-profile-menu")336 if controller.draft != nil {337 HStack(spacing: 3) {338 Image(systemName: isActive ? "bolt.fill" : "bolt.slash").font(.system(size: 9, weight: .bold))339 Text(isActive ? "Active" : "Not active").font(.system(size: 10.5, weight: .semibold))340 }341 .foregroundStyle(isActive ? ORIX.Palette.success : ORIX.Palette.textTertiary)342 .padding(.horizontal, 7).frame(height: 18).overlay(Capsule().strokeBorder(ORIX.Palette.hairline))343 .accessibilityElement(children: .combine).accessibilityIdentifier("midi-profile-state")344 if controller.dirty {345 Label("Unsaved changes", systemImage: "pencil.circle").font(.system(size: 10.5, weight: .medium)).foregroundStyle(ORIX.Palette.warning)346 .accessibilityIdentifier("midi-profile-dirty")347 }348 }349 Spacer()350 if controller.draft != nil {351 if controller.dirty {352 Button("Revert") { controller.reloadProfiles(model: model) }.accessibilityIdentifier("midi-profile-revert")353 }354 Button("Save") { controller.save(model: model) }.disabled(!controller.dirty).keyboardShortcut("s", modifiers: [.command])355 .accessibilityIdentifier("midi-profile-save")356 if isActive {357 Button("Deactivate") { controller.deactivate(model: model) }.help("Stops the profile from driving ORIX DJ. Messages still show in the monitor.")358 .accessibilityIdentifier("midi-profile-deactivate")359 } else {360 Button("Activate") { controller.activate(model: model) }.help("Saves the profile and makes it the one that drives ORIX DJ.")361 .accessibilityIdentifier("midi-profile-activate")362 }363 }364 Menu {365 Button("New Profile") { controller.newProfile(model: model) }.disabled(controller.dirty)366 Button("Duplicate") { controller.duplicate(model: model) }.disabled(controller.draft == nil)367 Button("Rename…") { controller.renameText = controller.draft?.name }.disabled(controller.draft == nil)368 Divider()369 Button("Import…") { controller.importProfile(model: model) }.disabled(controller.dirty)370 Button("Export…") { controller.exportProfile(model: model) }.disabled(controller.draft == nil)371 Divider()372 Button("Delete…", role: .destructive) { controller.deleteRequested = true }.disabled(controller.storedName == nil)373 } label: { Label("Profiles", systemImage: "ellipsis.circle") }374 .menuStyle(.borderlessButton).fixedSize()375 .accessibilityIdentifier("midi-profile-actions")376 }377 .controlSize(.small)378 .padding(.horizontal, ORIX.Space.sm).frame(height: 40)379 }380381 @ViewBuilder private func learnBar(_ draft: MIDIMappingProfile) -> some View {382 @Bindable var controller = controller383 HStack(spacing: ORIX.Space.xs) {384 if let learned = controller.learned, controller.learning == .newMapping {385 Image(systemName: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.success)386 Text("Learned").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)387 Text(verbatim: "\(MIDIText.control(learned.control)) · \(learned.device.name)").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)388 .accessibilityIdentifier("midi-learned-control")389 if MIDIController.looksRelative(learned) {390 Text("looks like an endless encoder").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)391 }392 Text("Target").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)393 MIDITargetMenu(target: controller.pendingTarget) { controller.pendingTarget = $0 }.accessibilityIdentifier("midi-learned-target")394 Spacer()395 Button("Cancel") { controller.cancelLearn(model: model) }.accessibilityIdentifier("midi-learn-cancel")396 Button("Add Mapping") { controller.addLearned() }.keyboardShortcut(.defaultAction).accessibilityIdentifier("midi-learn-add")397 } else if controller.learning != nil {398 ProgressView().controlSize(.small)399 Text(controller.learning == .newMapping ? "Move or press the control to map…" : "Move or press the control for this mapping…")400 .font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.accent)401 .accessibilityIdentifier("midi-learn-waiting")402 Text("While learning, the controller does not drive ORIX DJ.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)403 Spacer()404 Button("Cancel") { controller.cancelLearn(model: model) }.accessibilityIdentifier("midi-learn-cancel")405 } else {406 Button { controller.beginLearn(.newMapping, model: model) } label: { Label("Learn New Mapping", systemImage: "dot.radiowaves.left.and.right") }407 .accessibilityIdentifier("midi-learn-new")408 Text(draft.mappings.count == 1 ? "1 mapping" : "\(draft.mappings.count) mappings").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)409 .accessibilityIdentifier("midi-mapping-count")410 let general = draft.validate().map(MIDIText.issue).filter { $0.mapping.isEmpty }411 ForEach(Array(general.enumerated()), id: \.offset) { _, issue in412 Label { Text(verbatim: issue.text) } icon: { Image(systemName: "exclamationmark.triangle.fill") }.font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning)413 }414 Spacer()415 Text("Controller name hint").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)416 TextField("optional", text: Binding(get: { controller.draft?.controllerNameHint ?? "" }, set: { controller.draft?.controllerNameHint = $0; controller.dirty = true }))417 .textFieldStyle(.roundedBorder).frame(width: 150)418 .help("Part of the controller's name this profile was made for. Informative only.")419 .accessibilityLabel("Controller name hint").accessibilityIdentifier("midi-profile-hint")420 }421 }422 .controlSize(.small)423 .padding(.horizontal, ORIX.Space.sm).frame(height: 38)424 .background(controller.learning != nil ? ORIX.Palette.accent.opacity(0.08) : Color.clear)425 }426427 private func mappingList(_ draft: MIDIMappingProfile) -> some View {428 let issues = draft.validate().map(MIDIText.issue)429 return VStack(spacing: 0) {430 HStack(spacing: 8) {431 head("Control", 138); head("Target", nil); head("Mode", 100); head("Min %", 46); head("Max %", 46)432 head("Invert", 44); head("Soft", 38); head("", 22)433 }434 .padding(.horizontal, ORIX.Space.sm).frame(height: 22).background(ORIX.Palette.surfaceRaised.opacity(0.5))435 Divider().overlay(ORIX.Palette.hairline)436 if draft.mappings.isEmpty {437 EmptyState(symbol: "dot.radiowaves.left.and.right", title: "No mapping yet",438 message: "Choose Learn New Mapping, move a control on your controller, then pick what it drives.")439 } else {440 ScrollView {441 LazyVStack(spacing: 0) {442 ForEach(Array(draft.mappings.enumerated()), id: \.element.id) { index, mapping in443 MIDIMappingRow(index: index, mapping: mapping, issues: issues.filter { $0.mapping.contains(mapping.id) }.map(\.text), controller: controller)444 Divider().overlay(ORIX.Palette.hairline)445 }446 }447 }448 .accessibilityIdentifier("midi-mapping-list")449 }450 }451 }452453 private func head(_ title: LocalizedStringKey, _ width: CGFloat?) -> some View {454 Text(title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textTertiary).textCase(.uppercase)455 .frame(width: width, alignment: .leading).frame(maxWidth: width == nil ? .infinity : nil, alignment: .leading)456 }457}458459/// Target chooser grouped the way `ControlTargets.all` groups them, with the kind of each target.460struct MIDITargetMenu: View {461 var target: String462 var onChange: (String) -> Void463464 private static let groups: [(name: String, targets: [ControlTarget])] = {465 var order: [String] = []466 var map: [String: [ControlTarget]] = [:]467 for t in ControlTargets.all {468 if map[t.group] == nil { order.append(t.group) }469 map[t.group, default: []].append(t)470 }471 return order.map { ($0, map[$0] ?? []) }472 }()473474 static func kindWord(_ kind: ControlTargetKind) -> String {475 switch kind {476 case .value: String(localized: "value")477 case .toggle: String(localized: "on / off")478 case .trigger: String(localized: "action")479 }480 }481482 var body: some View {483 let current = ControlTargets.target(target)484 Menu {485 ForEach(Self.groups, id: \.name) { group in486 Menu(group.name) {487 ForEach(group.targets) { t in488 Button { onChange(t.id) } label: { Text(verbatim: "\(t.name) · \(Self.kindWord(t.kind))") }489 }490 }491 }492 } label: {493 if let current {494 Text(verbatim: "\(current.group) · \(current.name)").font(.system(size: 12)).lineLimit(1)495 } else {496 Text(target.isEmpty ? "Choose a target" : "Unknown target").font(.system(size: 12)).foregroundStyle(ORIX.Palette.warning)497 }498 }499 .menuStyle(.borderlessButton)500 .accessibilityLabel("Target")501 .accessibilityValue(Text(verbatim: current.map { "\($0.group), \($0.name), \(Self.kindWord($0.kind))" } ?? "none"))502 }503}504505private struct MIDIMappingRow: View {506 @Environment(AppModel.self) private var model507 var index: Int508 var mapping: MIDIMapping509 var issues: [String]510 var controller: MIDIController511512 private func percent(_ keyPath: WritableKeyPath<MIDIMapping, Double>) -> Binding<Double> {513 Binding(get: { (mapping[keyPath: keyPath] * 100).rounded() }, set: { v in controller.update(mapping.id) { $0[keyPath: keyPath] = min(1, max(0, v / 100)) } })514 }515516 var body: some View {517 let learningThis = controller.learning == .mapping(mapping.id)518 let target = ControlTargets.target(mapping.target)519 let buttonMode = mapping.mode == .toggle || mapping.mode == .trigger || mapping.mode == .momentary520 VStack(alignment: .leading, spacing: 4) {521 HStack(spacing: 8) {522 HStack(spacing: 5) {523 Text(verbatim: MIDIText.control(mapping.control)).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1).minimumScaleFactor(0.75)524 .help(mapping.control.kind == .note ? "Note number \(mapping.control.number)" : "")525 Spacer(minLength: 0)526 Button { if learningThis { controller.cancelLearn(model: model) } else { controller.beginLearn(.mapping(mapping.id), model: model) } } label: {527 Text(learningThis ? "Waiting…" : "Learn").font(.system(size: 10.5, weight: .semibold))528 .padding(.horizontal, 6).frame(height: 18)529 .foregroundStyle(learningThis ? ORIX.Palette.onTint : ORIX.Palette.textPrimary)530 .background(learningThis ? AnyShapeStyle(ORIX.Palette.accent) : AnyShapeStyle(ORIX.Palette.surfaceRaised), in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))531 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous).strokeBorder(ORIX.Palette.hairline))532 }533 .buttonStyle(.plain)534 .accessibilityLabel(Text("MIDI Learn for mapping \(index + 1)")).accessibilityValue(learningThis ? Text("waiting for a control") : Text(verbatim: MIDIText.control(mapping.control)))535 .accessibilityIdentifier("midi-row-\(index)-learn")536 }537 .frame(width: 138, alignment: .leading)538539 HStack(spacing: 6) {540 MIDITargetMenu(target: mapping.target) { controller.setTarget(mapping.id, target: $0) }541 .fixedSize().accessibilityIdentifier("midi-row-\(index)-target")542 if let target {543 Text(verbatim: MIDITargetMenu.kindWord(target.kind)).font(.system(size: 10, weight: .medium)).foregroundStyle(ORIX.Palette.textTertiary)544 .lineLimit(1).fixedSize()545 .padding(.horizontal, 5).frame(height: 15).overlay(Capsule().strokeBorder(ORIX.Palette.hairline))546 }547 Spacer(minLength: 0)548 }549 .frame(maxWidth: .infinity, alignment: .leading)550551 Picker("Mode", selection: Binding(get: { mapping.mode }, set: { v in controller.update(mapping.id) { $0.mode = v } })) {552 ForEach(MIDIMappingMode.allCases, id: \.self) { m in Text(m.title).tag(m) }553 }554 .labelsHidden().frame(width: 100)555 .accessibilityLabel(Text("Mode of mapping \(index + 1)")).accessibilityIdentifier("midi-row-\(index)-mode")556557 TextField("0", value: percent(\.minValue), format: .number.precision(.fractionLength(0))).textFieldStyle(.roundedBorder).frame(width: 46)558 .disabled(buttonMode).accessibilityLabel(Text("Minimum of mapping \(index + 1), percent")).accessibilityIdentifier("midi-row-\(index)-min")559 TextField("100", value: percent(\.maxValue), format: .number.precision(.fractionLength(0))).textFieldStyle(.roundedBorder).frame(width: 46)560 .disabled(buttonMode).accessibilityLabel(Text("Maximum of mapping \(index + 1), percent")).accessibilityIdentifier("midi-row-\(index)-max")561 Toggle("Invert", isOn: Binding(get: { mapping.invert }, set: { v in controller.update(mapping.id) { $0.invert = v } }))562 .labelsHidden().toggleStyle(.checkbox).frame(width: 44, alignment: .leading)563 .help("Faders: mirrors the control. Encoders: reverses direction. Buttons: swaps press and release.")564 .accessibilityLabel(Text("Invert mapping \(index + 1)")).accessibilityIdentifier("midi-row-\(index)-invert")565 Toggle("Soft takeover", isOn: Binding(get: { mapping.softTakeover }, set: { v in controller.update(mapping.id) { $0.softTakeover = v } }))566 .labelsHidden().toggleStyle(.checkbox).frame(width: 38, alignment: .leading)567 .disabled(mapping.mode != .absolute || mapping.control.kind == .note)568 .help("Soft takeover: the control does nothing until it reaches the value shown on screen, so nothing jumps.")569 .accessibilityLabel(Text("Soft takeover for mapping \(index + 1)")).accessibilityIdentifier("midi-row-\(index)-soft")570 Button { controller.removeMapping(mapping.id) } label: { Image(systemName: "trash").font(.system(size: 11)).frame(width: 22, height: 20).contentShape(Rectangle()) }571 .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textSecondary)572 .accessibilityLabel(Text("Delete mapping \(index + 1)")).accessibilityIdentifier("midi-row-\(index)-delete")573 }574 if mapping.mode == .relative {575 HStack(spacing: 8) {576 Text("Encoder sends").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)577 Picker("Encoding", selection: Binding(get: { mapping.relativeEncoding }, set: { v in controller.update(mapping.id) { $0.relativeEncoding = v } })) {578 ForEach(MIDIRelativeEncoding.allCases, id: \.self) { e in Text(e.title).tag(e) }579 }580 .labelsHidden().fixedSize()581 .accessibilityLabel(Text("Relative encoding of mapping \(index + 1)")).accessibilityIdentifier("midi-row-\(index)-encoding")582 Text("Sensitivity").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)583 TextField("1", value: Binding(get: { mapping.sensitivity }, set: { v in controller.update(mapping.id) { $0.sensitivity = v } }), format: .number.precision(.fractionLength(0 ... 2)))584 .textFieldStyle(.roundedBorder).frame(width: 56)585 .help("One encoder step moves the value by sensitivity / 127 of its range.")586 .accessibilityLabel(Text("Sensitivity of mapping \(index + 1)")).accessibilityIdentifier("midi-row-\(index)-sensitivity")587 }588 .padding(.leading, 146)589 }590 ForEach(issues, id: \.self) { issue in591 Label { Text(verbatim: issue) } icon: { Image(systemName: "exclamationmark.triangle.fill") }592 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).padding(.leading, 146)593 .accessibilityIdentifier("midi-row-\(index)-issue")594 }595 }596 .controlSize(.small)597 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 6)598 .background(learningThis ? ORIX.Palette.accent.opacity(0.08) : Color.clear)599 }600}601