Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Racks redesign: one rack card, MIDI Effect Rack, MIDI effects in Instrument Rack chains (#331)
Egor Khindikaynenc01c0b968c1f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 485df780..4c8914bf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,9 +20,40 @@ the GitHub release and the news posts — comes from the curated, summarisedEntry categories: `Added`, `Changed`, `Fixed`, `Removed`.+### Changed+- **The rack cards are redesigned** (Instrument, Audio Effect and the new MIDI Effect Rack share+ one card): eight macro knobs; Chains, Zones (Audio: Select) and Macros tabs; the chosen+ chain's devices as compact cards with their key parameters; a Chain / Rack out panel; a+ status line. Every theme draws it in its own colours.+- **Map a macro in place**: press Map and click parameters right on the chain's devices; Esc+ ends it. The Macros tab sets each target's range (min above max inverts) and the macro's+ curve, shown as Mixed when an older project gave its targets different curves.+- **Zones are dragged by their edges**, and hovering the keyboard strip shows which chains a+ note would play.++### Fixed+- Undoing or redoing a rack edit puts back what the rack's macros drive, and changes to a+ mapping's range, curve or a macro's name are undoable.+- "Save preset" on a MIDI effect's card saves that MIDI effect.+## [Unreleased]### Added+- **MIDI Effect Rack**: a new MIDI effect with chains of MIDI effects. Each chain takes the+ notes its key and velocity zone lets in (or, in Select mode, the chains whose select range+ holds the selector), runs them through its Arp, Chord, Scale and so on, can transpose them+ and scale their velocity, and the chains' notes merge before the instrument. Merge duplicate+ notes and pass notes outside every zone through are switches. In the Browser under MIDI+ effects · Racks; saved with the project and in presets; the MCP tools are `midi_rack_*`.+- **MIDI effects in Instrument Rack chains** (nota-daw/nota#329): a chain runs MIDI effects →+ instrument → audio effects, like a track, so an instrument and its Arp or Chord can live in+ one rack. They keep time with the song exactly as on a track.+- **Mono and glide on the Instrument Rack**: Mono (last note) plays one note at a time; Glide+ slides each new note from the previous pitch on instruments that take per-note bend.+- **Duplicate a rack chain**, with its devices, zones, mix and macro mappings.+- **Map a rack's selector to a macro** (Audio Effect and MIDI Effect Racks).+- **Nota Vocoder in rack chains**: add it to an Instrument or Audio Effect Rack chain from the+ card's menu or the Browser; inside a rack it uses its own Saw or Noise carrier.- **Move clips with the keyboard** (nota-daw/nota#302): in the Arrangement, ← / → nudge theselected clips by the grid step and ⌥← / ⌥→ by a 64th note, stopping at the song start;⌥↑ / ⌥↓ move them to the next track up or down that takes them, at the same beats. Eachdiff --git a/FEATURES.md b/FEATURES.mdindex a35b676f..9b3ea8f4 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -836,7 +836,8 @@ audio effects after it keep running and keep their settings; saved with the projwith a Tilt. 8–32 bands between Low and High, Q, Formant ±12 st, Attack, Release; Unvoiced noisefor consonants, Hold, Mix, Gain. A live graph of each band's voice level and the carrier, withdraggable range edges; 7 factory presets; a carrier track is routed over MCP with- `set_device_sidechain`.+ `set_device_sidechain`. It also goes in Instrument and Audio Effect Rack chains, with its own+ Saw or Noise carrier.- **Forge**, **Valve** and **Vintage** each carry an **OVERSAMPLE** selector(Off/2×/4×/8×) to suppress aliasing under heavy drive.@@ -882,9 +883,18 @@ audio effects after it keep running and keep their settings; saved with the projfull automation, MCP tools (`get_chord` / `set_chord` / `set_chord_shift`).### Racks-- **Nota Instrument Rack** — 8 named macros (mapped with Linear/Exp/Log/S curves), chains- with **key and velocity zones**, gain/meter/M·S, horizontal device cards (GUI / Params),- a zone map, rack output (Volume/Glide), Fold/Save.+- **One rack card** for the Instrument, Audio Effect and MIDI Effect Racks: eight macro knobs+ (name, value, target count) with a **Map** key; **Chains** (chain list with M·S, zone summary+ and level · the chosen chain's devices left to right as compact cards with their key+ parameters, Browser drops, + Chain, grip reorder, Open for the full editor), **Zones** /+ **Select** (drag zone edges; hover the keyboard strip to see which chains a note plays) and+ **Macros** tabs (rename, curve Lin/Exp/Log/S — "Mixed" when targets differ — and each+ target's range, min above max inverts); a **Chain** panel (Volume, Pan or Transpose, zones,+ Duplicate, Delete) and a **Rack out** / **Output** panel; a status line. **Map** works in+ place: click parameters on the chain's devices to add or remove them; Esc ends it.+- **Nota Instrument Rack** — layered chains of MIDI effects → instrument → audio effects, each+ with **key and velocity zones**, gain, pan, M·S; Rack out: Volume, Glide and **Mono (last+ note)** — glide bends each new note from the last one on instruments that take per-note bend.- **Nota Drum Rack** — 4×4 pads (banks C1–C4, up to 64 pads), Pads, Mixer, Chain and Macro views,per-pad Volume/Pan/Tune/Decay, named pads (rename, re-choke or remove from a pad'sright-click menu), choke groups (monophonic cut), Swing/Humanize, hot-swap, a pad@@ -909,13 +919,19 @@ audio effects after it keep running and keep their settings; saved with the projan existing Drum Rack or Rhythm to replace its pads / voices. The one-shots are synthesized on first launch rather thanshipped as audio (nothing added to the installer) and appear in the Files tab under**Nota Kits**, ready to drag anywhere a sample goes.-- **Nota Audio Effect Rack** — **Parallel / Series / Select** modes (by input level),- Dry/Wet + Gain, PDC, Fold, Save; chains with gain/meter/M·S; named macros and mappings;- the "+ Device" menu lists built-in effects and a Plug-ins submenu. ⌘G on a selected audio- effect wraps it in a new rack (**Group into rack**); ⌘⇧G puts a one-chain rack's devices back.-- Devices inside chains appear as cards with knobs, a **Full** button (the device's- complete UI in a popup — the native GUI for a plugin, the tabbed editor for the- Sampler), a ✕ delete button, and drag-to-reorder.+- **Nota Audio Effect Rack** — chains run **Parallel / Serial / Select**; in Select mode a+ selector (dragged, mapped to a macro, or following the input level) picks the chains whose+ select range holds it; Dry/wet, Gain, latency compensation; the add menu lists built-in+ effects and a Plug-ins submenu. ⌘G on a selected audio effect wraps it in a new rack+ (**Group into rack**); ⌘⇧G puts a one-chain rack's devices back.+- **Nota MIDI Effect Rack** — a MIDI effect with up to 16 chains of MIDI effects (Arp, Chord,+ Scale, Length, Velocity, Random). Each chain takes the notes its key and velocity zone lets in+ (or, in Select mode, the chains whose select range holds the selector), can transpose them+ and scale their velocity (Volume 0–200 %), and the chains' notes merge before the instrument.+ Output: Merge duplicate notes, Pass through outside zones. MCP `get_midi_rack` and the+ `midi_rack_*` tools.+- Every rack: duplicate a chain with its mappings, map the selector or any chain parameter to a+ macro, save it as a preset; edits are undoable.---@@ -1212,10 +1228,14 @@ Coverage:follow, insert / duplicate / capture / move / delete scenes, stop buttons, launch andrelease a slot, launch and stop a scene, launch quantization, the follow switch, slot andscene recording with a fixed length, back to arrangement, slot ↔ arrangement).-- **Racks** (Instrument/Drum): chain snapshot, add and remove a chain and change its+- **Racks** (Instrument/Drum): chain snapshot, add, duplicate and remove a chain and change itsinstrument, parameters, mix (gain/pan/mute/solo), key and velocity zones, trigger note,- 8 macros and their mappings, rack volume and glide; for the Drum Rack, per-pad- choke/tune/decay and kit swing/humanize.+ 8 macros and their mappings (range, curve), rack volume, glide and mono, a chain's MIDI+ effects (`*_rack_chain_midi_fx`); for the Drum Rack, per-pad choke/tune/decay and kit+ swing/humanize.+- **MIDI Effect Rack**: snapshot, chains and their MIDI effects, zones, select ranges,+ transpose, velocity scale, Parallel/Select, selector, merge and pass-through, macros and+ mappings (`get_midi_rack`, `midi_rack_*`).- **Samples**: create a Sampler or Grain with a file (optionally taking the root from the filename), load a sample onto a track or into a rack chain, read sample info, and read / shape aSampler in real units (`read_sampler`, `set_sampler`).@@ -1225,7 +1245,8 @@ Coverage:- **Presets**: factory (list, apply to a new track or in place) and user (list, apply,save).- **Audio Effect Rack**: snapshot, Parallel/Series/Select mode, dry/wet, volume,- chain-select, add and remove chains, parameters, 8 macros.+ chain-select, add, duplicate and remove chains, parameters, 8 macros, the selector as a+ macro target.- **Export** the master or stems to WAV (pcm16/pcm24/float32), FLAC (pcm16/pcm24) orMP3 (CBR 128–320 kbps) — `format` picks it, `bitrateKbps` tunes MP3, `startBeat` setswhere the render starts.diff --git a/specs/040-racks-redesign/checklists/requirements.md b/specs/040-racks-redesign/checklists/requirements.mdnew file mode 100644index 00000000..9ae8e917--- /dev/null+++ b/specs/040-racks-redesign/checklists/requirements.md@@ -0,0 +1,37 @@+# Specification Quality Checklist: Racks redesign and MIDI Effect Rack++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-26+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs)+- [x] Focused on user value and business needs+- [x] Written for non-technical stakeholders+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic (no implementation details)+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] No implementation details leak into specification++## Notes++- FR-016 resolved 2026-10-26: curves stay per target, the macro shows "Mixed" until one is picked.+- The Nota Context section names feature areas (engine / managed / UI) and the design+ translation rules by design of the project template; that is intended, not a leak.+- Items marked incomplete require spec updates before `/speckit-clarify` or `/speckit-plan`diff --git a/specs/040-racks-redesign/contracts/c-abi.md b/specs/040-racks-redesign/contracts/c-abi.mdnew file mode 100644index 00000000..ca39b7c3--- /dev/null+++ b/specs/040-racks-redesign/contracts/c-abi.md@@ -0,0 +1,128 @@+# Contract: C ABI additions (`include/nota/nota_engine.h`)++All calls are message-thread, pure C (AR-7), `NotaEngine*` first. Structural edits+fork the rack for undo (`rackForEdit` pattern, #236) and publish a new snapshot (AR-5);+value setters are relaxed atomics (AR-4/AR-6). Every new call is covered by the smoke test.++## Generic MIDI effect state (any MIDI effect)++```c+/* Opaque state blob of a MIDI effect (MIDI Effect Rack: its whole structure).+ * out == NULL returns the size; otherwise writes up to cap bytes and returns the count. */+int32_t nota_midi_effect_get_state(const NotaEngine*, int32_t track_id, int32_t index, uint8_t* out, int32_t cap);+/* Restore a state blob; checkpoints undo when checkpoint != 0. */+NotaResult nota_midi_effect_set_state(NotaEngine*, int32_t track_id, int32_t index, const uint8_t* data, int32_t size, int32_t checkpoint);+```++`nota_track_add_midi_effect(engine, track, 6)` adds a MIDI Effect Rack with one empty chain.++## MIDI Effect Rack family — `nota_midirack_*(engine, track_id, midi_index, …)`++Mirrors `nota_rackdev_*`; `midi_index` is the MIDI effect's index on the track. Calls on+an index that isn't a MIDI rack return `<0` / `NOTA_ERR_*` / 0.++Structure:++```c+int32_t nota_midirack_chain_count(…);+int32_t nota_midirack_add_chain(…); /* returns index, <0 at the 16-chain limit */+NotaResult nota_midirack_remove_chain(…, int32_t chain);+NotaResult nota_midirack_duplicate_chain(…, int32_t chain); /* inserts after; copies devices + controls + its mappings */+NotaResult nota_midirack_move_chain(…, int32_t from, int32_t to);+int32_t nota_midirack_chain_device_count(…, int32_t chain);+int32_t nota_midirack_add_chain_device(…, int32_t chain, int32_t midi_kind); /* kinds 0–5; 6 refused */+NotaResult nota_midirack_remove_chain_device(…, int32_t chain, int32_t dev);+NotaResult nota_midirack_move_chain_device(…, int32_t chain, int32_t from, int32_t to);+int32_t nota_midirack_chain_device_kind(…, int32_t chain, int32_t dev);+const char* nota_midirack_chain_device_name(…, int32_t chain, int32_t dev);+int32_t nota_midirack_chain_device_param_count(…, int32_t chain, int32_t dev);+const char* nota_midirack_chain_device_param_name(…, int32_t chain, int32_t dev, int32_t p);+float nota_midirack_chain_device_param_min/max/get(…, int32_t chain, int32_t dev, int32_t p);+void nota_midirack_chain_device_param_set(…, int32_t chain, int32_t dev, int32_t p, float v);+void nota_midirack_set_chain_device_bypassed(…, int32_t chain, int32_t dev, int32_t b);+int32_t nota_midirack_chain_device_bypassed(…, int32_t chain, int32_t dev);+```++Chain controls:++```c+const char* nota_midirack_chain_name(…, int32_t chain); void nota_midirack_set_chain_name(…, int32_t chain, const char*);+void nota_midirack_set_chain_mute/solo(…, int32_t chain, int32_t on); int32_t nota_midirack_chain_mute/solo(…);+void nota_midirack_set_chain_zone(…, int32_t chain, int32_t key_lo, int32_t key_hi, int32_t vel_lo, int32_t vel_hi);+void nota_midirack_chain_zone(…, int32_t chain, int32_t* key_lo, int32_t* key_hi, int32_t* vel_lo, int32_t* vel_hi);+void nota_midirack_set_chain_select(…, int32_t chain, int32_t lo, int32_t hi);+void nota_midirack_chain_select_range(…, int32_t chain, int32_t* lo, int32_t* hi);+void nota_midirack_set_chain_transpose(…, int32_t chain, int32_t semitones); /* −48…+48 */+int32_t nota_midirack_chain_transpose(…, int32_t chain);+void nota_midirack_set_chain_vel_scale(…, int32_t chain, float scale); /* 0–2 */+float nota_midirack_chain_vel_scale(…, int32_t chain);+float nota_midirack_chain_activity(…, int32_t chain); /* 0–1, decays */+```++Rack:++```c+void nota_midirack_set_mode(…, int32_t mode); int32_t nota_midirack_mode(…); /* 0 Parallel, 2 Select */+void nota_midirack_set_selector(…, float v01); float nota_midirack_selector(…);+void nota_midirack_set_merge(…, int32_t on); int32_t nota_midirack_merge(…);+void nota_midirack_set_thru(…, int32_t on); int32_t nota_midirack_thru(…);+```++Macros and mappings (same semantics as `nota_rackdev_*`):++```c+float nota_midirack_macro_get(…, int32_t m); void nota_midirack_macro_set(…, int32_t m, float v);+const char* nota_midirack_macro_name(…, int32_t m); void nota_midirack_set_macro_name(…, int32_t m, const char*);+int32_t nota_midirack_add_macro_mapping(…, int32_t macro, int32_t chain, int32_t device, int32_t param, float lo, float hi);+int32_t nota_midirack_mapping_count(…);+int32_t nota_midirack_mapping_info(…, int32_t i, int32_t* macro, int32_t* chain, int32_t* device, int32_t* param, float* lo, float* hi, int32_t* curve);+NotaResult nota_midirack_remove_mapping(…, int32_t i);+NotaResult nota_midirack_set_mapping_range(…, int32_t i, float lo, float hi);+NotaResult nota_midirack_set_mapping_curve(…, int32_t i, int32_t curve);+```++Automation of macros goes through the existing plugin-param / MIDI-effect param surface+(macros appear as the rack's params 0–7), so automation lanes, MIDI Learn and+`begin/end_automation_write` work unchanged.++## Instrument Rack additions — `nota_rack_*(engine, track_id, …)`++Chain MIDI effects (issue #329), addressed like chain audio devices:++```c+int32_t nota_rack_chain_midi_count(…, int32_t chain);+int32_t nota_rack_add_chain_midi(…, int32_t chain, int32_t midi_kind); /* kinds 0–5 */+NotaResult nota_rack_remove_chain_midi(…, int32_t chain, int32_t idx);+NotaResult nota_rack_move_chain_midi(…, int32_t chain, int32_t from, int32_t to);+int32_t nota_rack_chain_midi_kind(…, int32_t chain, int32_t idx);+const char* nota_rack_chain_midi_name(…, int32_t chain, int32_t idx);+int32_t nota_rack_chain_midi_param_count(…, int32_t chain, int32_t idx);+const char* nota_rack_chain_midi_param_name(…, int32_t chain, int32_t idx, int32_t p);+float nota_rack_chain_midi_param_min/max/get(…, int32_t chain, int32_t idx, int32_t p);+void nota_rack_chain_midi_param_set(…, int32_t chain, int32_t idx, int32_t p, float v);+void nota_rack_set_chain_midi_bypassed(…, int32_t chain, int32_t idx, int32_t b);+int32_t nota_rack_chain_midi_bypassed(…, int32_t chain, int32_t idx);+/* Editor telemetry/commands so the full MIDI-effect cards work inside a chain: */+int32_t nota_rack_chain_midi_last_in/last_out(…, int32_t chain, int32_t idx);+int32_t nota_rack_chain_midi_scope(…, int32_t chain, int32_t idx, float* out, int32_t max_n);+void nota_rack_chain_midi_command(…, int32_t chain, int32_t idx, int32_t cmd);+```++Macro mappings to a chain MIDI effect use `device = NOTA_RACK_MIDI_DEVICE_BASE − idx`+(`#define NOTA_RACK_MIDI_DEVICE_BASE (-1000)`).++```c+void nota_rack_set_mono(…, int32_t on); int32_t nota_rack_mono(…);+/* glide: existing nota_rack_set_glide / nota_rack_glide — now audible in mono mode */+```++## Shared rack-control mapping target++`device = −3, param = 0` in `*_add_macro_mapping` targets the rack selector (Audio and+MIDI racks). Range is in selector units 0–1.++## Mapping uniqueness++`nota_rack_add_macro_mapping`, `nota_rackdev_add_macro_mapping` and+`nota_midirack_add_macro_mapping` move an existing mapping of the same (chain, device,+param) to the new macro instead of adding a second one, and return its index.diff --git a/specs/040-racks-redesign/contracts/mcp-tools.md b/specs/040-racks-redesign/contracts/mcp-tools.mdnew file mode 100644index 00000000..fa041b08--- /dev/null+++ b/specs/040-racks-redesign/contracts/mcp-tools.md@@ -0,0 +1,57 @@+# Contract: MCP tools (`src/managed/Nota.Mcp/Tools`)++New `MidiRackTools.cs`, at parity with `RackTools` / `EffectRackTools`. All tools take+`trackId` and `midiIndex` (the MIDI effect index on the track) unless noted, run on the+engine dispatch, refresh the UI, and return the snapshot or a short result like the+existing rack tools. Writes are one undo step each.++| Tool | Arguments | Result |+|---|---|---|+| `get_midi_rack` | — | `{ mode, modeName, selector (0–127), merge, thru, chains: [{ index, name, mute, solo, keyLo, keyHi, velLo, velHi, selLo, selHi, transpose, velScale, devices: [{ index, kind, name, bypassed }] }] }` |+| `add_midi_rack_chain` | `name?` | new chain index |+| `remove_midi_rack_chain` | `chain` | ok |+| `duplicate_midi_rack_chain` | `chain` | new chain index |+| `set_midi_rack_chain_name` | `chain, name` | ok |+| `add_midi_rack_chain_device` | `chain, kind (0–5)` | device index |+| `remove_midi_rack_chain_device` | `chain, device` | ok |+| `move_midi_rack_chain_device` | `chain, from, to` | ok |+| `get_midi_rack_chain_params` | `chain, device` | `[{ index, name, min, max, value }]` |+| `set_midi_rack_chain_param` | `chain, device, param, value` | ok |+| `set_midi_rack_chain_bypass` | `chain, device, bypassed` | ok |+| `set_midi_rack_chain_mix` | `chain, mute?, solo?, transpose?, velScale?` | ok |+| `set_midi_rack_chain_zone` | `chain, keyLo?, keyHi?, velLo?, velHi?, selLo?, selHi?` | ok (accepts note names, e.g. "C3") |+| `set_midi_rack_mode` | `mode: "parallel" \| "select"` | ok |+| `set_midi_rack_selector` | `value 0–127` | ok |+| `set_midi_rack_output` | `merge?, thru?` | ok |+| `get_midi_rack_macros` | — | `[{ index, name, value, curve: "lin"\|"exp"\|"log"\|"s"\|"mixed", targets }]` |+| `set_midi_rack_macro` | `macro, value?, name?` | ok |+| `list_midi_rack_mappings` | — | `[{ index, macro, chain, device, param, min, max, curve }]` |+| `add_midi_rack_mapping` | `macro, chain, device (−3 = selector), param, min, max` | mapping index (moves an existing mapping of the same param) |+| `remove_midi_rack_mapping` | `index` | ok |+| `set_midi_rack_mapping` | `index, min?, max?, curve?` | ok |++Changes to existing tools:++- `list_midi_fx_kinds` lists kind 6 "Nota MIDI Effect Rack"; `add_midi_fx` accepts it.+- `set_rack_glide` description: audible only with mono on; new `set_rack_mono(trackId, on)`.+- `get_rack` / `get_effect_rack` gain `mono` (Instrument) and per-macro `curve` incl.+ `"mixed"`; new `set_macro_curve(trackId, deviceIndex, macro, curve)` and+ `set_mapping_range(…)` for Instrument/Audio racks so the Macros tab is fully scriptable.+- `add_macro_mapping` / `add_effect_rack_mapping` accept `deviceIndex = −3` (selector,+ Audio Effect Rack) and move an existing mapping of the same param.++Instrument Rack chain MIDI effects (issue #329), in `RackTools`:++| Tool | Arguments | Result |+|---|---|---|+| `add_rack_chain_midi_fx` | `trackId, chain, kind (0–5)` | index in the chain's MIDI section |+| `remove_rack_chain_midi_fx` | `trackId, chain, index` | ok |+| `move_rack_chain_midi_fx` | `trackId, chain, from, to` | ok |+| `get_rack_chain_midi_fx_params` | `trackId, chain, index` | `[{ index, name, min, max, value }]` |+| `set_rack_chain_midi_fx_param` | `trackId, chain, index, param, value` | ok |+| `set_rack_chain_midi_fx_bypass` | `trackId, chain, index, bypassed` | ok |++`get_rack` lists each chain's `midiEffects: [{ index, kind, name, bypassed }]`;+`add_macro_mapping` takes `midiFx: index` as an alternative to `deviceIndex`.++AI golden tests (`tests/Nota.SmokeTest/AiGoldenTests.cs`) gain a MIDI-rack scenario.diff --git a/specs/040-racks-redesign/contracts/ui-rack-card.md b/specs/040-racks-redesign/contracts/ui-rack-card.mdnew file mode 100644index 00000000..63c3f547--- /dev/null+++ b/specs/040-racks-redesign/contracts/ui-rack-card.md@@ -0,0 +1,87 @@+# Contract: the shared rack card (UI)++Source of layout: `nota-design/Nota Racks.html`, frames 1a–1f. Source of colour, type,+geometry, header and icons: `DESIGN.md` + `Theme/Themes/*.json` (they win any conflict).++## Frame++- Standard device card, `DeviceCardKit.CardH` tall, 700 wide, inside `BuildCardShell`:+ name · preset picker (when the rack has presets) · type badge "Rack" · power switch.+ Fold and A/B: where the shell already offers them (right-click menu / fold strip).+- Body (inset `NotaSpace.DeviceInset`), three columns + status line:++| Region | Width | Content |+|---|---|---|+| Macro column | ~116 | Section title "Macros", Map key (on = accent key; mapping in progress), 2 × 4 macro cells: `Knob` 22 px, name, value (mono, "—" when unmapped), target-count badge (teal wash) |+| Centre | fill | Tab strip (`segmented`): Chains · Zones (Audio: Select) · Macros, right-aligned mono summary; tab body |+| Right panel | ~160 | Tab strip: Chain · Rack out (MIDI: Output); panel body |+| Status line | 18 | One `Caption` line, left aligned; nothing on the right |++Columns are `DeviceCardKit.Section`s (rule on the facing edge), not framed boxes.++## Chains tab++- Chain list (124): rows 34 px — colour stripe (chain palette colour), name (accent ink+ when chosen), M / S keys (`Mute` / `Solo` fills + `InkOn` when on), summary (mono:+ `C-1–A#4 · v96+` / `sel 0–63` / `2 devices`), level bar (green safe range of the meter+ scale; MIDI: activity). Chosen row: accent seam + `Wash(Accent)`. "+ Chain" dashed key;+ one `Caption` hint at the bottom ("Drop an instrument to add a layer." /+ "Drop an effect to add a chain." / "Drop MIDI effects here.").+- Device strip: chosen chain's devices left → right; for Instrument Rack chains in three+ sections — MIDI effects (own dashed drop target, "MIDI" kind badge) · instrument · audio+ effects (issue #329); MIDI effects drag only within their section. 96 wide compact cards (power dot,+ name, kind badge, up to three key params as `SliderTrack` rows with mono values,+ "Open" + `Glyph.Grip`), chevron glyphs between cards, a dashed drop target at the end.+- While mapping: params of every compact card show a teal dashed (not mapped to this+ macro) or teal solid (mapped to it) frame, the cursor is "copy", the card scrolls through+ all params; a header line under the tabs reads "Mapping · Macro N · Name — click to add+ or remove". Resting slider fill = `VizInk`; mapped param = teal fill + "M n" tag.++## Zones / Select tab++- Ruler: Instrument/MIDI — note names at C0, C2, C4, C6, C8; Audio — 0, 32, 64, 96, 127.+- One 24 px row per chain: name, key-zone bar with drag edges (whole notes), velocity-zone+ bar (Instrument/MIDI); Audio: select-range bar. MIDI: an extra Selector row on top+ (and per-chain select bars) — shown inactive (next ink step) outside Select mode.+- Hover probe (Instrument/MIDI): 1 px teal line at the hovered key on every row; chains+ that would play at velocity 100 get a teal wash and teal name. Footer: hint left,+ result right (`C4 · vel 100 → Volt + Pentad` / `nothing`; Audio: `selector 30 → Crunch`).++## Macros tab++- Header: slot ("Macro 1"), name (double-click rename), value (mono), curve segmented+ Lin · Exp · Log · S (no key chosen = Mixed, with a "Mixed" caption), 30 × 22 curve+ preview via `NotaGraph` (VizInk curve, accent dot at the current value; Mixed → no+ curve, "Mixed" text), Map key.+- Rows: colour stripe, `chain › device ›` + param name, range bar (150) with min/max+ handles and a current-position marker, range text in the param's units, unmap+ (`Glyph.Close`). Empty state: one Ink-5 line.++## Right panel++- Chain: colour dot, name (double-click rename), "n / N"; Volume (dB; MIDI: velocity %),+ Pan (L/C/R; MIDI: Transpose, st), Keys / Vel or Select rows (click → Zones/Select tab),+ Duplicate · Delete (Delete disabled with one chain).+- Rack out — Instrument: Volume, Glide, switch "Mono (last note)". Audio: "Chains run"+ Parallel · Serial · Select + one-line explanation, Dry/wet, Gain, switch "Latency+ compensation". MIDI (Output): "Chains run" Parallel · Select + explanation, switches+ "Merge duplicate notes", "Pass through outside zones".++## Interaction contract++- All value controls: `Knob` / `SliderTrack` contract (no jump on click, double-click+ default, fine modifier, `GestureBegin/End` automation write, `MidiLearn.Bind`,+ live-follow skips while dragging).+- Esc ends mapping (registered shortcut). Switching away from Chains ends mapping.+- Drag-and-drop from the Browser: allowed kinds per rack (research D11); refused drops+ show a tooltip. Device reorder by `Grip` drag inside a chain.+- Theme switch recolours the card without a rebuild-induced state loss (tabs, chosen chain+ and macro persist).++## Labels (sentence case)++"Macros", "Map", "Chains", "Zones", "Select", "Chain", "Rack out", "Output", "Volume",+"Pan", "Transpose", "Keys", "Vel", "Duplicate", "Delete", "+ Chain", "Chains run",+"Parallel", "Serial", "Dry/wet", "Gain", "Glide", "Mono (last note)", "Latency+compensation", "Merge duplicate notes", "Pass through outside zones", "Curve", "Lin",+"Exp", "Log", "S", "Mixed", "Target", "Range", "Selector", "Open".diff --git a/specs/040-racks-redesign/data-model.md b/specs/040-racks-redesign/data-model.mdnew file mode 100644index 00000000..5b32f5c6--- /dev/null+++ b/specs/040-racks-redesign/data-model.md@@ -0,0 +1,98 @@+# Data Model: Racks redesign and MIDI Effect Rack++**Spec**: [spec.md](spec.md) · **Research**: [research.md](research.md)++Engine-side data lives in `RackCore` (`src/native/nota.engine/src/devices/racks/`) and+is persisted as the rack blob; view-side data lives in the card and is never saved.+**New** marks what this feature adds.++## Rack (engine)++| Field | Type / range | Kinds | Notes |+|---|---|---|---|+| kind | Instrument 3 (instrument) · Audio Effect 5 (device) · **MIDI Effect 6 (MIDI effect, new)** | all | Drum Rack (instrument kind 4) unchanged |+| chains | ordered list of Chain | all | MIDI: max 16 (**new limit**) |+| macros[8] | value 0–1, name (empty = "Macro N") | all | |+| mappings | list of MacroMapping | all | |+| volume | 0–4 linear | Instrument (rack out), Audio (gain) | existing |+| glide | 0–1 (→ 0–500 ms) | Instrument | **now applied** in mono mode (research D4) |+| **mono** | bool, default off | Instrument | last-note priority, chains share one voice |+| mode | Instrument: n/a · Audio: 0 Parallel, 1 Serial, 2 Select · **MIDI: 0 Parallel, 2 Select** | Audio, MIDI | MIDI reuses the same field; Serial (1) is refused for MIDI |+| dryWet | 0–1 | Audio | existing |+| pdc | bool | Audio | existing |+| chainSelect | 0–1 (UI shows 0–127) | Audio, **MIDI** | macro-mappable (existing target for Audio; **new** for MIDI) |+| selFollow | bool | Audio | existing, kept, not shown in the new card |+| **merge** | bool, default on | MIDI | merge duplicate output notes |+| **thru** | bool, default on | MIDI | pass notes outside every zone |+| bypassed | bool | all | the card's power switch |++## Chain++| Field | Type / range | Kinds | Notes |+|---|---|---|---|+| name | string (empty = first device's name) | all | existing (v8) |+| instrument | Instrument or none | Instrument | existing |+| devices | ordered audio Devices | Instrument, Audio | existing |+| **midiDevices** | ordered MidiDevices (kinds 0–5) | MIDI, **Instrument (issue #329)** | new; Instrument chains run MIDI effects → instrument → audio effects |+| gain | 0–4 linear | Instrument, Audio | existing |+| **velScale** | 0–2, default 1 | MIDI | the MIDI chain's "Volume" (FR-023a); 0 = sends nothing |+| pan | −1…+1 | Instrument, Audio | existing |+| **transpose** | −48…+48 semitones, default 0 | MIDI | output pitch clamped 0–127 |+| mute, solo | bool | all | existing |+| keyLo, keyHi | 0–127, lo ≤ hi | Instrument, MIDI | existing |+| velLo, velHi | 0–127, lo ≤ hi | Instrument, MIDI = velocity zone · **Audio = select range** | Audio meaning unchanged (research D2) |+| **selLo, selHi** | 0–127, lo ≤ hi, default 0–127 | MIDI | select range |+| meter | 0–1 peak, read-only | Instrument, Audio | MIDI: activity level (note-ons in the last ~100 ms, decays) |+| colour | palette index = chain index (view) | all | derived, not stored |++Validation: lo ≤ hi enforced on set (an edge cannot cross the other); all integer ranges+clamped.++## MacroMapping++| Field | Type | Notes |+|---|---|---|+| macro | 0–7 | |+| chainIndex | ≥ 0 | |+| deviceIndex | −1 instrument · ≥ 0 audio device (`devices`) · −2 pad controls (Drum) · **−3 rack control (new)** · **≤ −1000: chain MIDI device j = −1000 − j (new, all rack kinds)** | the `nota_midirack_*` ABI and MCP tools take plain indices and translate |+| paramIndex | ≥ 0 | for −3: 0 = selector |+| rangeMin, rangeMax | target units; min > max inverts | |+| curve | 0 Lin · 1 Exp · 2 Log · 3 S | kept per mapping (research D5) |++Rules: a (chain, device, param) triple belongs to at most one macro — adding a mapping+for a triple already mapped elsewhere moves it (one undo step). Deleting a chain or device+removes its mappings and re-indexes the rest.++*Selector as macro target*: today the selector cannot be mapped to a macro (it is set by+hand or follows the input level). The plan adds a rack-control mapping target+(`deviceIndex = −3`, param 0 = selector) so Audio and MIDI racks map it the same way+(FR-018). `applyMacro` writes `chainSelect` for it. Old projects have no such mappings.++## Blob versions++- **v8** (current): unchanged on read.+- **v9** (new): appends per chain `selLo, selHi, transpose, velScale, midiDeviceCount,+ { kind, paramCount, params[], stateSize, state[], bypassed }`, and per rack `mono,+ merge, thru`. Readers of v ≤ 8 use the defaults above.++## Project file++- `MidiDeviceDto.State` (**new**, optional blob reference): written when the MIDI effect's+ state blob is non-empty (the MIDI rack always; other MIDI effects stay params-only).+- Project format version +1; files without `State` load unchanged.++## View state (not persisted)++Per rack card instance, kept across rebuilds in the card's state object:++| Field | Values |+|---|---|+| centreTab | Chains · Zones/Select · Macros |+| rightTab | Chain · Rack out (MIDI: Output) |+| selectedChain | index (clamped after delete) |+| selectedMacro | 0–7 |+| mappingMacro | none or 0–7 (mapping on) |+| probePitch | none or 0–127 (hover) |++State transitions for mapping: `off → on(m)` by Map; `on(m) → on(m')` by selecting+macro m'; `on → off` by Map, Esc, or switching the centre tab away from Chains.diff --git a/specs/040-racks-redesign/plan.md b/specs/040-racks-redesign/plan.mdnew file mode 100644index 00000000..d0ffcb20--- /dev/null+++ b/specs/040-racks-redesign/plan.md@@ -0,0 +1,164 @@+# Implementation Plan: Racks redesign and MIDI Effect Rack++**Branch**: `040-racks-redesign` | **Date**: 2026-10-26 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `/specs/040-racks-redesign/spec.md`++## Summary++Rebuild the Instrument Rack and Audio Effect Rack cards as one shared card from+`nota-design/Nota Racks.html` (macro column · Chains / Zones-or-Select / Macros tabs ·+Chain / Rack out panel · status line). Mapping happens in place (no separate map view).+Add a new **MIDI Effect Rack**: a MIDI effect (kind 6) whose chains of built-in MIDI effects+take notes by key, velocity and select zones, and whose outputs merge into the+instrument. The engine reuses `RackCore` (snapshots, macros, per-target curves, blob,+undo-by-fork). It adds MIDI chains, a separate select range, chain transpose and velocity+scale, merge and thru, and a selector as macro target. The Instrument Rack gets mono plus+a glide that works. Its chains can also hold MIDI effects, running MIDI effects →+instrument → audio effects like a track ([nota-daw/nota#329](https://github.com/nota-daw/nota/issues/329)).+The rack does this through a new block-render hook on `Instrument`, so timing stays+sample-accurate (research D15). Everything is drawn from Studio tokens, so all four themes work and+recolour live (research D1–D14).++## Nota: Read Before Planning++Consult the matching source of truth before designing:++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): the AR rules table is binding (AR-4 lock-free queue, AR-5 immutable snapshots, AR-6 audio-thread restrictions, AR-7 pure C ABI, AR-9 `Transport` is the only source of musical time).+- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Studio design language) and the `nota-design` skill.+- **A built-in instrument / audio or MIDI effect** → the `nota-instrument` skill (DSP class, kind registration across C++ and C#, device-card UI).+- **Build / packaging** → [`BUILD.md`](../../BUILD.md).+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md): licensing, dependency policy, PR expectations.++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 + Avalonia 12 (app, MCP)++**Primary Dependencies**: none new (Avalonia, existing engine code; JUCE untouched, plug-ins not hosted in MIDI racks)++**Storage**: project file (`MidiDeviceDto.State` blob ref, format version +1); rack blob v9; user presets for kind 6++**Audio-Thread Impact**: `playEvents` gains one virtual check per block: instruments that render block events themselves (an Instrument Rack whose chains hold MIDI effects) take the whole block. In that case the rack runs each chain's MIDI effects and segment-renders that chain on member scratch (2 × 1024 events), with no allocation. New `MidiRack::process` runs on the audio thread inside the track's MIDI chain. It uses only member-preallocated buffers (16 chains × 2 × 1024 events, plus 128-entry routing and merge tables): no allocation, locks or I/O (AR-6). Structural edits publish a new `RackState` snapshot via `SnapshotHistory` (AR-5). Values are relaxed atomics on `ChainControls` (AR-4 pattern as existing racks). Instrument Rack mono/glide uses a fixed 128-entry note stack and block-rate `noteExpression` bend ramps.++**Testing**: `tests/Nota.SmokeTest` (engine through the C ABI, MCP, design guards), headless Avalonia captures for UI/themes (quickstart Q4–Q5)++**Target Platform**: macOS, Windows, Linux desktop++**Project Type**: desktop app (native engine + managed UI)++**Performance Goals**: a 3-chain MIDI rack adds no audible latency (same block, sample-accurate offsets kept); no xruns at 64-sample buffers; card rebuild on edit stays within one frame for interaction feedback++**Constraints**: real-time safe; existing projects with Instrument / Audio Effect racks load and sound identical; zero new design allow-list entries++**Scale/Scope**: 3 rack kinds share one card; 6 MIDI effect kinds in MIDI chains; ~40 rack-eligible device kinds need a key-param entry; ~25 new ABI calls; ~22 new MCP tools++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*++| Principle | Status | How |+|---|---|---|+| I. Real-time audio safety | Pass | Preallocated members, snapshot swap for structure, atomics for values, no allocation in `MidiRack::process`, mono/glide or the chain MIDI-effect path (research D3, D4, D15); perf gate run for the `playEvents` hook |+| II. Boundary discipline | Pass | New calls are plain C in `nota_engine.h` ([contracts/c-abi.md](contracts/c-abi.md)); no C++ types cross; JUCE untouched |+| III. Licensing hygiene | Pass | New files carry the SPDX header; no new dependency |+| IV. Verification gate | Pass | Smoke test extended: routing, stuck notes, persistence, mono/glide, mapping rules, v8 compatibility, key params, design guards (quickstart Q2) |+| V. One logical change per PR | Watch | Deliver as a stack of PRs in task order: (1) engine core + ABI + tests, (2) managed access + MCP + persistence, (3) shared card + themes, (4) docs. Each builds and passes on its own |+| VI. Docs in sync | Pass | CHANGELOG `[Unreleased]`, `nota-features`, `nota-docs` (EN + RU rack pages, new MIDI rack page, screenshots), `nota-shortcuts` (Esc ends mapping) |+| VII. Spec-first | Pass | spec + clarifications + this plan; tasks next |+| VIII. Rules not weakened | Pass | No allow-list growth, no audio-thread exceptions |++*Post-design re-check (after Phase 1)*: still passing. The design adds no global state and+no new thread. The only shared-format change is the backward-compatible blob v9.++## Project Structure++### Documentation (this feature)++```text+specs/040-racks-redesign/+├── plan.md # this file+├── research.md # Phase 0: findings + decisions D1–D14+├── data-model.md # Phase 1: rack / chain / mapping fields, blob v9, view state+├── quickstart.md # Phase 1: validation runs+├── contracts/+│ ├── c-abi.md # new C ABI+│ ├── mcp-tools.md # new / changed MCP tools+│ └── ui-rack-card.md # the shared card's layout, interaction and labels+├── checklists/requirements.md+└── tasks.md # Phase 2 (/speckit-tasks)+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # + midi_effect state, nota_midirack_*, nota_rack_set_mono, selector target+├── src/devices/racks/+│ ├── RackCore.h/.cpp # RackChain.midiDevices; ChainControls sel/transpose/velScale;+│ │ # mono/merge/thru; mapping target −3; move-on-add; blob v9+│ ├── RackInstrument.h/.cpp # mono note stack + glide via per-note bend;+│ │ # renderBlock: per-chain MIDI FX → instrument → FX (#329)+│ ├── RackDevice.cpp # selector mapping target (−3)+│ └── MidiRack.h/.cpp # NEW: MidiDevice + RackCore, routing/merge/thru (kind 6)+├── src/devices/Instrument.h # rendersBlockEvents/renderBlock, midiReset/midiTimeJump hooks (#329)+├── src/devices/DeviceFactory.cpp # makeMidiDevice(6)+├── src/engine/Engine_Rack.cpp, Engine.h # midiRackAt / midiRackForEdit (fork for undo), rack ops+├── src/engine/Engine_Devices.cpp # MIDI effect state get/set, clone path+├── src/engine/Engine_Render.cpp # playEvents → renderBlock hook; reset/loop-wrap fan-out to rack chains+└── src/abi/nota_engine_rack.cpp, nota_engine_device.cpp # new C entry points++src/managed/+├── Nota.Application/Engine/IAudioEngine.cs # + MidiRack*, MidiEffectGet/SetState, RackSetMono, curves+├── Nota.Presentation/Racks/RackKeyParams.cs # NEW: curated ≤3 key params per kind, by name (UI-free, smoke-tested)+├── Nota.Application/Palette/BuiltinDeviceCatalog.cs, DeviceCategories.cs # "Nota MIDI Effect Rack" (MIDI · Racks)+├── Nota.Infrastructure/Interop/NativeMethods.MidiRack.cs, NotaEngine.MidiRack.cs # NEW P/Invoke + wrapper+├── Nota.Infrastructure/Persistence/ProjectModel.cs, ProjectService.cs, PresetService.cs # MidiDeviceDto.State, format +1, presets+├── Nota.Mcp/Tools/MidiRackTools.cs # NEW; RackTools / EffectRackTools / MidiFxTools updated+└── Nota.App/+ ├── DeviceCards/Rack/+ │ ├── IRackAccess.cs # extended surface + MidiRackAccess+ │ ├── RackKindProfile.cs # NEW: per-kind labels, zones, modes, rack-out rows, drop rules+ │ ├── RackCard.cs # NEW: shared card shell parts + view state+ │ ├── RackCard.Macros.cs / .Chains.cs / .Zones.cs / .MacroTab.cs / .RightPanel.cs # NEW parts+ │ ├── RackCardView.cs # Ir*/Ae*/macro-map builders removed; entry points delegate to RackCard+ │ └── RackCardView.Drum.cs, MacroPanel.cs # Drum Rack: compile fixes only+ ├── DeviceChainView.Midi.cs # kind 6 → RackCard inside BuildCardShell+ └── (shortcut registration for Esc-ends-mapping)++tests/Nota.SmokeTest/+├── MidiRackTests.cs # NEW: routing, stuck notes, persistence, MCP+├── RackRedesignTests.cs # NEW: mono/glide, mapping rules, v8 fixtures, key params+├── RackChainMidiTests.cs # NEW (#329): chain Arp timing = track Arp, zones before MIDI FX, persistence, copy, undo, MCP+├── Fixtures/racks-v8/*.bin # NEW: saved v8 blobs (Instrument + Audio racks)+└── Program.cs # wire sections++CHANGELOG.md, FEATURES.md, ../nota-docs (EN + RU)+```++**Structure Decision**: Engine work stays in `devices/racks/` next to the existing racks+(one new class). Managed work stays in `DeviceCards/Rack/`, split into partial files by+card region so no file grows past the current 1.8 k-line `RackCardView.cs`. MCP gets a+new tool class like the existing per-device tool files.++## Phases (for /speckit-tasks)++1. **Engine core**: `RackCore` fields + blob v9 + mapping move/selector target; `MidiRack`;+ factory; Instrument Rack mono/glide; chain MIDI effects in Instrument Racks (`renderBlock`+ hook, reset/loop fan-out, ABI `nota_rack_chain_midi_*`) → US6, FR-030/032/034; Engine fork-for-edit for MIDI racks; ABI; smoke tests+ (routing, stuck notes, persistence, v8 fixtures). → US4 engine, FR-019, FR-026, FR-029.+2. **Managed plumbing**: interop, `IAudioEngine`, persistence (`State`, format bump),+ presets, catalog/Browser entry, MCP tools (MIDI rack + rack chain MIDI effects) + AI golden+ scenario. → US4, US6, FR-022, FR-025, FR-034.+3. **Shared card**: `RackKindProfile`, `RackKeyParams` (+ test), `RackCard` parts (macros,+ chains + in-place mapping, zones/select + probe, macros tab + Mixed, right panel, status+ line), Instrument chain strip with a MIDI section + drop/Add-menu rules, wire Instrument /+ Audio / MIDI entry points, remove old builders, Esc shortcut. → US1, US2, US3, US4, US6 UI+ (FR-031, FR-033).+4. **Themes + guards**: design-guard run with no allow-list growth, headless 4-theme+ captures, live-switch check. → US5, SC-003.+5. **Docs**: CHANGELOG, FEATURES (`nota-features`), user docs EN + RU + screenshots+ (`nota-docs`), Shortcuts (`nota-shortcuts`).++## Complexity Tracking++No constitution violations to justify.diff --git a/specs/040-racks-redesign/quickstart.md b/specs/040-racks-redesign/quickstart.mdnew file mode 100644index 00000000..94fe7472--- /dev/null+++ b/specs/040-racks-redesign/quickstart.md@@ -0,0 +1,106 @@+# Quickstart: validating the racks redesign++Runnable checks that prove the feature end to end. Contracts:+[c-abi.md](contracts/c-abi.md) · [mcp-tools.md](contracts/mcp-tools.md) ·+[ui-rack-card.md](contracts/ui-rack-card.md); entities: [data-model.md](data-model.md).++## Prerequisites++- macOS dev setup per `BUILD.md`; the engine in `build/` is a Release build.+- Scratch data dir for anything that starts App services: `NOTA_DATA_DIR=/tmp/nota-racks`.++## Q1 — Full gate++```bash+scripts/build.sh+```++Expect green: native + managed build, the smoke test (incl. the new MIDI-rack, mono/glide,+mapping and design checks below) passes.++## Q2 — Smoke test only (faster loop)++```bash+dotnet run --project tests/Nota.SmokeTest -c Release --nologo+```++New sections it must print as passing:++| Section | Proves |+|---|---|+| `racks: midi rack routing` | zones, velocity zones, Parallel vs Select (selector), mute/solo, transpose, velocity scale (100 % / 50 % / 0 %), merge on/off, thru on/off — notes in → notes out compared to an expected list (US4, FR-021–023a) |+| `racks: midi rack no stuck notes` | 1 000 random note-on/off interleaved with zone / mode / mute / transpose edits and chain deletes; at the end the instrument holds no notes (SC-005, FR-026) |+| `racks: midi rack persistence` | state blob → new rack → identical `get_midi_rack`; save/reopen project; undo/redo of each structural edit; preset save/load (SC-006) |+| `racks: instrument mono/glide` | mono on: one voice at a time, last-note priority; glide: per-note bend ramps from Δ to 0 over the glide time on an MPE synth; poly mode unchanged |+| `racks: mapping rules` | adding a mapping of an already-mapped param moves it; curve "Mixed" detection; set curve on a macro updates every target; selector target (−3) drives `chainSelect` |+| `racks: v8 compatibility` | stored v8 blobs of an Instrument Rack and an Audio Effect Rack (fixtures) render bit-identical before/after (SC-004) |+| `racks: chain MIDI effects` (#329) | an Arp in an Instrument Rack chain produces the same note-ons (pitch, sample offset) as the same Arp on a track over 8 bars, incl. a loop wrap and a stop/start; zones and mono run before chain MIDI effects; the other chain is unaffected; save/reopen, rack preset, track duplicate, device copy/paste, undo/redo and `add_rack_chain_midi_fx` round-trip |+| `racks: key params table` | every rack-eligible instrument / audio effect / MIDI effect kind has ≤ 3 valid key-param indices |+| `design: studio / themes / labels / icons` | the new card passes with no new allow-list lines (SC-003) |++## Q3 — MCP walkthrough (US4 via the AI surface)++With the app running (or the MCP smoke harness, `McpTestSupport`):++1. `add_instrument_track` → `add_midi_fx(kind=6)` → `get_midi_rack` shows one chain.+2. `add_midi_rack_chain` ×2; `add_midi_rack_chain_device(0, 0)` (Arp), `(1, 1)` (Chord),+ `(2, 5)` (Random).+3. `set_midi_rack_chain_zone(0, keyLo="C3")`, `(1, keyHi="B2")`, `(2, velLo=110)`.+4. Play notes C2, C4 @100, E4 @120 → chain 1 only, chain 0 only, chains 0 + 2.+5. `set_midi_rack_mode("select")`, `set_midi_rack_chain_zone(0, selLo=0, selHi=63)`,+ `set_midi_rack_selector(100)` → chain 0 receives nothing.+6. `save_version` / reopen → `get_midi_rack` unchanged.++## Q4 — UI flows (headless harness)++Use the headless Avalonia harness pattern (see the `nota-design` skill and the project's+UI-verify notes): a throwaway console project referencing `Nota.App`, a `DeviceChainView`+in a `Window`, synthetic pointer events, `CaptureRenderedFrame()`.++For each rack (Instrument with 3 chains, Audio Effect with 2, MIDI Effect with 3):++1. Chains tab: click chain rows → chosen chain changes, devices update, Chain panel follows.+2. Select Macro 2 → Map → click a param in a compact card → badge count +1, param shows+ "M2"; click it again → removed; press Esc → mapping ends.+3. Macros tab: drag a target's max below its min → readout inverts; pick Exp → preview and+ all targets update; on a project fixture with mixed curves the segmented shows "Mixed".+4. Zones (Select) tab: drag a key edge → label updates in note names; hover → probe line ++ footer names the chains.+5. Chain panel: Duplicate → new chain after the chosen one; Delete → mappings of that chain+ are gone; with one chain Delete is disabled.+6. Rack out: Instrument mono switch; Audio Parallel/Serial/Select explanation text; MIDI+ merge / thru switches.++## Q4b — Instrument Rack chain MIDI effects (US6, #329)++1. Two-chain Instrument Rack (Volt, Pentad). Drag Nota Arp from the Browser onto chain 1's+ strip → it lands in the MIDI section before Volt; drag Nota Chord onto the instrument+ slot → it also lands in the MIDI section.+2. Hold a C-major chord: chain 1 arpeggiates, chain 2 sustains.+3. Map Arp Rate to Macro 1 (Map → click the Arp's Rate in its compact card) → turning+ Macro 1 changes the rate.+4. Save as rack preset, load it on a new track → MIDI effects come back.++## Q4c — Perf gate (the `playEvents` hook)++```bash+scripts/perf-gate.sh develop+```++Expect no regression on the existing scenarios (CI runs the same check on the PR).++## Q5 — Themes (US5)++Capture every rack × centre tab × right tab in Studio Dark, Studio Light, Ember Graphite+and Ember Paper (switch with the reflected `NotaThemeService.Set(new AppearanceChoice(…))`),+then switch theme **while** the card is open and capture again without rebuilding.+Expect: no fixed dark surfaces in light themes, legible text (DESIGN.md readability bar),+accent only on the chosen chain / macro / tab, active switches and touched controls.+Attach the 4 × 3 sheet to the PR (before/after, `nota-pr` skill).++## Q6 — Compatibility (FR-029)++Open a project saved on `develop` before this change that has an Instrument Rack (with+zones, macros, per-target curves that differ within a macro) and an Audio Effect Rack in+Select mode. Expect identical sound (Q2 v8 section) and the Macros tab showing "Mixed" for+the mixed macro.diff --git a/specs/040-racks-redesign/research.md b/specs/040-racks-redesign/research.mdnew file mode 100644index 00000000..a8a09901--- /dev/null+++ b/specs/040-racks-redesign/research.md@@ -0,0 +1,279 @@+# Research: Racks redesign and MIDI Effect Rack++**Feature**: [spec.md](spec.md) · **Plan**: [plan.md](plan.md) · **Date**: 2026-10-26++What the code does today, and the decisions this plan takes. Each decision lists what it+was weighed against.++## Current state (findings)++- **Engine racks** (`src/native/nota.engine/src/devices/racks/`): `RackCore` holds an+ immutable `RackState` snapshot (chains + mappings) swapped through `SnapshotHistory`,+ 8 macros, per-mapping range and curve, chain controls as relaxed atomics+ (`ChainControls`: gain, pan, mute, solo, keyLo/keyHi, velLo/velHi, meter, drum-pad+ fields), rack-out values (volume, glide, mode, dry/wet, pdc, chainSelect, selFollow) and+ a shared blob format at **v8**. `RackInstrument` (kind 3) and `RackDevice` (audio kind+ 5) add the Instrument / Device interfaces; `DrumRack` derives from `RackInstrument`.+- **Undo for rack edits**: `Engine::rackForEdit` forks the rack (`RackCore::forkFrom`,+ children shared) and republishes the track, so the undo snapshot keeps the old rack (#236).+- **Audio Effect Rack Select mode reuses `velLo/velHi` as the chain's select range**+ (`RackDevice.cpp:73`). The MIDI rack needs both a velocity zone and a select range, so+ that reuse cannot carry over.+- **Glide is stored but does nothing** (`glide_` "stored/reserved"); the current card+ already shows a Glide slider. There is no mono mode.+- **Per-target curves** exist in the engine (`MacroMapping::curve`) and in the ABI+ (`set_mapping_curve`).+- **MIDI effects** are `MidiDevice`s (`MidiDevice.h`): `process(in, nIn, out, nOut,+ maxOut, frames, beatStart, spb, playing)`, `reset`, `timeJump`, generic float params,+ `getState/setState`, `clone`, bypass, fold. Kinds 0–5 (Arp, Chord, Scale, Length,+ Velocity, Random) built by `makeMidiDevice` (`DeviceFactory.cpp`). The track runs them in+ `Engine_Render.cpp` on a 1024-event stack scratch, then re-sorts.+- `Engine::cloneMidiDevice` already copies `getState()` blobs, so a stateful MIDI device+ survives track duplication, copy/paste and undo.+- **The ABI has no MIDI-effect state blob calls**; the project saves MIDI effects as+ kind + params (`MidiDeviceDto`), so a MIDI rack cannot be saved today.+- **Rack ABI** is two families: `nota_rack_*` (Instrument/Drum rack = the track's+ instrument) and `nota_rackdev_*` (Audio Effect Rack at an audio device index), plus+ structural calls; both resolve through `Engine::rackCoreAt(track, deviceIndex)`.+- **Managed card**: `DeviceCards/Rack/RackCardView.cs` (1806 lines) renders both racks+ through `IRackAccess` (`InstrumentRackAccess`, an effect-rack access), with a separate+ macro-map view (`InstrumentRackMacroMap`, Done button), Instrument-only and+ Audio-only layouts (`Ir*` / `Ae*` builders). `RackCardView.Drum.cs` and `MacroPanel.cs`+ serve the Drum Rack. Colours come from `NotaPalette` slots and `Wash` (no hex), but the+ labels are caps literals (`IrCap("RACK OUT")`, "GLIDE", "SPLIT").+- **MIDI effect cards**: `DeviceChainView.Midi.cs` wraps a body from+ `MidiDeviceCardFactory` in the shared `BuildCardShell` (`ChainKind.Midi`).+- **Catalog / Browser**: `BuiltinDeviceCatalog.cs` (MIDI kinds 0–5) and+ `DeviceCategories.cs` (MIDI tab: Generate, Shape).+- **MCP**: `RackTools.cs`, `EffectRackTools.cs`, `MidiFxTools.cs`.+- **Chain count**: the engine has no chain limit for Instrument / Audio racks.+- **Selector**: the Audio Effect Rack selector is set by hand or follows the input level+ (`selFollow`); it is not a macro target today. FR-018 needs a new rack-control mapping+ target (data-model: `deviceIndex = −3`).++## Decisions++### D1 — MIDI Effect Rack = `MidiDevice` + `RackCore`++- **Decision**: New `MidiRack : public MidiDevice, public RackCore` with `midiKind() == 6`,+ display name "Nota MIDI Effect Rack". `RackChain` gains+ `std::vector<std::shared_ptr<MidiDevice>> midiDevices` — used by MIDI rack chains (no+ instrument, no audio devices) and by Instrument Rack chains (issue #329, D15). Mappings+ address a chain MIDI device as `deviceIndex = kMidiDeviceBase − j` (`kMidiDeviceBase =+ −1000`) in every rack kind, so audio-device indices keep their meaning.+- **Rationale**: Reuses the snapshot swap, macros, mappings (with curves), names, blob+ format, `forkFrom` undo and the Drum/Instrument conventions; only routing is new.+- **Alternatives**: A standalone class duplicating `RackCore` (rejected: two copies of the+ macro/mapping/persistence machinery to keep in step). Templating `RackCore` on the child+ type (rejected: large churn in a shared, tested class for one new kind).++### D2 — Separate select range fields++- **Decision**: `ChainControls` gains `selLo/selHi` (0–127). The MIDI rack uses them for+ Select mode; the Audio Effect Rack keeps reading `velLo/velHi` as its select range so v8+ blobs and the existing ABI keep their meaning. The managed access layer exposes one+ "select range" call per rack kind and hides which fields back it.+- **Rationale**: Zero migration risk for existing Audio Effect Racks (FR-029).+- **Alternatives**: Migrate the Audio Effect Rack to `selLo/selHi` on load (rejected: a+ blob migration plus ABI semantics change for no user-visible gain).++### D3 — MIDI rack routing on the audio thread++- **Decision**: Per block, `MidiRack::process`:+ 1. Splits the sorted input: note-ons go to each chain that passes mute/solo, key zone,+ velocity zone and (Select mode) select range; the chain set is recorded per input+ pitch (`routeMask[128]`, one bit per chain) so the matching note-off goes to the same+ chains even if zones change in between (no stuck notes, FR-026).+ 2. Runs each chain's `midiDevices` in order on per-chain ping-pong buffers preallocated+ as members (`kMaxMidiChains = 16` chains × 2 × 1024 events) — no allocation (AR-6).+ 3. Applies chain transpose (−48…+48, clamped to 0–127) and velocity scale (0–2; 0 drops+ the chain's note-ons), tracking each chain's sounding output pitches in a 128-bit set.+ 4. Merges chain outputs: with *Merge duplicate notes* a per-pitch counter emits note-on+ only on 0→1 and note-off on 1→0; without it every event passes.+ 5. *Pass through outside zones*: input notes that reach no chain are forwarded unchanged+ (their pitch is recorded so the note-off follows).+ 6. Sorts the merged output (`midiEvLess`) and writes at most `maxOut`.+- **Snapshot change** (chain removed / reordered, mode or zone edit): on the first block+ that sees a new `RackState*`, the rack emits note-offs for output pitches held by chains+ that no longer exist and rebuilds `routeMask` indices by chain identity (the chain's+ `ctl` pointer), so surviving chains keep sounding.+- `reset()` / `timeJump()` fan out to every chain device and clear the rack's tables.+- **Rationale**: Mirrors how the engine already runs a MIDI chain; bounded memory; note+ bookkeeping is per pitch, independent of chain internals (an Arp's generated notes are+ tracked on its output side).+- **Alternatives**: Cutting all held notes on any edit (rejected: an edit during playback+ would chop sustained notes); unbounded chains (rejected: needs allocation on the audio+ thread or unbounded member memory).++### D4 — Mono (last note) and real glide for the Instrument Rack++- **Decision**: `RackInstrument` gains `mono_` (blob v9). With mono on, the rack keeps a+ note stack (fixed 128 array); a new note-on releases the sounding pitch in every chain+ and starts the new one; releasing the top note returns to the previous held note.+ Glide (0–1 → 0–500 ms, the current UI scale) applies in mono mode: the new note starts+ with a per-note `ExprBend` equal to *previous − new* semitones and the rack ramps it to 0+ over the glide time at block rate through `noteExpression` (the instruments smooth it per+ sample, see `NoteExpression.h`). Chains whose instrument does not support MPE+ (`supportsMpe() == false`) retrigger without the glide. Glide has no effect in poly mode;+ the Glide row says so in its tooltip. Mono runs on the notes entering the rack, before+ any chain MIDI effects (FR-032); glide applies only to chains without MIDI effects, since+ a chord or arp in front of the instrument makes the previous pitch undefined.+- **Rationale**: Makes the existing Glide control do what it says without per-instrument+ plumbing; almost every built-in synth (Synth, Volt, Aurora, Operator, Physical, Pentad,+ Keys, Mosaic) takes per-note bend.+- **Alternatives**: Dropping Glide from Rack out (rejected: it is in the design and in+ saved projects); driving each instrument's own glide parameter (rejected: kind-specific+ coupling, and several instruments have none).++### D5 — Per-target curves, macro shows "Mixed"++- **Decision** (Clarification 2026-10-26): curves stay per mapping. The UI derives the+ macro's curve: all targets equal → that curve; otherwise **Mixed**. Picking a curve calls+ `set_mapping_curve` for every target of that macro (one undo step). A target added to a+ Mixed macro gets Lin; to a uniform macro it gets that curve.+- **Alternatives**: Per-macro curve in the engine (rejected by the user: changes old projects).++### D6 — Selected chain and UI-only state stay in the view++- **Decision**: Selected chain, selected macro, active tab, right-panel tab, mapping on/off+ and probe position are view state (per rack, kept in the card's state object across+ rebuilds), not engine or project data — as today's `_splitAxis` / `_macroMapMode`.+- **Rationale**: No ABI or file-format change for pure presentation.++### D7 — One card for three racks++- **Decision**: Replace the `Ir*` / `Ae*` / macro-map builders with one `RackCard` built+ from small parts (macro column, centre tabs: Chains / Zones-or-Select / Macros; right+ panel: Chain / Rack out; status line), parameterised by a `RackKindProfile` (labels,+ which zone rows exist, routing modes, rack-out rows, which device kinds may be dropped).+ `IRackAccess` gains the calls the new parts need (select range, mode, rack-out values,+ MIDI transpose / velocity scale, mapping curve) and a third implementation,+ `MidiRackAccess`. The Drum Rack card (`RackCardView.Drum.cs`, `MacroPanel.cs`) is not+ touched beyond compile fixes.+- **Shell**: the card body sits in `BuildCardShell` (name · preset · type badge · power).+ The mockup's Bypass / Fold / A/B are not rebuilt: power switch = bypass; fold and A/B+ stay in the shell's existing places. The status line is the bottom 18 px of the body.+- **Rationale**: FR-001 (shared layout), FR-002, DESIGN.md "never build a header of your own".++### D8 — Compact device cards: curated key parameters++- **Decision** (Clarification 2026-10-26): a static table `RackKeyParams` maps+ (device family, kind) → up to three parameter indices, covering every instrument,+ audio effect and MIDI effect that can live in a rack; a kind missing from the table falls+ back to its first three parameters. While mapping, the compact card shows a scrollable+ list of all parameters. A smoke test asserts every rack-eligible kind has an entry+ whose indices are in range.+- **Alternatives**: first-three only (rejected by the user); user-chosen (rejected:+ needs new persisted state).++### D9 — Theme safety++- **Decision**: All colours from `NotaPalette` slots, `Wash`, `InkOn`, `Derived`; chain+ colours from a palette-index (`ArrangementView.TrackBrush(index)`-style lookup, read at+ render time) so they re-tint per theme; mapping marks use `NotaPalette.Teal` (a graph+ chroma allowed for modulation/mapping); selection = accent; Mute / Solo semantic fills+ with `InkOn`; resting slider fills `VizInk`; no `Opacity` (inactive = `Inactive.Set`);+ sentence-case labels via `NotaText.Label`; icons via `Glyph` (new `GlyphKind`s only if+ needed: e.g. drag handle, chevrons already exist — check before adding).+ Live theme switch is covered by `DynamicResource` / slot brushes; no brush is created+ from a `.Color` outside `Render`.+- **Verification**: `DesignTokenCheck` (`RunStudio`, `RunThemes`, `RunLabels`, `RunIcons`)+ with no new allow-list lines; headless renders of the three cards in all four themes+ (quickstart Q7).+- **Note**: `RackCardView.cs` currently passes the guards with caps literals routed through+ `IrCap`; the new card must not carry that helper over.++### D10 — Persistence, presets, MCP++- **Decision**:+ - ABI: `nota_midi_effect_get_state` / `nota_midi_effect_set_state` (generic, any MIDI+ effect) + a `nota_midirack_*` family addressed by (track, MIDI effect index), mirroring+ `nota_rackdev_*`; structural calls (add/remove/move chain, add/remove/move chain+ device, mappings) also in that family. Details: [contracts/c-abi.md](contracts/c-abi.md).+ - Project: `MidiDeviceDto.State` (blob ref, optional) — written when the state is+ non-empty; older files without it load as before. Project format version bump.+ - Presets: a MIDI rack user preset stores its state blob (same path the Audio Effect+ Rack uses for kind 5).+ - Blob **v9**: per chain `selLo, selHi, transpose, velScale` and its `midiDevices`+ (kind, params, state, bypass); rack `mono`, `merge`, `thru`. v8 and older read with+ defaults (`selLo 0, selHi 127, transpose 0, velScale 1`, mono off, merge on, thru on).+ - MCP: `midi_rack_*` tools at parity with `RackTools` / `EffectRackTools`+ ([contracts/mcp-tools.md](contracts/mcp-tools.md)); `add_midi_fx` accepts kind 6.++### D11 — Device kinds allowed per rack++- Instrument Rack chain: built-in MIDI effects (kinds 0–5, issue #329) + one instrument+ (built-in or plug-in, as today) + audio effects. A dropped MIDI effect always lands in the+ chain's MIDI section.+- Audio Effect Rack chain: audio effects (built-in or plug-in, as today).+- MIDI Effect Rack chain: built-in MIDI effects kinds 0–5 only; no nested racks (kind 6+ refused), no plug-ins. Racks are not nested in any rack kind (unchanged).+- A refused drop shows a short tooltip on the drop target.++### D12 — Chain limit++- Instrument / Audio Effect Rack: unchanged (no engine limit).+- MIDI Effect Rack: 16 chains (D3 preallocation); "+ Chain", Duplicate and drops are+ disabled with a tooltip at the limit.++### D13 — Status line++- Left: the one-line summary (FR-008). Right: empty (Clarification 2026-10-26).++### D14 — Keyboard++- Esc ends mapping while the rack card has focus or mapping is on (registered with the+ app's shortcut layer so it doesn't swallow Esc elsewhere); added to Preferences →+ Shortcuts via the `nota-shortcuts` skill.++### D15 — MIDI effects inside Instrument Rack chains (issue #329)++- **Problem**: the engine feeds an instrument one note at a time between render segments+ (`playEvents` in `Engine_Render.cpp`, used by the arrangement, Session and live paths),+ but a `MidiDevice` needs the whole block's events with offsets and the block clock.+- **As built** (supersedes the hook below): `Instrument::takesBlockMidi()` / `blockMidi(evs, n,+ frames)` / `midiTimeJump(delta)`. `playEvents` hands the block's sorted events to the rack once,+ before its usual event-by-event loop; the rack routes them to its MIDI chains (zones, a route+ per held key shared across forks), runs each chain's MIDI effects with the clock from+ `setTransport`, and its `render` then plays each MIDI chain's output into that chain's+ instrument in sub-segments at the exact samples. Expression, live input and bypass stay on the+ existing path; `allNotesOff` flushes chain MIDI effects; the loop seam calls `midiTimeJump`.+ Mono and the sustain pedal act on the chains without MIDI effects. Verified bit-exact against+ the same Arp on a track across loop seams.+- **Decision (planned)**: a new optional `Instrument` hook,+ `virtual bool rendersBlockEvents() const` + `virtual void renderBlock(float* out, int32_t+ frames, const MidiEv* evs, int n, const ExprEv* xev, int xn, double beatStart, double spb,+ bool playing, LiveHook)`. `playEvents` calls it instead of its own segment loop when the+ instrument returns true. `RackInstrument` returns true when any chain has MIDI effects+ (checked on the live snapshot). In `renderBlock` the rack, per chain: filters the block's+ events by zone (mono first, D4), runs the chain's MIDI effects with the block clock (the+ same values `applyMidiEffects` gets), then renders the chain instrument with the same+ segment loop as `playEvents` (shared helper, no copy), runs its audio effects and sums.+ Chains without MIDI effects use the same path with an empty MIDI section. Expression+ events and the live-expression hook are delivered per chain as `playEvents` does.+- `reset()` / `timeJump()` from the engine's stop / seek / loop-wrap / slot-switch calls+ fan out to chain MIDI effects through new `Instrument::midiReset()` /+ `midiTimeJump(delta)` virtuals (no-ops by default), called next to the track's own MIDI+ chain calls.+- Buffers: per-chain event scratch is a rack member (2 × 1024 events, reused chain by+ chain) — no allocation (AR-6).+- Latency: none added; offsets stay sample-accurate.+- **Alternatives**: buffering notes inside the rack and running chain MIDI effects one+ block late (rejected: adds a block of latency and breaks Arp timing); moving chain MIDI+ effects into the track's pre-pass (rejected: the zones and mono would have to run in the+ engine, outside the rack).+- Drum Rack (derived from `RackInstrument`) keeps returning false and does not show MIDI+ sections (out of scope).++## Open risks++- `RackCardView.cs` is large; the rewrite lands the new card behind the same entry points+ (`BuildInstrumentRackBody`, `BuildEffectRackBody`) to keep `DeviceChainView` stable.+- Mono/glide changes how an Instrument Rack with mono on sounds; mono defaults off, so+ existing projects are unaffected.+- The MIDI rack's routing table assumes ≤ 1024 events per block per chain, the same cap+ the track's MIDI chain already uses.+- D15 touches `playEvents`, the hot path for every instrument: the hook is one virtual call+ per block, and the perf gate (`scripts/perf-gate.sh`, spec 034) must show no regression.+- Instrument Rack chains that run MIDI effects share the per-chain scratch sequentially;+ parallel per-chain rendering stays out of scope.diff --git a/specs/040-racks-redesign/spec.md b/specs/040-racks-redesign/spec.mdnew file mode 100644index 00000000..0a355052--- /dev/null+++ b/specs/040-racks-redesign/spec.md@@ -0,0 +1,323 @@+# Feature Specification: Racks redesign and MIDI Effect Rack++**Feature Branch**: `040-racks-redesign`++**Created**: 2026-10-26++**Status**: Draft++**Input**: User description: "Я обновил дизайн в nota-design, добавил Nota Racks.html. Нужно добавить Midi Effect Rack и обновить Instrument Rack / Audio Effect Rack. Важно, чтобы все текущие темы поддерживались." Design source: `nota-design/Nota Racks.html`, frames 1a–1f (1a–1b Instrument, 1c–1d Audio Effect, 1e–1f MIDI Effect). Also covers [nota-daw/nota#329](https://github.com/nota-daw/nota/issues/329) "Instrument Rack: chains can hold MIDI effects" (added 2026-10-26).++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++Main area: UI (the shared rack card), with an engine part for the new MIDI Effect Rack.++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++**Design translation.** The mockup is drawn in fixed hex colours of one dark look, with+caps-and-tracking labels, a 24 px header holding text "Fold", "Bypass" and an A/B switch,+and teal as a mapping colour. The app version keeps the mockup's layout, content and+interactions but is built from Nota's Studio rules: the shared device header (name ·+preset · badges · power), sentence-case labels, theme tokens only, the accent only for+what is live or chosen, resting values in the neutral value ink, Mute / Solo in their+semantic fills. A/B and fold stay where the shared header and the right-click menu+already put them.++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Layer and split instruments in the reworked Instrument Rack (Priority: P1)++A producer builds a layered keys patch: three chains (two synths and an electric piano),+each with its own effects. On the rack card they see every chain at once with its zone+summary and level, pick a chain to see its devices left to right with their main+parameters, and on the Zones tab drag key and velocity edges so the piano only answers hard+hits. Hovering over the keyboard strip tells them which chains a note would play.++**Why this priority**: The Instrument Rack is the most used rack; the new layout is the+heart of the design and is shared by all three racks, so it must exist first.++**Independent Test**: Open a project with an Instrument Rack of three chains, use the+Chains, Zones and Chain panels, and confirm every action changes the sound and is shown+in the card — no other story needed.++**Acceptance Scenarios**:++1. **Given** an Instrument Rack with three chains, **When** the user opens its card, **Then** the card shows the macro column, the Chains tab with one row per chain (colour stripe, name, mute, solo, key/velocity summary, live level) and the first chain's devices, and the Chain panel on the right.+2. **Given** the Chains tab, **When** the user clicks a chain row, **Then** that chain becomes the chosen one (marked as chosen), its devices appear in the centre and the Chain panel shows its volume, pan, key and velocity range.+3. **Given** the Zones tab, **When** the user drags the high edge of a chain's key zone, **Then** the zone follows the pointer in whole notes, the label shows the new range as note names, and notes above the new edge no longer reach that chain.+4. **Given** the Zones tab, **When** the user hovers over a key position, **Then** a probe line marks that key, the chains that would play it are highlighted, and the footer reads the note and the chains (or "nothing").+5. **Given** the Rack out panel, **When** the user changes volume or glide or turns on mono (last note), **Then** the rack's output follows, and with mono on all chains share one voice.+6. **Given** a chain is chosen, **When** the user presses Duplicate or Delete in the Chain panel, **Then** the chain is copied next to it (with its devices and settings) or removed, and macro mappings that pointed at a removed chain are removed with it.++---++### User Story 2 - Map macros directly in the chain (Priority: P1)++The producer wants one knob to brighten the patch. They select Macro 1, press Map, and the+parameters in the chain's device cards light up as mappable. Clicking a parameter maps it,+clicking again unmaps it. On the Macros tab they set each target's range (min above max+inverts) and the macro's response curve, and rename the macro. There is no separate map+screen and no Done button.++**Why this priority**: Macros are the reason to build a rack; the old separate map mode is+the main usability complaint the design fixes. Shared by all three racks.++**Independent Test**: In any rack, map two parameters to one macro, set ranges and a+curve, turn the macro, and confirm both parameters move within their ranges.++**Acceptance Scenarios**:++1. **Given** a rack card, **When** the user selects a macro and presses Map, **Then** the card switches to the Chains tab, the Map button shows it is on, and every mappable parameter in the visible devices is marked as a target (already mapped to this macro vs. not yet).+2. **Given** mapping is on, **When** the user clicks an unmapped parameter, **Then** it becomes a target of the selected macro with a default range around its current value, shows the macro's tag, and the macro's target-count badge goes up by one.+3. **Given** mapping is on and a parameter is mapped to another macro, **When** the user clicks it, **Then** it moves to the selected macro (a parameter belongs to at most one macro).+4. **Given** mapping is on, **When** the user clicks a parameter mapped to the selected macro, presses Map again, or presses Esc, **Then** respectively the parameter is unmapped, or mapping ends.+5. **Given** mapping is off and a parameter is mapped, **When** the user clicks it, **Then** the Macros tab opens on the macro that drives it; the parameter cannot be dragged by hand while mapped.+6. **Given** the Macros tab, **When** the user drags a target's min or max handle, **Then** the range and its readout (in the parameter's own units) follow, a marker shows where the macro currently drives the parameter, and min above max inverts the response.+7. **Given** the Macros tab, **When** the user picks Lin, Exp, Log or S, **Then** the curve preview and every target of that macro follow the new response.+9. **Given** an older project where one macro's targets have different curves, **When** the user opens the Macros tab on it, **Then** the curve choice shows "Mixed", each target keeps responding as before, and picking a curve applies it to all targets.+8. **Given** a macro knob, **When** the user drags it vertically or double-clicks it, **Then** it turns (fine with a modifier) or resets, all its targets follow, and the drag can be recorded as automation and bound with MIDI Learn like other value controls.++---++### User Story 3 - Route audio through the reworked Audio Effect Rack (Priority: P2)++A mix engineer builds a "Crunch & Space" rack with two chains. In Rack out they choose how+chains run — Parallel (summed), Serial (top to bottom) or Select (only chains whose select+range contains the selector) — and set dry/wet, output gain and latency compensation. On+the Select tab they drag each chain's select range and the selector itself, and can map the+selector to a macro.++**Why this priority**: The Audio Effect Rack already routes this way; the story moves it to+the shared layout so all racks behave the same.++**Independent Test**: Build a two-chain Audio Effect Rack, switch the three modes and drag+the selector; confirm audibly and in the card's status line which chains play.++**Acceptance Scenarios**:++1. **Given** an Audio Effect Rack, **When** the user opens its card, **Then** the centre tabs read Chains · Select · Macros and the chain rows show their select range in Select mode or their device count otherwise.+2. **Given** Rack out, **When** the user picks Parallel, Serial or Select, **Then** the routing changes, a one-line explanation under the choice describes it, and the status line names the mode.+3. **Given** Select mode and the Select tab, **When** the user drags the selector, **Then** only chains whose range contains it play, they are highlighted, and the footer names them (or "silence").+4. **Given** Parallel or Serial mode, **When** the user opens the Select tab, **Then** the ranges are still editable and the footer says they apply only in Select mode.++---++### User Story 4 - Split and transform notes with the new MIDI Effect Rack (Priority: P2)++A producer wants an arpeggio above C3, chords below, and random accents only on hard hits,+all feeding one synth. They add a MIDI Effect Rack before the track's instrument, create+three chains (Arp → Scale, Chord → Velocity, Random), set each chain's key and velocity+zone, and every incoming note goes to the chains whose zone it hits; the chains' outputs+merge into the instrument.++**Why this priority**: The only new device in the design; it depends on the shared card+(stories 1–2) but brings a new musical capability.++**Independent Test**: Add a MIDI Effect Rack with two chains of built-in MIDI effects on an+instrument track, play notes across the split, and confirm in the instrument's output and+the card's probe which chain processed each note.++**Acceptance Scenarios**:++1. **Given** an instrument track, **When** the user adds MIDI Effect Rack from the Browser (or drops it onto the MIDI effects area), **Then** it appears with the other MIDI effects, before the instrument, with one empty chain.+2. **Given** a MIDI Effect Rack, **When** the user drops a built-in MIDI effect onto a chain, onto the chain list or onto "+ Chain", **Then** it is added to that chain or to a new chain; devices in a chain run left to right.+3. **Given** chains with key/velocity zones and Parallel mode, **When** a note is played, **Then** it reaches every unmuted chain whose zone contains its pitch and velocity (solo respected), and all chains' output notes reach the instrument.+4. **Given** Select mode, **When** a note is played, **Then** only the chains whose select range contains the selector (and whose key/velocity zone the note hits) receive it; dragging the selector or turning its macro switches chains.+5. **Given** "Merge duplicate notes" is on, **When** two chains emit the same pitch at the same time, **Then** the instrument plays one note; with it off it receives both.+6. **Given** "Pass through outside zones" is on, **When** a note hits no chain's zone, **Then** it reaches the instrument unchanged; with it off it is dropped.+7. **Given** the Chain panel of a MIDI chain, **When** the user changes the chain's transpose, **Then** that chain's output notes shift by that many semitones.+8. **Given** the Chain panel of a MIDI chain, **When** the user sets Volume to 50 %, **Then** that chain's output notes reach the instrument at half their velocity (at least 1); at 0 % the chain sends nothing.+9. **Given** a project with a MIDI Effect Rack, **When** it is saved, reopened, undone/redone, saved as a preset or driven through the MCP tools, **Then** its chains, devices, zones, macros and output settings come back exactly.++---++### User Story 6 - MIDI effects inside an Instrument Rack chain (Priority: P2)++A producer groups an instrument with its own note processing: in one Instrument Rack, the+pad chain plays Chord → Nota Pentad → Reverb while the lead chain plays Arp → Nota Volt.+Each Instrument Rack chain runs **MIDI effects → instrument → audio effects**, like a+track (issue #329).++**Why this priority**: Needed to pack an instrument together with its MIDI effects into+one rack (split out of #326); it builds on the shared card (stories 1–2) and the MIDI+effect hosting the MIDI Effect Rack brings (story 4).++**Independent Test**: Put an Arp in one chain of a two-chain Instrument Rack, play a held+chord, and confirm only that chain arpeggiates while the other sustains; save, reopen,+save as rack preset, load it on another track — the Arp is still there.++**Acceptance Scenarios**:++1. **Given** an Instrument Rack chain, **When** the user opens it on the Chains tab, **Then** the device strip shows a MIDI effects section before the instrument, then the instrument, then the audio effects, each with its own drop target.+2. **Given** a chain, **When** the user drops a built-in MIDI effect from the Browser onto the MIDI section or picks it from the chain's Add menu, **Then** it is added there; dropping it elsewhere in the strip places it in the MIDI section; MIDI effects reorder within their section only.+3. **Given** a chain with MIDI effects and a key/velocity zone, **When** notes are played, **Then** the zone picks which notes enter the chain, the chain's MIDI effects transform them in order, and only that chain's instrument plays the result, sample-accurately and in time with the transport (an Arp in a rack chain plays the same pattern as on a track).+4. **Given** mono (last note) is on, **When** some chains hold MIDI effects, **Then** mono shapes the chains without MIDI effects; a chain with MIDI effects gets the notes its zone takes as played (its effects decide what sounds).+5. **Given** a chain's MIDI effect, **When** the user maps one of its parameters to a macro, bypasses it, or opens its full editor, **Then** this works as for the chain's other devices.+6. **Given** a rack whose chains hold MIDI effects, **When** the project is saved and reopened, the rack is saved as a preset and loaded elsewhere, the track or rack is duplicated, an edit is undone/redone, or the rack is driven through the MCP rack tools, **Then** the MIDI effects and their settings come back exactly.++---++### User Story 5 - The racks look right in every theme (Priority: P1)++A user who works in Studio Light (or either Ember theme) opens any of the three racks. The+card reads as part of the app in that theme: no dark islands, no unreadable text, the+accent only on what is live or chosen. Switching theme while the card is open recolours it+immediately.++**Why this priority**: An explicit hard requirement of the request; a rack that only works+in one theme blocks release.++**Independent Test**: Open each rack in each built-in theme (and switch live), compare+against the mockup's structure and the design guide's readability bar.++**Acceptance Scenarios**:++1. **Given** any built-in theme, **When** each of the three rack cards is shown with every tab and both right-panel tabs, **Then** every surface, line, label and value uses that theme's colours and meets the design guide's readability bar.+2. **Given** a rack card is open, **When** the user switches theme in Preferences → Appearance (or the system switches it under Follow system), **Then** the card recolours at once without reopening.+3. **Given** a chain is muted or soloed, **Then** its M / S keys use the Mute and Solo fills of the current theme with legible ink.+4. **Given** the design guard checks, **When** the smoke test runs, **Then** it passes with no new entries in any allow list.++---++### Edge Cases++- A rack with one chain: Delete is disabled (a rack keeps at least one chain).+- A rack at the chain limit: "+ Chain", Duplicate and drops that would add a chain are refused with a short tooltip.+- A chain with no devices: the device strip shows only the drop target; an Instrument Rack chain with no instrument is silent; a MIDI chain with no devices passes its zone's notes through unchanged.+- A macro with no targets shows "—" instead of a value, a muted knob, and on the Macros tab a one-line empty state telling the user to press Map.+- Mapping on, then the user switches to another chain: mapping stays on and the new chain's parameters are mappable; switching to Zones/Select or Macros tab ends mapping.+- Deleting a device or chain that has mapped parameters removes those mappings and updates every count badge.+- Zone edges cannot cross: dragging low past high stops at high (and vice versa); ranges are whole MIDI values 0–127.+- Velocity zones exist only for racks that receive notes (Instrument, MIDI); the Audio Effect Rack shows select ranges instead.+- Device kinds that cannot live in a rack (an instrument in a MIDI rack, a MIDI effect in an Audio Effect Rack, an audio effect in a MIDI rack, a second instrument in an Instrument Rack chain, any rack inside a rack) are refused on drop with a tooltip.+- An Instrument Rack chain with MIDI effects but no instrument is silent; its MIDI effects still advance so they stay in time when an instrument is added.+- Transport stop, seek, loop wrap and Session slot switches reset or shift the MIDI effects inside rack chains exactly as they do for a track's MIDI effects (no ghost notes, Arp phase kept across a loop).+- The rack is bypassed with the power switch: the body stays readable but marked inactive (no opacity), and a bypassed MIDI Effect Rack passes notes straight through.+- Stuck notes: changing zones, mode, mute, solo, transpose or deleting a chain while notes are held must not leave notes hanging in the instrument.+- Projects saved before this change with Instrument or Audio Effect Racks (including per-target curves that differ within one macro) open and sound the same.+- Long chain, device and macro names are cut with an ellipsis; numbers never shift layout.++## Clarifications++### Session 2026-10-26++- Q: Existing projects can hold different curves per target of one macro — keep per-target curves or adopt one curve per macro on load? → A: Keep curves per target; the macro's curve choice shows "Mixed" until the user picks one, which then applies to all its targets.+- Q: What picks the chain in the MIDI Effect Rack's Select mode? → A: A selector 0–127 with per-chain select ranges, as in the Audio Effect Rack; shown as a Selector row on the MIDI rack's Zones tab and mappable to a macro.+- Q: Which parameters does a compact device card on the Chains tab show? → A: Up to three key parameters curated per device kind; while mapping, the card scrolls to offer every parameter of the device.+- Q: What does a MIDI Effect Rack chain's Volume do? → A: It scales the velocity of the chain's output notes (shown in percent, 100 % = unchanged, 0 % = the chain's notes are not sent).+- Q: What goes on the right side of the rack's status line? → A: Nothing — the status line carries only the one-line summary; no sample rate, device count or CPU.++## Requirements *(mandatory)*++### Functional Requirements++**Shared rack card (all three racks)**++- **FR-001**: Instrument Rack, Audio Effect Rack and MIDI Effect Rack MUST share one card layout at the standard device-card size: macro column (left), tabbed work area (centre), tabbed chain/output panel (right), status line (bottom).+- **FR-002**: The card header MUST be the shared device header (name, preset picker where presets exist, type badge, power switch); the mockup's text Bypass, Fold and A/B controls MUST NOT be added as separate header buttons — bypass is the power switch, fold and A/B stay where the app already offers them.+- **FR-003**: The macro column MUST show 8 macros (2 × 4) each with a knob, name, value and a badge with its number of targets when it has any, plus one Map button for the selected macro.+- **FR-004**: The centre tabs MUST be Chains · Zones · Macros (Audio Effect Rack: Chains · Select · Macros), with a short summary on the right of the tab strip (chain count and routing; zone scale; "N of 8 mapped").+- **FR-005**: The Chains tab MUST list chains with colour stripe, name, mute, solo, zone/range summary and a live level meter, a "+ Chain" control, and the chosen chain's devices left to right as compact cards with on/off, name, kind and up to three key parameters (a curated list per device kind) as horizontal sliders with values; while mapping, a compact card MUST let the user scroll to and map any parameter of its device.+- **FR-006**: Users MUST be able to add a device to a chain or create a new chain by dropping a device from the Browser on the chain list, "+ Chain" or the device strip; each compact device card MUST offer to open the device's full editor.+- **FR-007**: The right panel MUST have a Chain tab (chosen chain: name with rename, index "n / N", volume (for MIDI chains: velocity scale), pan — for MIDI chains transpose instead of pan —, key and velocity range or select range linking to the Zones/Select tab, Duplicate, Delete) and a Rack out tab (Output for the MIDI rack).+- **FR-008**: The status line MUST summarise the rack in one line (chains, routing or zone probe result, mapped macros) and show nothing else — no sample rate, device count or CPU readout.+- **FR-009**: All value controls on the card MUST follow the app's value-control contract: no value jump on click, double-click to default, fine adjustment with a modifier, automation write gestures, MIDI Learn, live follow that pauses while dragging, values always visible in a number font.+- **FR-010**: Chain rows MUST be colour-coded with a stable per-chain colour that stays recognisable in every theme.++**Macro mapping**++- **FR-011**: The separate macro-map view with its Done button MUST be removed; Map MUST turn on mapping for the selected macro in place, switching to the Chains tab.+- **FR-012**: While mapping, every mappable parameter in the visible device cards MUST be marked as a target, distinguishing parameters already mapped to the selected macro; clicking toggles the mapping; a parameter MUST belong to at most one macro (mapping it to another macro moves it).+- **FR-013**: Mapping MUST end on Map pressed again, Esc, or leaving the Chains tab; selecting another macro while mapping MUST switch mapping to that macro.+- **FR-014**: A mapped parameter MUST show its macro's tag, follow the macro, refuse manual drags, and open the Macros tab on its macro when clicked outside mapping.+- **FR-015**: The Macros tab MUST show the selected macro's slot, name (rename by double-click), value, response curve choice (Lin, Exp, Log, S) with a small preview marking the current position, and each target (chain › device › parameter) with a draggable min/max range, the current driven position, a readout in the parameter's units, and unmap; min above max MUST invert.+- **FR-016**: The response curve is chosen per macro on the Macros tab: picking a curve MUST apply it to all of that macro's targets. Curves MUST stay stored per target, so a project whose targets of one macro hold different curves keeps responding exactly as before; for such a macro the curve choice MUST show "Mixed" (no curve key chosen, no single preview) until the user picks one, which then applies to all its targets. A target added while the macro is Mixed takes Lin.++**Zones and Select**++- **FR-017**: Instrument and MIDI racks MUST offer per-chain key zones (note names, whole notes) and velocity zones (0–127) edited by dragging either edge, with a keyboard ruler and an on-hover probe that marks the hovered key, highlights the chains that would play it (at a reference velocity) and names them in the footer.+- **FR-018**: The Audio Effect Rack (on its Select tab) and the MIDI Effect Rack (as a Selector row and per-chain select ranges on its Zones tab) MUST offer per-chain select ranges (0–127) and a draggable selector, mappable to a macro; outside Select mode the ranges MUST be shown as inactive with a one-line note.++**Rack out**++- **FR-019**: Instrument Rack Rack out MUST offer volume, glide and a mono (last-note) switch under which all chains share one voice.+- **FR-020**: Audio Effect Rack Rack out MUST offer chain routing Parallel · Serial · Select with a one-line explanation, dry/wet, gain and latency compensation.+- **FR-021**: MIDI Effect Rack Output MUST offer chain routing Parallel · Select with a one-line explanation, "Merge duplicate notes" and "Pass through outside zones".++**MIDI Effect Rack (new device)**++- **FR-022**: The system MUST provide a MIDI Effect Rack device placed among a track's MIDI effects, before the instrument, available from the Browser and the add-device menus like the other racks.+- **FR-023**: Each MIDI rack chain MUST hold an ordered series of built-in MIDI effects, a key zone, a velocity zone, mute, solo, transpose and a velocity-scaling volume; notes MUST be routed to chains per FR-017 and the routing mode, and the chains' outputs merged into the track's note stream with FR-021's options.+- **FR-023a**: A MIDI chain's Volume MUST scale the velocity of its output notes, 0–200 % shown in percent: 100 % leaves velocity unchanged, results are clamped to 1–127, and at 0 % the chain sends no notes. It is automatable and mappable to a macro like any chain volume.+- **FR-024**: The MIDI Effect Rack MUST support 8 macros mapped to its devices' parameters with the same behaviour as the other racks.+- **FR-025**: The MIDI Effect Rack MUST be saved with the project, take part in undo/redo, support user presets (and factory presets if shipped), and be controllable through the MCP tools at parity with the existing rack tools (create, chains, devices, zones, macros, mappings, output settings, read back).+- **FR-026**: Changing routing, zones, mute/solo, transpose or removing chains/devices while notes are held MUST NOT leave notes stuck in the instrument.++**MIDI effects in Instrument Rack chains (issue #329)**++- **FR-030**: An Instrument Rack chain MUST hold an ordered list of built-in MIDI effects before its instrument; the chain processes MIDI effects → instrument → audio effects.+- **FR-031**: The chain's device strip MUST show the MIDI effects as their own section before the instrument; Browser drag-and-drop and the chain's Add menu MUST accept MIDI effects and place them in that section; reordering stays within the section.+- **FR-032**: Notes MUST pass the chain's key/velocity zone before the chain's MIDI effects (mono and the sustain pedal shape the chains without MIDI effects only); MIDI effect output MUST reach only that chain's instrument, sample-accurate within the block, on the same clock a track's MIDI effects use (transport, stopped-but-live, Session slot), with reset / loop-wrap behaviour identical to a track's.+- **FR-033**: Parameters of chain MIDI effects MUST be mappable to macros, bypassable and openable in their full editor like other chain devices.+- **FR-034**: Chain MIDI effects MUST be saved with the project and rack presets, copied by track/rack duplication and device copy/paste, take part in undo/redo, and be reachable from the MCP rack tools (list, add, remove, move, params, bypass).++**Themes and compatibility**++- **FR-027**: Every surface, line, text, fill and graph on all three rack cards MUST take its colour from the active theme and recolour live on a theme switch; this MUST hold for Studio Dark, Studio Light, Ember Graphite and Ember Paper and any theme added later through the theme files.+- **FR-028**: The cards MUST follow the design guide: sentence-case labels, the accent only for what is live or chosen (selected chain/macro/tab, active toggle, a value control while touched), resting values in the neutral value ink, Mute/Solo in their semantic fills with derived ink, mapping marks in a non-accent colour, no opacity for inactive state, icons from the app's glyph set (no unicode symbols such as ‹ › ▾ × ⠿).+- **FR-029**: Projects, presets and MCP scripts made with the current Instrument and Audio Effect Racks MUST load and sound unchanged; the Drum Rack is unaffected.++### Key Entities++- **Rack**: a device of kind Instrument, Audio Effect or MIDI Effect; has chains, 8 macros, routing mode and output settings (per kind), bypass state, preset.+- **Chain**: name, colour, ordered devices (Instrument Rack: MIDI effects, then an instrument, then audio effects; Audio: effects; MIDI: MIDI effects), volume, pan or transpose, mute, solo, key zone, velocity zone, select range (Audio and MIDI racks), level.+- **Macro**: slot 1–8, name, value 0–1, targets; its shown curve is the targets' common curve or "Mixed".+- **Macro target (mapping)**: chain, device, parameter, min, max (min > max inverts), response curve (kept per target; the macro shows one curve or "Mixed").+- **Selector**: Audio Effect / MIDI Effect rack value 0–127 that picks chains in Select mode (chains whose select range contains it); can be a macro target.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: A user can map a parameter to a macro in at most 3 clicks from an open rack card (select macro, Map, click parameter), with no screen change other than the tab switch.+- **SC-002**: A user can build a two-way key split in an Instrument or MIDI Effect Rack in under one minute without opening any window other than the rack card.+- **SC-003**: All three rack cards, with every tab, pass the design readability bar and the design guard checks in all 4 built-in themes, with zero new allow-list entries.+- **SC-004**: 100 % of projects in the existing rack test set (Instrument and Audio Effect Racks) render identically before and after the change.+- **SC-005**: A MIDI Effect Rack routing notes through three chains adds no audible timing shift and no stuck notes across 1 000 random note-on/off and zone/mode changes in the end-to-end smoke test.+- **SC-006**: Every MIDI Effect Rack setting survives save → reopen, undo → redo, and preset save → load with no difference.++## Assumptions++- The mockup is authoritative for layout, content and interaction; DESIGN.md and the theme files are authoritative for colour, type, header, geometry and icons where they disagree (DESIGN.md wins the conflict, the mockup's hex values are not used).+- The status line is part of the rack body inside the standard card height, so the card stays the standard device-card size.+- The chain limit stays what the racks allow today; the mockup's limit of 4 is a mockup simplification.+- MIDI rack chains hold built-in Nota MIDI effects only (Arp, Chord, Scale, Velocity, Random, Length and the others in the MIDI effect list); hosted plug-ins inside a MIDI rack are out of scope.+- The MIDI rack's probe and the Instrument rack's probe use velocity 100 as the reference velocity.+- Every device kind that can live in a rack gets a curated list of up to three key parameters for its compact card; a kind without a list falls back to its first three parameters. The full editor opens from the card.+- Engine support for audio-rack routing, select ranges, latency compensation, key/velocity zones, glide and macro curves already exists and is reused; mono (last note) for the Instrument Rack and everything for the MIDI Effect Rack are new.+- Drum Rack keeps its own card and is out of scope, including MIDI effects in drum pads.+- MIDI effects in Instrument Rack chains are built-in Nota MIDI effects only (kinds as in the MIDI Effect Rack); a MIDI Effect Rack cannot be nested in a chain.+- CHANGELOG, FEATURES.md, user docs (EN + RU) and the Shortcuts list (Esc ends mapping) are updated as part of this feature.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [ ] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5)+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)+- [ ] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/040-racks-redesign/tasks.md b/specs/040-racks-redesign/tasks.mdnew file mode 100644index 00000000..b1770b17--- /dev/null+++ b/specs/040-racks-redesign/tasks.md@@ -0,0 +1,444 @@+---++description: "Task list for the racks redesign, the MIDI Effect Rack and MIDI effects in Instrument Rack chains"+---++# Tasks: Racks redesign and MIDI Effect Rack++**Input**: Design documents from `/specs/040-racks-redesign/`++**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/](contracts/), [quickstart.md](quickstart.md)++**Tests**: Included. Constitution IV requires the smoke test to cover every engine behaviour change, and quickstart Q2 lists the sections.++**Organization**: Tasks are grouped by user story. P1 stories come first (US1, US2, US5), then P2 (US3, US4, US6).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: Can run in parallel (different files, no dependencies)+- **[Story]**: Which user story this task belongs to (US1–US6)+- Engine root `E = src/native/nota.engine`; app root `A = src/managed/Nota.App`; smoke tests `T = tests/Nota.SmokeTest`. Paths below are written in full.++---++## Phase 1: Setup (Shared Infrastructure)++**Purpose**: Freeze today's behaviour before anything changes, and scaffold the test files.++- [X] T001 On the current `develop` engine (before any engine edit), add a one-off generator in `tests/Nota.SmokeTest/RackRedesignTests.cs` (`--rack-fixtures`). It writes to `tests/Nota.SmokeTest/Fixtures/racks-v8/`:+ - an Instrument Rack (3 chains, key/vel zones, names, mix, chain devices, 4 macros with **different curves on two targets of one macro**, an inverted range, glide 0.3) as `instrument.bin` plus a settings dump `instrument.txt`. Its audio is not compared: the built-in synths free-run, so renders differ between runs;+ - an Audio Effect Rack in Select mode (2 chains of deterministic Utility / EQ-3, select ranges via velLo/velHi, dry/wet 0.7, pdc on, a macro target) as `effect.bin`, `effect.txt` and a 1 s 48 kHz render of a generated tone clip, `effect.f32`.++ Commit the fixtures with the tests.+- [X] T002 [P] Create test scaffolds with the SPDX header and empty `Run()` returning `(bool ok, string label)` lists: `tests/Nota.SmokeTest/RackRedesignTests.cs`, `tests/Nota.SmokeTest/MidiRackTests.cs`, `tests/Nota.SmokeTest/RackChainMidiTests.cs`+- [X] T003 Wire the sections into `tests/Nota.SmokeTest/Program.cs`. The full run prints `racks: midi rack routing`, `racks: midi rack no stuck notes`, `racks: midi rack persistence`, `racks: instrument mono/glide`, `racks: mapping rules`, `racks: v8 compatibility`, `racks: key params table`, `racks: chain MIDI effects`. Add a standalone `--racks` switch following the `--device-copy` pattern++---++## Phase 2: Foundational (Blocking Prerequisites)++**Purpose**: Shared engine fields, blob v9, mapping rules and the empty shared card that every story builds on.++**⚠️ CRITICAL**: No user story work can begin until this phase is complete.++### Engine core++- [X] T004 Extend `RackCore` in `src/native/nota.engine/src/devices/racks/RackCore.h`:+ - `RackChain.midiDevices` (`std::vector<std::shared_ptr<MidiDevice>>`);+ - `ChainControls` fields `selLo`/`selHi` (0–127, default 0–127), `transpose` (−48…+48, default 0), `velScale` (0–2, default 1);+ - rack atomics `mono_` (default off), `merge_` (default on), `thru_` (default on);+ - constants `kRackControl = −3` and `kMidiDeviceBase = −1000` ("chain MIDI device j = −1000 − j").++ Clamp every setter. Lo/hi setters never let an edge cross the other ("lo ≤ hi enforced on set").+- [X] T005 Implement in `src/native/nota.engine/src/devices/racks/RackCore.cpp`:+ - copy the new fields in `forkFrom` (chain `midiDevices` shared, like `devices`);+ - `addChainMidiDevice` / `removeChainMidiDevice` / `moveChainMidiDevice` / `chainMidiDeviceAt` / `chainMidiDeviceCount` (kinds 0–5 via `makeMidiDevice`; kind 6 refused; snapshot swap, AR-5);+ - chain `setRates` / `forwardTempo` reach chain MIDI devices.+- [X] T006 Blob **v9** in `src/native/nota.engine/src/devices/racks/RackCore.cpp` `serialize`/`deserialize`:+ - append per chain `selLo, selHi, transpose, velScale, midiDeviceCount, { kind, paramCount, params[], stateSize, state[], bypassed }`;+ - append per rack `mono, merge, thru`;+ - readers of v ≤ 8 use the defaults (`selLo 0, selHi 127, transpose 0, velScale 1`, mono off, merge on, thru on);+ - bump the version comment list.+- [X] T007 Mapping rules in `src/native/nota.engine/src/devices/racks/RackCore.cpp`:+ - `addMacroMapping` moves an existing mapping of the same (chain, device, param) to the new macro and returns its index;+ - `applyMacro` drives `deviceIndex = kRackControl, param 0` → `chainSelect` (0–1) and `deviceIndex ≤ kMidiDeviceBase` → chain MIDI device params;+ - removing a chain or chain MIDI device drops its mappings and re-indexes the rest.+- [X] T008 Generic MIDI-effect state ABI:+ - `nota_midi_effect_get_state` / `nota_midi_effect_set_state` (checkpoint flag) in `src/native/nota.engine/include/nota/nota_engine.h` and `src/native/nota.engine/src/abi/nota_engine_device.cpp`;+ - backing `Engine` methods in `src/native/nota.engine/src/engine/Engine_Devices.cpp` + `Engine.h`. Reuse `cloneMidiDevice`'s state path.+- [X] T009 Selector mapping target and mapping-move ABI semantics:+ - update `nota_rack_add_macro_mapping` / `nota_rackdev_add_macro_mapping` docs in `src/native/nota.engine/include/nota/nota_engine.h` (device −3 = selector; same param moves);+ - add `#define NOTA_RACK_MIDI_DEVICE_BASE (-1000)` and `NOTA_RACK_CONTROL (-3)`;+ - curves stay on the existing `nota_*_mapping_curve` calls (no change to `*_mapping_info`).++### Managed plumbing shared by all racks++- [X] T010 [P] P/Invoke the T008/T009 calls in `src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs` + `src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs`; add `MidiEffectGetState`/`MidiEffectSetState` to `src/managed/Nota.Application/Engine/IAudioEngine.cs`+- [X] T011 Extend `IRackAccess` in `src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs`:+ - `RackKind`;+ - select range get/set (`SelectRange(chain)` / `SetSelectRange`);+ - `MappingCurve` for all mappings;+ - `MoveChain`, `DuplicateChain`;+ - default-implemented MIDI-section members (`ChainMidiCount`, `AddChainMidi`, …) returning "unsupported".++ Map the Audio Effect Rack's select range onto `velLo/velHi` inside `RackDevAccess` (research D2) so the card never knows.+- [X] T012 [P] Create `src/managed/Nota.App/DeviceCards/Rack/RackKindProfile.cs`: per kind (Instrument, Audio, MIDI) the zone tab label ("Zones" / "Select"), whether velocity zones / select rows / selector row exist, routing modes (none · Parallel/Serial/Select · Parallel/Select), right-tab label ("Rack out" / "Output"), Rack-out rows, chain Volume/Pan vs Volume(velocity %)/Transpose, the chains-foot hint text, and allowed drop kinds per section (research D11)+- [X] T013 [P] Create `src/managed/Nota.Presentation/Racks/RackKeyParams.cs` (UI-free, so the smoke test can check it): a static table (device family, kind) → up to three key parameter **names**, resolved to indices against the device's own names at run time, for every rack-eligible instrument, audio effect and MIDI effect kind (names as in the mockup where they exist, e.g. Volt Cutoff/Reso/Drive, Valve Gain/Tone/Mix, Arp Rate/Gate/Octaves). A missing kind falls back to its first three parameters+- [X] T014 Create the shared card skeleton `src/managed/Nota.App/DeviceCards/Rack/RackCard.cs` (region placeholders in `RackCard.Macros.cs`, `.Chains.cs`, `.Zones.cs`, `.MacroTab.cs`, `.RightPanel.cs`):+ - view state per rack instance, kept across rebuilds and theme switches: centreTab, rightTab, selectedChain, selectedMacro, mappingMacro, probePitch (data-model "View state");+ - three `DeviceCardKit.Section` columns (~116 · fill · ~160) and the 18 px status line, all inside `BuildCardShell` from `src/managed/Nota.App/DeviceChainView.Shell.cs`;+ - segmented tab strips with sentence-case labels via `NotaText.Label`;+ - empty region builders that the story phases fill in.++ No hex, no `IrCap`, no `Opacity` (contracts/ui-rack-card.md § Frame).+- [X] T015 [P] Smoke: in `tests/Nota.SmokeTest/RackRedesignTests.cs` add:+ - `racks: v8 compatibility` — load the T001 fixtures into fresh racks; the settings dumps must match and the Audio Effect Rack render must match `effect.f32` within 1e-5 (SC-004);+ - `racks: mapping rules` — move-on-add, selector target −3 drives `chainSelect`, chain delete drops mappings;+ - `racks: key params table` — every rack-eligible kind has ≤ 3 in-range indices.++**Checkpoint**: Engine fields, blob v9 and mapping rules are tested; the empty shared card is there. Stories can start.++---++## Phase 3: User Story 1 - Layer and split instruments in the reworked Instrument Rack (Priority: P1) 🎯 MVP++**Goal**: The Instrument Rack uses the shared card: chains, compact device strip, zones with hover probe, Chain panel, and Rack out with volume, working glide and mono.++**Independent Test**: Open a three-chain Instrument Rack; chains, zones and the Chain / Rack out panels change the sound and show it in the card (spec US1; quickstart Q4 steps 1, 4, 5, 6).++### Tests for User Story 1++- [X] T016 [P] [US1] Smoke `racks: instrument mono/glide` in `tests/Nota.SmokeTest/RackRedesignTests.cs`:+ - mono on: one sounding pitch per chain, last-note priority, release returns to the previous held note;+ - glide 0.5 on a Volt chain: per-note bend starts at (prev − new) semitones and reaches 0 after ~250 ms;+ - a chain with a non-MPE instrument retriggers without bend;+ - poly mode is unchanged against a fixture render.++### Implementation for User Story 1++- [X] T017 [US1] Mono note stack in `src/native/nota.engine/src/devices/racks/RackInstrument.cpp`/`.h` (fixed 128-entry stack, no allocation). Glide via block-rate `noteExpression(pitch, ExprBend, …)` ramps over `glide × 500 ms`, only for chains whose instrument `supportsMpe()` (research D4)+- [X] T018 [US1] ABI `nota_rack_set_mono` / `nota_rack_mono` in `src/native/nota.engine/include/nota/nota_engine.h` + `src/native/nota.engine/src/abi/nota_engine_rack.cpp` + `src/native/nota.engine/src/engine/Engine_Rack.cpp`. Add `nota_rack_duplicate_chain` and `nota_rackdev_duplicate_chain`: insert after, copy devices, controls and the chain's mappings, as one undo step through `rackForEdit`+- [X] T019 [P] [US1] Interop for T018 in `src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs`, `NotaEngine.Rack.cs`, `NativeMethods.RackDev.cs`, `NotaEngine.RackDev.cs` and `src/managed/Nota.Application/Engine/IAudioEngine.cs`+- [X] T020 [US1] Macro column (display and turning only; mapping comes in US2) in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Macros.cs`:+ - 2 × 4 cells with a 22 px `Knob`, name, mono value ("—" when unmapped), target-count badge;+ - knob contract: vertical drag, fine modifier, double-click resets, `GestureBegin/End` automation write on the rack's macro params, `MidiLearn.Bind`, live follow that skips while dragging.+- [X] T021 [US1] Chains tab in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs`.+ - Chain list:+ - 34 px rows: colour stripe from the chain palette index (resolved at render time); name in accent ink when chosen;+ - M/S keys with `NotaPalette.Mute`/`Solo` fills and `InkOn`; mono zone summary (`C-1–A#4 · v96+`); level bar;+ - "+ Chain"; chains-foot hint.+ - Device strip of the chosen chain: 96 px compact cards with power dot, name, kind badge, `RackKeyParams` sliders (`SliderTrack`, `VizInk` at rest), "Open" and `Glyph.Grip` reorder; chevron glyphs between cards; a dashed drop target.+ - Browser drops follow `RackKindProfile` rules; refused drops show a tooltip.+- [X] T022 [US1] Zones tab in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs`.+ - Ruler C0…C8.+ - Per-chain 24 px rows: key bar and velocity bar with drag edges (whole values, edges never cross), mono labels in note names.+ - Hover probe: teal 1 px line on every row; chains hit at velocity 100 get a teal wash and name. The footer shows the hint and the result ("C4 · vel 100 → Volt + Pentad" / "nothing").+- [X] T023 [US1] Right panel in `src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs`.+ - Chain tab:+ - colour dot, name with double-click rename, "n / N";+ - Volume (dB) and Pan (L/C/R) via `DeviceCardKit.SliderRow`;+ - Keys/Vel rows that open the Zones tab;+ - Duplicate and Delete (Delete disabled with one chain).+ - Rack out tab for Instrument: Volume, Glide (ms, tooltip "Glides in mono mode"), switch "Mono (last note)".+- [X] T024 [US1] Status line summary for Instrument in `src/managed/Nota.App/DeviceCards/Rack/RackCard.cs`: chains · probe result or zone summary · "N macros mapped". Nothing on the right+- [X] T025 [US1] Route `BuildInstrumentRackBody` in `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs` to `RackCard` (Instrument profile). Delete the `Ir*` builders (`InstrumentRackMain`, `IrMacroStrip`, `IrChainList`, `IrDeviceArea`, `IrZoneMap`, `IrRackRail`, `IrCap`…) that nothing else uses. Keep `RackCardView.Drum.cs` and `MacroPanel.cs` compiling+- [X] T026 [US1] MCP: `set_rack_mono(trackId, on)` and `get_rack` gains `mono` in `src/managed/Nota.Mcp/Tools/RackTools.cs`. The `set_rack_glide` description says it is audible in mono mode++**Checkpoint**: An Instrument Rack can be built, split and played from the new card (mapping still read-only).++---++## Phase 4: User Story 2 - Map macros directly in the chain (Priority: P1)++**Goal**: Map in place (no Done screen). The Macros tab has ranges, inversion, curves and "Mixed".++**Independent Test**: In any rack, map two params to one macro, set ranges and a curve, turn the macro; both params follow (spec US2; quickstart Q4 steps 2–3).++### Tests for User Story 2++- [X] T027 [P] [US2] Extend `racks: mapping rules` in `tests/Nota.SmokeTest/RackRedesignTests.cs`:+ - the curve of a macro reads "mixed" when its targets differ;+ - setting a macro curve updates every target in one undo step;+ - min > max inverts the response;+ - the T001 fixture's mixed macro still renders identically.++### Implementation for User Story 2++- [X] T028 [US2] Mapping mode in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs` and `RackCard.Macros.cs`:+ - Map key: accent key while on. Map switches to the Chains tab and sets `mappingMacro`; selecting another macro moves mapping to it.+ - Compact cards in mapping mode: teal dashed frame (not this macro) or solid frame (this macro), "copy" cursor, and a scrollable list of **all** params of the device.+ - Click toggles the mapping (default range ±0.3 around the current value). A param mapped to another macro moves (engine T007).+ - Header line "Mapping · Macro N · Name — click to add or remove".+ - Outside mapping, a mapped param shows the teal "M n" tag, ignores drags and opens the Macros tab on its macro when clicked.+- [X] T029 [US2] Esc ends mapping: register it with the app's key handling in `src/managed/Nota.App/MainWindow.MenuKeys.cs`, active only while a rack card is mapping, so other Esc uses are untouched. Leaving the Chains tab also ends mapping+- [X] T030 [US2] Macros tab in `src/managed/Nota.App/DeviceCards/Rack/RackCard.MacroTab.cs`.+ - Header:+ - slot "Macro N", name with double-click rename, mono value;+ - "Curve" segmented Lin · Exp · Log · S. "Mixed" means no key chosen plus a caption; picking a curve applies it to every target in one undo step;+ - a 30 × 22 `NotaGraph` preview (`VizInk` curve, accent dot; none when Mixed);+ - Map key.+ - Target rows:+ - colour stripe, "chain › device ›" and param name;+ - a 150 px range bar with min/max handles and a current-position marker;+ - range text in the param's units, unmap via `Glyph.Close`.+ - One Ink-5 empty-state line.+ - New targets get the macro's curve, or Lin when the macro is Mixed (research D5).+- [X] T031 [US2] Remove `InstrumentRackMacroMap`, `IrMappingRow` and `_macroMapMode` from `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs`+- [X] T032 [P] [US2] MCP in `src/managed/Nota.Mcp/Tools/RackTools.cs` and `src/managed/Nota.Mcp/Tools/EffectRackTools.cs`:+ - `set_macro_curve(trackId, deviceIndex, macro, curve)`;+ - `set_mapping_range(trackId, deviceIndex, index, min, max)`;+ - per-macro `curve` with `"mixed"` in `get_rack` / `get_effect_rack`;+ - add-mapping moves an existing mapping (contracts/mcp-tools.md).++**Checkpoint**: US1 + US2 make a complete Instrument Rack. This is the MVP.++---++## Phase 5: User Story 5 - The racks look right in every theme (Priority: P1)++**Goal**: The shared card passes the design guards and reads correctly in all four themes, and recolours live.++**Independent Test**: Capture the card in each theme, switch live, run the guards (quickstart Q5, SC-003).++- [X] T033 [US5] Run the smoke test design sections (`RunStudio`, `RunThemes`, `RunLabels`, `RunIcons` in `tests/Nota.SmokeTest/DesignTokenCheck*.cs`). Fix every hit in `src/managed/Nota.App/DeviceCards/Rack/RackCard*.cs` **without** adding lines to any `*AllowList.txt`+- [X] T034 [US5] Audit `src/managed/Nota.App/DeviceCards/Rack/RackCard*.cs` for colour snapshots:+ - no `new SolidColorBrush(slot.Color)` outside `Render`;+ - no `static readonly` palette-derived brush except slots and `Wash`;+ - chain colours resolved per render.++ Confirm that view state (tabs, chosen chain and macro) survives a theme switch.+- [X] T035 [US5] Headless capture harness (scratch project, not committed). Capture the Instrument Rack card × 3 centre tabs × 2 right tabs × {Studio Dark, Studio Light, Ember Graphite, Ember Paper}, plus a live switch without rebuild. Check each frame against the DESIGN.md readability bar and keep the sheet for the PR++**Checkpoint**: The P1 slice (US1, US2, US5) can ship as the first UI PR.++---++## Phase 6: User Story 3 - Route audio through the reworked Audio Effect Rack (Priority: P2)++**Goal**: The Audio Effect Rack uses the shared card with a Select tab, the selector and the Rack-out routing modes.++**Independent Test**: A two-chain Audio Effect Rack; switch the modes and drag the selector; audio and status line agree (spec US3).++- [X] T036 [P] [US3] Smoke in `tests/Nota.SmokeTest/RackRedesignTests.cs`: duplicate chain on an Audio Effect Rack copies its devices and mappings; a selector mapped to a macro switches the active chain mid-render+- [X] T037 [US3] Select tab for the Audio profile in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs`:+ - ruler 0/32/64/96/127;+ - Selector row (accent handle, drag to set, mappable via Map);+ - per-chain select-range bars;+ - outside Select mode the bars use the next ink step and the footer says "Ranges apply when Chains run is set to Select";+ - footer result "selector 30 → Crunch" / "silence".+- [X] T038 [US3] Rack out for the Audio profile in `src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs`:+ - "Chains run" Parallel · Serial · Select with a one-line explanation;+ - Dry/wet (%) and Gain (dB, centred);+ - switch "Latency compensation".++ Chain rows show `sel lo–hi` in Select mode and "N devices" otherwise.+- [X] T039 [US3] Status line for Audio in `src/managed/Nota.App/DeviceCards/Rack/RackCard.cs` (mode · chain names · dry/wet · macros). Route `BuildEffectRackBody` in `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs` to `RackCard` (Audio profile) and delete the `Ae*` builders+- [X] T040 [P] [US3] MCP: `add_effect_rack_mapping` accepts `deviceIndex = −3` (selector) in `src/managed/Nota.Mcp/Tools/EffectRackTools.cs`++**Checkpoint**: Instrument and Audio Effect Racks share one card.++---++## Phase 7: User Story 4 - Split and transform notes with the new MIDI Effect Rack (Priority: P2)++**Goal**: A new MIDI effect (kind 6) with zoned chains of MIDI effects, Parallel/Select routing, merge and thru. Saved, undoable, presettable and scriptable.++**Independent Test**: A MIDI Effect Rack with two chains on an instrument track; notes across the split go to the right chain; save, reopen and undo restore it (spec US4; quickstart Q3).++### Tests for User Story 4++- [X] T041 [P] [US4] Smoke `racks: midi rack routing` in `tests/Nota.SmokeTest/MidiRackTests.cs`: feed fixed events through a rack on an instrument track and compare the instrument's note-ons with expected lists for:+ - key and velocity zones; mute and solo;+ - Parallel vs Select (selector + select ranges);+ - transpose +12 and −48 clamping;+ - velScale 100 % / 50 % (at least 1) / 0 % (no notes);+ - merge on/off with two chains sending the same pitch;+ - thru on/off for a note outside every zone;+ - a bypassed rack passes notes through.+- [X] T042 [P] [US4] Smoke `racks: midi rack no stuck notes` in `tests/Nota.SmokeTest/MidiRackTests.cs`: 1 000 random note-on/off interleaved with zone, mode, mute and transpose edits and chain deletes (fixed seed). At the end the instrument holds no notes (`heldNotes == 0`) (SC-005)+- [X] T043 [P] [US4] Smoke `racks: midi rack persistence` in `tests/Nota.SmokeTest/MidiRackTests.cs`:+ - state blob → new rack → identical `get_midi_rack`;+ - project save/reopen;+ - undo/redo of every structural call;+ - user preset save/load;+ - track duplicate and MIDI-effect copy/paste (SC-006).++### Implementation for User Story 4++- [X] T044 [US4] Create `src/native/nota.engine/src/devices/racks/MidiRack.h/.cpp`: `class MidiRack : public MidiDevice, public RackCore`, `midiKind() 6`, "Nota MIDI Effect Rack". `process` follows research D3:+ - routing by zones + select;+ - `routeMask[128]` per input pitch;+ - per-chain ping-pong buffers, members only, 16 chains × 2 × 1024 events;+ - transpose and velScale;+ - per-chain held-output bitsets;+ - merge counters and thru;+ - reconcile on a snapshot change: note-offs for pitches of chains that are gone;+ - sorted output capped at `maxOut`.++ Also: `reset` / `timeJump` fan-out; macros as params 0–7; `getState/setState` = blob; `clone`; Serial mode refused. No allocation, lock or I/O in `process` (AR-6).+- [X] T045 [US4] Register kind 6 in `makeMidiDevice` in `src/native/nota.engine/src/devices/DeviceFactory.cpp`. New racks start with one empty chain. Cap chains at 16 (`addChain` returns <0 at the limit)+- [X] T046 [US4] Engine methods in `src/native/nota.engine/src/engine/Engine_Rack.cpp` + `Engine.h`:+ - `midiRackAt(track, midiIndex)`;+ - `midiRackForEdit`: fork + republish for undo, like `rackForEdit`, carrying bypass and fold;+ - the structural and value operations behind the ABI.+- [X] T047 [US4] `nota_midirack_*` ABI from `specs/040-racks-redesign/contracts/c-abi.md` in `src/native/nota.engine/include/nota/nota_engine.h` + `src/native/nota.engine/src/abi/nota_engine_rack.cpp`: structure, chain controls, rack, macros and mappings. Plain MIDI indices are translated to `kMidiDeviceBase − j` internally. Add the new symbols to `src/native/nota.engine/nota_exports.txt` and `nota_exports.map`+- [X] T048 [P] [US4] P/Invoke + wrapper: create `src/managed/Nota.Infrastructure/Interop/NativeMethods.MidiRack.cs` and `src/managed/Nota.Infrastructure/Interop/NotaEngine.MidiRack.cs`; add the `MidiRack*` members to `src/managed/Nota.Application/Engine/IAudioEngine.cs`+- [X] T049 [US4] Persistence:+ - `MidiDeviceDto.State` (optional blob ref) in `src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs`;+ - in `src/managed/Nota.Infrastructure/Persistence/ProjectService.cs`, write the state when non-empty and restore it after `AddMidiEffect`;+ - bump `CurrentFormatVersion` 23 → 24; files without `State` load unchanged;+ - add a no-op entry in `ProjectMigrations.cs` if versions are listed there.+- [X] T050 [US4] Presets: user presets for MIDI effects (kind 6 with its state blob) in `src/managed/Nota.Infrastructure/Persistence/PresetService.cs` (`CaptureMidiEffect`, state restored on apply); the card menu's "Save preset" addresses a MIDI effect as `PresetService.MidiEffectBase − i` (it used to pass the MIDI index as an audio device index)+- [X] T051 [P] [US4] Catalog: add "Nota MIDI Effect Rack" (MIDI, kind 6, "rack", "midirack split layer", "Splits notes across chains of MIDI effects.") in `src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs`, and a "Racks" category on the MIDI tab in `src/managed/Nota.Application/Palette/DeviceCategories.cs`+- [X] T052 [US4] Add `MidiRackAccess` (on `nota_midirack_*`) to `src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs`. In `src/managed/Nota.App/DeviceChainView.Midi.cs`, build kind 6 as `RackCard` (MIDI profile) inside `BuildCardShell`, width 700+- [X] T053 [US4] MIDI profile UI:+ - in `RackCard.Zones.cs`: Selector row and per-chain select bars on the Zones tab, inactive outside Select mode;+ - in `RackCard.RightPanel.cs`:+ - Chain tab: Volume as velocity % (0–200, 100 = unchanged) and Transpose (st, −48…+48);+ - Output tab: "Chains run" Parallel · Select + explanation, switches "Merge duplicate notes" and "Pass through outside zones";+ - in `RackCard.Chains.cs`: an activity bar instead of the level meter;+ - status line: mode · "N chains → merged MIDI" · probe result.++ Refuse adding chains at 16 with a tooltip.+- [X] T054 [US4] MCP: create `src/managed/Nota.Mcp/Tools/MidiRackTools.cs` with the 22 tools in `specs/040-racks-redesign/contracts/mcp-tools.md` (zones accept note names). `list_midi_fx_kinds` / `add_midi_fx` gain kind 6 in `src/managed/Nota.Mcp/Tools/MidiFxTools.cs`. Register the tool type where the others are registered+- [X] T055 [P] [US4] MCP scenario "split arp above C3, chords below, accents on hard hits" as the `racks: midi rack MCP` section in `tests/Nota.SmokeTest/MidiRackTests.cs` (AiGoldenTests covers the AI models, not MCP)++**Checkpoint**: All three rack kinds exist and share the card.++---++## Phase 8: User Story 6 - MIDI effects inside an Instrument Rack chain (Priority: P2, issue #329)++**Goal**: Instrument Rack chains run MIDI effects → instrument → audio effects, sample-accurate, saved and scriptable.++**Independent Test**: An Arp in one chain of a two-chain Instrument Rack arpeggiates only that chain. Save, preset and reopen keep it (spec US6; quickstart Q4b).++### Tests for User Story 6++- [X] T056 [P] [US6] Smoke `racks: chain MIDI effects` in `tests/Nota.SmokeTest/RackChainMidiTests.cs`:+ - an Arp in chain 0 produces the same note-ons (pitch and sample offset) as the same Arp on a plain track over 8 bars, including a loop wrap and a stop/start;+ - chain 1 receives the raw notes;+ - zones and mono run before chain MIDI effects;+ - save/reopen, rack preset, track duplicate, device copy/paste, undo/redo and `add_rack_chain_midi_fx` all round-trip;+ - a chain MIDI effect param mapped to a macro follows it.++### Implementation for User Story 6++- [X] T057 [US6] Add `virtual bool rendersBlockEvents() const`, `virtual void renderBlock(float* out, int32_t frames, const MidiEv* evs, int n, const ExprEv* xev, int xn, double beatStart, double spb, bool playing, …live hook…)`, `virtual void midiReset()` and `virtual void midiTimeJump(double)` to `src/native/nota.engine/src/devices/Instrument.h` (defaults: false / no-op)+- [X] T058 [US6] In `src/native/nota.engine/src/engine/Engine_Render.cpp`:+ - make `playEvents` call `inst.renderBlock(...)` when `inst.rendersBlockEvents()`;+ - extract its segment loop into a shared helper the rack reuses, without changing behaviour for other instruments;+ - call `midiReset` / `midiTimeJump` wherever the track's MIDI chain gets `reset` / `timeJump` (stop, seek, loop wrap, Session slot switch).+- [X] T059 [US6] In `src/native/nota.engine/src/devices/racks/RackInstrument.cpp`/`.h`:+ - `rendersBlockEvents()` = any chain has MIDI devices, read from the live snapshot; Drum Rack returns false;+ - `renderBlock` per chain: zone filter (mono first) → chain MIDI devices on member scratch (2 × 1024 events) with the block clock → the shared segment helper on the chain instrument → chain audio devices → sum;+ - glide only for chains without MIDI devices (research D4/D15);+ - `midiReset` / `midiTimeJump` fan out to the chain MIDI devices;+ - no allocation.+- [X] T060 [US6] ABI `nota_rack_chain_midi_*` (contracts/c-abi.md § Instrument Rack additions) in `src/native/nota.engine/include/nota/nota_engine.h` + `src/native/nota.engine/src/abi/nota_engine_rack.cpp` + `src/native/nota.engine/src/engine/Engine_Rack.cpp`, with edits through `rackForEdit`. Update the export lists+- [X] T061 [P] [US6] Interop for T060 in `src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs`, `NotaEngine.Rack.cs` and `src/managed/Nota.Application/Engine/IAudioEngine.cs`. Implement the MIDI-section members of `InstrumentRackAccess` in `src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs`+- [X] T062 [US6] Chain strip MIDI section for the Instrument profile in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs`:+ - MIDI effects (own dashed drop target, "MIDI" kind badge) · instrument · audio effects;+ - a MIDI effect dropped anywhere on the strip lands in the MIDI section;+ - reorder only within the section;+ - the chain's Add menu lists MIDI effects;+ - "Open" shows the full MIDI-effect card from `src/managed/Nota.App/DeviceCards/Midi/MidiDeviceCardFactory.cs` bound to the chain device.++ Mapping uses device `−1000 − j`.+- [X] T063 [US6] Browser drops of MIDI effects onto an Instrument Rack chain: handled by the card's own drop targets (chain row, list, MIDI section) in `RackCard.Chains.cs`; chain devices have no copy/paste today, so chain MIDI effects follow (none)+- [X] T064 [P] [US6] MCP in `src/managed/Nota.Mcp/Tools/RackTools.cs`:+ - `add_rack_chain_midi_fx`, `remove_rack_chain_midi_fx`, `move_rack_chain_midi_fx`;+ - `get_rack_chain_midi_fx_params`, `set_rack_chain_midi_fx_param`, `set_rack_chain_midi_fx_bypass`;+ - `get_rack` lists `midiEffects`;+ - `add_macro_mapping` accepts `midiFx`.++**Checkpoint**: Issue #329 is done; every story works on its own.++---++## Phase 9: Polish & Cross-Cutting Concerns++- [ ] T065 Theme pass over all three racks: repeat T033–T035 for the Audio and MIDI profiles and the Instrument MIDI section (4 themes × 3 racks sheet for the PR, quickstart Q5)+- [ ] T066 [P] Perf gate for the `playEvents` hook: `scripts/perf-gate.sh develop` reports no regression (quickstart Q4c)+- [ ] T067 Run quickstart.md Q1–Q6 end to end and record the results in the PR description++### Nota closing tasks *(always include — these are the PR gates)*++- [X] T068 Run `scripts/build.sh` (and on CI `scripts/build-linux.sh` / `scripts/build-win.ps1`) until native + managed + smoke test are green+- [X] T069 AGPL-3.0-only SPDX two-line header on every new source file: `MidiRack.h/.cpp`, `RackKindProfile.cs`, `RackKeyParams.cs`, `RackCard*.cs`, `NativeMethods.MidiRack.cs`, `NotaEngine.MidiRack.cs`, `MidiRackTools.cs`, the three new test files+- [X] T070 New dependency: none → N/A in the PR+- [X] T071 `CHANGELOG.md` `[Unreleased]` entries: Added — MIDI Effect Rack; MIDI effects in Instrument Rack chains (#329); mono (last note) and working glide on the Instrument Rack; the selector as a macro target. Changed — redesigned Instrument and Audio Effect Rack cards, macro mapping without a separate screen+- [X] T072 `nota-features` (FEATURES.md), `nota-docs` (EN + RU rack pages, a new MIDI Effect Rack page, screenshots in all themes as the docs use them) and `nota-shortcuts` (Esc ends macro mapping in the Preferences → Shortcuts list in `src/managed/Nota.App/PreferencesWindow.cs`)+- [X] T073 Engine behaviour change: covered by T015, T016, T027, T036, T041–T043, T055 and T056. Confirm every section prints in the full smoke run++---++## Dependencies & Execution Order++### Phase dependencies++- **Setup (1)**: T001 must run on the unmodified engine, before T004–T009.+- **Foundational (2)**: depends on Setup; blocks all stories.+- **US1 (3)** → **US2 (4)**: US2 builds on the US1 card regions (macro column, chain strip).+- **US5 (5)**: after US1 + US2; re-run in Polish (T065) for the other racks.+- **US3 (6)**: after US2 (shared mapping and Macros tab); independent of US4 and US6.+- **US4 (7)**: engine and ABI tasks T041–T051 depend only on Foundational; UI tasks T052–T053 after US2.+- **US6 (8)**: engine tasks T056–T061 depend only on Foundational (T004–T007); UI tasks T062–T063 after US1.+- **Polish (9)**: after the stories being shipped.++### Within each story++Tests first (they should fail), then engine → ABI → interop → managed → UI → MCP.++### Suggested PR stack (Constitution V)++1. Engine core + ABI + smoke: T001–T009, T015, T016–T018, T036 (engine part), T041–T047, T056–T060.+2. Managed plumbing + persistence + MCP: T010, T019, T026, T032, T040, T048–T051, T054–T055, T061, T064.+3. Shared card + themes: T011–T014, T020–T025, T028–T031, T033–T035, T037–T039, T052–T053, T062–T063, T065.+4. Docs: T071–T072.++Each PR runs T068.++---++## Parallel Examples++```bash+# Foundational, after T004–T007 land:+Task: "T010 P/Invoke midi-effect state in NativeMethods.Devices.cs / NotaEngine.Devices.cs"+Task: "T012 RackKindProfile.cs"+Task: "T013 RackKeyParams.cs"+Task: "T015 v8 compatibility + mapping rules + key params smoke sections"++# US4 tests together:+Task: "T041 midi rack routing" Task: "T042 no stuck notes" Task: "T043 persistence"++# US4 and US6 engine work in parallel (different files):+Task: "T044 MidiRack.h/.cpp" Task: "T059 RackInstrument renderBlock"+```++---++## Implementation Strategy++### MVP (P1)++1. Phases 1–2.+2. US1 (Instrument Rack on the new card) → US2 (in-place mapping) → US5 (themes).+3. **Stop and validate**: quickstart Q2 (v8, mono/glide, mapping sections), Q4 steps 1–6 for the Instrument Rack, Q5 for the Instrument card.++### Incremental delivery++4. US3: the Audio Effect Rack moves onto the card.+5. US4: MIDI Effect Rack.+6. US6: MIDI effects in Instrument Rack chains (#329).+7. Polish: all-rack theme sheet, perf gate, docs.++---++## Notes++- Never add lines to `tests/Nota.SmokeTest/*AllowList.txt` (Constitution VIII, SC-003).+- No allocation, lock or I/O on the audio thread in `MidiRack::process`, the mono/glide path or `renderBlock` (AR-6).+- `RackCardView.Drum.cs` / `MacroPanel.cs`: compile fixes only. The Drum Rack is out of scope.+- The user makes the commits: leave changes uncommitted for review.diff --git a/src/managed/Nota.App/Controls/RackBars.cs b/src/managed/Nota.App/Controls/RackBars.csnew file mode 100644index 00000000..9d22d179--- /dev/null+++ b/src/managed/Nota.App/Controls/RackBars.cs@@ -0,0 +1,303 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The small drawn controls of the shared rack card (specs/040):+// - RackRangeBar: a chain's key, velocity or select range (two draggable edges), or the+// Select-mode selector (one handle); a teal probe line marks the key under the pointer.+// - RackRuler: tick labels over the range bars.+// - RackCurvePreview: a macro's response curve with its current position (a graph window).+// - RackMapRangeBar: a macro target's min/max (min above max inverts) and where the macro+// drives it now.+// Colours are read from the palette slots while rendering, so a theme switch repaints them.+// Left button only: a right-click bubbles to the card's menus.++using System;+using System.Collections.Generic;+using System.Globalization;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;++namespace Nota.App;++internal sealed class RackRangeBar : Control+{+ private const double EdgeGrab = 6;++ public int Lo { get; set; }+ public int Hi { get; set; } = 127;+ public int Max { get; init; } = 127;+ /// <summary>One handle at <see cref="Lo"/> (the selector) instead of a range.</summary>+ public bool Single { get; init; }+ public IBrush? Hue { get; set; }+ public bool Highlight { get; set; }+ public bool Dim { get; set; }+ public int Probe { get; set; } = -1;+ public Func<int, int, string>? Label { get; init; }++ /// <summary>The range (or the selector) moved under the pointer.</summary>+ public event Action<int, int>? Changed;+ /// <summary>The drag ended.</summary>+ public event Action? Committed;+ /// <summary>The pointer is over value v (−1 when it leaves).</summary>+ public event Action<int>? Hover;++ private int _dragEdge = -1; // 0 lo, 1 hi+ private bool _hot;++ public RackRangeBar()+ {+ Height = 12;+ Cursor = new Cursor(StandardCursorType.SizeWestEast);+ ClipToBounds = false;+ }++ private double X(int v) => Math.Clamp(v / (double)Max, 0, 1) * Bounds.Width;+ private int V(double x) => (int)Math.Round(Math.Clamp(x / Math.Max(1, Bounds.Width), 0, 1) * Max);++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ double x = e.GetPosition(this).X;+ if (Single) _dragEdge = 0;+ else+ {+ double dl = Math.Abs(x - X(Lo)), dh = Math.Abs(x - X(Hi));+ _dragEdge = dl <= dh ? 0 : 1;+ if (Math.Min(dl, dh) > EdgeGrab && Lo == Hi) _dragEdge = x < X(Lo) ? 0 : 1;+ }+ _hot = true;+ e.Pointer.Capture(this);+ Move(x);+ e.Handled = true;+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ double x = e.GetPosition(this).X;+ if (_dragEdge >= 0) Move(x);+ else Hover?.Invoke(V(x));+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (_dragEdge < 0) return;+ _dragEdge = -1;+ _hot = false;+ e.Pointer.Capture(null);+ InvalidateVisual();+ Committed?.Invoke();+ }++ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ base.OnPointerCaptureLost(e);+ if (_dragEdge < 0) return;+ _dragEdge = -1;+ _hot = false;+ InvalidateVisual();+ Committed?.Invoke();+ }++ protected override void OnPointerExited(PointerEventArgs e)+ {+ base.OnPointerExited(e);+ if (_dragEdge < 0) Hover?.Invoke(-1);+ }++ private void Move(double x)+ {+ int v = V(x);+ if (Single) { Lo = Hi = v; }+ else if (_dragEdge == 0) Lo = Math.Min(v, Hi); // an edge never crosses the other+ else Hi = Math.Max(v, Lo);+ InvalidateVisual();+ Changed?.Invoke(Lo, Hi);+ }++ public override void Render(DrawingContext ctx)+ {+ var size = Bounds.Size;+ if (size.Width <= 0 || size.Height <= 0) return;+ var well = new Rect(size).Deflate(0.5);+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.Rule, 1), new RoundedRect(well, NotaRadius.ClipValue));+ var hue = Hue ?? NotaPalette.VizInk;+ if (Single)+ {+ double x = X(Lo);+ var ink = _hot ? NotaPalette.Accent : NotaPalette.VizInk; // the accent only while in the hand+ ctx.DrawRectangle(ink, null, new RoundedRect(new Rect(x - 3, -2, 6, size.Height + 4), NotaRadius.BarValue));+ }+ else+ {+ double x0 = X(Lo), x1 = X(Hi);+ var span = new Rect(x0, 1, Math.Max(2, x1 - x0), size.Height - 2);+ var color = (hue as ISolidColorBrush)?.Color ?? Colors.Transparent;+ byte alpha = Dim ? (byte)0x22 : Highlight ? (byte)0x88 : (byte)0x4C;+ ctx.DrawRectangle(new SolidColorBrush(color, alpha / 255.0), null, span);+ var edgeInk = Dim ? NotaPalette.TextDisabled : hue;+ ctx.DrawRectangle(edgeInk, null, new Rect(x0, 1, 2, size.Height - 2));+ ctx.DrawRectangle(edgeInk, null, new Rect(Math.Max(x0, x1 - 2), 1, 2, size.Height - 2));+ if (Label is not null)+ {+ var ft = NotaGraph.AxisText(Label(Lo, Hi), Dim ? NotaPalette.TextDisabled : NotaPalette.TextPrimary, 7);+ bool right = x1 / Math.Max(1, size.Width) > 0.7;+ double tx = right ? x1 - ft.Width - 4 : x0 + 4;+ if (tx < 2) tx = 2;+ ctx.DrawText(ft, new Point(tx, (size.Height - ft.Height) / 2));+ }+ }+ if (Probe >= 0)+ {+ double px = X(Probe);+ ctx.DrawRectangle(NotaPalette.Teal, null, new Rect(px - 0.5, -1, 1, size.Height + 2));+ }+ }+}++internal sealed class RackRuler : Control+{+ public IReadOnlyList<(int Value, string Label)> Ticks { get; init; } = [];+ public int Max { get; init; } = 127;++ public RackRuler() => Height = 10;++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width;+ foreach (var (v, label) in Ticks)+ {+ var ft = NotaGraph.AxisText(label, NotaPalette.TextAxis, 7);+ double x = Math.Clamp(v / (double)Max * w - ft.Width / 2, 0, Math.Max(0, w - ft.Width));+ ctx.DrawText(ft, new Point(x, Bounds.Height - ft.Height));+ }+ }+}++internal sealed class RackCurvePreview : Control+{+ /// <summary>0 Lin, 1 Exp, 2 Log, 3 S; −1 = mixed (the macro's targets differ).</summary>+ public int Curve { get; set; }+ public double Position { get; set; }++ public RackCurvePreview()+ {+ Width = 30;+ Height = 22;+ }++ public static double Apply(int curve, double v) => curve switch+ {+ 1 => v * v,+ 2 => Math.Sqrt(v),+ 3 => v * v * (3 - 2 * v),+ _ => v,+ };++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ NotaGraph.Window(ctx, r);+ if (Curve < 0) return;+ var plot = r.Deflate(new Thickness(3, 3, 3, 3));+ var geo = new StreamGeometry();+ using (var g = geo.Open())+ {+ for (int k = 0; k <= 16; k++)+ {+ double x = k / 16.0;+ var p = new Point(plot.X + x * plot.Width, plot.Bottom - Apply(Curve, x) * plot.Height);+ if (k == 0) g.BeginFigure(p, false); else g.LineTo(p);+ }+ g.EndFigure(false);+ }+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, geo);+ double pos = Math.Clamp(Position, 0, 1);+ NotaGraph.Node(ctx, new Point(plot.X + pos * plot.Width, plot.Bottom - Apply(Curve, pos) * plot.Height), true);+ }+}++internal sealed class RackMapRangeBar : Control+{+ /// <summary>The target's range as fractions of its full span; Min above Max inverts.</summary>+ public double Min { get; set; }+ public double Max { get; set; } = 1;+ /// <summary>Where the macro drives the target now, as a fraction.</summary>+ public double Current { get; set; }++ public event Action<double, double>? Changed;+ public event Action? Began;+ public event Action? Committed;++ private int _drag = -1; // 0 min, 1 max++ public RackMapRangeBar()+ {+ Height = 8;+ Cursor = new Cursor(StandardCursorType.SizeWestEast);+ }++ private double F(double x) => Math.Clamp(x / Math.Max(1, Bounds.Width), 0, 1);++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ double f = F(e.GetPosition(this).X);+ _drag = Math.Abs(f - Min) <= Math.Abs(f - Max) ? 0 : 1;+ Began?.Invoke();+ e.Pointer.Capture(this);+ Move(f);+ e.Handled = true;+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (_drag >= 0) Move(F(e.GetPosition(this).X));+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (_drag < 0) return;+ _drag = -1;+ e.Pointer.Capture(null);+ Committed?.Invoke();+ }++ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ base.OnPointerCaptureLost(e);+ if (_drag < 0) return;+ _drag = -1;+ Committed?.Invoke();+ }++ private void Move(double f)+ {+ if (_drag == 0) Min = f; else Max = f; // min may pass max: the response inverts+ InvalidateVisual();+ Changed?.Invoke(Min, Max);+ }++ public override void Render(DrawingContext ctx)+ {+ var size = Bounds.Size;+ if (size.Width <= 0) return;+ var well = new Rect(size).Deflate(0.5);+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.Rule, 1), new RoundedRect(well, NotaRadius.ClipValue));+ double w = size.Width, h = size.Height;+ double a = Math.Min(Min, Max) * w, b = Math.Max(Min, Max) * w;+ var teal = NotaPalette.Teal.Color;+ ctx.DrawRectangle(new SolidColorBrush(teal, 0x55 / 255.0), null, new Rect(a, 1, Math.Max(1, b - a), h - 2));+ var handle = NotaPalette.TealBright;+ ctx.DrawRectangle(handle, null, new RoundedRect(new Rect(Min * w - 2, -3, 4, h + 6), NotaRadius.BarValue));+ ctx.DrawRectangle(handle, null, new RoundedRect(new Rect(Max * w - 2, -3, 4, h + 6), NotaRadius.BarValue));+ ctx.DrawRectangle(NotaPalette.Accent, null, new Rect(Math.Clamp(Current, 0, 1) * w - 1, -2, 2, h + 4)); // live position+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs b/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.csindex e2516aee..dc8a5bfb 100644--- a/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs@@ -2,7 +2,7 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Detail · Devices — a uniform view over a rack (Instrument Rack via Rack*, Audio-// Effect Rack via RackDev*), so the one card renders both. HasInstrumentChains hides+// Effect Rack via RackDev*, MIDI Effect Rack via MidiRack*), so the one card renders all. HasInstrumentChains hides// the per-chain instrument selector for effect racks; AutomationDeviceIndex is the// plugin-param device index used when driving/recording the macros.@@ -10,10 +10,15 @@ using Nota.Application;namespace Nota.App;+/// <summary>Which rack a card shows (specs/040): the three share one card.</summary>+internal enum RackKind { Instrument, AudioEffect, MidiEffect }+internal interface IRackAccess{bool HasInstrumentChains { get; }int AutomationDeviceIndex { get; }+ /// <summary>The rack in a MIDI Learn rack target (MidiTarget.DeviceIndex).</summary>+ int LearnDeviceIndex => AutomationDeviceIndex;int ChainCount();int AddChain(int instKind);bool RemoveChain(int chain);@@ -64,6 +69,72 @@ internal interface IRackAccessint ChainDeviceLayerWave(int chain, int dev, int layer, float[] outSamples, int maxSamples) => 0;string ChainDeviceText(int chain, int dev, int id) => "";void ChainDeviceAction(int chain, int dev, int id, int iarg, float farg) { }++ // ---- shared rack card surface (specs/040) --------------------------------+ // Defaults describe "not supported", so an access only implements what its rack has.+ RackKind Kind => HasInstrumentChains ? RackKind.Instrument : RackKind.AudioEffect;+ float MacroGet(int i) => 0f;+ void MacroSet(int i, float v) { }+ string ChainName(int chain) => "";+ void SetChainName(int chain, string name) { }+ /// <summary>Key and velocity zone (Instrument and MIDI racks).</summary>+ void ChainZone(int chain, out int keyLo, out int keyHi, out int velLo, out int velHi) { keyLo = 0; keyHi = 127; velLo = 0; velHi = 127; }+ void SetChainZone(int chain, int keyLo, int keyHi, int velLo, int velHi) { }+ /// <summary>Select-mode range, 0..127 (Audio Effect and MIDI racks). Which engine fields hold+ /// it is the access's business: the Audio Effect Rack keeps it in its velocity fields.</summary>+ void SelectRange(int chain, out int lo, out int hi) { lo = 0; hi = 127; }+ void SetSelectRange(int chain, int lo, int hi) { }+ bool MoveChain(int from, int to) => false;+ /// <summary>Copies a chain (devices, controls, its mappings) after itself; the new index or <0.</summary>+ int DuplicateChain(int chain) => -1;++ // Chain MIDI effects: a MIDI Effect Rack chain, or the MIDI section in front of an+ // Instrument Rack chain's instrument (issue #329). None by default.+ int ChainMidiCount(int chain) => 0;+ int AddChainMidi(int chain, int kind) => -1;+ bool RemoveChainMidi(int chain, int idx) => false;+ void MoveChainMidi(int chain, int from, int to) { }+ int ChainMidiKind(int chain, int idx) => -1;+ string ChainMidiName(int chain, int idx) => "";+ int ChainMidiParamCount(int chain, int idx) => 0;+ string ChainMidiParamName(int chain, int idx, int p) => "";+ float ChainMidiParamMin(int chain, int idx, int p) => 0f;+ float ChainMidiParamMax(int chain, int idx, int p) => 1f;+ float ChainMidiParamGet(int chain, int idx, int p) => 0f;+ void ChainMidiParamSet(int chain, int idx, int p, float v) { }+ bool ChainMidiBypassed(int chain, int idx) => false;+ void SetChainMidiBypassed(int chain, int idx, bool b) { }++ // Rack output and routing (what each rack has: see RackKindProfile).+ int RackMode() => 0; // 0 Parallel, 1 Serial, 2 Select+ void SetRackMode(int mode) { }+ float Selector() => 0.5f; // Select-mode selector, 0..1 (the manual one)+ void SetSelector(float v) { }+ bool SelectorFollows() => false; // Audio Effect Rack: the selector follows the input level+ void SetSelectorFollows(bool on) { }+ float LiveSelector() => Selector(); // where the selector is now (follow or manual)+ float RackVolume() => 1f; // linear+ void SetRackVolume(float v) { }+ float RackGlide() => 0f; // 0..1 = 0..500 ms+ void SetRackGlide(float v) { }+ bool RackMono() => false;+ void SetRackMono(bool on) { }+ float RackDryWet() => 1f;+ void SetRackDryWet(float v) { }+ bool RackPdc() => false;+ void SetRackPdc(bool on) { }+ bool RackMerge() => true;+ void SetRackMerge(bool on) { }+ bool RackThru() => true;+ void SetRackThru(bool on) { }+ int ChainTranspose(int chain) => 0; // MIDI chains, semitones+ void SetChainTranspose(int chain, int st) { }+ float ChainVelScale(int chain) => 1f; // MIDI chains' Volume, 0..2+ void SetChainVelScale(int chain, float v) { }++ /// <summary>Where a macro's moves are recorded as automation, and what MIDI Learn binds it to.</summary>+ (AutomationTarget Target, int Device, int Param, string Id) MacroAutomation(int i) => (AutomationTarget.PluginParam, AutomationDeviceIndex, -1, $"macro{i + 1}");+ MidiTarget MacroLearnTarget(int track, int i) => MidiTarget.PluginParam(track, AutomationDeviceIndex, i);}internal sealed class InstrumentRackAccess(IAudioEngine e, int t) : IRackAccess@@ -122,6 +193,35 @@ internal sealed class InstrumentRackAccess(IAudioEngine e, int t) : IRackAccesspublic bool SetMappingRange(int i, float lo, float hi) => e.RackSetMappingRange(t, i, lo, hi);public int MappingCurve(int i) => e.RackMappingCurve(t, i);public bool SetMappingCurve(int i, int curve) => e.RackSetMappingCurve(t, i, curve);+ public RackKind Kind => RackKind.Instrument;+ public float MacroGet(int i) => e.RackMacroGet(t, i);+ public void MacroSet(int i, float v) => e.RackMacroSet(t, i, v);+ public string ChainName(int c) => e.RackChainName(t, c);+ public void SetChainName(int c, string name) => e.RackSetChainName(t, c, name);+ public void ChainZone(int c, out int kl, out int kh, out int vl, out int vh) => e.RackChainZone(t, c, out kl, out kh, out vl, out vh);+ public void SetChainZone(int c, int kl, int kh, int vl, int vh) => e.RackSetChainZone(t, c, kl, kh, vl, vh);+ public int DuplicateChain(int c) => e.RackDuplicateChain(t, c);+ public float RackVolume() => e.RackVolume(t);+ public void SetRackVolume(float v) => e.RackSetVolume(t, v);+ public float RackGlide() => e.RackGlide(t);+ public void SetRackGlide(float v) => e.RackSetGlide(t, v);+ public bool RackMono() => e.RackMono(t);+ public void SetRackMono(bool on) => e.RackSetMono(t, on);+ // MIDI effects in front of a chain's instrument (#329).+ public int ChainMidiCount(int c) => e.RackChainMidiCount(t, c);+ public int AddChainMidi(int c, int kind) => e.RackChainMidiAdd(t, c, kind);+ public bool RemoveChainMidi(int c, int i) => e.RackChainMidiRemove(t, c, i);+ public void MoveChainMidi(int c, int f, int to) => e.RackChainMidiMove(t, c, f, to);+ public int ChainMidiKind(int c, int i) => e.RackChainMidiKind(t, c, i);+ public string ChainMidiName(int c, int i) => e.RackChainMidiName(t, c, i);+ public int ChainMidiParamCount(int c, int i) => e.RackChainMidiParamCount(t, c, i);+ public string ChainMidiParamName(int c, int i, int p) => e.RackChainMidiParamName(t, c, i, p);+ public float ChainMidiParamMin(int c, int i, int p) => e.RackChainMidiParamMin(t, c, i, p);+ public float ChainMidiParamMax(int c, int i, int p) => e.RackChainMidiParamMax(t, c, i, p);+ public float ChainMidiParamGet(int c, int i, int p) => e.RackChainMidiParamGet(t, c, i, p);+ public void ChainMidiParamSet(int c, int i, int p, float v) => e.RackChainMidiParamSet(t, c, i, p, v);+ public bool ChainMidiBypassed(int c, int i) => e.RackChainMidiBypassed(t, c, i);+ public void SetChainMidiBypassed(int c, int i, bool b) => e.RackChainMidiSetBypassed(t, c, i, b);}internal sealed class EffectRackAccess(IAudioEngine e, int t, int di) : IRackAccess@@ -180,6 +280,26 @@ internal sealed class EffectRackAccess(IAudioEngine e, int t, int di) : IRackAccpublic bool SetMappingRange(int i, float lo, float hi) => e.RackDevSetMappingRange(t, di, i, lo, hi);public int MappingCurve(int i) => e.RackDevMappingCurve(t, di, i);public bool SetMappingCurve(int i, int curve) => e.RackDevSetMappingCurve(t, di, i, curve);+ public RackKind Kind => RackKind.AudioEffect;+ public float MacroGet(int i) => e.RackDevMacroGet(t, di, i);+ public void MacroSet(int i, float v) => e.RackDevMacroSet(t, di, i, v);+ // The Audio Effect Rack keeps its select range in the chain's velocity fields (v7 blobs).+ public void SelectRange(int c, out int lo, out int hi) => e.RackDevChainZone(t, di, c, out lo, out hi);+ public void SetSelectRange(int c, int lo, int hi) => e.RackDevSetChainZone(t, di, c, lo, hi);+ public int DuplicateChain(int c) => e.RackDevDuplicateChain(t, di, c);+ public int RackMode() => e.RackDevMode(t, di);+ public void SetRackMode(int mode) => e.RackDevSetMode(t, di, mode);+ public float Selector() => e.RackDevChainSelect(t, di);+ public void SetSelector(float v) => e.RackDevSetChainSelect(t, di, v);+ public bool SelectorFollows() => e.RackDevSelFollow(t, di);+ public void SetSelectorFollows(bool on) => e.RackDevSetSelFollow(t, di, on);+ public float LiveSelector() => e.RackDevSelFollow(t, di) ? e.RackDevLiveSelector(t, di) : e.RackDevChainSelect(t, di);+ public float RackVolume() => e.RackDevVolume(t, di);+ public void SetRackVolume(float v) => e.RackDevSetVolume(t, di, v);+ public float RackDryWet() => e.RackDevDryWet(t, di);+ public void SetRackDryWet(float v) => e.RackDevSetDryWet(t, di, v);+ public bool RackPdc() => e.RackDevPdc(t, di);+ public void SetRackPdc(bool on) => e.RackDevSetPdc(t, di, on);}// Nota Rhythm's eight voices as effect-only "chains": each voice's insert chain through the@@ -239,3 +359,119 @@ internal sealed class RhythmVoiceAccess(IAudioEngine e, int t) : IRackAccesspublic int MappingCurve(int i) => 0;public bool SetMappingCurve(int i, int curve) => false;}++// The MIDI Effect Rack (MIDI kind 6, specs/040) at MIDI effect index mi. Its chains hold MIDI+// effects only. The card addresses a chain's MIDI effect j as RackMacroMapping.MidiDeviceBase − j;+// the MidiRack* calls take plain j, so mappings translate on the way in and out. Its macros+// are the MIDI effect's parameters 0..7 (automation, MIDI Learn).+internal sealed class MidiRackAccess(IAudioEngine e, int t, int mi) : IRackAccess+{+ private static int Plain(int target) => target <= RackMacroMapping.MidiDeviceBase ? RackMacroMapping.MidiDeviceBase - target : target;+ private static int Card(int device) => device >= 0 ? RackMacroMapping.MidiDeviceBase - device : device;++ public RackKind Kind => RackKind.MidiEffect;+ public bool HasInstrumentChains => false;+ public bool HostsPlugins => false;+ public int AutomationDeviceIndex => mi;+ public int LearnDeviceIndex => MidiTarget.MidiRackBase - mi; // not an audio rack's index+ public (AutomationTarget Target, int Device, int Param, string Id) MacroAutomation(int i) => (AutomationTarget.MidiDeviceParam, mi, i, "");+ public MidiTarget MacroLearnTarget(int track, int i) => MidiTarget.MidiDeviceParam(track, mi, i);++ public int ChainCount() => e.MidiRackChainCount(t, mi);+ public int AddChain(int instKind) => e.MidiRackAddChain(t, mi);+ public bool RemoveChain(int c) => e.MidiRackRemoveChain(t, mi, c);+ public int DuplicateChain(int c) => e.MidiRackDuplicateChain(t, mi, c);+ public string ChainName(int c) => e.MidiRackChainName(t, mi, c);+ public void SetChainName(int c, string name) => e.MidiRackSetChainName(t, mi, c, name);++ // No instrument, no audio devices.+ public bool SetChainInstrument(int c, int k) => false;+ public int ChainInstrumentKind(int c) => -2;+ public string ChainInstrumentName(int c) => "";+ public int ChainInstrumentParamCount(int c) => 0;+ public string ChainInstrumentParamName(int c, int p) => "";+ public float ChainInstrumentParamGet(int c, int p) => 0f;+ public void ChainInstrumentParamSet(int c, int p, float v) { }+ public int ChainDeviceCount(int c) => 0;+ public int AddChainDevice(int c, int k) => -1;+ public int AddPluginInstrumentChain(int catalogIndex) => -1;+ public int AddPluginChainDevice(int c, int catalogIndex) => -1;+ public bool RemoveChainDevice(int c, int d) => false;+ public void MoveChainDevice(int c, int f, int to) { }+ public string ChainDeviceName(int c, int d) => "";+ public int ChainDeviceParamCount(int c, int d) => 0;+ public string ChainDeviceParamName(int c, int d, int p) => "";+ public float ChainDeviceParamMin(int c, int d, int p) => 0f;+ public float ChainDeviceParamMax(int c, int d, int p) => 1f;+ public float ChainDeviceParamGet(int c, int d, int p) => 0f;+ public void ChainDeviceParamSet(int c, int d, int p, float v) { }+ public bool ChainDeviceBypassed(int c, int d) => false;+ public void SetChainDeviceBypassed(int c, int d, bool b) { }+ public int ChainDeviceBuiltinKind(int c, int d) => -1;+ public void OpenChainDeviceEditor(int c, int d) { }++ // Chain MIDI effects.+ public int ChainMidiCount(int c) => e.MidiRackChainDeviceCount(t, mi, c);+ public int AddChainMidi(int c, int kind) => e.MidiRackChainDeviceAdd(t, mi, c, kind);+ public bool RemoveChainMidi(int c, int i) => e.MidiRackChainDeviceRemove(t, mi, c, i);+ public void MoveChainMidi(int c, int f, int to) => e.MidiRackChainDeviceMove(t, mi, c, f, to);+ public int ChainMidiKind(int c, int i) => e.MidiRackChainDeviceKind(t, mi, c, i);+ public string ChainMidiName(int c, int i) => e.MidiRackChainDeviceName(t, mi, c, i);+ public int ChainMidiParamCount(int c, int i) => e.MidiRackChainDeviceParamCount(t, mi, c, i);+ public string ChainMidiParamName(int c, int i, int p) => e.MidiRackChainDeviceParamName(t, mi, c, i, p);+ public float ChainMidiParamMin(int c, int i, int p) => e.MidiRackChainDeviceParamMin(t, mi, c, i, p);+ public float ChainMidiParamMax(int c, int i, int p) => e.MidiRackChainDeviceParamMax(t, mi, c, i, p);+ public float ChainMidiParamGet(int c, int i, int p) => e.MidiRackChainDeviceParamGet(t, mi, c, i, p);+ public void ChainMidiParamSet(int c, int i, int p, float v) => e.MidiRackChainDeviceParamSet(t, mi, c, i, p, v);+ public bool ChainMidiBypassed(int c, int i) => e.MidiRackChainDeviceBypassed(t, mi, c, i);+ public void SetChainMidiBypassed(int c, int i, bool b) => e.MidiRackChainDeviceSetBypassed(t, mi, c, i, b);++ // Chain controls: Volume scales velocity; Transpose instead of Pan.+ public float ChainGain(int c) => e.MidiRackChainVelScale(t, mi, c);+ public void SetChainGain(int c, float v) => e.MidiRackSetChainVelScale(t, mi, c, v);+ public float ChainPan(int c) => 0f;+ public void SetChainPan(int c, float v) { }+ public bool ChainMute(int c) => e.MidiRackChainMute(t, mi, c);+ public void SetChainMute(int c, bool b) => e.MidiRackSetChainMute(t, mi, c, b);+ public bool ChainSolo(int c) => e.MidiRackChainSolo(t, mi, c);+ public void SetChainSolo(int c, bool b) => e.MidiRackSetChainSolo(t, mi, c, b);+ public int ChainTriggerNote(int c) => -1;+ public void SetChainTriggerNote(int c, int note) { }+ public float ChainMeter(int c) => e.MidiRackChainActivity(t, mi, c);+ public void ChainZone(int c, out int kl, out int kh, out int vl, out int vh) => e.MidiRackChainZone(t, mi, c, out kl, out kh, out vl, out vh);+ public void SetChainZone(int c, int kl, int kh, int vl, int vh) => e.MidiRackSetChainZone(t, mi, c, kl, kh, vl, vh);+ public void SelectRange(int c, out int lo, out int hi) => e.MidiRackChainSelectRange(t, mi, c, out lo, out hi);+ public void SetSelectRange(int c, int lo, int hi) => e.MidiRackSetChainSelect(t, mi, c, lo, hi);+ public int ChainTranspose(int c) => e.MidiRackChainTranspose(t, mi, c);+ public void SetChainTranspose(int c, int st) => e.MidiRackSetChainTranspose(t, mi, c, st);+ public float ChainVelScale(int c) => e.MidiRackChainVelScale(t, mi, c);+ public void SetChainVelScale(int c, float v) => e.MidiRackSetChainVelScale(t, mi, c, v);++ // Rack.+ public int RackMode() => e.MidiRackMode(t, mi);+ public void SetRackMode(int mode) => e.MidiRackSetMode(t, mi, mode);+ public float Selector() => e.MidiRackSelector(t, mi);+ public void SetSelector(float v) => e.MidiRackSetSelector(t, mi, v);+ public bool RackMerge() => e.MidiRackMerge(t, mi);+ public void SetRackMerge(bool on) => e.MidiRackSetMerge(t, mi, on);+ public bool RackThru() => e.MidiRackThru(t, mi);+ public void SetRackThru(bool on) => e.MidiRackSetThru(t, mi, on);++ // Macros and mappings.+ public float MacroGet(int i) => e.MidiRackMacroGet(t, mi, i);+ public void MacroSet(int i, float v) => e.MidiRackMacroSet(t, mi, i, v);+ public string MacroName(int i) => e.MidiRackMacroName(t, mi, i);+ public void SetMacroName(int i, string name) => e.MidiRackSetMacroName(t, mi, i, name);+ public int AddMacroMapping(int m, int c, int td, int p, float lo, float hi) => e.MidiRackAddMacroMapping(t, mi, m, c, Plain(td), p, lo, hi);+ public int MappingCount() => e.MidiRackMappingCount(t, mi);+ public bool TryGetMapping(int i, out RackMacroMapping m)+ {+ if (e.MidiRackMappingInfo(t, mi, i, out int macro, out int chain, out int device, out int param, out float lo, out float hi, out _) == 0) { m = default; return false; }+ m = new RackMacroMapping(macro, chain, Card(device), param, lo, hi);+ return true;+ }+ public bool RemoveMapping(int i) => e.MidiRackRemoveMapping(t, mi, i);+ public bool SetMappingRange(int i, float lo, float hi) => e.MidiRackSetMappingRange(t, mi, i, lo, hi);+ public int MappingCurve(int i) => e.MidiRackMappingInfo(t, mi, i, out _, out _, out _, out _, out _, out _, out int curve) != 0 ? curve : 0;+ public bool SetMappingCurve(int i, int curve) => e.MidiRackSetMappingCurve(t, mi, i, curve);+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.csnew file mode 100644index 00000000..f5ff0164--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs@@ -0,0 +1,726 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the rack card's Chains tab (specs/040): the chain list (colour stripe,+// name, mute, solo, zone summary, level) beside the chosen chain's devices left to right as+// compact cards. An Instrument Rack chain shows three sections: its MIDI effects, its+// instrument, its audio effects (issue #329). A compact card shows a device's key+// parameters (RackKeyParams); while a macro is being mapped it lists every parameter and a+// click maps or unmaps it. A mapped parameter follows its macro and opens it on a click.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Collections;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Controls.Shapes;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using Nota.Presentation;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal enum RcSlot { Midi, Instrument, Effect }++internal sealed partial class RackCardView+{+ private const double RcChainListWidth = 124, RcCompactWidth = 96;++ // A device's parameter surface, however the rack addresses it.+ private sealed record RcParams(int Count, Func<int, string> Name, Func<int, float> Min, Func<int, float> Max,+ Func<int, float> Get, Action<int, float> Set, Func<float, string> Text);++ private RcParams RcParamsOf(int c, RcSlot slot, int idx)+ {+ var a = _ra;+ return slot switch+ {+ RcSlot.Instrument => new(a.ChainInstrumentParamCount(c), p => a.ChainInstrumentParamName(c, p), _ => 0f, _ => 1f,+ p => a.ChainInstrumentParamGet(c, p), (p, v) => a.ChainInstrumentParamSet(c, p, v), v => Pct(v)),+ RcSlot.Midi => new(a.ChainMidiParamCount(c, idx), p => a.ChainMidiParamName(c, idx, p), p => a.ChainMidiParamMin(c, idx, p),+ p => a.ChainMidiParamMax(c, idx, p), p => a.ChainMidiParamGet(c, idx, p), (p, v) => a.ChainMidiParamSet(c, idx, p, v), DeviceParamControls.Fmt),+ _ => new(a.ChainDeviceParamCount(c, idx), p => a.ChainDeviceParamName(c, idx, p), p => a.ChainDeviceParamMin(c, idx, p),+ p => a.ChainDeviceParamMax(c, idx, p), p => a.ChainDeviceParamGet(c, idx, p), (p, v) => a.ChainDeviceParamSet(c, idx, p, v), DeviceParamControls.Fmt),+ };+ }++ /// <summary>The mapping address of a chain child: −1 the instrument, ≥ 0 an audio device, ≤ −1000 a MIDI effect.</summary>+ private static int RcTarget(RcSlot slot, int idx) => slot switch+ {+ RcSlot.Instrument => -1,+ RcSlot.Midi => RackMacroMapping.MidiDeviceBase - idx,+ _ => idx,+ };++ // ---- the tab ----------------------------------------------------------------------++ private Control RcChainsTab()+ {+ var list = RcChainList();+ list.Width = RcChainListWidth;+ var lane = RcDeviceLane();+ Grid.SetColumn(lane, 1);+ return new Grid { ColumnDefinitions = new ColumnDefinitions($"{RcChainListWidth},*"), ColumnSpacing = 6, Children = { list, lane } };+ }++ // ---- chain list -------------------------------------------------------------------++ private Control RcChainList()+ {+ var a = _ra;+ var rows = new StackPanel { Spacing = 3 };+ for (int c = 0; c < a.ChainCount(); c++) rows.Children.Add(RcChainRow(c));+ var add = RcAddChainKey();+ rows.Children.Add(add);+ var scroll = new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };+ var hint = Hint(_rp.ChainsHint);+ if (hint is TextBlock tb) { tb.TextWrapping = TextWrapping.Wrap; tb.FontSize = 7.5; }+ DockPanel.SetDock(hint, Dock.Bottom);+ var dock = new DockPanel { LastChildFill = true, Background = Brushes.Transparent, Children = { hint, scroll } };+ // A device dropped on the list (not on a row) starts a new chain.+ DragDrop.SetAllowDrop(dock, true);+ DragDrop.AddDragOverHandler(dock, (_, e) =>+ {+ if (!BrowserView.IsBrowserDrag || BrowserView.CurrentDrag is not { } it || !RcIsDevice(it)) { e.DragEffects = DragDropEffects.None; return; }+ e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow();+ });+ DragDrop.AddDropHandler(dock, (_, e) =>+ {+ if (BrowserView.CurrentDrag is not { } it) return;+ e.Handled = true;+ RcDropAsNewChain(it);+ });+ return dock;+ }++ private Control RcAddChainKey()+ {+ var label = Glyph.Labeled("Chain", GlyphKind.Plus, 8, NotaType.KnobLabel);+ var key = new Panel { Height = 16, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent };+ var dash = new Rectangle+ {+ Stroke = NotaPalette.BorderStrong, StrokeThickness = 1, StrokeDashArray = new AvaloniaList<double> { 3, 2.5 },+ RadiusX = NotaRadius.ClipValue, RadiusY = NotaRadius.ClipValue,+ };+ label.HorizontalAlignment = HorizontalAlignment.Center;+ label.VerticalAlignment = VerticalAlignment.Center;+ key.Children.Add(dash);+ key.Children.Add(label);+ bool full = _rp.Kind == RackKind.MidiEffect && _ra.ChainCount() >= RcMidiChainLimit;+ ToolTip.SetTip(key, full ? $"A MIDI Effect Rack holds up to {RcMidiChainLimit} chains" : "Add a chain — or drop a device from the Browser on the list");+ key.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(key).Properties.IsLeftButtonPressed || full) return;+ e.Handled = true;+ if (_rp.TakesInstrument) { ShowAddChainMenu(_ra, key); return; }+ int c = _ra.AddChain(-1);+ if (c >= 0) Sel = c;+ DeferRebuild();+ };+ return key;+ }++ private const int RcMidiChainLimit = 16;++ private Control RcChainRow(int c)+ {+ var a = _ra;+ bool chosen = c == Sel, audible = RcAudible(c);+ string name = RcChainName(c);++ var stripe = new Border { Width = 3, Height = 9, CornerRadius = NotaRadius.Bar, Background = ChainHue(c), VerticalAlignment = VerticalAlignment.Center };+ var nameTb = RcName(name, chosen ? NotaPalette.AccentBright : audible ? NotaPalette.TextPrimary : NotaPalette.TextDisabled, NotaType.KnobLabel);+ var m = IrMsBtn("M", a.ChainMute(c), NotaPalette.Mute, () => { a.SetChainMute(c, !a.ChainMute(c)); DeferRebuild(); });+ var s = IrMsBtn("S", a.ChainSolo(c), NotaPalette.Solo, () => { a.SetChainSolo(c, !a.ChainSolo(c)); DeferRebuild(); });+ ToolTip.SetTip(m, "Mute chain");+ ToolTip.SetTip(s, "Solo chain");+ MidiLearn.Bind(m, MidiTarget.RackChainMute(T, a.LearnDeviceIndex, c), "Chain Mute");+ MidiLearn.Bind(s, MidiTarget.RackChainSolo(T, a.LearnDeviceIndex, c), "Chain Solo");+ var top = new DockPanel { LastChildFill = true, Children = { RcDock(stripe, Dock.Left), RcDock(s, Dock.Right), RcDock(m, Dock.Right), nameTb } };+ stripe.Margin = new Thickness(0, 0, 4, 0);+ m.Margin = new Thickness(0, 0, 2, 0);++ var summary = RcMono(RcChainSummary(c), NotaPalette.TextSecondary, 7.5);+ var meterFill = new Border { Background = NotaPalette.Success, HorizontalAlignment = HorizontalAlignment.Left, CornerRadius = NotaRadius.Bar, Width = 0 };+ var meter = new Border { Height = 3, MinWidth = 16, Background = NotaPalette.BgSunken, CornerRadius = NotaRadius.Bar, Child = meterFill, VerticalAlignment = VerticalAlignment.Center };+ _irTick.Add(() => meterFill.Width = meter.Bounds.Width * Math.Clamp(a.ChainMeter(c), 0, 1));+ summary.Margin = new Thickness(0, 0, 5, 0);+ var bottom = new DockPanel { LastChildFill = true, Children = { RcDock(summary, Dock.Left), meter } };++ var row = new Border+ {+ Height = 34, CornerRadius = NotaRadius.Clip, BorderThickness = new Thickness(1), Padding = new Thickness(5, 0),+ Background = chosen ? RowSel : NotaPalette.SurfaceRaised, BorderBrush = chosen ? NotaPalette.Accent : NotaPalette.BorderDefault,+ Cursor = new Cursor(StandardCursorType.Hand),+ Child = new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { top, bottom } },+ };+ if (!audible) row.AttachedToVisualTree += (_, _) => Inactive.Set(row, true, interactive: true);+ row.PointerPressed += (_, e) =>+ {+ var pt = e.GetCurrentPoint(row).Properties;+ if (pt.IsRightButtonPressed) { e.Handled = true; RcChainMenu(row, c); return; }+ if (!pt.IsLeftButtonPressed) return;+ if (e.ClickCount == 2 && nameTb.IsPointerOver) { RcPromptRename(nameTb, name, n => a.SetChainName(c, n)); return; }+ if (Sel != c) { Sel = c; DeferRebuild(); }+ };+ DragDrop.SetAllowDrop(row, true);+ DragDrop.AddDragOverHandler(row, (_, e) =>+ {+ if (!BrowserView.IsBrowserDrag || BrowserView.CurrentDrag is not { } it || !RcIsDevice(it)) { e.DragEffects = DragDropEffects.None; return; }+ e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow(); row.BorderBrush = NotaPalette.AccentBright;+ });+ DragDrop.AddDragLeaveHandler(row, (_, _) => row.BorderBrush = chosen ? NotaPalette.Accent : NotaPalette.BorderDefault);+ DragDrop.AddDropHandler(row, (_, e) =>+ {+ row.BorderBrush = chosen ? NotaPalette.Accent : NotaPalette.BorderDefault;+ if (BrowserView.CurrentDrag is not { } it) return;+ e.Handled = true;+ Sel = c;+ RcDropOnChain(c, it);+ });+ return row;+ }++ private string RcChainSummary(int c)+ {+ var a = _ra;+ if (_rp.Kind == RackKind.AudioEffect)+ {+ if (a.RackMode() == RackKindProfile.Select) { a.SelectRange(c, out int lo, out int hi); return $"sel {lo}–{hi}"; }+ int n = a.ChainDeviceCount(c);+ return n == 1 ? "1 device" : $"{n} devices";+ }+ a.ChainZone(c, out int kl, out int kh, out int vl, out int vh);+ string s = $"{NoteName(kl)}–{NoteName(kh)}";+ if (vl > 0 || vh < 127) s += $" · v{vl}–{vh}";+ return s;+ }++ private void RcChainMenu(Control anchor, int c)+ {+ var a = _ra;+ var f = new MenuFlyout();+ f.Items.Add(MenuKit.Header(RcChainName(c), null, $"Chain · {c + 1}"));+ f.Items.Add(new Separator());+ var rename = new MenuItem { Header = "Rename…" };+ rename.Click += (_, _) => RcPromptRename(anchor, RcChainName(c), n => a.SetChainName(c, n));+ f.Items.Add(rename);+ bool full = _rp.Kind == RackKind.MidiEffect && a.ChainCount() >= RcMidiChainLimit;+ var dup = new MenuItem { Header = "Duplicate", IsEnabled = !full };+ dup.Click += (_, _) => { int d = a.DuplicateChain(c); if (d >= 0) Sel = d; DeferRebuild(); };+ f.Items.Add(dup);+ if (a.ChainCount() > 1)+ {+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Danger("Delete chain", GlyphKind.Trash, () => RcDeleteChain(c)));+ }+ f.ShowAt(anchor, showAtPointer: true);+ }++ private void RcDeleteChain(int c)+ {+ if (_ra.ChainCount() <= 1) return; // a rack keeps one chain+ _ra.RemoveChain(c);+ Sel = Math.Max(0, c - 1);+ DeferRebuild();+ }++ // ---- drops ------------------------------------------------------------------------++ private static bool RcIsDevice(BrowserItem it) => it.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument+ or BrowserItemKind.BuiltinEffect or BrowserItemKind.PluginEffect or BrowserItemKind.BuiltinMidiEffect;++ private static bool RcIsInstrument(BrowserItem it) => it.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument;++ // A rack takes only its own kinds; a refused drop says why in the status bar.+ private bool RcAccepts(BrowserItem it, out string why)+ {+ why = "";+ if (RcIsInstrument(it))+ {+ if (_rp.TakesInstrument) return true;+ why = _rp.Kind == RackKind.MidiEffect ? "A MIDI Effect Rack takes MIDI effects only." : "An Audio Effect Rack takes audio effects only.";+ return false;+ }+ if (IsEffect(it))+ {+ if (!_rp.TakesAudioEffects) { why = "A MIDI Effect Rack takes MIDI effects only."; return false; }+ if (it.Kind == BrowserItemKind.PluginEffect && !_ra.HostsPlugins) { why = "This rack can't host plug-ins."; return false; }+ if (it.Kind == BrowserItemKind.BuiltinEffect && it.BuiltinKind == 5) { why = "A rack can't go inside a rack."; return false; }+ return true;+ }+ if (it.Kind == BrowserItemKind.BuiltinMidiEffect)+ {+ if (!_rp.TakesMidiEffects) { why = "An Audio Effect Rack takes audio effects only."; return false; }+ if (it.BuiltinKind is < 0 or > 5) { why = "A rack can't go inside a rack."; return false; }+ return true;+ }+ why = "Drop a device here.";+ return false;+ }++ private void RcDropOnChain(int c, BrowserItem it)+ {+ if (!RcAccepts(it, out var why)) { _ctx.Status(why); return; }+ var a = _ra;+ if (RcIsInstrument(it))+ {+ // On a chain an instrument replaces the chain's own; a plug-in starts a new layer.+ if (it.Kind == BrowserItemKind.BuiltinInstrument && a.SetChainInstrument(c, it.BuiltinKind)) { DeferRebuild(); return; }+ RcDropAsNewChain(it);+ return;+ }+ if (it.Kind == BrowserItemKind.BuiltinMidiEffect) { a.AddChainMidi(c, it.BuiltinKind); DeferRebuild(); return; }+ DropEffectOnChain(a, c, it);+ }++ private void RcDropAsNewChain(BrowserItem it)+ {+ if (!RcAccepts(it, out var why)) { _ctx.Status(why); return; }+ var a = _ra;+ if (_rp.Kind == RackKind.MidiEffect && a.ChainCount() >= RcMidiChainLimit) { _ctx.Status($"A MIDI Effect Rack holds up to {RcMidiChainLimit} chains."); return; }+ int c = -1;+ if (it.Kind == BrowserItemKind.BuiltinInstrument) c = a.AddChain(it.BuiltinKind);+ else if (it.Kind == BrowserItemKind.PluginInstrument) c = a.AddPluginInstrumentChain(it.CatalogIndex);+ else+ {+ c = a.AddChain(-1);+ if (c >= 0) RcDropOnChain(c, it);+ }+ if (c >= 0) Sel = c;+ DeferRebuild();+ }++ // ---- device lane: the chosen chain, left to right ----------------------------------++ private Control RcDeviceLane()+ {+ var a = _ra;+ if (a.ChainCount() == 0) return new Border { Padding = new Thickness(4), Child = Hint("Add a chain to start.") };+ int c = Sel;+ Control head;+ if (_rs.Mapping)+ {+ var label = RcText("Mapping", NotaPalette.Teal, NotaType.KnobLabel, FontWeight.SemiBold);+ var macro = RcName($"Macro {_rs.MappingMacro + 1} · {a.MacroName(_rs.MappingMacro)}", NotaPalette.TextPrimary, NotaType.KnobLabel);+ var how = RcText("Click to add or remove", NotaPalette.TextSecondary, 7.5, FontWeight.Normal);+ head = new Border+ {+ Height = 16, CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 0), BorderThickness = new Thickness(1),+ Background = NotaPalette.Wash(NotaPalette.Teal, 0x24), BorderBrush = NotaPalette.Teal,+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { label, macro, how } },+ };+ }+ else+ {+ int n = (_rp.TakesInstrument && a.ChainInstrumentKind(c) > -2 ? 1 : 0) + a.ChainDeviceCount(c) + a.ChainMidiCount(c);+ var dot = new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Badge, Background = ChainHue(c), VerticalAlignment = VerticalAlignment.Center };+ string flow = _rp.Kind == RackKind.MidiEffect ? "notes" : "signal";+ head = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 6, Height = 16, Children =+ {+ dot, RcName(RcChainName(c), NotaPalette.TextPrimary, NotaType.RowLabel),+ RcMono($"{n} device{(n == 1 ? "" : "s")} · {flow} left → right", NotaPalette.TextTertiary, 7.5),+ },+ };+ }++ var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };+ void Chev() => strip.Children.Add(new Glyph(GlyphKind.ChevronRight, 8) { Foreground = NotaPalette.TextDisabled, VerticalAlignment = VerticalAlignment.Center });+ bool first = true;+ void Add(Control card) { if (!first) Chev(); strip.Children.Add(card); first = false; }++ if (_rp.TakesMidiEffects)+ {+ for (int j = 0; j < a.ChainMidiCount(c); j++) Add(RcCompactCard(c, RcSlot.Midi, j));+ if (_rp.TakesInstrument) { if (!first) Chev(); strip.Children.Add(RcDropTarget(c, RcSlot.Midi)); first = false; }+ }+ if (_rp.TakesInstrument)+ Add(a.ChainInstrumentKind(c) > -2 ? RcCompactCard(c, RcSlot.Instrument, 0) : RcNoInstrument(c));+ if (_rp.TakesAudioEffects)+ for (int d = 0; d < a.ChainDeviceCount(c); d++) Add(RcCompactCard(c, RcSlot.Effect, d));+ if (!first) Chev();+ strip.Children.Add(RcDropTarget(c, _rp.TakesAudioEffects ? RcSlot.Effect : RcSlot.Midi));++ var scroll = new ScrollViewer { Content = strip, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled, Margin = new Thickness(0, 4, 0, 0) };+ DockPanel.SetDock(head, Dock.Top);+ return new DockPanel { LastChildFill = true, Children = { head, scroll } };+ }++ // A chain without an instrument: a slot that picks one.+ private Control RcNoInstrument(int c)+ {+ var tb = Hint("No instrument");+ var slot = new Border+ {+ Width = RcCompactWidth, CornerRadius = NotaRadius.Panel, BorderThickness = new Thickness(1), BorderBrush = NotaPalette.BorderDefault,+ Background = NotaPalette.SurfaceRaised, Cursor = new Cursor(StandardCursorType.Hand), Child = new Border { Padding = new Thickness(6), Child = tb },+ };+ ToolTip.SetTip(slot, "Pick an instrument — or drop one from the Browser");+ slot.PointerPressed += (_, e) => { if (e.GetCurrentPoint(slot).Properties.IsLeftButtonPressed) { e.Handled = true; RcInstrumentMenu(slot, c); } };+ return slot;+ }++ private void RcInstrumentMenu(Control anchor, int c)+ {+ var f = new MenuFlyout();+ void Add(string h, int k) { var mi = new MenuItem { Header = h }; mi.Click += (_, _) => { _ra.SetChainInstrument(c, k); DeferRebuild(); }; f.Items.Add(mi); }+ Add("Nota Volt", 6); Add("Nota Physical", 2); Add("Nota Aurora", 5); Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10);+ Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15); Add("Nota Keys", 16);+ f.ShowAt(anchor, showAtPointer: true);+ }++ // The dashed target at the end of a section: click for the add menu, or drop a device.+ private Control RcDropTarget(int c, RcSlot slot)+ {+ var plus = new Glyph(GlyphKind.Plus, 10) { Foreground = NotaPalette.TextTertiary, HorizontalAlignment = HorizontalAlignment.Center };+ var word = new TextBlock { Text = slot == RcSlot.Midi ? "MIDI" : "FX", FontSize = 7, Foreground = NotaPalette.TextTertiary, HorizontalAlignment = HorizontalAlignment.Center };+ var dash = new Rectangle+ {+ Stroke = NotaPalette.BorderDefault, StrokeThickness = 1, StrokeDashArray = new AvaloniaList<double> { 3, 2.5 },+ RadiusX = NotaRadius.ControlValue, RadiusY = NotaRadius.ControlValue,+ };+ var box = new Panel+ {+ Width = 30, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent,+ Children = { dash, new StackPanel { VerticalAlignment = VerticalAlignment.Center, Spacing = 2, Children = { plus, word } } },+ };+ ToolTip.SetTip(box, slot == RcSlot.Midi ? "Add a MIDI effect — or drop one from the Browser" : "Add an effect — or drop one from the Browser");+ box.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ if (slot == RcSlot.Midi) RcAddMidiMenu(box, c); else ShowAddDeviceMenu(_ra, c, box);+ };+ DragDrop.SetAllowDrop(box, true);+ DragDrop.AddDragOverHandler(box, (_, e) =>+ {+ if (!BrowserView.IsBrowserDrag || BrowserView.CurrentDrag is not { } it || !RcIsDevice(it)) { e.DragEffects = DragDropEffects.None; return; }+ e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow();+ dash.Stroke = NotaPalette.Teal; dash.Fill = NotaPalette.Wash(NotaPalette.Teal, 0x22);+ });+ DragDrop.AddDragLeaveHandler(box, (_, _) => { dash.Stroke = NotaPalette.BorderDefault; dash.Fill = null; });+ DragDrop.AddDropHandler(box, (_, e) =>+ {+ dash.Stroke = NotaPalette.BorderDefault; dash.Fill = null;+ if (BrowserView.CurrentDrag is not { } it) return;+ e.Handled = true;+ RcDropOnChain(c, it);+ });+ return box;+ }++ private static readonly (string Name, int Kind)[] RcMidiKinds =+ [("Nota Arp", 0), ("Nota Chord", 1), ("Nota Scale", 2), ("Nota Length", 3), ("Nota Velocity", 4), ("Nota Random", 5)];++ private void RcAddMidiMenu(Control anchor, int c)+ {+ var f = new MenuFlyout();+ foreach (var (name, kind) in RcMidiKinds)+ {+ var mi = new MenuItem { Header = name };+ mi.Click += (_, _) => { _ra.AddChainMidi(c, kind); DeferRebuild(); };+ f.Items.Add(mi);+ }+ f.ShowAt(anchor, showAtPointer: true);+ }++ // ---- compact device card ----------------------------------------------------------++ private Control RcCompactCard(int c, RcSlot slot, int idx)+ {+ var a = _ra;+ string name; string tag; bool bypassed; int kind; RackDeviceFamily family;+ switch (slot)+ {+ case RcSlot.Instrument:+ name = a.ChainInstrumentName(c); kind = a.ChainInstrumentKind(c); tag = kind == -1 ? "Plug" : "Inst";+ bypassed = false; family = RackDeviceFamily.Instrument;+ break;+ case RcSlot.Midi:+ name = a.ChainMidiName(c, idx); kind = a.ChainMidiKind(c, idx); tag = "MIDI";+ bypassed = a.ChainMidiBypassed(c, idx); family = RackDeviceFamily.MidiEffect;+ break;+ default:+ name = a.ChainDeviceName(c, idx); kind = a.ChainDeviceBuiltinKind(c, idx); tag = kind < 0 ? "Plug" : "FX";+ bypassed = a.ChainDeviceBypassed(c, idx); family = RackDeviceFamily.AudioEffect;+ break;+ }+ if (string.IsNullOrEmpty(name)) name = slot == RcSlot.Instrument ? "Instrument" : "Device";+ bool canBypass = slot != RcSlot.Instrument;++ var dot = new Border+ {+ Width = 6, Height = 6, CornerRadius = NotaRadius.Control, VerticalAlignment = VerticalAlignment.Center,+ Background = bypassed ? NotaPalette.TextDisabled : NotaPalette.Success, Cursor = canBypass ? new Cursor(StandardCursorType.Hand) : Cursor.Default,+ };+ if (canBypass)+ {+ ToolTip.SetTip(dot, bypassed ? "Turn on" : "Turn off");+ dot.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(dot).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ if (slot == RcSlot.Midi) a.SetChainMidiBypassed(c, idx, !bypassed); else a.SetChainDeviceBypassed(c, idx, !bypassed);+ DeferRebuild();+ };+ }+ var nameTb = RcName(name, NotaPalette.TextPrimary, NotaType.KnobLabel);+ var tagTb = RcMono(tag, NotaPalette.TextTertiary, 7);+ dot.Margin = new Thickness(0, 0, 4, 0);+ tagTb.Margin = new Thickness(3, 0, 0, 0);+ var head = new Border+ {+ Height = 18, Padding = new Thickness(5, 0), BorderBrush = NotaPalette.Rule, BorderThickness = new Thickness(0, 0, 0, 1),+ Child = new DockPanel { LastChildFill = true, Children = { RcDock(dot, Dock.Left), RcDock(tagTb, Dock.Right), nameTb } },+ };++ // Parameters: the key ones at rest, every one while mapping (so any can be mapped).+ var P = RcParamsOf(c, slot, idx);+ int target = RcTarget(slot, idx);+ IEnumerable<int> shown = _rs.Mapping+ ? Enumerable.Range(0, P.Count)+ : RackKeyParams.Resolve(family, kind, P.Count, P.Name);+ var rows = new StackPanel { Spacing = 2 };+ foreach (int p in shown) rows.Children.Add(RcParamRow(c, target, P, p));+ Control body = _rs.Mapping+ ? new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }+ : rows;+ body.Margin = new Thickness(4, 3);++ var open = new TextBlock { Text = "Open", FontSize = 7.5, Foreground = NotaPalette.TextSecondary, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };+ ToolTip.SetTip(open, "Open the full editor");+ var grip = new Glyph(GlyphKind.Grip, 8) { Foreground = NotaPalette.TextDisabled, Cursor = new Cursor(StandardCursorType.SizeWestEast), VerticalAlignment = VerticalAlignment.Center };+ var foot = new Border+ {+ Height = 15, Padding = new Thickness(5, 0), BorderBrush = NotaPalette.Rule, BorderThickness = new Thickness(0, 1, 0, 0),+ Child = new DockPanel { LastChildFill = false, Children = { RcDock(open, Dock.Left), RcDock(grip, Dock.Right) } },+ };++ var card = new Border+ {+ Width = RcCompactWidth, CornerRadius = NotaRadius.Panel, BorderThickness = new Thickness(1), ClipToBounds = true,+ Background = NotaPalette.SurfaceRaised, BorderBrush = NotaPalette.BorderDefault,+ };+ DockPanel.SetDock(head, Dock.Top);+ DockPanel.SetDock(foot, Dock.Bottom);+ card.Child = new DockPanel { LastChildFill = true, Children = { head, foot, body } };+ if (bypassed) card.AttachedToVisualTree += (_, _) => Inactive.Set(card, true, interactive: true);++ void Open()+ {+ switch (slot)+ {+ case RcSlot.Instrument: OpenChainInstrumentGui(a, c, card); break;+ case RcSlot.Midi: RcOpenChainMidi(c, idx, card); break;+ default: OpenChainDeviceGui(a, c, idx, card); break;+ }+ }+ open.PointerPressed += (_, e) => { if (e.GetCurrentPoint(open).Properties.IsLeftButtonPressed) { e.Handled = true; Open(); } };+ head.PointerPressed += (_, e) =>+ {+ var pt = e.GetCurrentPoint(head).Properties;+ if (pt.IsRightButtonPressed) { e.Handled = true; RcCardMenu(card, c, slot, idx, bypassed, Open); }+ else if (pt.IsLeftButtonPressed && e.ClickCount == 2) { e.Handled = true; Open(); }+ };+ if (slot != RcSlot.Instrument) RcGripReorder(grip, c, slot, idx);+ else grip.IsVisible = false;+ return card;+ }++ private void RcCardMenu(Control anchor, int c, RcSlot slot, int idx, bool bypassed, Action open)+ {+ var a = _ra;+ var f = new MenuFlyout();+ var o = new MenuItem { Header = "Open" };+ o.Click += (_, _) => open();+ f.Items.Add(o);+ if (slot == RcSlot.Instrument)+ {+ var replace = new MenuItem { Header = "Replace instrument" };+ replace.Click += (_, _) => RcInstrumentMenu(anchor, c);+ f.Items.Add(replace);+ }+ else+ {+ var b = new MenuItem { Header = bypassed ? "Turn on" : "Turn off" };+ b.Click += (_, _) =>+ {+ if (slot == RcSlot.Midi) a.SetChainMidiBypassed(c, idx, !bypassed); else a.SetChainDeviceBypassed(c, idx, !bypassed);+ DeferRebuild();+ };+ f.Items.Add(b);+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Danger("Remove", GlyphKind.Trash, () =>+ {+ if (slot == RcSlot.Midi) a.RemoveChainMidi(c, idx); else a.RemoveChainDevice(c, idx);+ DeferRebuild();+ }));+ }+ f.ShowAt(anchor, showAtPointer: true);+ }++ // Drag a card by its grip along the strip: it moves by whole cards within its section.+ private void RcGripReorder(Control grip, int c, RcSlot slot, int idx)+ {+ double startX = 0;+ bool down = false;+ grip.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(grip).Properties.IsLeftButtonPressed) return;+ down = true; startX = e.GetPosition(null).X; e.Pointer.Capture(grip); e.Handled = true;+ };+ grip.PointerReleased += (_, e) =>+ {+ if (!down) return;+ down = false; e.Pointer.Capture(null);+ int steps = (int)Math.Round((e.GetPosition(null).X - startX) / (RcCompactWidth + 14));+ if (steps == 0) return;+ if (slot == RcSlot.Midi) _ra.MoveChainMidi(c, idx, idx + steps); else _ra.MoveChainDevice(c, idx, idx + steps);+ DeferRebuild();+ };+ grip.PointerCaptureLost += (_, _) => down = false;+ }++ // ---- a parameter row in a compact card --------------------------------------------++ private Control RcParamRow(int c, int target, RcParams P, int p)+ {+ var a = _ra;+ string name = P.Name(p);+ float min = P.Min(p), max = P.Max(p);+ float span = Math.Max(1e-6f, max - min);+ int macro = MappedMacro(a, c, target, p);+ bool mapped = macro >= 0, mapping = _rs.Mapping, onThis = mapping && macro == _rs.MappingMacro;++ var label = new TextBlock+ {+ Text = NotaText.Label(name), FontSize = 7.5, FontWeight = FontWeight.Medium, TextTrimming = TextTrimming.CharacterEllipsis,+ Foreground = mapped ? NotaPalette.Teal : NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Center,+ };+ var value = RcMono(P.Text(P.Get(p)), mapped ? NotaPalette.TealBright : NotaPalette.TextPrimary, 7.5);+ var top = new DockPanel { LastChildFill = true };+ top.Children.Add(RcDock(value, Dock.Right));+ if (mapped)+ {+ var tag = new Border+ {+ CornerRadius = NotaRadius.Badge, Padding = new Thickness(2, 0), Margin = new Thickness(3, 0, 0, 0), Background = NotaPalette.Wash(NotaPalette.Teal, 0x33),+ VerticalAlignment = VerticalAlignment.Center, Child = RcMono($"M{macro + 1}", NotaPalette.TealBright, 7),+ };+ top.Children.Add(RcDock(tag, Dock.Right));+ }+ top.Children.Add(label);++ var track = new SliderTrack { Norm = (P.Get(p) - min) / span };+ if (mapped) track.Ink = NotaPalette.Teal;+ if (mapped || mapping) track.IsHitTestVisible = false; // a mapped parameter follows its macro+ track.Changed += v => { P.Set(p, (float)(min + v * span)); value.Text = P.Text(P.Get(p)); };+ _ctx.AddRackParamRefresher(() =>+ {+ if (track.Dragging) return;+ float nv = P.Get(p);+ double n = (nv - min) / span;+ if (Math.Abs(n - track.Norm) > 1e-4) track.Norm = n;+ value.Text = P.Text(nv);+ });++ var row = new Border+ {+ CornerRadius = NotaRadius.Badge, Padding = new Thickness(2, 1), BorderThickness = new Thickness(1),+ BorderBrush = mapping ? NotaPalette.Teal : Brushes.Transparent,+ Background = onThis ? NotaPalette.Wash(NotaPalette.Teal, 0x30) : Brushes.Transparent,+ Child = new StackPanel { Spacing = 2, Children = { top, track } },+ };+ if (mapping)+ {+ row.Cursor = new Cursor(StandardCursorType.Hand);+ ToolTip.SetTip(row, onThis ? $"Unmap from {a.MacroName(_rs.MappingMacro)}" : $"Map to {a.MacroName(_rs.MappingMacro)}");+ row.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(row).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ RcToggleMapping(c, target, p, P);+ };+ }+ else if (mapped)+ {+ row.Cursor = new Cursor(StandardCursorType.Hand);+ ToolTip.SetTip(row, $"Controlled by {a.MacroName(macro)} · click to open the macro");+ row.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(row).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ _rs.SelectedMacro = macro;+ _rs.Centre = RackCentreTab.Macros;+ DeferRebuild();+ };+ }+ return row;+ }++ private void RcToggleMapping(int c, int target, int p, RcParams P)+ {+ var a = _ra;+ int m = _rs.MappingMacro;+ if (m < 0) return;+ if (MappedMacro(a, c, target, p) == m) { RemoveParamMapping(a, c, target, p); DeferRebuild(); return; }+ float min = P.Min(p), max = P.Max(p), span = max - min, cur = P.Get(p);+ RcAddMapping(m, c, target, p, Math.Max(min, cur - 0.3f * span), Math.Min(max, cur + 0.3f * span));+ DeferRebuild();+ }++ /// <summary>Map a target to a macro as one undo step: a new target takes the macro's curve (a+ /// Mixed macro gives it Lin); one moved from another macro keeps its own range and curve.</summary>+ private void RcAddMapping(int macro, int c, int target, int p, float min, float max)+ {+ var a = _ra;+ int curve = RcMacroCurve(macro);+ bool was = MappedMacro(a, c, target, p) >= 0;+ E.BeginUndoGroup();+ try+ {+ int i = a.AddMacroMapping(macro, c, target, p, min, max);+ if (i >= 0 && !was && curve > 0) a.SetMappingCurve(i, curve);+ }+ finally { E.EndUndoGroup(); }+ }++ /// <summary>A macro's curve: its targets' common curve, −1 when they differ (Mixed), 0 with none.</summary>+ private int RcMacroCurve(int macro)+ {+ int curve = int.MinValue;+ for (int i = 0; i < _ra.MappingCount(); i++)+ {+ if (!_ra.TryGetMapping(i, out var m) || m.Macro != macro) continue;+ int k = _ra.MappingCurve(i);+ if (curve == int.MinValue) curve = k;+ else if (curve != k) return -1;+ }+ return curve == int.MinValue ? 0 : curve;+ }++ private static Control RcDock(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }++ // A chain's MIDI effect in the device window: its parameters as rows.+ private void RcOpenChainMidi(int c, int j, Control anchor)+ {+ var a = _ra;+ var P = RcParamsOf(c, RcSlot.Midi, j);+ Control Row(int p)+ {+ float min = P.Min(p), max = P.Max(p), span = Math.Max(1e-6f, max - min);+ var row = SliderRow(P.Name(p), () => (P.Get(p) - min) / span, v => { P.Set(p, (float)(min + v * span)); _ctx.InvokeRackParamRefreshers(); },+ () => P.Text(P.Get(p)), out var sync, labelWidth: 70);+ _ctx.AddRackParamRefresher(sync);+ return row;+ }+ OpenParamWindow(anchor, a.ChainMidiName(c, j), P.Count, Row, () => $"{RcChainName(c)} · MIDI effect {j + 1}");+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.MacroTab.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.MacroTab.csnew file mode 100644index 00000000..14608d72--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.MacroTab.cs@@ -0,0 +1,177 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the rack card's Macros tab (specs/040): the chosen macro's name+// (double-click renames), value and response curve, and each of its targets with a range+// whose ends drag (min above max inverts) and a marker where the macro drives it now.+// Curves are kept per target (an older project can hold different ones on one macro): the+// curve keys then show none chosen and "Mixed" until one is picked, which applies to all+// the macro's targets as one undo step.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed partial class RackCardView+{+ private static readonly string[] RcCurveNames = ["Lin", "Exp", "Log", "S"];++ private Control RcMacrosTab()+ {+ var a = _ra;+ int m = _rs.SelectedMacro;+ string name = a.MacroName(m);+ int curve = RcMacroCurve(m);+ var targets = new List<int>();+ for (int i = 0; i < a.MappingCount(); i++)+ if (a.TryGetMapping(i, out var mm) && mm.Macro == m) targets.Add(i);+ bool mixed = curve < 0;++ // Header: slot, name, value · curve keys, preview, Map.+ var slot = RcText($"Macro {m + 1}", NotaPalette.TextTertiary, 7.5);+ var nameTb = RcName(name, NotaPalette.TextPrimary, 10);+ nameTb.Cursor = new Cursor(StandardCursorType.Hand);+ ToolTip.SetTip(nameTb, "Double-click to rename");+ nameTb.DoubleTapped += (_, _) => RcPromptRename(nameTb, name, s => a.SetMacroName(m, s));+ var value = RcMono(NotaNum.Pct(a.MacroGet(m)), NotaPalette.TextPrimary, 9);+ value.Margin = new Thickness(8, 0, 0, 0);+ var who = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center, Children = { slot, nameTb } };++ var curveKeys = Segments(RcCurveNames, () => RcMacroCurve(m) is var k && k >= 0 && targets.Count > 0 ? k : -1, k =>+ {+ E.BeginUndoGroup();+ try { foreach (int i in targets) a.SetMappingCurve(i, k); }+ finally { E.EndUndoGroup(); }+ DeferRebuild();+ }, out var curveSync, padX: 4, fontSize: NotaType.KnobLabel, dim: () => targets.Count == 0);+ var preview = new RackCurvePreview { Curve = targets.Count == 0 ? 0 : curve, Position = a.MacroGet(m), VerticalAlignment = VerticalAlignment.Center };+ _irTick.Add(() =>+ {+ double v = a.MacroGet(m);+ if (Math.Abs(preview.Position - v) > 1e-4) { preview.Position = v; preview.InvalidateVisual(); }+ value.Text = NotaNum.Pct(v);+ });+ var curveLabel = RcText(mixed ? "Curve · mixed" : "Curve", NotaPalette.TextTertiary, 7.5);+ var map = RcKey("Map", () => { _rs.MappingMacro = m; _rs.Centre = RackCentreTab.Chains; DeferRebuild(); },+ tip: "Map this macro: click parameters on the Chains tab");+ var right = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center,+ Children = { curveLabel, curveKeys, preview, map },+ };+ var header = new DockPanel+ {+ LastChildFill = false, Height = 30,+ Children = { RcDock(who, Dock.Left), RcDock(value, Dock.Left), RcDock(right, Dock.Right) },+ };+ var head = Section(header);+ DockPanel.SetDock(head, Dock.Top);++ if (targets.Count == 0)+ {+ var empty = new Border { Padding = new Thickness(4, 8), Child = Hint("No targets yet. Press Map, then click parameters on the Chains tab.") };+ return new DockPanel { LastChildFill = true, Children = { head, empty } };+ }++ var cols = new Grid { ColumnDefinitions = new ColumnDefinitions("*,150,56,12"), ColumnSpacing = 6, Height = 12, Margin = new Thickness(0, 4, 0, 0) };+ cols.Children.Add(RcText("Target", NotaPalette.TextTertiary, 7.5));+ var rangeTitle = RcText("Range", NotaPalette.TextTertiary, 7.5);+ ToolTip.SetTip(rangeTitle, "Drag the ends · min above max inverts");+ Grid.SetColumn(rangeTitle, 1); cols.Children.Add(rangeTitle);+ var rows = new StackPanel { Spacing = 2 };+ rows.Children.Add(cols);+ foreach (int i in targets) rows.Children.Add(RcTargetRow(m, i));+ var scroll = new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };+ return new DockPanel { LastChildFill = true, Children = { head, scroll } };+ }++ // What a mapping drives: its chain's colour, "Chain · Device ·", the parameter, and how to+ // read and show its values.+ private (IBrush Hue, string Where, string Param, float Min, float Max, Func<float, string> Text) RcTargetInfo(RackMacroMapping m)+ {+ var a = _ra;+ if (m.DeviceIndex == RackMacroMapping.RackControl)+ return (NotaPalette.VizInk, "Rack ·", "Selector", 0f, 1f, v => NotaNum.F($"{v * 127:0}"));+ string chain = RcChainName(m.Chain);+ if (m.DeviceIndex == -1)+ return (ChainHue(m.Chain), $"{chain} · {RcShort(a.ChainInstrumentName(m.Chain))} ·", a.ChainInstrumentParamName(m.Chain, m.ParamIndex), 0f, 1f, v => Pct(v));+ if (m.DeviceIndex <= RackMacroMapping.MidiDeviceBase)+ {+ int j = RackMacroMapping.MidiDeviceBase - m.DeviceIndex;+ return (ChainHue(m.Chain), $"{chain} · {RcShort(a.ChainMidiName(m.Chain, j))} ·", a.ChainMidiParamName(m.Chain, j, m.ParamIndex),+ a.ChainMidiParamMin(m.Chain, j, m.ParamIndex), a.ChainMidiParamMax(m.Chain, j, m.ParamIndex), DeviceParamControls.Fmt);+ }+ if (m.DeviceIndex == RackMacroMapping.PadControls)+ return (ChainHue(m.Chain), $"{chain} ·", $"Pad {m.ParamIndex + 1}", 0f, 1f, v => Pct(v));+ return (ChainHue(m.Chain), $"{chain} · {RcShort(a.ChainDeviceName(m.Chain, m.DeviceIndex))} ·", a.ChainDeviceParamName(m.Chain, m.DeviceIndex, m.ParamIndex),+ a.ChainDeviceParamMin(m.Chain, m.DeviceIndex, m.ParamIndex), a.ChainDeviceParamMax(m.Chain, m.DeviceIndex, m.ParamIndex), DeviceParamControls.Fmt);+ }++ private static string RcShort(string device) => device.StartsWith("Nota ", StringComparison.Ordinal) ? device[5..] : device;++ private Control RcTargetRow(int macro, int index)+ {+ var a = _ra;+ if (!a.TryGetMapping(index, out var m)) return new Border();+ var (hue, where, param, min, max, text) = RcTargetInfo(m);+ float span = Math.Max(1e-6f, max - min);+ int curve = a.MappingCurve(index);++ var stripe = new Border { Width = 3, Height = 9, CornerRadius = NotaRadius.Bar, Background = hue, VerticalAlignment = VerticalAlignment.Center };+ var whereTb = new TextBlock { Text = where, FontSize = NotaType.KnobLabel, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center };+ var paramTb = new TextBlock { Text = NotaText.Label(param), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { stripe, whereTb, paramTb } };++ var bar = new RackMapRangeBar+ {+ Min = (m.RangeMin - min) / span, Max = (m.RangeMax - min) / span, VerticalAlignment = VerticalAlignment.Center,+ };+ string RangeText(float lo, float hi) => $"{text(lo)} → {text(hi)}";+ var range = RcMono(RangeText(m.RangeMin, m.RangeMax), NotaPalette.TextSecondary, 7.5);+ range.HorizontalAlignment = HorizontalAlignment.Right;+ bool grouped = false;+ bar.Began += () => { if (!grouped) { E.BeginUndoGroup(); grouped = true; } };+ bar.Committed += () => { if (grouped) { E.EndUndoGroup(); grouped = false; } };+ bar.Changed += (lo, hi) =>+ {+ float l = (float)(min + lo * span), h = (float)(min + hi * span);+ a.SetMappingRange(index, l, h);+ range.Text = RangeText(l, h);+ _ctx.InvokeRackParamRefreshers();+ };+ void Place()+ {+ double v = RackCurvePreview.Apply(curve, a.MacroGet(macro));+ bar.Current = bar.Min + v * (bar.Max - bar.Min);+ bar.InvalidateVisual();+ }+ Place();+ _irTick.Add(Place);++ var remove = new Glyph(GlyphKind.Close, 8) { Foreground = NotaPalette.TextTertiary, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };+ ToolTip.SetTip(remove, "Unmap");+ remove.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(remove).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ a.RemoveMapping(index);+ DeferRebuild();+ };++ var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,150,56,12"), ColumnSpacing = 6, Height = 20 };+ row.Children.Add(label);+ Grid.SetColumn(bar, 1); row.Children.Add(bar);+ Grid.SetColumn(range, 2); row.Children.Add(range);+ Grid.SetColumn(remove, 3); row.Children.Add(remove);+ return row;+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Macros.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Macros.csnew file mode 100644index 00000000..cf306444--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Macros.cs@@ -0,0 +1,145 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the rack card's macro column (specs/040): eight macros as small+// knobs, 2 × 4, each with its name, value and target count, and the Map key that maps the+// chosen macro in place on the Chains tab. A click picks a macro; while mapping, it moves+// mapping to that macro. A macro knob is a full value control: vertical drag, fine with a+// modifier, double-click resets, typed values, automation write and MIDI Learn.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed partial class RackCardView+{+ private Control RcMacroColumn()+ {+ bool mapping = _rs.Mapping;+ var map = RcKey("Map", () =>+ {+ if (_rs.Mapping) _rs.MappingMacro = -1;+ else { _rs.MappingMacro = _rs.SelectedMacro; _rs.Centre = RackCentreTab.Chains; }+ DeferRebuild();+ }, on: mapping, tip: mapping ? "Stop mapping (Esc)" : "Map the chosen macro: click parameters in the chain");+ map.HorizontalAlignment = HorizontalAlignment.Right;+ var title = RcText("Macros", NotaPalette.TextTertiary, NotaType.KnobLabel, FontWeight.SemiBold);+ var head = new Grid { Height = RcTabHeight, ColumnDefinitions = new ColumnDefinitions("*,Auto"), Children = { title, map } };+ Grid.SetColumn(map, 1);++ var grid = new Grid+ {+ ColumnDefinitions = new ColumnDefinitions("*,*"), RowDefinitions = new RowDefinitions("*,*,*,*"),+ ColumnSpacing = 3, RowSpacing = 3, Margin = new Thickness(0, 4, 0, 0),+ };+ for (int i = 0; i < 8; i++)+ {+ var cell = RcMacroCell(i);+ Grid.SetColumn(cell, i % 2);+ Grid.SetRow(cell, i / 2);+ grid.Children.Add(cell);+ }+ DockPanel.SetDock(head, Dock.Top);+ return new DockPanel { LastChildFill = true, Children = { head, grid } };+ }++ private Control RcMacroCell(int i)+ {+ var a = _ra;+ int count = RcTargetCount(i);+ bool has = count > 0, chosen = _rs.SelectedMacro == i, mapping = _rs.MappingMacro == i;+ string name = a.MacroName(i);++ var knob = new Knob(a.MacroGet(i), 1.0)+ {+ Inline = true, Accent = has, IsDim = !has, Default = 0,+ HorizontalAlignment = HorizontalAlignment.Center,+ Format = v => NotaNum.F($"{v * 100:0}"),+ };+ if (mapping) knob.ArcColor = NotaPalette.Teal;+ var value = RcMono(has ? NotaNum.F($"{a.MacroGet(i) * 100:0}") : "—", has ? NotaPalette.TextPrimary : NotaPalette.TextDisabled, 7.5);+ value.HorizontalAlignment = HorizontalAlignment.Center;+ var label = RcName(name, mapping ? NotaPalette.Teal : chosen ? NotaPalette.AccentBright : has ? NotaPalette.TextSecondary : NotaPalette.TextDisabled, 7.5);+ label.MaxWidth = 50;++ knob.ValueChanged += v =>+ {+ a.MacroSet(i, (float)v);+ if (has) value.Text = NotaNum.F($"{v * 100:0}");+ _ctx.InvokeRackParamRefreshers();+ };+ var (target, device, param, id) = a.MacroAutomation(i);+ bool picked = false;+ knob.GestureBegin += () =>+ {+ // Turning a macro picks it (and, while mapping, maps to it); the card catches up+ // once the drag ends, so the knob isn't torn down under the pointer.+ picked = _rs.SelectedMacro != i || (_rs.Mapping && _rs.MappingMacro != i);+ _rs.SelectedMacro = i;+ if (_rs.Mapping) _rs.MappingMacro = i;+ E.BeginAutomationWrite(T, target, device, param, id);+ };+ knob.GestureEnd += () =>+ {+ E.EndAutomationWrite(T, target, device, param, id);+ if (picked) DeferRebuild();+ };+ ValueEntry.Attach(knob, $"Macro · {name}", value);+ MidiLearn.Bind(knob, a.MacroLearnTarget(T, i), $"Macro · {name}", v => knob.Value = v);+ _irTick.Add(() =>+ {+ if (knob.Dragging) return;+ float v = a.MacroGet(i);+ if (Math.Abs(v - knob.Value) > 1e-4) knob.Value = v;+ if (has) value.Text = NotaNum.F($"{v * 100:0}");+ });++ // Knob and value side by side, the name under them: four rows fit the column.+ knob.HorizontalAlignment = HorizontalAlignment.Left;+ value.HorizontalAlignment = HorizontalAlignment.Right;+ value.VerticalAlignment = VerticalAlignment.Bottom;+ var top = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Children = { knob, value } };+ Grid.SetColumn(value, 1);+ label.HorizontalAlignment = HorizontalAlignment.Left;+ var stack = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(3, 0), Children = { top, label } };+ var host = new Panel { Children = { stack } };+ if (has)+ {+ var badge = new Border+ {+ CornerRadius = NotaRadius.Badge, Padding = new Thickness(2, 0), Background = NotaPalette.Wash(NotaPalette.Teal, 0x33),+ HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 2, 2, 0),+ Child = RcMono(count.ToString(NotaNum.Culture), NotaPalette.TealBright, 7),+ };+ host.Children.Add(badge);+ }+ var cell = new Border+ {+ CornerRadius = NotaRadius.Clip, BorderThickness = new Thickness(1), ClipToBounds = true, Cursor = new Cursor(StandardCursorType.Hand),+ Background = mapping ? NotaPalette.Wash(NotaPalette.Teal, 0x24) : chosen ? RowSel : NotaPalette.SurfaceRaised,+ BorderBrush = mapping ? NotaPalette.Teal : chosen ? NotaPalette.Accent : NotaPalette.BorderDefault,+ Child = host,+ };+ ToolTip.SetTip(cell, has+ ? $"{name} → {count} target{(count == 1 ? "" : "s")} · drag to turn · double-click resets"+ : "Not mapped · pick it and press Map");+ cell.PointerPressed += (_, e) =>+ {+ var pt = e.GetCurrentPoint(cell).Properties;+ if (pt.IsRightButtonPressed) { e.Handled = true; ShowMacroMenu(a, cell, i); return; }+ if (!pt.IsLeftButtonPressed) return;+ if (e.ClickCount == 2 && label.IsPointerOver) { RcPromptRename(label, name, s => a.SetMacroName(i, s)); return; }+ if (_rs.SelectedMacro == i && (!_rs.Mapping || _rs.MappingMacro == i)) return;+ _rs.SelectedMacro = i;+ if (_rs.Mapping) _rs.MappingMacro = i;+ DeferRebuild();+ };+ return cell;+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.csnew file mode 100644index 00000000..73e9f692--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs@@ -0,0 +1,213 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the rack card's right panel (specs/040) and status line.+// Chain: the chosen chain's name, its mix (Volume and Pan; a MIDI chain's Volume scales+// velocity and it has Transpose instead of Pan), its zone or select range (a click opens+// that tab), Duplicate and Delete. Rack out / Output: how chains run (Audio, MIDI) and the+// rack's own output — Instrument: volume, glide, mono; Audio: dry/wet, gain, latency+// compensation; MIDI: merge duplicate notes, pass notes outside every zone through.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed partial class RackCardView+{+ private const double RcRowLabel = 50;++ private Control RcChainPanel()+ {+ var a = _ra;+ int n = a.ChainCount();+ if (n == 0) return new Border { Padding = new Thickness(2), Child = Hint("No chain yet.") };+ int c = Sel;+ var stack = new StackPanel { Spacing = 7 };++ var dot = new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Badge, Background = ChainHue(c), VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0) };+ string name = RcChainName(c);+ var nameTb = RcName(name, NotaPalette.TextPrimary, NotaType.RowLabel);+ nameTb.Cursor = new Cursor(StandardCursorType.Hand);+ ToolTip.SetTip(nameTb, "Double-click to rename");+ nameTb.DoubleTapped += (_, _) => RcPromptRename(nameTb, name, s => a.SetChainName(c, s));+ var idx = RcMono($"{c + 1} / {n}", NotaPalette.TextTertiary, 7.5);+ stack.Children.Add(new DockPanel { LastChildFill = true, Children = { RcDock(dot, Dock.Left), RcDock(idx, Dock.Right), nameTb } });++ // Mix.+ if (_rp.VolumeIsVelocity)+ {+ stack.Children.Add(RcSlider("Volume", () => a.ChainVelScale(c) / 2.0, v => a.SetChainVelScale(c, (float)(v * 2)),+ () => NotaNum.Pct(a.ChainVelScale(c)), reset: () => a.SetChainVelScale(c, 1f)));+ }+ else+ {+ var row = RcSlider("Volume", () => VolNorm(a.ChainGain(c)), v => a.SetChainGain(c, NormVol(v)),+ () => VolText(a.ChainGain(c)), reset: () => a.SetChainGain(c, 1f));+ MidiLearn.Bind(row, MidiTarget.RackChainGain(T, a.LearnDeviceIndex, c), "Chain Volume");+ stack.Children.Add(row);+ }+ if (_rp.ChainTranspose)+ stack.Children.Add(RcSlider("Transpose", () => (a.ChainTranspose(c) + 48) / 96.0, v => a.SetChainTranspose(c, (int)Math.Round(v * 96 - 48)),+ () => NotaNum.Unit(a.ChainTranspose(c), "+0;−0;0", "st"), reset: () => a.SetChainTranspose(c, 0), bipolar: true));+ if (_rp.ChainPan)+ stack.Children.Add(RcSlider("Pan", () => (a.ChainPan(c) + 1) / 2.0, v => a.SetChainPan(c, (float)(v * 2 - 1)),+ () => NotaNum.Pan(a.ChainPan(c)), reset: () => a.SetChainPan(c, 0f), bipolar: true));++ // Zone / select range: a click opens the tab that edits it.+ if (_rp.KeyZones)+ {+ a.ChainZone(c, out int kl, out int kh, out int vl, out int vh);+ stack.Children.Add(RcInfoRow("Keys", $"{NoteName(kl)} – {NoteName(kh)}"));+ stack.Children.Add(RcInfoRow("Vel", $"{vl}–{vh}"));+ }+ if (_rp.SelectRanges)+ {+ a.SelectRange(c, out int sl, out int sh);+ stack.Children.Add(RcInfoRow("Select", $"{sl}–{sh}"));+ }++ bool full = _rp.Kind == RackKind.MidiEffect && n >= RcMidiChainLimit;+ var dup = RcKey("Duplicate", () => { int d = a.DuplicateChain(c); if (d >= 0) Sel = d; DeferRebuild(); }, enabled: !full,+ tip: full ? $"A MIDI Effect Rack holds up to {RcMidiChainLimit} chains" : "Copy this chain after itself");+ var del = RcKey("Delete", () => RcDeleteChain(c), enabled: n > 1, tip: n > 1 ? "Delete this chain" : "A rack keeps at least one chain");+ dup.HorizontalAlignment = del.HorizontalAlignment = HorizontalAlignment.Stretch;+ var buttons = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4, Children = { dup, del } };+ Grid.SetColumn(del, 1);+ var foot = Section(buttons, SectionEdge.Top);+ DockPanel.SetDock(foot, Dock.Bottom);+ return new DockPanel { LastChildFill = true, Children = { foot, stack } };+ }++ private Control RcInfoRow(string key, string value)+ {+ var k = RcText(key, NotaPalette.TextTertiary, NotaType.KnobLabel);+ k.Width = RcRowLabel;+ var v = RcMono(value, NotaPalette.TextPrimary, 8);+ var chev = new Glyph(GlyphKind.ChevronRight, 7) { Foreground = NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Center };+ var row = new DockPanel+ {+ LastChildFill = true, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Children = { RcDock(k, Dock.Left), RcDock(chev, Dock.Right), v },+ };+ ToolTip.SetTip(row, $"Edit on the {_rp.ZoneTab} tab");+ row.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(row).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ _rs.Centre = RackCentreTab.Zones;+ DeferRebuild();+ };+ return row;+ }++ private Control RcSlider(string label, Func<double> norm, Action<double> set, Func<string> text, Action? reset = null, bool bipolar = false)+ {+ var row = SliderRow(label, norm, set, text, out var sync, reset: reset, bipolar: bipolar, labelWidth: RcRowLabel, valueWidth: 36);+ _irTick.Add(sync);+ return row;+ }++ private Control RcOutputPanel()+ {+ var a = _ra;+ var stack = new StackPanel { Spacing = 8 };+ if (_rp.Modes.Length > 0)+ {+ var labels = Array.ConvertAll(_rp.Modes, m => m.Label);+ int Cur() { int mode = a.RackMode(); return Array.FindIndex(_rp.Modes, m => m.Id == mode); }+ var seg = Segments(labels, Cur, i => { a.SetRackMode(_rp.Modes[i].Id); DeferRebuild(); }, out var segSync, fill: true, padX: 2, fontSize: NotaType.KnobLabel);+ _irTick.Add(segSync);+ var hint = new TextBlock+ {+ Text = _rp.ModeHint(a.RackMode()), FontSize = 7.5, Foreground = NotaPalette.TextSecondary, TextWrapping = TextWrapping.Wrap,+ };+ stack.Children.Add(new StackPanel { Spacing = 4, Children = { RcText("Chains run", NotaPalette.TextTertiary, NotaType.KnobLabel), seg, hint } });+ }++ var toggles = new StackPanel { Spacing = 6 };+ switch (_rp.Kind)+ {+ case RackKind.Instrument:+ {+ var vol = RcSlider("Volume", () => VolNorm(a.RackVolume()), v => a.SetRackVolume(NormVol(v)), () => VolText(a.RackVolume()), reset: () => a.SetRackVolume(1f));+ MidiLearn.Bind(vol, MidiTarget.RackVolume(T, a.LearnDeviceIndex), "Rack Volume");+ stack.Children.Add(vol);+ var glide = RcSlider("Glide", () => a.RackGlide(), v => a.SetRackGlide((float)v), () => NotaNum.Unit(a.RackGlide() * 500, "0", "ms"), reset: () => a.SetRackGlide(0f));+ ToolTip.SetTip(glide, "Glides between notes in mono mode");+ stack.Children.Add(glide);+ toggles.Children.Add(Switch("Mono (last note)", () => a.RackMono(), () => a.SetRackMono(!a.RackMono()), out var monoSync));+ _irTick.Add(monoSync);+ ToolTip.SetTip(toggles.Children[^1], "All chains share one voice, the last key wins");+ break;+ }+ case RackKind.AudioEffect:+ {+ stack.Children.Add(RcSlider("Dry/wet", () => a.RackDryWet(), v => a.SetRackDryWet((float)v), () => NotaNum.Pct(a.RackDryWet()), reset: () => a.SetRackDryWet(1f)));+ // Gain: ±12 dB around unity, centred.+ static double GainNorm(float lin) => Math.Clamp((lin <= 0.0001f ? -12 : 20 * Math.Log10(lin)) / 24.0 + 0.5, 0, 1);+ static float NormGain(double v) => (float)Math.Pow(10, (v - 0.5) * 24 / 20);+ var gain = RcSlider("Gain", () => GainNorm(a.RackVolume()), v => a.SetRackVolume(NormGain(v)),+ () => NotaNum.Db(20 * Math.Log10(Math.Max(1e-6, a.RackVolume())), signed: true), reset: () => a.SetRackVolume(1f), bipolar: true);+ MidiLearn.Bind(gain, MidiTarget.RackVolume(T, a.LearnDeviceIndex), "Rack Gain");+ stack.Children.Add(gain);+ toggles.Children.Add(Switch("Follow input level", () => a.SelectorFollows(), () => { a.SetSelectorFollows(!a.SelectorFollows()); DeferRebuild(); }, out var followSync));+ _irTick.Add(followSync);+ ToolTip.SetTip(toggles.Children[^1], "In Select mode the selector follows the input level instead of its handle");+ toggles.Children.Add(Switch("Latency compensation", () => a.RackPdc(), () => a.SetRackPdc(!a.RackPdc()), out var pdcSync));+ _irTick.Add(pdcSync);+ ToolTip.SetTip(toggles.Children[^1], "Line up chains with different latency");+ break;+ }+ default:+ toggles.Children.Add(Switch("Merge duplicate notes", () => a.RackMerge(), () => a.SetRackMerge(!a.RackMerge()), out var mSync));+ _irTick.Add(mSync);+ ToolTip.SetTip(toggles.Children[^1], "Two chains sending the same pitch play one note");+ toggles.Children.Add(Switch("Pass through outside zones", () => a.RackThru(), () => a.SetRackThru(!a.RackThru()), out var tSync));+ _irTick.Add(tSync);+ ToolTip.SetTip(toggles.Children[^1], "Notes no chain takes reach the instrument unchanged");+ break;+ }+ var foot = Section(toggles, SectionEdge.Top);+ DockPanel.SetDock(foot, Dock.Bottom);+ return new DockPanel { LastChildFill = true, Children = { foot, stack } };+ }++ // ---- status line ------------------------------------------------------------------++ private string RcStatusText()+ {+ var a = _ra;+ int n = a.ChainCount(), mapped = RcMappedMacros();+ string chains = n == 1 ? "1 chain" : $"{n} chains";+ string macros = mapped == 1 ? "1 macro mapped" : $"{mapped} macros mapped";+ switch (_rp.Kind)+ {+ case RackKind.AudioEffect:+ {+ string mode = a.RackMode() switch+ {+ RackKindProfile.Serial => "Serial",+ RackKindProfile.Select => $"Select {(int)Math.Round(a.LiveSelector() * 127)}{(a.SelectorFollows() ? " · follows input" : "")}",+ _ => "Parallel",+ };+ return $"{mode} · {chains} · dry/wet {NotaNum.Pct(a.RackDryWet())} · {macros}";+ }+ case RackKind.MidiEffect:+ return $"{(a.RackMode() == RackKindProfile.Select ? "Select" : "Parallel")} · {chains} → merged MIDI · {macros}";+ default:+ {+ var hits = RcProbeHits(_rs.ProbePitch);+ string probe = _rs.ProbePitch >= 0 && _rs.Centre == RackCentreTab.Zones+ ? $"{NoteName(_rs.ProbePitch)} → {(hits.Count > 0 ? string.Join(" + ", hits.ConvertAll(RcChainName)) : "nothing")}"+ : a.RackMono() ? "mono" : "poly";+ return $"{chains} · {probe} · {macros}";+ }+ }+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.csnew file mode 100644index 00000000..1d0fbfdd--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs@@ -0,0 +1,218 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the rack card's Zones / Select tab (specs/040). Instrument and MIDI+// racks: each chain's key and velocity zone, dragged by their edges, and a probe — hover a+// key and every row shows whether that chain would play it (at velocity 100), the footer+// names them. Audio Effect and MIDI racks: each chain's select range and the selector, which+// only counts in Select mode (the rows go faint otherwise). Edges move the engine live; the+// card rebuilds when a drag ends so the chain list's summaries follow.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Layout;+using Avalonia.Media;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed partial class RackCardView+{+ private const double RcZoneNameWidth = 80, RcVelWidth = 64;+ private const int RcProbeVelocity = 100;++ private Control RcZonesTab()+ {+ var a = _ra;+ int n = a.ChainCount();+ bool keys = _rp.KeyZones, vel = _rp.VelocityZones, select = _rp.SelectRanges;+ bool selectOn = a.RackMode() == RackKindProfile.Select;+ var keyBars = new List<RackRangeBar>();+ var rowHosts = new List<(Border Row, TextBlock Name, int Chain)>();+ TextBlock result = RcMono("", NotaPalette.TextTertiary, 7.5);++ var rows = new StackPanel { Spacing = 3 };++ // Column titles + ruler.+ var ruler = new RackRuler+ {+ Ticks = keys ? [(12, "C0"), (36, "C2"), (60, "C4"), (84, "C6"), (108, "C8")] : [(0, "0"), (32, "32"), (64, "64"), (96, "96"), (127, "127")],+ };+ var titles = new Grid { ColumnDefinitions = new ColumnDefinitions($"{RcZoneNameWidth},*{(vel ? $",{RcVelWidth}" : "")}"), ColumnSpacing = 8, Height = 12 };+ titles.Children.Add(RcText("Chain", NotaPalette.TextTertiary, 7.5));+ Grid.SetColumn(ruler, 1); titles.Children.Add(ruler);+ if (vel) { var vt = RcText("Velocity", NotaPalette.TextTertiary, 7.5); Grid.SetColumn(vt, 2); titles.Children.Add(vt); }+ rows.Children.Add(titles);++ // The selector (Select mode picks the chains whose select range holds it).+ if (select)+ {+ bool follows = a.SelectorFollows();+ int sel = (int)Math.Round(a.LiveSelector() * 127);+ var bar = new RackRangeBar { Single = true, Lo = sel, Hi = sel, Dim = !selectOn || follows, Height = 10, IsHitTestVisible = !follows };+ ToolTip.SetTip(bar, follows+ ? "The selector follows the input level · turn Follow input off on the Rack out tab to set it by hand"+ : "Drag to choose which chains play · right-click to map it to a macro");+ bar.Changed += (lo, _) => { a.SetSelector(lo / 127f); RcProbeUpdate(); };+ bar.Committed += DeferRebuild;+ bar.ContextRequested += (_, e) => { e.Handled = true; RcSelectorMenu(bar); };+ var row = new Grid { ColumnDefinitions = new ColumnDefinitions($"{RcZoneNameWidth},*{(vel ? $",{RcVelWidth}" : "")}"), ColumnSpacing = 8, Height = 14 };+ row.Children.Add(RcText("Selector", NotaPalette.TextSecondary, NotaType.KnobLabel));+ Grid.SetColumn(bar, 1); row.Children.Add(bar);+ rows.Children.Add(row);+ _irTick.Add(() =>+ {+ int live = (int)Math.Round(a.LiveSelector() * 127);+ if (live != bar.Lo) { bar.Lo = bar.Hi = live; bar.InvalidateVisual(); RcProbeUpdate(); }+ });+ }++ for (int c = 0; c < n; c++)+ {+ int cc = c;+ var hue = ChainHue(c);+ var stripe = new Border { Width = 3, Height = 9, CornerRadius = NotaRadius.Bar, Background = hue, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 4, 0) };+ var name = RcName(RcChainName(c), c == Sel ? NotaPalette.AccentBright : NotaPalette.TextPrimary, NotaType.KnobLabel);+ var nameCell = new DockPanel { LastChildFill = true, Children = { RcDock(stripe, Dock.Left), name } };+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions($"{RcZoneNameWidth},*{(vel ? $",{RcVelWidth}" : "")}"), ColumnSpacing = 8, Height = 22, VerticalAlignment = VerticalAlignment.Center };+ grid.Children.Add(nameCell);++ if (keys)+ {+ a.ChainZone(c, out int kl, out int kh, out int vl, out int vh);+ var kb = new RackRangeBar { Lo = kl, Hi = kh, Hue = hue, Label = (lo, hi) => $"{NoteName(lo)}–{NoteName(hi)}" };+ kb.Changed += (lo, hi) => { a.ChainZone(cc, out _, out _, out int l, out int h); a.SetChainZone(cc, lo, hi, l, h); RcProbeUpdate(); };+ kb.Committed += () => { Sel = cc; DeferRebuild(); };+ kb.Hover += v => { _rs.ProbePitch = v; RcProbeUpdate(); };+ ToolTip.SetTip(kb, "Drag the edges to set the key zone · hover to test a note");+ Grid.SetColumn(kb, 1); grid.Children.Add(kb);+ keyBars.Add(kb);+ if (vel)+ {+ var vb = new RackRangeBar { Lo = vl, Hi = vh, Hue = hue, Label = (lo, hi) => $"{lo}–{hi}" };+ vb.Changed += (lo, hi) => { a.ChainZone(cc, out int k0, out int k1, out _, out _); a.SetChainZone(cc, k0, k1, lo, hi); RcProbeUpdate(); };+ vb.Committed += () => { Sel = cc; DeferRebuild(); };+ ToolTip.SetTip(vb, "Drag the edges to set the velocity zone");+ Grid.SetColumn(vb, 2); grid.Children.Add(vb);+ }+ if (select)+ {+ // MIDI rack: the select range sits under the key zone, faint outside Select mode.+ a.SelectRange(c, out int sl, out int sh);+ var sb = new RackRangeBar { Lo = sl, Hi = sh, Hue = hue, Dim = !selectOn, Height = 6, Margin = new Thickness(0, 14, 0, 0), VerticalAlignment = VerticalAlignment.Top };+ sb.Changed += (lo, hi) => { a.SetSelectRange(cc, lo, hi); RcProbeUpdate(); };+ sb.Committed += () => { Sel = cc; DeferRebuild(); };+ ToolTip.SetTip(sb, "Select range: in Select mode this chain plays while the selector is inside it");+ kb.VerticalAlignment = VerticalAlignment.Top;+ kb.Height = 12;+ grid.Children.Remove(kb); // it moves into the stack with the select bar+ var stack = new Panel { Children = { kb, sb } };+ Grid.SetColumn(stack, 1); grid.Children.Add(stack);+ grid.Height = 24;+ }+ }+ else+ {+ a.SelectRange(c, out int sl, out int sh);+ var sb = new RackRangeBar { Lo = sl, Hi = sh, Hue = hue, Dim = !selectOn, Label = (lo, hi) => $"{lo}–{hi}" };+ sb.Changed += (lo, hi) => { a.SetSelectRange(cc, lo, hi); RcProbeUpdate(); };+ sb.Committed += () => { Sel = cc; DeferRebuild(); };+ ToolTip.SetTip(sb, "Drag the edges to set the select range");+ Grid.SetColumn(sb, 1); grid.Children.Add(sb);+ }+ var rowBorder = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(4, 0, 0, 0), Child = grid };+ rows.Children.Add(rowBorder);+ rowHosts.Add((rowBorder, name, c));+ }++ string hint = keys ? "Drag zone edges · hover to test a note"+ : selectOn ? "Drag the selector or map it to a macro" : "Ranges apply when Chains run is set to Select";+ var foot = new DockPanel+ {+ LastChildFill = false, Height = 16,+ Children = { RcDock(RcText(hint, NotaPalette.TextTertiary, 7.5, FontWeight.Normal), Dock.Left), RcDock(result, Dock.Right) },+ };+ var footer = Section(foot, SectionEdge.Top);+ DockPanel.SetDock(footer, Dock.Bottom);+ var scroll = new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };++ // Probe: which chains play the hovered key (or the selector, for an audio rack).+ _rcProbe = () =>+ {+ int probe = _rs.ProbePitch;+ var hits = RcProbeHits(probe);+ foreach (var kb in keyBars) { kb.Probe = keys ? probe : -1; kb.InvalidateVisual(); }+ foreach (var (row, nm, ch) in rowHosts)+ {+ bool hit = hits.Contains(ch);+ row.Background = hit ? NotaPalette.Wash(NotaPalette.Teal, 0x22) : Brushes.Transparent;+ nm.Foreground = hit ? NotaPalette.TealBright : ch == Sel ? NotaPalette.AccentBright : NotaPalette.TextPrimary;+ }+ string names = string.Join(keys ? " + " : ", ", hits.Select(RcChainName));+ if (keys)+ result.Text = probe < 0 ? "Hover the zones" : $"{NoteName(probe)} · vel {RcProbeVelocity} → {(names.Length > 0 ? names : "nothing")}";+ else+ result.Text = $"selector {(int)Math.Round(a.LiveSelector() * 127)} → {(names.Length > 0 ? names : "silence")}{(selectOn ? "" : " · inactive")}";+ result.Foreground = hits.Count > 0 ? NotaPalette.TealBright : NotaPalette.TextTertiary;+ };+ RcProbeUpdate();+ return new DockPanel { LastChildFill = true, Children = { footer, scroll } };+ }++ // Map the selector to a macro (the selector is a rack control, not a chain parameter).+ private void RcSelectorMenu(Control anchor)+ {+ var f = new MenuFlyout();+ f.Items.Add(MenuKit.Header("Selector", null, "Map to a macro"));+ f.Items.Add(new Separator());+ for (int m = 0; m < 8; m++)+ {+ int mm = m;+ var mi = new MenuItem { Header = $"Macro {m + 1} · {_ra.MacroName(m)}" };+ mi.Click += (_, _) => RcMapSelector(mm);+ f.Items.Add(mi);+ }+ f.ShowAt(anchor, showAtPointer: true);+ }++ private void RcMapSelector(int macro)+ {+ RcAddMapping(macro, 0, Nota.Application.RackMacroMapping.RackControl, 0, 0f, 1f);+ _rs.SelectedMacro = macro;+ DeferRebuild();+ }++ private Action? _rcProbe;+ private void RcProbeUpdate() => _rcProbe?.Invoke();++ /// <summary>The chains that would take a note at <paramref name="pitch"/> (velocity 100), or, for an+ /// audio rack, the chains the selector picks.</summary>+ private List<int> RcProbeHits(int pitch)+ {+ var a = _ra;+ var hits = new List<int>();+ bool selectOn = a.RackMode() == RackKindProfile.Select;+ int selector = (int)Math.Round(a.LiveSelector() * 127);+ for (int c = 0; c < a.ChainCount(); c++)+ {+ if (!RcAudible(c)) continue;+ if (_rp.SelectRanges && (selectOn || !_rp.KeyZones))+ {+ a.SelectRange(c, out int sl, out int sh);+ if (selector < sl || selector > sh) continue;+ }+ if (_rp.KeyZones)+ {+ if (pitch < 0) continue;+ a.ChainZone(c, out int kl, out int kh, out int vl, out int vh);+ if (pitch < kl || pitch > kh || RcProbeVelocity < vl || RcProbeVelocity > vh) continue;+ }+ hits.Add(c);+ }+ return hits;+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.csnew file mode 100644index 00000000..a302cac1--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.cs@@ -0,0 +1,294 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the shared rack card (specs/040, nota-design "Nota Racks", frames+// 1a–1f): one body for the Instrument, Audio Effect and MIDI Effect racks, drawn inside+// the shared device shell (which owns the header: name, preset, badge, power switch).+//+// macros (116) │ Chains · Zones|Select · Macros │ Chain · Rack out|Output (160)+// ─────────────┴─────────────────────────────────┴──────────────────────────────+// status line (18)+//+// The columns are card sections (a rule where they meet), never framed boxes. What differs+// between the racks comes from RackKindProfile; the regions live in the RackCard.*.cs+// partials of RackCardView, so they share its device popups, add menus and Browser drops.+// The card is rebuilt after every structural edit, so the view state (tabs, the chosen+// macro, mapping, the probe) lives in RackCardState, keyed by the rack, and survives+// rebuilds and theme switches; the chosen chain stays in the context. Colour only from+// NotaPalette slots: every theme recolours it live.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal enum RackCentreTab { Chains, Zones, Macros }++/// <summary>A rack card's view state. Not saved with the project.</summary>+internal sealed class RackCardState+{+ public RackCentreTab Centre = RackCentreTab.Chains;+ public bool OutputTab; // right panel: false = Chain, true = Rack out / Output+ public int SelectedMacro;+ public int MappingMacro = -1; // the macro being mapped in place, or -1+ public int ProbePitch = -1; // the key under the pointer on the Zones tab, or -1+ public int SelectedChain; // the chain shown in the device lane and the Chain panel++ public bool Mapping => MappingMacro >= 0;++ private static readonly Dictionary<(int Track, RackKind Kind, int Index), RackCardState> Store = new();++ /// <summary>The state of one rack: a track's instrument rack, or the rack at an audio or MIDI device index.</summary>+ public static RackCardState For(int trackId, RackKind kind, int index)+ {+ var key = (trackId, kind, index);+ if (!Store.TryGetValue(key, out var s)) Store[key] = s = new RackCardState();+ return s;+ }++ /// <summary>Ends macro mapping on every rack card (Esc). True when one was mapping.</summary>+ public static bool EndAllMapping()+ {+ bool any = false;+ foreach (var s in Store.Values)+ if (s.Mapping) { s.MappingMacro = -1; any = true; }+ return any;+ }++ /// <summary>Whether any rack card is mapping a macro right now.</summary>+ public static bool AnyMapping()+ {+ foreach (var s in Store.Values) if (s.Mapping) return true;+ return false;+ }+}++internal sealed partial class RackCardView+{+ public const double RcMacroWidth = 116, RcRightWidth = 166, RcStatusHeight = 18, RcTabHeight = 20, RcGutter = 6;++ private IRackAccess _ra = null!;+ private RackKindProfile _rp = RackKindProfile.Instrument;+ private RackCardState _rs = new();++ /// <summary>The shared rack card body for <paramref name="a"/>. <paramref name="rackIndex"/> tells+ /// racks on one track apart (-1 = the track's instrument, else its device or MIDI effect index).</summary>+ internal Control BuildRackCard(IRackAccess a, int rackIndex)+ {+ _ra = a;+ _rp = RackKindProfile.For(a.Kind);+ _rs = RackCardState.For(T, a.Kind, rackIndex);+ _ownSel = true;+ _irTick.Clear();+ int n = a.ChainCount();+ Sel = n > 0 ? Math.Clamp(Sel, 0, n - 1) : 0;+ _rs.SelectedMacro = Math.Clamp(_rs.SelectedMacro, 0, 7);+ if (_rs.Centre != RackCentreTab.Chains) _rs.MappingMacro = -1;++ var grid = new Grid+ {+ ColumnDefinitions = new ColumnDefinitions($"{RcMacroWidth},*,{RcRightWidth}"),+ RowDefinitions = new RowDefinitions($"*,{RcStatusHeight}"),+ ColumnSpacing = RcGutter, RowSpacing = 3,+ Margin = new Thickness(NotaSpace.DeviceInset, NotaSpace.DeviceInset, NotaSpace.DeviceInset, 0),+ };+ // A section's rule is on its left edge: pad the content off it by a gutter, so the rule+ // sits halfway between the columns.+ RcPlace(grid, Section(RcMacroColumn()), 0, 0);+ RcPlace(grid, new RuleSection { Padding = new Thickness(RcGutter, 0, 0, 0), Child = RcCentre() }, 0, 1);+ RcPlace(grid, new RuleSection { Padding = new Thickness(RcGutter, 0, 0, 0), Child = RcRightPanel() }, 0, 2);+ var status = Section(RcStatusLine(), SectionEdge.Top);+ Grid.SetColumnSpan(status, 3);+ RcPlace(grid, status, 1, 0);++ if (_irTick.Count > 0) _ctx.AddDeviceRefresher(() => { for (int i = 0; i < _irTick.Count; i++) _irTick[i](); });+ return grid;+ }++ private static void RcPlace(Grid g, Control c, int row, int col)+ {+ Grid.SetRow(c, row);+ Grid.SetColumn(c, col);+ g.Children.Add(c);+ }++ // ---- centre: tabs over the chosen tab's body -------------------------------------++ private Control RcCentre()+ {+ var tabs = Segments(["Chains", _rp.ZoneTab, "Macros"], () => (int)_rs.Centre, i =>+ {+ _rs.Centre = (RackCentreTab)i;+ if (_rs.Centre != RackCentreTab.Chains) _rs.MappingMacro = -1; // mapping happens on the chain+ DeferRebuild();+ }, out _, fontSize: NotaType.RowLabel);+ var summary = RcMono(RcCentreSummary(), NotaPalette.TextTertiary);+ summary.HorizontalAlignment = HorizontalAlignment.Right;+ Grid.SetColumn(summary, 1);+ var head = new Grid { Height = RcTabHeight, ColumnDefinitions = new ColumnDefinitions("Auto,*"), Children = { tabs, summary } };++ Control body = _rs.Centre switch+ {+ RackCentreTab.Zones => RcZonesTab(),+ RackCentreTab.Macros => RcMacrosTab(),+ _ => RcChainsTab(),+ };+ body.Margin = new Thickness(0, 4, 0, 0);+ DockPanel.SetDock(head, Dock.Top);+ return new DockPanel { LastChildFill = true, Children = { head, body } };+ }++ private string RcCentreSummary()+ {+ int n = _ra.ChainCount();+ string chains = n == 1 ? "1 chain" : $"{n} chains";+ return _rs.Centre switch+ {+ RackCentreTab.Zones => _rp.KeyZones ? "Keys C−1–G9 · vel 0–127" : "Select 0–127",+ RackCentreTab.Macros => $"{RcMappedMacros()} of 8 mapped",+ _ => _rp.Modes.Length > 0 ? $"{chains} · {RcModeWord()}" : chains,+ };+ }++ private string RcModeWord() => _ra.RackMode() switch+ {+ RackKindProfile.Serial => "serial",+ RackKindProfile.Select => "select",+ _ => _rp.Kind == RackKind.MidiEffect ? "parallel · merged" : "parallel · summed",+ };++ // ---- right panel: Chain · Rack out|Output -----------------------------------------++ private Control RcRightPanel()+ {+ var tabs = Segments(["Chain", _rp.OutputTab], () => _rs.OutputTab ? 1 : 0, i =>+ {+ _rs.OutputTab = i == 1;+ DeferRebuild();+ }, out _, fill: true, fontSize: NotaType.RowLabel);+ var head = new Border { Height = RcTabHeight, Child = tabs };+ DockPanel.SetDock(head, Dock.Top);+ var body = _rs.OutputTab ? RcOutputPanel() : RcChainPanel();+ body.Margin = new Thickness(0, 6, 0, 0);+ return new DockPanel { LastChildFill = true, Children = { head, body } };+ }++ // ---- status line ------------------------------------------------------------------++ private Control RcStatusLine()+ {+ var text = new TextBlock+ {+ Text = RcStatusText(), FontSize = NotaType.KnobLabel, Foreground = NotaPalette.TextSecondary,+ VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,+ };+ return new Border { Height = RcStatusHeight, Padding = new Thickness(2, 0), Child = text };+ }++ // ---- shared helpers ---------------------------------------------------------------++ private int RcMappedMacros()+ {+ var seen = new bool[8];+ int n = 0;+ for (int i = 0; i < _ra.MappingCount(); i++)+ if (_ra.TryGetMapping(i, out var m) && m.Macro is >= 0 and < 8 && !seen[m.Macro]) { seen[m.Macro] = true; n++; }+ return n;+ }++ private int RcTargetCount(int macro)+ {+ int n = 0;+ for (int i = 0; i < _ra.MappingCount(); i++)+ if (_ra.TryGetMapping(i, out var m) && m.Macro == macro) n++;+ return n;+ }++ /// <summary>The chain's display name: its own name, else its first device's.</summary>+ private string RcChainName(int c)+ {+ string n = _ra.ChainName(c);+ if (n.Length > 0) return n;+ if (_rp.TakesInstrument) { n = _ra.ChainInstrumentName(c); if (n.Length > 0) return n; }+ if (_rp.Kind == RackKind.MidiEffect && _ra.ChainMidiCount(c) > 0) return _ra.ChainMidiName(c, 0);+ if (_rp.Kind == RackKind.AudioEffect && _ra.ChainDeviceCount(c) > 0) return _ra.ChainDeviceName(c, 0);+ return $"Chain {c + 1}";+ }++ /// <summary>Whether a chain sounds: not muted, and soloed when any chain is.</summary>+ private bool RcAudible(int c)+ {+ if (_ra.ChainMute(c)) return false;+ for (int i = 0; i < _ra.ChainCount(); i++)+ if (_ra.ChainSolo(i)) return _ra.ChainSolo(c);+ return true;+ }++ private static TextBlock RcMono(string text, IBrush ink, double size = NotaType.KnobValue) => new()+ {+ Text = text, FontFamily = NotaFonts.MonoFamily, FontSize = size, Foreground = ink,+ VerticalAlignment = VerticalAlignment.Center,+ };++ private static TextBlock RcText(string text, IBrush ink, double size = NotaType.KnobLabel, FontWeight? weight = null) => new()+ {+ Text = NotaText.Label(text), FontSize = size, Foreground = ink, FontWeight = weight ?? FontWeight.Medium,+ VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,+ };++ /// <summary>A name the user typed (chain, macro): never re-cased.</summary>+ private static TextBlock RcName(string text, IBrush ink, double size = NotaType.KnobLabel) => new()+ {+ Text = text, FontSize = size, Foreground = ink, FontWeight = FontWeight.SemiBold,+ VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,+ };++ /// <summary>A small raised key (Map, Duplicate, …): neutral, or a solid fill with derived ink while on.</summary>+ private static Border RcKey(string text, Action click, bool on = false, SolidColorBrush? onFill = null, bool enabled = true, string? tip = null)+ {+ var fill = onFill ?? NotaPalette.Accent;+ var tb = new TextBlock+ {+ Text = NotaText.Label(text), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Medium,+ Foreground = on ? NotaPalette.InkOn(fill) : enabled ? NotaPalette.TextSecondary : NotaPalette.TextDisabled,+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ };+ var b = new Border+ {+ Height = 16, MinWidth = 26, Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Badge,+ Background = on ? fill : NotaPalette.SurfaceRaised, BorderBrush = on ? fill : NotaPalette.BorderDefault,+ BorderThickness = new Thickness(1), Cursor = enabled ? new Cursor(StandardCursorType.Hand) : Cursor.Default,+ VerticalAlignment = VerticalAlignment.Center, Child = tb,+ };+ if (tip is not null) ToolTip.SetTip(b, tip);+ b.PointerPressed += (_, e) =>+ {+ if (!enabled || !e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ click();+ };+ return b;+ }++ /// <summary>A one-line rename field under <paramref name="anchor"/>.</summary>+ private void RcPromptRename(Control anchor, string current, Action<string> apply)+ {+ var box = new TextBox { Text = current, FontSize = 9, Width = 110, Height = 20, Padding = new Thickness(4, 0) };+ var fly = new Flyout { Content = box };+ box.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Enter) { apply(box.Text ?? ""); fly.Hide(); DeferRebuild(); }+ else if (e.Key == Key.Escape) fly.Hide();+ };+ fly.ShowAt(anchor);+ box.Focus();+ box.SelectAll();+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex e8394338..f978b686 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -1,14 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the rack cards, shared by the Instrument Rack (track instrument,-// kind 3), the Audio Effect Rack (a device, builtin kind 5) and the Drum Rack (kind 4).-// All present the same body: a 4×2 grid of macro faders on the left, a chain list (or a-// 4×4 pad grid for the drum rack) in the middle, and the selected chain's device chain-// on the right. The two rack addressings differ only via IRackAccess. Built per-rebuild-// with a DeviceCardContext; all mutable state (selected chain, refreshers, drop glow,-// rebuild) lives in the view behind the context. The Drum Rack body is in-// RackCardView.Drum.cs.+// Detail · Devices — the rack cards. The Instrument Rack (track instrument, kind 3), the+// Audio Effect Rack (a device, builtin kind 5) and the MIDI Effect Rack (a MIDI effect,+// kind 6) share one card, built in the RackCard.*.cs partials (specs/040); this file holds+// their entry points and what the card and the Drum Rack (kind 4, RackCardView.Drum.cs)+// share: the device windows for a chain's instrument and effects, the add menus, Browser+// drops and macro menus. The racks' addressing differs only via IRackAccess. Built+// per-rebuild with a DeviceCardContext; the selected chain, refreshers, drop glow and+// rebuild live in the view behind the context.using System;using System.Collections.Generic;@@ -28,14 +28,21 @@ namespace Nota.App;internal sealed partial class RackCardView(DeviceCardContext ctx){- private static readonly string[] RackDeviceNames = { "Nota EQ-3", "Nota EQ-8", "Nota Dynamic EQ-8", "Nota Compressor", "Nota Prism", "Nota Reverb", "Nota Chamber", "Nota Delay", "Nota Utility", "Nota Level", "Nota Lens", "Nota Ceiling", "Nota Shutter", "Nota Valve", "Nota Auto Filter", "Nota Vintage", "Nota Forge", "Nota Crush", "Nota Chorus", "Nota Flanger", "Nota Phaser", "Nota Orbit", "Nota Auto Shift", "Nota Beat Repeat", "Nota Strata" };- private static readonly int[] RackDeviceKinds = { 16, 0, 13, 1, 21, 2, 20, 3, 4, 18, 22, 14, 19, 6, 7, 8, 17, 12, 25, 23, 24, 9, 10, 11, 15 };+ private static readonly string[] RackDeviceNames = { "Nota EQ-3", "Nota EQ-8", "Nota Dynamic EQ-8", "Nota Compressor", "Nota Prism", "Nota Reverb", "Nota Chamber", "Nota Delay", "Nota Utility", "Nota Level", "Nota Lens", "Nota Ceiling", "Nota Shutter", "Nota Valve", "Nota Auto Filter", "Nota Vintage", "Nota Forge", "Nota Crush", "Nota Chorus", "Nota Flanger", "Nota Phaser", "Nota Orbit", "Nota Auto Shift", "Nota Beat Repeat", "Nota Strata", "Nota Vocoder" };+ private static readonly int[] RackDeviceKinds = { 16, 0, 13, 1, 21, 2, 20, 3, 4, 18, 22, 14, 19, 6, 7, 8, 17, 12, 25, 23, 24, 9, 10, 11, 15, 26 };private static readonly IBrush RowSel = NotaPalette.Wash(NotaPalette.Accent, 0x22); // selected chain washprivate readonly DeviceCardContext _ctx = ctx;private IAudioEngine E => _ctx.Engine;private int T => _ctx.TrackId;- private int Sel { get => _ctx.SelectedChain; set => _ctx.SelectedChain = value; }+ // The chosen chain: each shared rack card keeps its own (several racks can sit on one+ // track); the Drum Rack uses the device view's.+ private bool _ownSel;+ private int Sel+ {+ get => _ownSel ? _rs.SelectedChain : _ctx.SelectedChain;+ set { if (_ownSel) _rs.SelectedChain = value; else _ctx.SelectedChain = value; }+ }// ---- Instrument Rack (mockup 2p) shared bits ----private static readonly IBrush IrHdr = NotaPalette.SurfaceCard;@@ -50,10 +57,6 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)private static readonly IBrush IrTxt = NotaPalette.TextPrimary;private static readonly IBrush IrMuted = NotaPalette.TextTertiary;private static readonly IBrush IrRed = NotaPalette.AccentHover; // a state, not an alert: red is kept for recording and overload- private static bool _macroMapMode; // Instrument Rack: second (Macro-map) view- private static int _splitAxis; // 0 = Key zone, 1 = Velocity- private static bool _aeMacroMap; // Audio Effect Rack: macro-map view- private static bool _aeFold; // Audio Effect Rack: fold device cards to titlesprivate readonly System.Collections.Generic.List<Action> _irTick = new();// Rebuild on the NEXT dispatcher cycle, never synchronously inside a pointer handler:@@ -64,169 +67,21 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)// The palette slot itself, not a copy of its colour: these brushes are handed to// Borders that outlive a theme change, and a snapshot would freeze the chain hues.private static IBrush ChainHue(int c) => NotaPalette.TrackBrushes[((c % 8) + 8) % 8];- private static TextBlock IrMono(string t, IBrush c, double fs = 8) { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }private static TextBlock IrCap(string t, IBrush? c = null) => new() { Text = NotaText.Label(t), FontSize = 8, FontWeight = FontWeight.Medium, Foreground = c ?? IrMuted, VerticalAlignment = VerticalAlignment.Center };// ---- entry points ------------------------------------------------------ // Instrument Rack body (the track's instrument, mockup 2p, 700×260). The shared device- // shell draws the header (name, presets, "Rack · N chains"); this is everything below it.+ // The rack bodies (700 × 238 under the shared device shell's header, which draws the+ // name, presets and "Rack · N chains").public Control BuildInstrumentRackBody(out int chains){var a = new InstrumentRackAccess(E, T);chains = a.ChainCount();- Sel = chains > 0 ? Math.Clamp(Sel, 0, chains - 1) : 0;- _irTick.Clear();- Control content = _macroMapMode ? InstrumentRackMacroMap(a) : InstrumentRackMain(a);- if (_irTick.Count > 0) _ctx.AddDeviceRefresher(() => { for (int i = 0; i < _irTick.Count; i++) _irTick[i](); });- return new Border { Background = NotaPalette.BgApp, Child = content };- }-- private Control InstrumentRackMain(IRackAccess a)- {- var strip = IrMacroStrip(a);- var chainList = IrChainList(a);- var rail = IrRackRail(a);- DockPanel.SetDock(chainList, Dock.Left); DockPanel.SetDock(rail, Dock.Right);- var body = new DockPanel { LastChildFill = true, Children = { chainList, rail, IrDeviceArea(a) } };- DockPanel.SetDock(strip, Dock.Top);- return new DockPanel { LastChildFill = true, Children = { strip, body } };+ return RcBody(BuildRackCard(a, -1));}- // ---- macro strip (34): 8 named horizontal macro sliders ----- private Control IrMacroStrip(IRackAccess a)- {- var grid = new Grid { VerticalAlignment = VerticalAlignment.Center };- grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));- var lbl = IrCap("MACROS"); Grid.SetColumn(lbl, 0); grid.Children.Add(lbl);- for (int i = 0; i < 8; i++)- {- grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));- var cell = IrMacroSlider(a, i); Grid.SetColumn(cell, i + 1); grid.Children.Add(cell);- }- grid.ColumnSpacing = 6;- return new Border { Height = 34, Background = IrHdr, BorderBrush = IrBorder, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child = grid };- }-- private Control IrMacroSlider(IRackAccess a, int i)- {- int adi = a.AutomationDeviceIndex;- bool mapped = false;- for (int m = 0; m < a.MappingCount(); m++) if (a.TryGetMapping(m, out var mm) && mm.Macro == i) { mapped = true; break; }- var name = new TextBlock { Text = a.MacroName(i), FontSize = 8, Foreground = mapped ? IrTxt : IrMuted, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };- var val = IrMono("0", IrMuted, 8); val.TextAlignment = TextAlignment.Right;- var fill = new Border { Height = 3, Background = mapped ? NotaPalette.VizInk : NotaPalette.TextDisabled, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var handle = new Border { Width = 6, Height = 8, Background = NotaPalette.TextSecondary, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var slot = new Panel { Height = 10, Children = { new Border { Height = 3, Background = IrInset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center }, fill, handle } };- void Vis(double v) { double W = slot.Bounds.Width; fill.Width = v * W; handle.Margin = new Thickness(Math.Clamp(v * W - 3, 0, Math.Max(0, W - 6)), 0, 0, 0); }- bool drag = false;- void SetFromX(double x) { double v = Math.Clamp(x / Math.Max(1, slot.Bounds.Width), 0, 1); E.PluginParamSet(T, adi, i, (float)v); Vis(v); _ctx.InvokeRackParamRefreshers(); }- slot.PointerPressed += (_, e) => { drag = true; e.Pointer.Capture(slot); SetFromX(e.GetPosition(slot).X); };- slot.PointerMoved += (_, e) => { if (drag) SetFromX(e.GetPosition(slot).X); };- slot.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- slot.PointerCaptureLost += (_, _) => drag = false;- name.DoubleTapped += (_, _) => PromptRenameMacro(a, i, name);- ValueEntry.Attach(val, () => E.PluginParamGet(T, adi, i), v => E.PluginParamSet(T, adi, i, (float)v),- () => NotaNum.F($"{E.PluginParamGet(T, adi, i) * 100:0}"),- after: () => { double v = E.PluginParamGet(T, adi, i); Vis(v); val.Text = NotaNum.F($"{v * 100:0}"); _ctx.InvokeRackParamRefreshers(); });- _irTick.Add(() => { double v = E.PluginParamGet(T, adi, i); if (!drag) Vis(v); val.Text = $"{v * 100:0}"; });- var head = new DockPanel { LastChildFill = true, Children = { WithRight(val), name } };- var cell = new StackPanel { Spacing = 2, Children = { head, slot } };- // MIDI-learn: a macro is a plugin-param on the rack device (adi = automation device- // index). Tag the cell so the learn overlay highlights + binds it like any knob.- MidiLearn.Bind(cell, MidiTarget.PluginParam(T, adi, i), $"Macro · {a.MacroName(i)}", v => Vis(v));- return cell;- }-- private void PromptRenameMacro(IRackAccess a, int i, TextBlock label)- {- var box = new TextBox { Text = a.MacroName(i), FontSize = 9, Width = 90, Height = 20, Padding = new Thickness(4, 0) };- var fly = new Flyout { Content = box };- box.KeyDown += (_, e) => { if (e.Key == Avalonia.Input.Key.Enter) { a.SetMacroName(i, box.Text ?? ""); label.Text = a.MacroName(i); fly.Hide(); _ctx.RequestRebuild(); } };- fly.ShowAt(label);- box.Focus();- }-- // ---- chain list (186) ----- private Control IrChainList(IRackAccess a)- {- var rows = new StackPanel { Spacing = 4 };- int chains = a.ChainCount();- for (int c = 0; c < chains; c++) rows.Children.Add(IrChainRow(a, c));- var addBtn = new Border { BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(0, 3),- Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = "+ Add chain", FontSize = 9, Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center } };- addBtn.PointerPressed += (_, _) => ShowAddChainMenu(a, addBtn);- rows.Children.Add(addBtn);-- var header = new DockPanel { LastChildFill = false, Margin = new Thickness(0, 0, 0, 7), Children = { IrCap("CHAINS"), WithRight(new TextBlock { Text = "zone · vel · out", FontSize = 8, Foreground = IrMuted, VerticalAlignment = VerticalAlignment.Center }) } };- var split = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { IrCap("SPLIT"), IrSeg(new[] { "Key", "Vel" }, _splitAxis, i => { _splitAxis = i; _ctx.RequestRebuild(); }) } };- var scroll = new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, Padding = new Thickness(0, 0, 6, 0) };- DockPanel.SetDock(header, Dock.Top); DockPanel.SetDock(split, Dock.Bottom);- var inner = new DockPanel { LastChildFill = true, Children = { header, split, scroll } };- return new Border { Width = 186, Background = IrRail, BorderBrush = IrBorder, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(8, 6), Child = inner };- }-- private Control IrChainRow(IRackAccess a, int c)- {- bool sel = c == Sel;- string name = a.ChainInstrumentName(c); if (string.IsNullOrEmpty(name)) name = $"Chain {c + 1}";- int devs = a.ChainDeviceCount(c);- E.RackChainZone(T, c, out int kLo, out int kHi, out int vLo, out int vHi);- var nameTb = new TextBlock { Text = name, FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = sel ? IrAmberLit : IrTxt, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };- var head = new DockPanel { LastChildFill = true, Children = { WithRight(ChainDelBtn(a, c)), WithRight(IrMono($"{devs} dev", IrMuted)), nameTb } };-- var zone = IrMono($"{NoteName(kLo)}–{NoteName(kHi)}", NotaPalette.TextSecondary);- var vel = IrMono($"{vLo}–{vHi}", IrMuted);- double db = a.ChainGain(c) <= 0.001 ? -60 : 20 * Math.Log10(a.ChainGain(c));- var dbT = IrMono(db <= -59 ? "−∞" : $"{db:+0.0;−0.0;0.0}", NotaPalette.TextSecondary);- var meterFill = new Border { Background = Success, HorizontalAlignment = HorizontalAlignment.Left, CornerRadius = NotaRadius.Bar };- var meter = new Border { Width = 20, Height = 3, Background = IrInset, CornerRadius = NotaRadius.Bar, Child = meterFill, VerticalAlignment = VerticalAlignment.Center };- _irTick.Add(() => meterFill.Width = 20 * Math.Clamp(E.RackChainMeter(T, c), 0, 1));- var m = IrMsBtn("M", a.ChainMute(c), NotaPalette.Mute, () => { a.SetChainMute(c, !a.ChainMute(c)); _ctx.RequestRebuild(); });- var s = IrMsBtn("S", a.ChainSolo(c), NotaPalette.Solo, () => { a.SetChainSolo(c, !a.ChainSolo(c)); _ctx.RequestRebuild(); });- MidiLearn.Bind(m, MidiTarget.RackChainMute(T, a.AutomationDeviceIndex, c), "Chain Mute");- MidiLearn.Bind(s, MidiTarget.RackChainSolo(T, a.AutomationDeviceIndex, c), "Chain Solo");- var info = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { zone, vel, WithRight(dbT), meter, m, s } };- DockPanel.SetDock(dbT, Dock.Right);-- var row = new Border { Background = sel ? RowSel : IrCard, BorderBrush = sel ? IrAmber : IrBorder, BorderThickness = new Thickness(1, 1, 1, 1), CornerRadius = NotaRadius.Control, Padding = new Thickness(6, 4), Cursor = new Cursor(StandardCursorType.Hand),- Child = new StackPanel { Spacing = 3, Children = { head, info } } };- row.Background = sel ? RowSel : IrCard;- // left accent = chain hue, hidden while selected (the amber selection is enough).- var accent = new Border { Width = 2, Background = sel ? Brushes.Transparent : ChainHue(c), CornerRadius = new CornerRadius(NotaRadius.ClipValue, 0, 0, NotaRadius.ClipValue) };- var wrap = new DockPanel { LastChildFill = true, Children = { accent, row } };- DockPanel.SetDock(accent, Dock.Left);- wrap.PointerPressed += (_, e) => { if (e.GetCurrentPoint(wrap).Properties.IsLeftButtonPressed && Sel != c) { Sel = c; _ctx.RequestRebuild(); } };- DragDrop.SetAllowDrop(wrap, true);- DragDrop.AddDragOverHandler(wrap, (_, e) => { if (!BrowserView.IsBrowserDrag || !IsEffect(BrowserView.CurrentDrag)) { e.DragEffects = DragDropEffects.None; return; } e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow(); row.BorderBrush = AccentBright; });- DragDrop.AddDragLeaveHandler(wrap, (_, _) => row.BorderBrush = sel ? IrAmber : IrBorder);- DragDrop.AddDropHandler(wrap, (_, e) => { row.BorderBrush = sel ? IrAmber : IrBorder; if (BrowserView.CurrentDrag is { } it && IsEffect(it)) { Sel = c; DropEffectOnChain(a, c, it); e.Handled = true; } });- return wrap;- }-- // ---- device area (center): device slots + key/velocity zone map ----- private Control IrDeviceArea(IRackAccess a)- {- if (a.ChainCount() == 0)- return new Border { Padding = new Thickness(9, 7), Child = new TextBlock { Text = "Add a chain to build its device chain.", FontSize = 9, Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center } };- int sc = Sel;- string inm = a.ChainInstrumentName(sc); if (string.IsNullOrEmpty(inm)) inm = "Instrument";- var hdr = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 7), Children = {- new Border { Width = 7, Height = 7, CornerRadius = NotaRadius.Clip, Background = ChainHue(sc), VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = inm, FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = IrTxt, VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = "chain devices · signal left → right", FontSize = 8, Foreground = IrMuted, VerticalAlignment = VerticalAlignment.Center } } };- var slots = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5 };- if (a.HasInstrumentChains) slots.Children.Add(IrInstrumentSlot(a, sc));- int dc = a.ChainDeviceCount(sc);- for (int d = 0; d < dc; d++) slots.Children.Add(IrDeviceSlot(a, sc, d));- slots.Children.Add(IrAddDeviceSlot(a, sc));- var row = new ScrollViewer { Content = slots, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled };- var inner = new DockPanel { LastChildFill = true };- DockPanel.SetDock(hdr, Dock.Top); inner.Children.Add(hdr);- if (!_foldZone) { var zm = IrZoneMap(a); DockPanel.SetDock(zm, Dock.Bottom); inner.Children.Add(zm); }- inner.Children.Add(row);- return new Border { Padding = new Thickness(8, 6), Child = inner };- }+ // The shared card fills the shell slot under the header (700 × 238).+ private static Control RcBody(Control card) => new Border { Height = DeviceCardKit.CardH - DeviceCardKit.HeaderH, ClipToBounds = true, Child = card };// A minimal device "slot" — name + type + two open buttons (full GUI / param knobs)// + macro/bypass footer.@@ -353,62 +208,6 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)f.ShowAt(anchor, showAtPointer: true);}- private Control IrZoneMap(IRackAccess a)- {- int n = a.ChainCount();- var los = new int[n]; var his = new int[n]; var cols = new IBrush[n];- for (int c = 0; c < n; c++) { E.RackChainZone(T, c, out int kLo, out int kHi, out int vLo, out int vHi); los[c] = _splitAxis == 0 ? kLo : vLo; his[c] = _splitAxis == 0 ? kHi : vHi; cols[c] = ChainHue(c); }- var map = new RackZoneMap(los, his, cols, Sel, _splitAxis == 0);- map.RangeEdited += (c, lo, hi) =>- {- E.RackChainZone(T, c, out int kLo, out int kHi, out int vLo, out int vHi);- if (_splitAxis == 0) E.RackSetChainZone(T, c, lo, hi, vLo, vHi);- else E.RackSetChainZone(T, c, kLo, kHi, lo, hi);- DeferRebuild(); // not from inside the map's own pointer handler (#202)- };- return new Border { Height = 38, Background = IrInset, BorderBrush = IrField, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(4), Margin = new Thickness(0, 5, 0, 0), Child = map };- }-- // ---- rack rail (96): volume · glide · macro-map · fold/save ----- private Control IrRackRail(IRackAccess a)- {- var volVal = IrMono("0.0\u2009dB", IrTxt, 9); volVal.HorizontalAlignment = HorizontalAlignment.Center;- var vol = new Knob(Math.Clamp(E.RackVolume(T) / 2.0, 0, 1), 1.0) { Accent = true, Width = 40, Height = 40, HorizontalAlignment = HorizontalAlignment.Center };- string VolDb(double lin) => lin <= 0.001 ? "−∞\u2009dB" : $"{20 * Math.Log10(lin):+0.0;−0.0;0.0}\u2009dB";- vol.ValueChanged += v => { E.RackSetVolume(T, (float)(v * 2.0)); volVal.Text = VolDb(v * 2.0); };- vol.Default = 0.5; // unity gain- vol.Format = v => VolDb(v * 2.0);- ValueEntry.Attach(vol, "Rack volume", volVal);- volVal.Text = VolDb(E.RackVolume(T));- MidiLearn.Bind(vol, MidiTarget.RackVolume(T, a.AutomationDeviceIndex), "Rack Volume");- var volCell = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, Children = { IrCap("VOLUME"), vol, volVal } };-- var glideVal = IrMono("0\u2009ms", IrTxt, 8); glideVal.VerticalAlignment = VerticalAlignment.Center;- var gFill = new Border { Height = 3, Background = NotaPalette.VizInk, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var gSlot = new Panel { Height = 8, MinWidth = 30, Children = { new Border { Height = 3, Background = IrInset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center }, gFill } };- string GlideMs(double v) => $"{v * 500:0}\u2009ms";- void GUpd() { double v = E.RackGlide(T); gFill.Width = v * gSlot.Bounds.Width; glideVal.Text = GlideMs(v); }- bool gd = false; void GSet(double x) { double v = Math.Clamp(x / Math.Max(1, gSlot.Bounds.Width), 0, 1); E.RackSetGlide(T, (float)v); GUpd(); }- gSlot.PointerPressed += (_, e) => { gd = true; e.Pointer.Capture(gSlot); GSet(e.GetPosition(gSlot).X); };- gSlot.PointerMoved += (_, e) => { if (gd) GSet(e.GetPosition(gSlot).X); };- gSlot.PointerReleased += (_, e) => { if (gd) { gd = false; e.Pointer.Capture(null); } };- gSlot.PointerCaptureLost += (_, _) => gd = false;- _irTick.Add(() => { if (!gd) GUpd(); });- var glideRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 4, Children = { IrCap("GLIDE"), WithCol(gSlot, 1), WithCol(glideVal, 2) } };-- var mapBtn = new Border { BorderBrush = IrTeal, BorderThickness = new Thickness(1), Background = NotaPalette.Wash(NotaPalette.Teal, 0x24), CornerRadius = NotaRadius.Control, Padding = new Thickness(0, 3), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = "Macro map", FontSize = 8, FontWeight = FontWeight.Medium, Foreground = IrTeal, HorizontalAlignment = HorizontalAlignment.Center, TextAlignment = TextAlignment.Center } };- mapBtn.PointerPressed += (_, _) => { _macroMapMode = true; _ctx.RequestRebuild(); };-- var fold = IrRailBtn(_foldZone ? "Unfold" : "Fold", () => { _foldZone = !_foldZone; _ctx.RequestRebuild(); });- var save = IrRailBtn("Save", () => _ctx.RequestPresetSave(-1));- var foldSave = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4, [DockPanel.DockProperty] = Dock.Bottom, Children = { fold, WithCol(save, 1) } };-- var top = new StackPanel { Spacing = 6, [DockPanel.DockProperty] = Dock.Top, Children = { IrCap("RACK OUT"), volCell, glideRow, new Border { Height = 1, Background = IrCard }, mapBtn } };- var inner = new DockPanel { LastChildFill = false, Children = { top, foldSave } };- return new Border { Width = 96, Background = IrRail, BorderBrush = IrBorder, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child = inner };- }-private static readonly InstrumentCardFactory _irFactory = new();private static readonly DeviceCardFactory _irDeviceFactory = new();@@ -617,24 +416,9 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)f.ShowAt(anchor, showAtPointer: true);}- private static bool _foldZone;private static Control WithRight(Control c) { DockPanel.SetDock(c, Dock.Right); return c; }private static Control WithCol(Control c, int col) { Grid.SetColumn(c, col); return c; }- private Control IrSeg(string[] names, int sel, Action<int> onSel)- {- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };- for (int i = 0; i < names.Length; i++)- {- int iv = i; bool on = i == sel;- var c = new Border { CornerRadius = NotaRadius.Clip, Padding = new Thickness(6, 1), Cursor = new Cursor(StandardCursorType.Hand), Background = on ? IrAmber : Brushes.Transparent,- Child = new TextBlock { Text = names[i], FontSize = 8, FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal, Foreground = on ? NotaPalette.TextOnAccent : IrMuted } };- c.PointerPressed += (_, _) => onSel(iv);- row.Children.Add(c);- }- return new Border { Background = IrInset, BorderBrush = IrBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = row };- }-private Border IrMsBtn(string t, bool on, SolidColorBrush fill, Action onClick){var b = new Border { MinWidth = 13, Height = 12, CornerRadius = NotaRadius.Clip, BorderThickness = new Thickness(1), BorderBrush = on ? fill : NotaPalette.BorderStrong, Background = on ? fill : IrCard, Cursor = new Cursor(StandardCursorType.Hand),@@ -643,568 +427,14 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)return b;}- private Border IrRailBtn(string t, Action onClick)- {- var b = new Border { BorderThickness = new Thickness(1), BorderBrush = NotaPalette.BorderStrong, Background = IrCard, CornerRadius = NotaRadius.Badge, Padding = new Thickness(0, 2), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = t, FontSize = 9, Foreground = NotaPalette.TextSecondary, HorizontalAlignment = HorizontalAlignment.Center } };- b.PointerPressed += (_, _) => onClick();- return b;- }-// ---- second view: Macro map (mockup 2p card 2) ----- private static int _mapMacro;- // Both racks show this view inside the shared device shell; a custom onDone lets the- // Audio Effect Rack leave it its own way.- private Control InstrumentRackMacroMap(IRackAccess a, Action? onDone = null)- {- // MAPPING strip.- var done = new Border { BorderBrush = IrTeal, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(10, 2), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = "Done", FontSize = 9, Foreground = IrTeal, HorizontalAlignment = HorizontalAlignment.Center, TextAlignment = TextAlignment.Center }, [DockPanel.DockProperty] = Dock.Right };- done.PointerPressed += (_, _) => { if (onDone != null) onDone(); else { _macroMapMode = false; _ctx.RequestRebuild(); } };- var strip = new Border { Height = 34, Background = IrHdr, BorderBrush = IrBorder, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child =- new DockPanel { LastChildFill = false, Children = { done, new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = {- IrCap("MAPPING", IrTeal), new TextBlock { Text = a.MacroName(_mapMacro), FontSize = 9, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = "→ click any control to add · drag its range below", FontSize = 8, Foreground = IrMuted, VerticalAlignment = VerticalAlignment.Center } } } } } };-- // Macros list (left).- var macList = new StackPanel { Spacing = 3 };- macList.Children.Add(IrCap("MACROS"));- for (int i = 0; i < 8; i++)- {- int iv = i; int tCount = 0;- for (int m = 0; m < a.MappingCount(); m++) if (a.TryGetMapping(m, out var mm) && mm.Macro == i) tCount++;- bool cur = i == _mapMacro;- var nm = new TextBlock { Text = a.MacroName(i), FontSize = 9, Foreground = cur ? IrAmberLit : (tCount > 0 ? IrTxt : IrMuted), Width = 60, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };- var fill = new Border { Height = 3, Background = NotaPalette.VizInk, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var slot = new Panel { Height = 6, Children = { new Border { Height = 3, Background = IrInset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center }, fill } };- _irTick.Add(() => fill.Width = E.PluginParamGet(T, a.AutomationDeviceIndex, iv) * slot.Bounds.Width);- var cnt = IrMono(tCount.ToString(), cur ? IrTeal : IrMuted);- var rowg = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 5, Cursor = new Cursor(StandardCursorType.Hand), Children = { nm, WithCol(slot, 1), WithCol(cnt, 2) } };- rowg.PointerPressed += (_, _) => { _mapMacro = iv; _ctx.RequestRebuild(); };- macList.Children.Add(rowg);- }- var macCol = new Border { Width = 186, Background = IrRail, BorderBrush = IrBorder, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(8, 6), Child = macList };-- // Targets (right).- var targetStack = new StackPanel { Spacing = 4 };- int nTargets = 0;- for (int m = 0; m < a.MappingCount(); m++) if (a.TryGetMapping(m, out var mm) && mm.Macro == _mapMacro) nTargets++;- targetStack.Children.Add(new DockPanel { LastChildFill = false, Children = { IrCap($"{a.MacroName(_mapMacro)} → {nTargets} target{(nTargets == 1 ? "" : "s")}"), WithRight(new TextBlock { Text = "min — max", FontSize = 8, Foreground = IrMuted, VerticalAlignment = VerticalAlignment.Center }) } });- for (int m = 0; m < a.MappingCount(); m++)- {- if (!a.TryGetMapping(m, out var mm) || mm.Macro != _mapMacro) continue;- targetStack.Children.Add(IrMappingRow(a, m, mm));- }- targetStack.Children.Add(new Border { BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(0, 4),- Child = new TextBlock { Text = "click a control in any device to map it here", FontSize = 9, Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center } });-- var curveSeg = IrSeg(new[] { "Linear", "Exp", "Log", "S" }, CommonCurve(a, _mapMacro), i => { for (int m = 0; m < a.MappingCount(); m++) if (a.TryGetMapping(m, out var mm) && mm.Macro == _mapMacro) a.SetMappingCurve(m, i); _ctx.RequestRebuild(); });- var unmap = new Border { BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), [DockPanel.DockProperty] = Dock.Right,- Child = new TextBlock { Text = "Unmap all", FontSize = 9, Foreground = IrRed } };- unmap.PointerPressed += (_, _) => { for (int m = a.MappingCount() - 1; m >= 0; m--) if (a.TryGetMapping(m, out var mm) && mm.Macro == _mapMacro) a.RemoveMapping(m); _ctx.RequestRebuild(); };- var bottom = new DockPanel { LastChildFill = false, [DockPanel.DockProperty] = Dock.Bottom, Children = { unmap, new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { IrCap("CURVE"), curveSeg } } } };- var tScroll = new ScrollViewer { Content = targetStack, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };- var tInner = new DockPanel { LastChildFill = true, Children = { bottom, tScroll } };- var targets = new Border { Padding = new Thickness(9, 6), Child = tInner };-- DockPanel.SetDock(macCol, Dock.Left);- var body = new DockPanel { LastChildFill = true, Children = { macCol, targets } };- DockPanel.SetDock(strip, Dock.Top);- var root = new DockPanel { LastChildFill = true };- root.Children.Add(strip); root.Children.Add(body);- return root;- }-- private int CommonCurve(IRackAccess a, int macro)- {- for (int m = 0; m < a.MappingCount(); m++) if (a.TryGetMapping(m, out var mm) && mm.Macro == macro) return a.MappingCurve(m);- return 0;- }-- private Control IrMappingRow(IRackAccess a, int mappingIndex, RackMacroMapping mm)- {- bool pad = mm.DeviceIndex == RackMacroMapping.PadControls && mm.ParamIndex is >= 0 and < 4;- string dev = pad ? $"Chain {mm.Chain + 1}" : mm.DeviceIndex < 0 ? a.ChainInstrumentName(mm.Chain) : a.ChainDeviceName(mm.Chain, mm.DeviceIndex);- string pn = pad ? RackMacroMapping.PadParamNames[mm.ParamIndex] : mm.DeviceIndex < 0 ? a.ChainInstrumentParamName(mm.Chain, mm.ParamIndex) : a.ChainDeviceParamName(mm.Chain, mm.DeviceIndex, mm.ParamIndex);- float pMin = 0, pMax = 1;- if (pad) { pMin = RackMacroMapping.PadParamMin[mm.ParamIndex]; pMax = RackMacroMapping.PadParamMax[mm.ParamIndex]; }- else if (mm.DeviceIndex >= 0) { pMin = a.ChainDeviceParamMin(mm.Chain, mm.DeviceIndex, mm.ParamIndex); pMax = a.ChainDeviceParamMax(mm.Chain, mm.DeviceIndex, mm.ParamIndex); }- double span = Math.Max(1e-6, pMax - pMin);- double fLo = Math.Clamp((mm.RangeMin - pMin) / span, 0, 1), fHi = Math.Clamp((mm.RangeMax - pMin) / span, 0, 1);- var name = new TextBlock { Text = $"{dev} · {pn}", FontSize = 9, Foreground = IrTxt, Width = 122, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };- var band = new Border { Height = 6, Background = NotaPalette.Wash(NotaPalette.Teal, 0x73), CornerRadius = NotaRadius.Badge, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var track = new Panel { Height = 6, MinWidth = 60, Children = { new Border { Height = 6, Background = NotaPalette.BgSunken, CornerRadius = NotaRadius.Badge, VerticalAlignment = VerticalAlignment.Center }, band } };- var vals = IrMono($"{mm.RangeMin * 100:0}\u2009%–{mm.RangeMax * 100:0}\u2009%", NotaPalette.TextSecondary);- void Upd() { double w = track.Bounds.Width; band.Margin = new Thickness(fLo * w, 0, 0, 0); band.Width = Math.Max(2, (fHi - fLo) * w); }- int drag = 0; // 1 = min, 2 = max- void Apply(double x) { double f = Math.Clamp(x / Math.Max(1, track.Bounds.Width), 0, 1); if (drag == 1) fLo = Math.Min(f, fHi); else fHi = Math.Max(f, fLo); Upd(); }- track.PointerPressed += (_, e) => { double x = e.GetPosition(track).X, w = track.Bounds.Width; drag = Math.Abs(x - fLo * w) <= Math.Abs(x - fHi * w) ? 1 : 2; e.Pointer.Capture(track); Apply(x); };- track.PointerMoved += (_, e) => { if (drag != 0) Apply(e.GetPosition(track).X); };- void EndDrag() { drag = 0; a.SetMappingRange(mappingIndex, (float)(pMin + fLo * span), (float)(pMin + fHi * span)); _ctx.RequestRebuild(); }- track.PointerReleased += (_, e) => { if (drag != 0) { EndDrag(); e.Pointer.Capture(null); } };- track.PointerCaptureLost += (_, _) => { if (drag != 0) EndDrag(); };- _irTick.Add(Upd);- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Children = { name, WithCol(track, 1), WithCol(vals, 2) } };- return new Border { Background = IrInset, BorderBrush = IrField, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 4), Child = g };- }-// Audio Effect Rack body (a device, kind 5): wrapped by the view's DeviceShell.// Audio Effect Rack (mockup 2r): the shared device shell provides the header; this// body is the macro strip + (chains | devices | rack rail), with a MODE switch// (Parallel / Series / Select). Series swaps the body for stacked chain columns.- public Control BuildEffectRackBody(int di)- {- var a = new EffectRackAccess(E, T, di);- _irTick.Clear();- int chains = a.ChainCount();- Sel = chains > 0 ? Math.Clamp(Sel, 0, chains - 1) : 0;-- Control root;- if (_aeMacroMap)- {- root = InstrumentRackMacroMap(a, () => { _aeMacroMap = false; DeferRebuild(); });- }- else- {- int mode = E.RackDevMode(T, di);- var strip = IrMacroStrip(a);- Control body = mode == 1 ? AeSeriesBody(a, di) : AeParallelBody(a, di);- DockPanel.SetDock(strip, Dock.Top);- root = new DockPanel { LastChildFill = true, Children = { strip, body } };- }- if (_irTick.Count > 0) _ctx.AddDeviceRefresher(() => { for (int i = 0; i < _irTick.Count; i++) _irTick[i](); });- return new Border { Height = DeviceCardKit.CardH - DeviceCardKit.HeaderH, ClipToBounds = true, Child = root }; // fills the full-bleed shell slot (700)- }-- // Parallel (mode 0) / Select (mode 2): chain list | devices | rack rail.- private Control AeParallelBody(IRackAccess a, int di)- {- var list = AeChainList(a, di);- var rail = AeRackRail(a, di);- var devs = AeDeviceArea(a, di);- DockPanel.SetDock(list, Dock.Left); DockPanel.SetDock(rail, Dock.Right);- return new DockPanel { LastChildFill = true, Children = { list, rail, devs } };- }-- // ---- chain list (196) ----- private Control AeChainList(IRackAccess a, int di)- {- int mode = E.RackDevMode(T, di);- int chains = a.ChainCount();- string sub = mode == 2 ? $"{AeActiveCount(a, di)} active" : (mode == 1 ? "series" : "parallel · summed");- var header = new DockPanel { LastChildFill = false, Margin = new Thickness(0, 0, 0, 5), Children = {- IrCap("CHAINS"), WithRight(new TextBlock { Text = sub, FontSize = 8, Foreground = IrMuted, VerticalAlignment = VerticalAlignment.Center }) } };- var rows = new StackPanel { Spacing = 4 };- for (int c = 0; c < chains; c++) rows.Children.Add(AeChainRow(a, di, c));- var add = new Border { BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(0, 3), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = "+ Add chain", FontSize = 9, Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center } };- add.PointerPressed += (_, _) => { int c = a.AddChain(-1); if (c >= 0) Sel = c; _ctx.RequestRebuild(); };- rows.Children.Add(add);- var scroll = new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, Padding = new Thickness(0, 0, 6, 0) };- DockPanel.SetDock(header, Dock.Top);- var inner = new DockPanel { LastChildFill = true, Children = { header, scroll } };- return new Border { Width = 196, Background = IrRail, BorderBrush = IrBorder, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(8, 6), Child = inner };- }-- private Control AeChainRow(IRackAccess a, int di, int c)- {- bool sel = c == Sel;- string name = a.ChainInstrumentName(c); if (string.IsNullOrEmpty(name)) name = $"Chain {c + 1}";- int devs = a.ChainDeviceCount(c);- var nameTb = new TextBlock { Text = name, FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = sel ? IrAmberLit : IrTxt, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };- var head = new DockPanel { LastChildFill = true, Children = { WithRight(ChainDelBtn(a, c)), WithRight(IrMono($"{devs} dev", IrMuted)), nameTb } };- double db = a.ChainGain(c) <= 0.001 ? -60 : 20 * Math.Log10(a.ChainGain(c));- var dbT = IrMono(db <= -59 ? "−∞" : $"{db:+0.0;−0.0;0.0}", NotaPalette.TextSecondary);- var meterFill = new Border { Background = Success, HorizontalAlignment = HorizontalAlignment.Left, CornerRadius = NotaRadius.Bar };- var meter = new Border { Height = 3, Background = IrInset, CornerRadius = NotaRadius.Bar, Child = meterFill, VerticalAlignment = VerticalAlignment.Center };- _irTick.Add(() => meterFill.Width = meter.Bounds.Width * Math.Clamp(a.ChainMeter(c), 0, 1));- var m = IrMsBtn("M", a.ChainMute(c), NotaPalette.Mute, () => { a.SetChainMute(c, !a.ChainMute(c)); _ctx.RequestRebuild(); });- var s = IrMsBtn("S", a.ChainSolo(c), NotaPalette.Solo, () => { a.SetChainSolo(c, !a.ChainSolo(c)); _ctx.RequestRebuild(); });- MidiLearn.Bind(m, MidiTarget.RackChainMute(T, a.AutomationDeviceIndex, c), "Chain Mute");- MidiLearn.Bind(s, MidiTarget.RackChainSolo(T, a.AutomationDeviceIndex, c), "Chain Solo");- var meterGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 4, VerticalAlignment = VerticalAlignment.Center };- meterGrid.Children.Add(dbT); Grid.SetColumn(meter, 1); meterGrid.Children.Add(meter);- Grid.SetColumn(m, 2); meterGrid.Children.Add(m); Grid.SetColumn(s, 3); meterGrid.Children.Add(s);- var stack = new StackPanel { Spacing = 3, Children = { head, meterGrid } };- // Built exactly like the Instrument Rack row (Border + PointerPressed), so it sizes to- // its content. Clicking is reliable now that the full-bleed body removed the earlier- // fixed-width overflow that skewed hit-testing inside the device shell.- var row = new Border { Background = sel ? RowSel : IrCard, BorderBrush = sel ? IrAmber : IrBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(6, 4), Cursor = new Cursor(StandardCursorType.Hand), Child = stack };- // left accent = chain hue, hidden while selected (the amber selection is enough).- var accent = new Border { Width = 2, Background = sel ? Brushes.Transparent : ChainHue(c), CornerRadius = new CornerRadius(NotaRadius.ClipValue, 0, 0, NotaRadius.ClipValue) };- var wrap = new DockPanel { LastChildFill = true, Children = { accent, row } };- DockPanel.SetDock(accent, Dock.Left);- wrap.PointerPressed += (_, e) => { if (e.GetCurrentPoint(wrap).Properties.IsLeftButtonPressed && Sel != c) { Sel = c; _ctx.RequestRebuild(); } };- DragDrop.SetAllowDrop(wrap, true);- DragDrop.AddDragOverHandler(wrap, (_, e) => { if (!BrowserView.IsBrowserDrag || !IsEffect(BrowserView.CurrentDrag)) { e.DragEffects = DragDropEffects.None; return; } e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow(); row.BorderBrush = AccentBright; });- DragDrop.AddDragLeaveHandler(wrap, (_, _) => row.BorderBrush = sel ? IrAmber : IrBorder);- DragDrop.AddDropHandler(wrap, (_, e) => { row.BorderBrush = sel ? IrAmber : IrBorder; if (BrowserView.CurrentDrag is { } it && IsEffect(it)) { Sel = c; DropEffectOnChain(a, c, it); e.Handled = true; } });- return wrap;- }-- // A small borderless ✕ that removes a rack chain (shared by both rack kinds).- private Control ChainDelBtn(IRackAccess a, int c)- {- var glyph = new Glyph(GlyphKind.Close, 9) { Foreground = IrMuted };- var b = new Border { Width = 14, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Stretch, Child = glyph };- ToolTip.SetTip(b, "Remove chain");- b.PointerEntered += (_, _) => glyph.Foreground = IrRed;- b.PointerExited += (_, _) => glyph.Foreground = IrMuted;- b.PointerPressed += (_, e) => { e.Handled = true; int n = a.ChainCount(); a.RemoveChain(c); if (Sel > c) Sel--; Sel = Math.Clamp(Sel, 0, Math.Max(0, n - 2)); DeferRebuild(); };- return b;- }-- // ---- device area (center): horizontal device cards + (Select) level selector ----- private Control AeDeviceArea(IRackAccess a, int di)- {- if (a.ChainCount() == 0)- return new Border { Padding = new Thickness(9, 7), Child = new TextBlock { Text = "Add a chain to build its device chain.", FontSize = 9, Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center } };- int sc = Sel, mode = E.RackDevMode(T, di);- double pdcMs = E.RackDevPdc(T, di) ? 0 : 0; // (informational; latency in samples is host-side)- var hdr = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 6), Children = {- new Border { Width = 7, Height = 7, CornerRadius = NotaRadius.Clip, Background = ChainHue(sc), VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = $"Chain {sc + 1}", FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = IrTxt, VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = "devices · signal left → right", FontSize = 8, Foreground = IrMuted, VerticalAlignment = VerticalAlignment.Center } } };-- var slots = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5 };- int dc = a.ChainDeviceCount(sc);- if (_aeFold)- for (int d = 0; d < dc; d++) slots.Children.Add(AeFoldedSlot(a, sc, d));- else- for (int d = 0; d < dc; d++) slots.Children.Add(IrDeviceSlot(a, sc, d));- slots.Children.Add(IrAddDeviceSlot(a, sc));- var row = new ScrollViewer { Content = slots, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled };-- var inner = new DockPanel { LastChildFill = true };- DockPanel.SetDock(hdr, Dock.Top); inner.Children.Add(hdr);- if (mode == 2) { var selMap = AeSelectorMap(a, di); DockPanel.SetDock(selMap, Dock.Bottom); inner.Children.Add(selMap); }- inner.Children.Add(row);- return new Border { Padding = new Thickness(8, 6), Child = inner };- }-- // Folded device: a compact name chip (no GUI/params body).- private Control AeFoldedSlot(IRackAccess a, int sc, int d)- {- bool byp = a.ChainDeviceBypassed(sc, d);- var chip = new Border { Height = 22, Background = IrCard, BorderBrush = IrBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(7, 0), VerticalAlignment = VerticalAlignment.Top,- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {- new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Badge, Background = byp ? IrMuted : Success, VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = a.ChainDeviceName(sc, d), FontSize = 9, Foreground = IrTxt, VerticalAlignment = VerticalAlignment.Center },- SlotDelBtn(() => { a.RemoveChainDevice(sc, d); DeferRebuild(); }) } } };- if (byp) chip.AttachedToVisualTree += (_, _) => Inactive.Set(chip, true, interactive: true); // no opacity for state- Border b = chip; b.PointerPressed += (_, e) => { e.Handled = true; OpenChainDeviceGui(a, sc, d, b); };- return chip;- }-- // ---- chain selector on an input-level axis (Select mode) ----- private int AeActiveCount(IRackAccess a, int di)- {- float sel = E.RackDevLiveSelector(T, di);- int n = 0, chains = a.ChainCount();- for (int c = 0; c < chains; c++)- {- E.RackDevChainZone(T, di, c, out int lo, out int hi);- if (sel >= lo / 127.0f && sel <= hi / 127.0f && !a.ChainMute(c)) n++;- }- return n;- }-- private Control AeSelectorMap(IRackAccess a, int di)- {- int n = a.ChainCount();- var los = new int[n]; var his = new int[n]; var cols = new IBrush[n];- for (int c = 0; c < n; c++) { E.RackDevChainZone(T, di, c, out int lo, out int hi); los[c] = lo; his[c] = hi; cols[c] = ChainHue(c); }- var map = new RackZoneMap(los, his, cols, Sel, keyMode: false);- map.RangeEdited += (c, lo, hi) => { E.RackDevSetChainZone(T, di, c, lo, hi); DeferRebuild(); };- bool follow = E.RackDevSelFollow(T, di);- var marker = new Border { Width = 1.5, Background = IrAmberLit, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch };- var mapHost = new Panel { Children = { map, marker } };- _irTick.Add(() => marker.Margin = new Thickness(E.RackDevLiveSelector(T, di) * mapHost.Bounds.Width, 0, 0, 0));- // When not following the input, click/drag on the axis sets the manual selector.- if (!follow)- mapHost.PointerPressed += (_, e) => { if (e.GetCurrentPoint(mapHost).Properties.IsRightButtonPressed) { double x = e.GetPosition(mapHost).X; E.RackDevSetChainSelect(T, di, (float)Math.Clamp(x / Math.Max(1, mapHost.Bounds.Width), 0, 1)); } };-- var readout = IrMono("", NotaPalette.TextSecondary);- _irTick.Add(() => readout.Text = $"in {(int)Math.Round(E.RackDevLiveSelector(T, di) * 48 - 48)}\u2009dB → {AeActiveCount(a, di)} chain{(AeActiveCount(a, di) == 1 ? "" : "s")}");- var head = new DockPanel { LastChildFill = false, Children = { IrCap("CHAIN SELECTOR"),- WithRight(DrumChip(follow ? "Follow" : "Manual", follow, () => { E.RackDevSetSelFollow(T, di, !follow); DeferRebuild(); })),- WithRight(readout) } };- DockPanel.SetDock(head, Dock.Top);- var body = new DockPanel { LastChildFill = true, Children = { head, mapHost } };- return new Border { Height = 52, Background = IrInset, BorderBrush = IrField, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(6, 4), Margin = new Thickness(0, 5, 0, 0), Child = body };- }-- // ---- rack rail (96): MODE · dry/wet · gain · macro-map · pdc · fold/save ----- private Control AeRackRail(IRackAccess a, int di)- {- int mode = E.RackDevMode(T, di);- var modeSeg = AeModeSeg(mode, di);-- var dwVal = IrMono("", IrTxt, 9); dwVal.HorizontalAlignment = HorizontalAlignment.Center;- var dw = new Knob(Math.Clamp(E.RackDevDryWet(T, di), 0, 1), 1.0) { Accent = true, Width = 38, Height = 38, HorizontalAlignment = HorizontalAlignment.Center };- dw.ValueChanged += v => { E.RackDevSetDryWet(T, di, (float)v); dwVal.Text = $"{v * 100:0}\u2009%"; };- dw.Format = v => $"{v * 100:0}\u2009%";- ValueEntry.Attach(dw, "Dry / wet", dwVal);- dwVal.Text = $"{E.RackDevDryWet(T, di) * 100:0}\u2009%";- var dwCell = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, Children = { IrCap("DRY / WET"), dw, dwVal } };-- string GainDb(double lin) => lin <= 0.001 ? "−∞" : $"{20 * Math.Log10(lin):+0.0;−0.0;0.0}";- var gainVal = IrMono(GainDb(E.RackDevVolume(T, di)), IrTxt, 8); gainVal.VerticalAlignment = VerticalAlignment.Center;- var gFill = new Border { Height = 3, Background = NotaPalette.VizInk, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var gSlot = new Panel { Height = 8, MinWidth = 26, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent, Children = { new Border { Height = 3, Background = IrInset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center }, gFill } };- void GUpd() { double v = Math.Clamp(E.RackDevVolume(T, di) / 2.0, 0, 1); gFill.Width = v * gSlot.Bounds.Width; gainVal.Text = GainDb(E.RackDevVolume(T, di)); }- bool gd = false; void GSet(double x) { double v = Math.Clamp(x / Math.Max(1, gSlot.Bounds.Width), 0, 1); E.RackDevSetVolume(T, di, (float)(v * 2.0)); GUpd(); }- gSlot.PointerPressed += (_, e) => { gd = true; e.Pointer.Capture(gSlot); GSet(e.GetPosition(gSlot).X); };- gSlot.PointerMoved += (_, e) => { if (gd) GSet(e.GetPosition(gSlot).X); };- gSlot.PointerReleased += (_, e) => { if (gd) { gd = false; e.Pointer.Capture(null); } };- gSlot.PointerCaptureLost += (_, _) => gd = false;- _irTick.Add(() => { if (!gd) GUpd(); });- MidiLearn.Bind(gSlot, MidiTarget.RackVolume(T, di), "Rack Volume");- var gainRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { IrCap("GAIN"), WithCol(gSlot, 1), WithCol(gainVal, 2) } };-- var macroMap = new Border { BorderBrush = IrTeal, BorderThickness = new Thickness(1), Background = NotaPalette.Wash(NotaPalette.Teal, 0x24), CornerRadius = NotaRadius.Control, Padding = new Thickness(0, 3), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = "Macro map", FontSize = 8, FontWeight = FontWeight.Medium, Foreground = IrTeal, HorizontalAlignment = HorizontalAlignment.Center, TextAlignment = TextAlignment.Center } };- macroMap.PointerPressed += (_, _) => { _aeMacroMap = true; DeferRebuild(); };- var pdc = AeRailToggle("PDC", E.RackDevPdc(T, di), () => { E.RackDevSetPdc(T, di, !E.RackDevPdc(T, di)); DeferRebuild(); });-- var fold = IrRailBtn(_aeFold ? "Unfold" : "Fold", () => { _aeFold = !_aeFold; DeferRebuild(); });- var save = IrRailBtn("Save", () => { try { _ctx.RequestPresetSave(di); } catch { /* no-op */ } });- var foldSave = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4, [DockPanel.DockProperty] = Dock.Bottom, Children = { fold, WithCol(save, 1) } };-- var top = new StackPanel { Spacing = 6, [DockPanel.DockProperty] = Dock.Top, Children = {- new StackPanel { Spacing = 3, Children = { IrCap("MODE"), modeSeg } },- IrCap("RACK OUT"), dwCell, gainRow,- new Border { Height = 1, Background = IrCard },- macroMap, pdc } };- var inner = new DockPanel { LastChildFill = false, Children = { top, foldSave } };- return new Border { Width = 96, Background = IrRail, BorderBrush = IrBorder, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child = inner };- }-- // Full-width 3-way MODE segment (fits the 96px rail).- private Control AeModeSeg(int mode, int di)- {- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 1 };- string[] names = { "Prl", "Ser", "Sel" };- for (int i = 0; i < 3; i++)- {- int iv = i; bool on = i == mode;- var cell = new Border { Background = on ? IrAmber : Brushes.Transparent, CornerRadius = NotaRadius.Clip, Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = names[i], FontSize = 8, FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal, Foreground = on ? NotaPalette.TextOnAccent : IrMuted, HorizontalAlignment = HorizontalAlignment.Center, TextAlignment = TextAlignment.Center, Padding = new Thickness(0, 1) } };- cell.PointerPressed += (_, _) => { E.RackDevSetMode(T, di, iv); DeferRebuild(); };- Grid.SetColumn(cell, i); g.Children.Add(cell);- }- return new Border { Background = IrInset, BorderBrush = IrBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(1), Child = g };- }-- // A pill toggle (PDC): label on the left, switch on the right, fits the rail width.- private Control AeRailToggle(string text, bool on, Action onClick)- {- // The label names the setting; the switch carries the state (colour and position).- return DeviceCardKit.Switch(text, () => on, onClick, out _);- }-- // ---- Series mode: chains as stacked columns you build top → bottom ----- private Control AeSeriesBody(IRackAccess a, int di)- {- var rail = AeRackRail(a, di);- var cols = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5 };- int chains = a.ChainCount();- for (int c = 0; c < chains; c++) cols.Children.Add(AeSeriesColumn(a, di, c));- var addCol = new Border { Width = 40, BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Cursor = new Cursor(StandardCursorType.Hand),- Child = new Glyph(GlyphKind.Plus, 10) { Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center } };- addCol.PointerPressed += (_, _) => { int nc = a.AddChain(-1); if (nc >= 0) Sel = nc; DeferRebuild(); };- cols.Children.Add(addCol);- var scroll = new ScrollViewer { Content = cols, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled, Padding = new Thickness(8, 7) };- DockPanel.SetDock(rail, Dock.Right);- return new DockPanel { LastChildFill = true, Children = { rail, scroll } };- }-- private Control AeSeriesColumn(IRackAccess a, int di, int c)- {- double db = a.ChainGain(c) <= 0.001 ? -60 : 20 * Math.Log10(a.ChainGain(c));- var head = new DockPanel { LastChildFill = true, Children = {- WithRight(IrMono(db <= -59 ? "−∞" : $"{db:+0.0;−0.0;0.0}", NotaPalette.TextSecondary)),- new TextBlock { Text = $"Chain {c + 1}", FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = IrTxt, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis } } };- var stack = new StackPanel { Spacing = 4, Children = { head } };- int dc = a.ChainDeviceCount(c);- for (int d = 0; d < dc; d++) stack.Children.Add(AeSeriesDeviceRow(a, c, d));- var addDev = new Border { BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(0, 2), Cursor = new Cursor(StandardCursorType.Hand), [DockPanel.DockProperty] = Dock.Bottom,- Child = new TextBlock { Text = "+ device", FontSize = 8, Foreground = IrMuted, HorizontalAlignment = HorizontalAlignment.Center } };- addDev.PointerPressed += (_, _) => ShowAddDeviceMenu(a, c, addDev);- DockPanel.SetDock(addDev, Dock.Bottom);- var inner = new DockPanel { LastChildFill = false, Children = { addDev, stack } };- return new Border { Width = 150, Background = IrRail, BorderBrush = ChainHue(c), BorderThickness = new Thickness(0, 2, 0, 0), CornerRadius = NotaRadius.Panel, Padding = new Thickness(6, 5), Child = inner };- }-- private Control AeSeriesDeviceRow(IRackAccess a, int c, int d)- {- bool byp = a.ChainDeviceBypassed(c, d);- int mc = MacrosOnTarget(a, c, d);- var rowInner = new DockPanel { LastChildFill = true, Children = {- WithRight(SlotDelBtn(() => { a.RemoveChainDevice(c, d); DeferRebuild(); })),- WithRight(new Glyph(GlyphKind.Grip, 8) { Foreground = IrMuted }),- WithRight(mc > 0 ? new TextBlock { Text = $"{mc}M", FontSize = 7, FontWeight = FontWeight.Medium, Foreground = IrTeal, VerticalAlignment = VerticalAlignment.Center } : (Control)new Border()),- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {- new Border { Width = 5, Height = 5, CornerRadius = NotaRadius.Badge, Background = byp ? IrMuted : Success, VerticalAlignment = VerticalAlignment.Center },- new TextBlock { Text = a.ChainDeviceName(c, d), FontSize = 9, Foreground = IrTxt, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis } } } } };- var row = new Border { Height = 24, Background = IrCard, BorderBrush = IrBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = rowInner };- if (byp) row.AttachedToVisualTree += (_, _) => Inactive.Set(row, true, interactive: true); // no opacity for state- Border b = row; b.PointerPressed += (_, e) => { e.Handled = true; OpenChainDeviceGui(a, c, d, b); };- return row;- }-- // ---- rack body (macros + chains), reused by both rack types ------------- // The 4×2 macro grid column, shared by the rack card and the drum-rack card.- private Control MacroColumn(IRackAccess a)- {- var macroGrid = new StackPanel { Spacing = 7 };- for (int r = 0; r < 4; r++)- {- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };- row.Children.Add(MacroCell(a, r * 2));- row.Children.Add(MacroCell(a, r * 2 + 1));- macroGrid.Children.Add(row);- }- return new StackPanel { Width = 210, Spacing = 8, Children = { SectionLabel("MACROS"), macroGrid } };- }-- // Rack layout: macros | chain list | the selected chain's device chain.- private Control RackBody(IRackAccess a)- {- int chains = a.ChainCount();- Sel = chains > 0 ? Math.Clamp(Sel, 0, chains - 1) : 0;-- var body = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 14 };- var macros = MacroColumn(a);- var list = ChainListColumn(a);- var devices = DeviceArea(a, Sel);- body.Children.Add(macros);- Grid.SetColumn(list, 1); body.Children.Add(list);- Grid.SetColumn(devices, 2); body.Children.Add(devices);- return body;- }-- // ---- chain list (left): selectable rows with gain/pan/M/S -------------- private Control ChainListColumn(IRackAccess a)- {- var listPanel = new StackPanel { Spacing = 5 };- int chains = a.ChainCount();- for (int c = 0; c < chains; c++) listPanel.Children.Add(ChainRow(a, c));- listPanel.Children.Add(AddChainButton(a));-- var col = new Grid { Width = 182, RowDefinitions = new RowDefinitions("Auto,*") };- col.Children.Add(SectionLabel("CHAINS"));- var scroll = new ScrollViewer- {- Content = listPanel, VerticalScrollBarVisibility = ScrollBarVisibility.Auto,- HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,- Padding = new Thickness(0, 0, 11, 0), // reserve room so the thin scrollbar never floats over the ✕ buttons- };- Grid.SetRow(scroll, 1); col.Children.Add(scroll);- return col;- }-- private Control ChainRow(IRackAccess a, int c)- {- bool sel = c == Sel;- string name = a.HasInstrumentChains ? a.ChainInstrumentName(c) : $"Chain {c + 1}";- if (string.IsNullOrEmpty(name)) name = $"Chain {c + 1}";-- var nameTb = new TextBlock { Text = name, FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = sel ? AccentBright : TextPrimary, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };- var rm = Glyph(GlyphKind.Close, true, () => { a.RemoveChain(c); if (Sel > 0) Sel--; _ctx.RequestRebuild(); });- ToolTip.SetTip(rm, "Remove chain");- var head = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };- head.Children.Add(nameTb);- Grid.SetColumn(rm, 1); head.Children.Add(rm);-- var gain = new MiniFader(a.ChainGain(c), 2.0) { Accent = true, Width = 58, Default = 1.0 };- gain.ValueChanged += v => a.SetChainGain(c, (float)v);- var pan = new MiniFader(a.ChainPan(c) * 0.5 + 0.5, 1.0) { Width = 40, Default = 0.5 };- pan.ValueChanged += v => a.SetChainPan(c, (float)(v * 2.0 - 1.0));- ValueEntry.Attach(gain, gain.EntryField("Chain gain", v => NotaNum.GainDb(v)));- ValueEntry.Attach(pan, pan.EntryField("Chain pan", v => NotaNum.Pan(v * 2 - 1)));- var m = Toggle("M", a.ChainMute(c), NotaPalette.Mute, () => { a.SetChainMute(c, !a.ChainMute(c)); _ctx.RequestRebuild(); });- var s = Toggle("S", a.ChainSolo(c), NotaPalette.Solo, () => { a.SetChainSolo(c, !a.ChainSolo(c)); _ctx.RequestRebuild(); });- var ctrls = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { gain, pan, m, s } };-- var row = new Border- {- Background = sel ? RowSel : Card2, BorderBrush = sel ? Brass : BorderDef, BorderThickness = new Thickness(1),- CornerRadius = NotaRadius.Tile, Padding = new Thickness(6, 5), Cursor = new Cursor(StandardCursorType.Hand),- Child = new StackPanel { Spacing = 5, Children = { head, ctrls } },- };- // Click the row (not its controls, which consume the press) to select it.- row.PointerPressed += (_, e) =>- {- if (e.GetCurrentPoint(row).Properties.IsLeftButtonPressed && Sel != c) { Sel = c; _ctx.RequestRebuild(); }- };- // Drop an effect onto a chain to append it (and select the chain).- DragDrop.SetAllowDrop(row, true);- DragDrop.AddDragOverHandler(row, (_, e) =>- {- if (!BrowserView.IsBrowserDrag || !IsEffect(BrowserView.CurrentDrag)) { e.DragEffects = DragDropEffects.None; return; }- e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow();- row.BorderBrush = AccentBright; // drop target: colour only- });- DragDrop.AddDragLeaveHandler(row, (_, _) => { row.BorderBrush = sel ? Brass : BorderDef; });- DragDrop.AddDropHandler(row, (_, e) =>- {- row.BorderBrush = sel ? Brass : BorderDef; row.BorderThickness = new Thickness(1);- if (BrowserView.CurrentDrag is { } it && IsEffect(it)) { Sel = c; DropEffectOnChain(a, c, it); e.Handled = true; }- });- return row;- }+ public Control BuildEffectRackBody(int di) => RcBody(BuildRackCard(new EffectRackAccess(E, T, di), di));- // ---- device area (right): the selected chain's instrument + effects ----- private Control DeviceArea(IRackAccess a, int sc, string? title = null)- {- var col = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), MinWidth = 300 };- if (a.ChainCount() == 0)- {- col.Children.Add(SectionLabel(title ?? "DEVICES"));- var hint = new TextBlock { Text = "Add a chain to build its device chain.", FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };- Grid.SetRow(hint, 1); col.Children.Add(hint);- return col;- }- col.Children.Add(SectionLabel(title ?? $"CHAIN {sc + 1} DEVICES"));- var rowSp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };- if (a.HasInstrumentChains) rowSp.Children.Add(ChainInstrumentCard(a, sc));- int dc = a.ChainDeviceCount(sc);- for (int d = 0; d < dc; d++) rowSp.Children.Add(ChainDeviceCard(a, sc, d));- rowSp.Children.Add(ChainAddDeviceCard(a, sc));- var scroll = new ScrollViewer- {- Content = rowSp, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,- VerticalScrollBarVisibility = ScrollBarVisibility.Disabled,- };- Grid.SetRow(scroll, 1); col.Children.Add(scroll);- return col;- }-- private Control ChainInstrumentCard(IRackAccess a, int sc)- {- int ik = a.ChainInstrumentKind(sc);- string nm = a.ChainInstrumentName(sc);- if (string.IsNullOrEmpty(nm)) nm = "Instrument";-- // Compact knob card (like the effect cards). The full bespoke UI opens in a pop-out- // window via the header's "Full" button — the tabbed Nota Sampler editor for the- // built-in Sampler, the plug-in's native GUI for a hosted instrument, or a roomy- // knob grid for everything else.- var body = new StackPanel { Spacing = 8 };- if (ik == -1)- body.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { ActionChip("Save preset", () => _ctx.RequestRackPresetSave(sc)) } });- int pc = a.ChainInstrumentParamCount(sc);- if (pc == 0) body.Children.Add(new TextBlock { Text = "No parameters", FontSize = 9, Foreground = TextTertiary });- for (int p = 0; p < pc; p++)- if (a.ChainInstrumentParamName(sc, p) != "View") body.Children.Add(RackInstParamRow(a, sc, p)); // the card size isn't sound-- Control fullBtn;- if (ik == -1) fullBtn = ActionChip("Full", () => { try { E.RackOpenChainInstrumentEditor(T, sc); } catch { /* no-op */ } });- else if (ik == 1) { Border b = null!; b = ActionChip("Full", () => OpenChainSamplerWindow(a, b, sc, InstrumentPresets(a, sc, ik))); fullBtn = b; }- else fullBtn = FullUiChip(nm, a.ChainInstrumentParamCount(sc), p => RackInstParamRow(a, sc, p), () => ChainLocation(a, sc));- return DeviceCardShell(nm, fullBtn, body, 180);- }+ public Control BuildMidiRackBody(int mi) => RcBody(BuildRackCard(new MidiRackAccess(E, T, mi), mi));// A roomy, non-bespoke "full UI": every param as a knob in a 3-column grid (the name// is on the device window's title bar).@@ -1225,70 +455,6 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)win.ShowFrom(anchor);}- // A small header button that pops out a device's knobs in the device window.- private Border FullUiChip(string name, int count, Func<int, Control> row, Func<string> status, DeviceWindowBypass? bypass = null)- {- Border chip = null!;- chip = ActionChip("Full", () => OpenParamWindow(chip, name, count, row, status, bypass));- return chip;- }-- private Control ChainDeviceCard(IRackAccess a, int sc, int d)- {- bool byp = a.ChainDeviceBypassed(sc, d);- int dc = a.ChainDeviceCount(sc);- var ctrls = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center };- string dnm = a.ChainDeviceName(sc, d);- // Full UI: hosted-plugin effect → its native window; built-in effect → roomy knob grid.- ctrls.Children.Add(a.ChainDeviceBuiltinKind(sc, d) < 0- ? ActionChip("Full", () => a.OpenChainDeviceEditor(sc, d))- : FullUiChip(dnm, a.ChainDeviceParamCount(sc, d), p => RackDeviceParamRow(a, sc, d, p), () => DeviceStatus(a, sc, d), ChainDeviceBypass(a, sc, d)));- ctrls.Children.Add(Glyph(GlyphKind.StepLeft, d > 0, () => { a.MoveChainDevice(sc, d, d - 1); _ctx.RequestRebuild(); }));- ctrls.Children.Add(Glyph(GlyphKind.StepRight, d < dc - 1, () => { a.MoveChainDevice(sc, d, d + 1); _ctx.RequestRebuild(); }));- ctrls.Children.Add(Glyph(GlyphKind.Close, true, () => { a.RemoveChainDevice(sc, d); _ctx.RequestRebuild(); }));-- var body = new StackPanel { Spacing = 7 };- body.Children.Add(Toggle(byp ? "Bypassed" : "Active", !byp, NotaPalette.Success, () => { a.SetChainDeviceBypassed(sc, d, !byp); _ctx.RequestRebuild(); }));- int pc = a.ChainDeviceParamCount(sc, d);- for (int p = 0; p < pc; p++) body.Children.Add(RackDeviceParamRow(a, sc, d, p));- var card = DeviceCardShell(a.ChainDeviceName(sc, d), ctrls, body, 180);- if (byp) card.AttachedToVisualTree += (_, _) => Inactive.Set(body, true, interactive: true);- return card;- }-- // The end of a chain: a slim "+" key (spec 012). Its dashed outline shows only while an- // effect is dragged over it.- private Control ChainAddDeviceCard(IRackAccess a, int sc)- {- var dash = new Rectangle- {- Stroke = BorderStrong, StrokeThickness = 1, StrokeDashArray = new AvaloniaList<double>(4, 3),- RadiusX = NotaRadius.ControlValue, RadiusY = NotaRadius.ControlValue, IsVisible = false,- };- var host = new Grid- {- Width = 28, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),- Children = { dash, new Glyph(GlyphKind.Plus, 12) { Foreground = TextTertiary } },- };- ToolTip.SetTip(host, "Add device — click for the list, or drop an effect here");- host.PointerPressed += (_, _) => ShowAddDeviceMenu(a, sc, host);- // Also a drop target for effects (built-in / plug-in) → append to this chain.- DragDrop.SetAllowDrop(host, true);- DragDrop.AddDragOverHandler(host, (_, e) =>- {- if (!BrowserView.IsBrowserDrag || !IsEffect(BrowserView.CurrentDrag)) { e.DragEffects = DragDropEffects.None; return; }- e.DragEffects = DragDropEffects.Copy; e.Handled = true; _ctx.HideDropGlow();- dash.Stroke = AccentBright; dash.IsVisible = true;- });- DragDrop.AddDragLeaveHandler(host, (_, _) => dash.IsVisible = false);- DragDrop.AddDropHandler(host, (_, e) =>- {- dash.IsVisible = false;- if (BrowserView.CurrentDrag is { } it && IsEffect(it)) { DropEffectOnChain(a, sc, it); e.Handled = true; }- });- return host;- }-// A compact device-area card: 24px header (title + optional controls) over a// scrollable body.private Border DeviceCardShell(string title, Control? headerRight, Control body, double width)@@ -1396,7 +562,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx){int cc = c, pp = p;var pit = new MenuItem { Header = a.ChainInstrumentParamName(c, p) };- pit.Click += (_, _) => { a.AddMacroMapping(m, cc, -1, pp, 0f, 1f); _ctx.RequestRebuild(); };+ pit.Click += (_, _) => { RcAddMapping(m, cc, -1, pp, 0f, 1f); _ctx.RequestRebuild(); };instItem.Items.Add(pit);}if (ipc > 0) chainItem.Items.Add(instItem);@@ -1411,7 +577,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)int cc = c, dd = d, pp = p;float lo = a.ChainDeviceParamMin(c, d, p), hi = a.ChainDeviceParamMax(c, d, p);var pit = new MenuItem { Header = a.ChainDeviceParamName(c, d, p) };- pit.Click += (_, _) => { a.AddMacroMapping(m, cc, dd, pp, lo, hi); _ctx.RequestRebuild(); };+ pit.Click += (_, _) => { RcAddMapping(m, cc, dd, pp, lo, hi); _ctx.RequestRebuild(); };dItem.Items.Add(pit);}if (dpc > 0) chainItem.Items.Add(dItem);@@ -1419,6 +585,12 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)map.Items.Add(chainItem);}f.Items.Add(map);+ if (a.Kind != RackKind.Instrument)+ {+ var sel = new MenuItem { Header = "Map to the selector" };+ sel.Click += (_, _) => { RcAddMapping(m, 0, RackMacroMapping.RackControl, 0, 0f, 1f); _ctx.RequestRebuild(); };+ f.Items.Add(sel);+ }int mapped = 0, n = a.MappingCount();for (int i = 0; i < n; i++) if (a.TryGetMapping(i, out var mm) && mm.Macro == m) mapped++;@@ -1459,46 +631,6 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)_ctx.RequestRebuild();}- private Control AddChainButton(IRackAccess a)- {- var b = new Border- {- BorderBrush = BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,- Padding = new Thickness(8, 5), Cursor = new Cursor(StandardCursorType.Hand), HorizontalAlignment = HorizontalAlignment.Left,- Child = Glyph.Labeled("Add chain", GlyphKind.Plus, 9, 8),- };- b.PointerPressed += (_, _) =>- {- if (!a.HasInstrumentChains) { a.AddChain(-1); _ctx.RequestRebuild(); return; } // effect chain (no instrument)- var f = new MenuFlyout();- var p = new MenuItem { Header = "Nota Physical" };- p.Click += (_, _) => { a.AddChain(2); _ctx.RequestRebuild(); };- var w = new MenuItem { Header = "Nota Aurora" };- w.Click += (_, _) => { a.AddChain(5); _ctx.RequestRebuild(); };- var vo = new MenuItem { Header = "Nota Volt" };- vo.Click += (_, _) => { a.AddChain(6); _ctx.RequestRebuild(); };- var pe = new MenuItem { Header = "Nota Pendulum" };- pe.Click += (_, _) => { a.AddChain(8); _ctx.RequestRebuild(); };- var op = new MenuItem { Header = "Nota Operator" };- op.Click += (_, _) => { a.AddChain(9); _ctx.RequestRebuild(); };- var gr = new MenuItem { Header = "Nota Grain" };- gr.Click += (_, _) => { a.AddChain(10); _ctx.RequestRebuild(); };- var fl = new MenuItem { Header = "Nota Flux" };- fl.Click += (_, _) => { a.AddChain(11); _ctx.RequestRebuild(); };- var mo = new MenuItem { Header = "Nota Monolith" };- mo.Click += (_, _) => { a.AddChain(13); _ctx.RequestRebuild(); };- var pd = new MenuItem { Header = "Nota Pentad" };- pd.Click += (_, _) => { a.AddChain(14); _ctx.RequestRebuild(); };- var co = new MenuItem { Header = "Nota Consort" };- co.Click += (_, _) => { a.AddChain(15); _ctx.RequestRebuild(); };- var ke = new MenuItem { Header = "Nota Keys" };- ke.Click += (_, _) => { a.AddChain(16); _ctx.RequestRebuild(); };- f.Items.Add(vo); f.Items.Add(p); f.Items.Add(w); f.Items.Add(pe); f.Items.Add(op); f.Items.Add(gr); f.Items.Add(fl); f.Items.Add(mo); f.Items.Add(pd); f.Items.Add(co); f.Items.Add(ke);- f.ShowAt(b, showAtPointer: true);- };- return b;- }-private Control RackDeviceParamRow(IRackAccess a, int c, int d, int p){string name = a.ChainDeviceParamName(c, d, p);@@ -1600,28 +732,6 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)private static Control SectionLabel(string text) => new TextBlock{ Text = NotaText.Label(text), FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextTertiary };- // A teal on/off chip (the Effect Rack's Follow / Manual selector).- private static Border DrumChip(string text, bool on, Action onClick)- {- var b = new Border { BorderThickness = new Thickness(1), BorderBrush = on ? IrTeal : NotaPalette.BorderStrong, Background = on ? NotaPalette.Wash(NotaPalette.Teal, 0x24) : IrCard, CornerRadius = NotaRadius.Control, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,- Child = new TextBlock { Text = text, FontSize = 9, Foreground = on ? IrTeal : NotaPalette.TextSecondary } };- b.PointerPressed += (_, e) => { e.Handled = true; onClick(); };- return b;- }-- // A small clickable chip (GUI / Save preset on the chain instrument card).- private static Border ActionChip(string text, Action onClick)- {- var b = new Border- {- Background = Card2, BorderBrush = BorderStrong, BorderThickness = new Thickness(1),- CornerRadius = NotaRadius.Control, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = text, FontSize = 9, Foreground = TextSecondary },- };- b.PointerPressed += (_, e) => { e.Handled = true; onClick(); };- return b;- }-private static Border Toggle(string text, bool active, SolidColorBrush activeBrush, Action onClick){var b = new Border@@ -1635,103 +745,6 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)}}-// Instrument-Rack key/velocity zone map: each chain's range drawn as a coloured bar over-// a keyboard (or a 0..127 strip in velocity mode); drag a bar's ends to edit the range.-internal sealed class RackZoneMap : Control-{- private static readonly IBrush KeyWhite = NotaPalette.MiniKeyWhite;- private static readonly IBrush KeyBlack = NotaPalette.MiniKeyBlack;- private readonly int[] _lo, _hi;- private readonly IBrush[] _cols;- private readonly int _sel;- private readonly bool _keyMode;- private int _drag = -1, _edge; // _drag = chain index; _edge: 0 lo, 1 hi, 2 move-- public event Action<int, int, int>? RangeEdited; // (chain, lo, hi)-- public RackZoneMap(int[] lo, int[] hi, IBrush[] cols, int sel, bool keyMode)- { _lo = lo; _hi = hi; _cols = cols; _sel = sel; _keyMode = keyMode; MinHeight = 28; ClipToBounds = true; }-- private double BarsH => Math.Max(8, Bounds.Height - 12);- private double X(int v) => v / 127.0 * Bounds.Width;-- protected override void OnPointerPressed(PointerPressedEventArgs e)- {- double w = Bounds.Width, bh = BarsH; if (w <= 0 || _lo.Length == 0) return;- double x = e.GetPosition(this).X, y = e.GetPosition(this).Y;- double rowH = bh / _lo.Length;- int c = Math.Clamp((int)(y / rowH), 0, _lo.Length - 1);- if (y > bh) return; // keyboard strip- double lx = X(_lo[c]), hx = X(_hi[c]);- _drag = c; _edge = Math.Abs(x - lx) < 7 ? 0 : Math.Abs(x - hx) < 7 ? 1 : 2;- e.Pointer.Capture(this); Apply(x); e.Handled = true;- }- protected override void OnPointerMoved(PointerEventArgs e) { if (_drag >= 0) Apply(e.GetPosition(this).X); }- // The drag ends before the edit is reported: the handler rebuilds the device chain, which- // takes this map out of the tree, and a drag still open then would report again from the- // capture loss, inside that rebuild — leaving a second copy of the rack card (#202).- protected override void OnPointerReleased(PointerReleasedEventArgs e)- {- if (_drag < 0) return;- int c = _drag; _drag = -1;- e.Pointer.Capture(null); InvalidateVisual();- RangeEdited?.Invoke(c, _lo[c], _hi[c]);- }-- // Capture taken away mid-drag (the window deactivates): commit the range as it stands and drop the accent.- protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)- {- base.OnPointerCaptureLost(e);- if (_drag < 0) return;- int c = _drag; _drag = -1;- InvalidateVisual();- RangeEdited?.Invoke(c, _lo[c], _hi[c]);- }-- private void Apply(double x)- {- int v = Math.Clamp((int)Math.Round(x / Math.Max(1, Bounds.Width) * 127), 0, 127);- int c = _drag;- if (_edge == 0) _lo[c] = Math.Min(v, _hi[c]);- else if (_edge == 1) _hi[c] = Math.Max(v, _lo[c]);- else { int span = _hi[c] - _lo[c]; int lo = Math.Clamp(v - span / 2, 0, 127 - span); _lo[c] = lo; _hi[c] = lo + span; }- InvalidateVisual();- }-- public override void Render(DrawingContext ctx)- {- double w = Bounds.Width, h = Bounds.Height; if (w <= 0 || h <= 0) return;- double bh = BarsH; int n = Math.Max(1, _lo.Length);- double rowH = bh / n;- for (int c = 0; c < _lo.Length; c++)- {- double y = c * rowH + 1, hgt = Math.Max(3, rowH - 2);- double x0 = X(_lo[c]), x1 = X(_hi[c]);- var col = ((SolidColorBrush)_cols[c]).Color;- byte al = (byte)(c == _sel ? 0xCC : 0x80);- ctx.DrawRectangle(new SolidColorBrush(Color.FromArgb(al, col.R, col.G, col.B)), null, new Rect(x0, y, Math.Max(2, x1 - x0), hgt), 2, 2);- }- // keyboard strip (key mode) or vel gradient ticks.- double ky = bh + 1, kh = h - bh - 2;- if (_keyMode)- {- int lo = 24, hi = 96; // C1..C7 span for the map- for (int note = lo; note <= hi; note++)- {- int pc = ((note % 12) + 12) % 12;- bool black = pc is 1 or 3 or 6 or 8 or 10;- double kx = (note - lo) / (double)(hi - lo) * w, kw = w / (hi - lo);- ctx.FillRectangle(black ? KeyBlack : KeyWhite, new Rect(kx, ky, Math.Max(1, kw - 0.6), kh));- }- }- else- {- ctx.FillRectangle(KeyWhite, new Rect(0, ky, w, kh));- for (int t = 1; t < 4; t++) ctx.DrawLine(new Pen(KeyBlack, 1), new Point(t / 4.0 * w, ky), new Point(t / 4.0 * w, ky + kh));- }- }-}-// Wraps an engine so a built-in instrument's own editor can drive a rack CHAIN instrument:// its plugin-param calls (trackId, deviceIndex −1, i) are redirected to the chain surface// (trackId, chain, i); automation writes are no-ops (chain params follow macros); everythingdiff --git a/src/managed/Nota.App/DeviceCards/Rack/RackKindProfile.cs b/src/managed/Nota.App/DeviceCards/Rack/RackKindProfile.csnew file mode 100644index 00000000..73f11fe6--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackKindProfile.cs@@ -0,0 +1,80 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — what differs between the three racks on the shared rack card+// (specs/040): the zone tab's name and rows, how chains can run, the right panel's output+// tab, a chain's mix controls and which device kinds a chain takes. The card reads these+// instead of branching on the rack kind, so the three stay one layout.++namespace Nota.App;++internal sealed record RackKindProfile(+ RackKind Kind,+ string ZoneTab, // centre tab between Chains and Macros+ bool KeyZones, // per-chain key range+ bool VelocityZones, // per-chain velocity range+ bool SelectRanges, // per-chain select range + the selector+ (int Id, string Label, string Hint)[] Modes, // how chains run; empty = no choice+ string OutputTab, // right panel's rack tab+ bool ChainPan, // Pan row (audio racks) …+ bool ChainTranspose, // … or Transpose (MIDI chains)+ bool VolumeIsVelocity, // a MIDI chain's Volume scales velocity, shown in %+ bool LevelMeter, // chain rows show an audio level (MIDI: note activity)+ bool TakesInstrument, // one instrument per chain+ bool TakesAudioEffects,+ bool TakesMidiEffects,+ string ChainsHint) // the one-line hint under the chain list+{+ // Engine routing ids (RackCore mode): 0 Parallel, 1 Serial, 2 Select.+ public const int Parallel = 0, Serial = 1, Select = 2;++ public static readonly RackKindProfile Instrument = new(+ RackKind.Instrument, "Zones", KeyZones: true, VelocityZones: true, SelectRanges: false,+ Modes: [], OutputTab: "Rack out", ChainPan: true, ChainTranspose: false, VolumeIsVelocity: false,+ LevelMeter: true, TakesInstrument: true, TakesAudioEffects: true, TakesMidiEffects: true,+ ChainsHint: "Drop an instrument to add a layer.");++ public static readonly RackKindProfile AudioEffect = new(+ RackKind.AudioEffect, "Select", KeyZones: false, VelocityZones: false, SelectRanges: true,+ Modes:+ [+ (Parallel, "Parallel", "All chains get the input. Outputs are summed."),+ (Serial, "Serial", "Chain 1 feeds chain 2, top to bottom."),+ (Select, "Select", "Only chains whose range holds the selector play."),+ ],+ OutputTab: "Rack out", ChainPan: true, ChainTranspose: false, VolumeIsVelocity: false,+ LevelMeter: true, TakesInstrument: false, TakesAudioEffects: true, TakesMidiEffects: false,+ ChainsHint: "Drop an effect to add a chain.");++ public static readonly RackKindProfile MidiEffect = new(+ RackKind.MidiEffect, "Zones", KeyZones: true, VelocityZones: true, SelectRanges: true,+ Modes:+ [+ (Parallel, "Parallel", "Each note goes to every chain whose zone it hits. Outputs merge before the instrument."),+ (Select, "Select", "Only chains whose range holds the selector get notes."),+ ],+ OutputTab: "Output", ChainPan: false, ChainTranspose: true, VolumeIsVelocity: true,+ LevelMeter: false, TakesInstrument: false, TakesAudioEffects: false, TakesMidiEffects: true,+ ChainsHint: "Drop MIDI effects here. Output goes to the track instrument.");++ public static RackKindProfile For(RackKind kind) => kind switch+ {+ RackKind.AudioEffect => AudioEffect,+ RackKind.MidiEffect => MidiEffect,+ _ => Instrument,+ };++ /// <summary>The explanation under the "Chains run" choice for an engine mode id.</summary>+ public string ModeHint(int mode)+ {+ foreach (var m in Modes) if (m.Id == mode) return m.Hint;+ return Modes.Length > 0 ? Modes[0].Hint : "";+ }++ /// <summary>The label of an engine mode id ("Parallel" when the rack has no choice).</summary>+ public string ModeLabel(int mode)+ {+ foreach (var m in Modes) if (m.Id == mode) return m.Label;+ return "Parallel";+ }+}diff --git a/src/managed/Nota.App/DeviceChainView.Clipboard.cs b/src/managed/Nota.App/DeviceChainView.Clipboard.csindex 60a47aa9..a0b59aa6 100644--- a/src/managed/Nota.App/DeviceChainView.Clipboard.cs+++ b/src/managed/Nota.App/DeviceChainView.Clipboard.cs@@ -13,6 +13,7 @@ using Avalonia;using Avalonia.Controls;using Avalonia.Input;using Avalonia.Media;+using Nota.Infrastructure;using static Nota.App.DeviceCardKit;namespace Nota.App;@@ -191,7 +192,7 @@ public sealed partial class DeviceChainViewheader?.Invoke(flyout); // ends with its own separatorbool selectable = SelectableKind(kind);MenuKit.AddGroups(flyout.Items,- new Control[] { MenuKit.Item("Save preset", GlyphKind.Save, () => PresetSaveRequested?.Invoke(di)) },+ new Control[] { MenuKit.Item("Save preset", GlyphKind.Save, () => PresetSaveRequested?.Invoke(kind == ChainKind.Midi ? PresetService.MidiEffectBase - di : di)) },new Control[]{MenuKit.Item("Copy", GlyphKind.Copy, CopySelectedDevice, MenuKit.CopyKey, selectable),diff --git a/src/managed/Nota.App/DeviceChainView.Midi.cs b/src/managed/Nota.App/DeviceChainView.Midi.csindex 11fed16d..fd16ce53 100644--- a/src/managed/Nota.App/DeviceChainView.Midi.cs+++ b/src/managed/Nota.App/DeviceChainView.Midi.cs@@ -13,12 +13,22 @@ namespace Nota.App;public sealed partial class DeviceChainView{+ private const int MidiRackKind = 6;+private Control MidiDeviceCard(int index, int count){bool bypassed = _engine.MidiEffectBypassed(_trackId, index);string name = _engine.MidiEffectName(_trackId, index);int kind = _engine.MidiEffectKind(_trackId, index);if (_engine.MidiEffectFolded(_trackId, index)) return FoldedStrip(ChainKind.Midi, index, name, bypassable: true, bypassed);+ if (kind == MidiRackKind) // the MIDI Effect Rack: the shared rack card, full bleed (specs/040)+ {+ int chains = _engine.MidiRackChainCount(_trackId, index);+ var rackSpec = new ShellSpec(+ Name: name, Subtitle: $"Rack · {chains} chain{(chains == 1 ? "" : "s")}", DeviceIndex: index, Count: count, Bypassed: bypassed, Bypassable: true,+ CanMove: true, CanDelete: true, PresetKind: kind, IsInstrument: false, Width: 700, Kind: ChainKind.Midi);+ return BuildCardShell(rackSpec, new RackCardView(NewCardContext()).BuildMidiRackBody(index));+ }var body = _midiFactory.Resolve(kind);var ctx = NewCardContext();double width = body.WidthFor(_engine, _trackId, index);diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.csindex a8416a46..ab390221 100644--- a/src/managed/Nota.App/DeviceChainView.cs+++ b/src/managed/Nota.App/DeviceChainView.cs@@ -217,6 +217,8 @@ public sealed partial class DeviceChainView : UserControlif (kind == 5) // Audio Effect Rack — full-bleed body (fills the shell; no body inset{ // that would overflow its fixed width and skew hit-testing).body = new RackCardView(NewCardContext()).BuildEffectRackBody(index); width = 700; fullBleed = true;+ int chains = _engine.RackDevChainCount(_trackId, index);+ tag = $"Rack · {chains} chain{(chains == 1 ? "" : "s")}";}else{diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.csindex ffce0ec3..dd255198 100644--- a/src/managed/Nota.App/MainWindow.Browser.cs+++ b/src/managed/Nota.App/MainWindow.Browser.cs@@ -17,6 +17,7 @@ using Avalonia.Media;using Avalonia.Platform.Storage;using Microsoft.Extensions.DependencyInjection;using Nota.Application;+using Nota.Infrastructure;using Nota.Presentation;namespace Nota.App;@@ -209,7 +210,9 @@ public partial class MainWindowint trackId = _deviceChain.TrackId;if (trackId <= 0) { _vm.StatusText = "Select a track first."; return; }- string label = Engine.DeviceName(trackId, deviceIndex);+ string label = deviceIndex <= PresetService.MidiEffectBase+ ? Engine.MidiEffectName(trackId, PresetService.MidiEffectBase - deviceIndex)+ : Engine.DeviceName(trackId, deviceIndex);if (string.IsNullOrEmpty(label)) label = "Instrument";var name = await new TextPromptWindow("Save preset", "Preset name", label).ShowDialog<string?>(this);if (string.IsNullOrEmpty(name)) return;diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.csindex 8293d9b4..5be046c2 100644--- a/src/managed/Nota.App/MainWindow.Input.cs+++ b/src/managed/Nota.App/MainWindow.Input.cs@@ -163,6 +163,13 @@ public partial class MainWindowe.Handled = true;return;}+ // Esc ends macro mapping on a rack card (specs/040) before it touches the arrangement.+ if (!mod && e.Key == Key.Escape && RackCardState.EndAllMapping())+ {+ if (DetailBody.Content is DeviceChainView chain) chain.Refresh();+ e.Handled = true;+ return;+ }if (!mod && e.Key == Key.Escape && Timeline.EscapePressed()){e.Handled = true;diff --git a/src/managed/Nota.App/MidiLearn.cs b/src/managed/Nota.App/MidiLearn.csindex a1dab2f0..f3d778f3 100644--- a/src/managed/Nota.App/MidiLearn.cs+++ b/src/managed/Nota.App/MidiLearn.cs@@ -77,7 +77,8 @@ public enum MidiTargetKindTrackVolume, TrackPan, TrackMute, TrackSolo,MasterVolume, TransportPlay, TransportStop, TransportRecord,// Rack controls. DeviceIndex encodes the rack: -1 = the track's Instrument Rack,- // >= 0 = an Audio Effect Rack device at that index. ParamIndex = chain (or unused).+ // >= 0 = an Audio Effect Rack device at that index, <= MidiTarget.MidiRackBase (−1000) − mi =+ // the MIDI Effect Rack at MIDI effect index mi. ParamIndex = chain (or unused).RackVolume, RackChainGain, RackChainMute, RackChainSolo,}@@ -96,7 +97,9 @@ public readonly record struct MidiTarget(MidiTargetKind Kind, int TrackId, int Dpublic static readonly MidiTarget TransportPlay = new(MidiTargetKind.TransportPlay, -1, -1, -1);public static readonly MidiTarget TransportStop = new(MidiTargetKind.TransportStop, -1, -1, -1);public static readonly MidiTarget TransportRecord = new(MidiTargetKind.TransportRecord, -1, -1, -1);- // Rack controls (di = -1 Instrument Rack / >= 0 Audio Effect Rack device index).+ // Rack controls (di = -1 Instrument Rack / >= 0 Audio Effect Rack device index /+ // MidiRackBase − mi MIDI Effect Rack).+ public const int MidiRackBase = -1000;public static MidiTarget RackVolume(int track, int di) => new(MidiTargetKind.RackVolume, track, di, -1);public static MidiTarget RackChainGain(int track, int di, int chain) => new(MidiTargetKind.RackChainGain, track, di, chain);public static MidiTarget RackChainMute(int track, int di, int chain) => new(MidiTargetKind.RackChainMute, track, di, chain);diff --git a/src/managed/Nota.App/MidiLearnService.cs b/src/managed/Nota.App/MidiLearnService.csindex 3233be3d..961323b4 100644--- a/src/managed/Nota.App/MidiLearnService.cs+++ b/src/managed/Nota.App/MidiLearnService.cs@@ -371,6 +371,8 @@ public sealed class MidiLearnServicecase MidiTargetKind.TrackPan:MixTouch(MixTarget.Pan(t.TrackId), () => _engine.SetTrackPan(t.TrackId, (float)(outv * 2.0 - 1.0)));break;+ case MidiTargetKind.RackVolume or MidiTargetKind.RackChainGain when t.DeviceIndex <= MidiTarget.MidiRackBase:+ break; // a MIDI Effect Rack has no audio levelcase MidiTargetKind.RackVolume:if (t.DeviceIndex < 0) _engine.RackSetVolume(t.TrackId, (float)(outv * RackGainMax));else _engine.RackDevSetVolume(t.TrackId, t.DeviceIndex, (float)(outv * RackGainMax));@@ -420,6 +422,18 @@ public sealed class MidiLearnServicecase MidiTargetKind.TransportRecord: _engine.SetRecording(!_engine.IsRecording); break;case MidiTargetKind.TrackMute: _engine.SetTrackMute(t.TrackId, !TrackFlag(t.TrackId, mute: true)); break;case MidiTargetKind.TrackSolo: _engine.SetTrackSolo(t.TrackId, !TrackFlag(t.TrackId, mute: false)); break;+ case MidiTargetKind.RackChainMute when t.DeviceIndex <= MidiTarget.MidiRackBase:+ {+ int mi = MidiTarget.MidiRackBase - t.DeviceIndex;+ _engine.MidiRackSetChainMute(t.TrackId, mi, t.ParamIndex, !_engine.MidiRackChainMute(t.TrackId, mi, t.ParamIndex));+ break;+ }+ case MidiTargetKind.RackChainSolo when t.DeviceIndex <= MidiTarget.MidiRackBase:+ {+ int mi = MidiTarget.MidiRackBase - t.DeviceIndex;+ _engine.MidiRackSetChainSolo(t.TrackId, mi, t.ParamIndex, !_engine.MidiRackChainSolo(t.TrackId, mi, t.ParamIndex));+ break;+ }case MidiTargetKind.RackChainMute:if (t.DeviceIndex < 0) _engine.RackSetChainMute(t.TrackId, t.ParamIndex, !_engine.RackChainMute(t.TrackId, t.ParamIndex));else _engine.RackDevSetChainMute(t.TrackId, t.DeviceIndex, t.ParamIndex, !_engine.RackDevChainMute(t.TrackId, t.DeviceIndex, t.ParamIndex));diff --git a/src/managed/Nota.App/NotaDocs.cs b/src/managed/Nota.App/NotaDocs.csindex 6dfe172f..7118efd1 100644--- a/src/managed/Nota.App/NotaDocs.cs+++ b/src/managed/Nota.App/NotaDocs.cs@@ -46,7 +46,8 @@ internal static class NotaDocsstring slug = kind switch{DeviceChainView.ChainKind.Instrument => Pick(Instruments, engineKind),- DeviceChainView.ChainKind.Midi => Pick(MidiEffects, engineKind) is { Length: > 0 } m ? "midi-effects/" + m : "",+ DeviceChainView.ChainKind.Midi => engineKind == 6 ? "racks/midi-effect-rack"+ : Pick(MidiEffects, engineKind) is { Length: > 0 } m ? "midi-effects/" + m : "",_ => engineKind == 5 ? "racks/audio-effect-rack": Pick(AudioEffects, engineKind) is { Length: > 0 } a ? "audio-effects/" + a : "",};diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 46c23f89..6d0ee106 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1206,6 +1206,15 @@ public sealed partial class PreferencesWindow : NotaWindow("⌘⇧G", "Take the devices out of a selected one-chain rack"),("Delete", "Delete the selected device"),}),+ ("Racks", new[]+ {+ ("Esc", "End macro mapping (Map on the rack card)"),+ ("Drag a zone edge", "Set a chain's key, velocity or select range · edges never cross"),+ ("Hover the zones", "See which chains a note would play"),+ ("Double-click a chain or macro name", "Rename it"),+ ("Right-click a macro", "Map it to a parameter or the selector · clear its mappings"),+ ("Drag a card's grip", "Move a device within its chain"),+ }),("Modular (after a click on the canvas)", new[]{("F", "Fit every node on screen"),diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex a1d41807..f06a4966 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -418,6 +418,10 @@ public readonly record struct RackMacroMapping({/// <summary>DeviceIndex of a mapping onto the chain's own controls (RackCore::kPadControls).</summary>public const int PadControls = -2;+ /// <summary>DeviceIndex of a mapping onto a rack-level control (NOTA_RACK_CONTROL); ParamIndex 0 = the selector.</summary>+ public const int RackControl = -3;+ /// <summary>DeviceIndex of a chain's MIDI effect j is MidiDeviceBase − j (NOTA_RACK_MIDI_DEVICE_BASE).</summary>+ public const int MidiDeviceBase = -1000;/// <summary>The pad controls a mapping can drive, by ParamIndex, with their ranges (gain is linear,/// pan −1..1, tune in semitones, decay 0..1 with 1 = hold).</summary>public static readonly string[] PadParamNames = { "Volume", "Pan", "Tune", "Decay" };diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 34c85fea..d12ea786 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -551,6 +551,10 @@ public interface IAudioEngine : IDisposableint MidiEffectScope(int trackId, int index, float[] outv);/// <summary>Send an editor command to a MIDI effect (Nota Arp: 1 = restart the pattern).</summary>void MidiEffectCommand(int trackId, int index, int cmd);+ /// <summary>A MIDI effect's opaque state blob (the MIDI Effect Rack: its whole structure); empty for params-only effects.</summary>+ byte[] MidiEffectGetState(int trackId, int index);+ /// <summary>Restores a MIDI effect's state blob; checkpoint makes it one undo step.</summary>+ bool MidiEffectSetState(int trackId, int index, byte[] data, bool checkpoint);string MidiEffectName(int trackId, int index);int MidiEffectParamCount(int trackId, int index);string MidiEffectParamName(int trackId, int index, int paramIndex);@@ -715,6 +719,11 @@ public interface IAudioEngine : IDisposablevoid RackSetMacroName(int trackId, int macro, string name);float RackVolume(int trackId);void RackSetVolume(int trackId, float v);+ /// <summary>Copies an Instrument Rack chain after itself (children, controls, its mappings); the new index or <0.</summary>+ int RackDuplicateChain(int trackId, int chain);+ /// <summary>Instrument Rack mono: one note at a time, last-note priority; glide bends between notes.</summary>+ bool RackMono(int trackId);+ void RackSetMono(int trackId, bool on);float RackGlide(int trackId);void RackSetGlide(int trackId, float v);bool RackSetMappingRange(int trackId, int index, float rangeMin, float rangeMax);@@ -796,6 +805,86 @@ public interface IAudioEngine : IDisposablevoid RackDevSetVolume(int trackId, int deviceIndex, float v);int RackDevMode(int trackId, int deviceIndex);void RackDevSetMode(int trackId, int deviceIndex, int mode);++ // ---- MIDI Effect Rack (MIDI kind 6, specs/040; midiIndex = its MIDI effect index) and the+ // MIDI effects in an Instrument Rack chain (#329). See nota_engine.h.+ int RackChainMidiCount(int trackId, int chain);+ int RackChainMidiAdd(int trackId, int chain, int midiKind);+ bool RackChainMidiRemove(int trackId, int chain, int index);+ bool RackChainMidiMove(int trackId, int chain, int fromIndex, int toIndex);+ int RackChainMidiKind(int trackId, int chain, int index);+ string RackChainMidiName(int trackId, int chain, int index);+ int RackChainMidiParamCount(int trackId, int chain, int index);+ string RackChainMidiParamName(int trackId, int chain, int index, int param);+ float RackChainMidiParamMin(int trackId, int chain, int index, int param);+ float RackChainMidiParamMax(int trackId, int chain, int index, int param);+ float RackChainMidiParamGet(int trackId, int chain, int index, int param);+ void RackChainMidiParamSet(int trackId, int chain, int index, int param, float value);+ void RackChainMidiSetBypassed(int trackId, int chain, int index, bool bypassed);+ bool RackChainMidiBypassed(int trackId, int chain, int index);+ int RackChainMidiLastIn(int trackId, int chain, int index);+ int RackChainMidiLastOut(int trackId, int chain, int index);+ int RackChainMidiScope(int trackId, int chain, int index, float[] outv);+ void RackChainMidiCommand(int trackId, int chain, int index, int cmd);+ int MidiRackChainDeviceCount(int trackId, int midiIndex, int chain);+ int MidiRackChainDeviceAdd(int trackId, int midiIndex, int chain, int midiKind);+ bool MidiRackChainDeviceRemove(int trackId, int midiIndex, int chain, int index);+ bool MidiRackChainDeviceMove(int trackId, int midiIndex, int chain, int fromIndex, int toIndex);+ int MidiRackChainDeviceKind(int trackId, int midiIndex, int chain, int index);+ string MidiRackChainDeviceName(int trackId, int midiIndex, int chain, int index);+ int MidiRackChainDeviceParamCount(int trackId, int midiIndex, int chain, int index);+ string MidiRackChainDeviceParamName(int trackId, int midiIndex, int chain, int index, int param);+ float MidiRackChainDeviceParamMin(int trackId, int midiIndex, int chain, int index, int param);+ float MidiRackChainDeviceParamMax(int trackId, int midiIndex, int chain, int index, int param);+ float MidiRackChainDeviceParamGet(int trackId, int midiIndex, int chain, int index, int param);+ void MidiRackChainDeviceParamSet(int trackId, int midiIndex, int chain, int index, int param, float value);+ void MidiRackChainDeviceSetBypassed(int trackId, int midiIndex, int chain, int index, bool bypassed);+ bool MidiRackChainDeviceBypassed(int trackId, int midiIndex, int chain, int index);+ int MidiRackChainDeviceLastIn(int trackId, int midiIndex, int chain, int index);+ int MidiRackChainDeviceLastOut(int trackId, int midiIndex, int chain, int index);+ int MidiRackChainDeviceScope(int trackId, int midiIndex, int chain, int index, float[] outv);+ void MidiRackChainDeviceCommand(int trackId, int midiIndex, int chain, int index, int cmd);+ int MidiRackChainCount(int trackId, int midiIndex);+ int MidiRackAddChain(int trackId, int midiIndex);+ bool MidiRackRemoveChain(int trackId, int midiIndex, int chain);+ int MidiRackDuplicateChain(int trackId, int midiIndex, int chain);+ /// <summary>One undo step for the in-place edits that follow (chain mix, mode, selector,+ /// output, macro values): forks the rack, keeping its MIDI effects and held notes.</summary>+ bool MidiRackCheckpoint(int trackId, int midiIndex);+ string MidiRackChainName(int trackId, int midiIndex, int chain);+ void MidiRackSetChainName(int trackId, int midiIndex, int chain, string name);+ void MidiRackSetChainMute(int trackId, int midiIndex, int chain, bool on);+ bool MidiRackChainMute(int trackId, int midiIndex, int chain);+ void MidiRackSetChainSolo(int trackId, int midiIndex, int chain, bool on);+ bool MidiRackChainSolo(int trackId, int midiIndex, int chain);+ void MidiRackSetChainZone(int trackId, int midiIndex, int chain, int keyLo, int keyHi, int velLo, int velHi);+ void MidiRackChainZone(int trackId, int midiIndex, int chain, out int keyLo, out int keyHi, out int velLo, out int velHi);+ void MidiRackSetChainSelect(int trackId, int midiIndex, int chain, int lo, int hi);+ void MidiRackChainSelectRange(int trackId, int midiIndex, int chain, out int lo, out int hi);+ void MidiRackSetChainTranspose(int trackId, int midiIndex, int chain, int semitones);+ int MidiRackChainTranspose(int trackId, int midiIndex, int chain);+ void MidiRackSetChainVelScale(int trackId, int midiIndex, int chain, float scale);+ float MidiRackChainVelScale(int trackId, int midiIndex, int chain);+ float MidiRackChainActivity(int trackId, int midiIndex, int chain);+ void MidiRackSetMode(int trackId, int midiIndex, int mode);+ int MidiRackMode(int trackId, int midiIndex);+ void MidiRackSetSelector(int trackId, int midiIndex, float v);+ float MidiRackSelector(int trackId, int midiIndex);+ void MidiRackSetMerge(int trackId, int midiIndex, bool on);+ bool MidiRackMerge(int trackId, int midiIndex);+ void MidiRackSetThru(int trackId, int midiIndex, bool on);+ bool MidiRackThru(int trackId, int midiIndex);+ float MidiRackMacroGet(int trackId, int midiIndex, int macro);+ void MidiRackMacroSet(int trackId, int midiIndex, int macro, float v);+ string MidiRackMacroName(int trackId, int midiIndex, int macro);+ void MidiRackSetMacroName(int trackId, int midiIndex, int macro, string name);+ int MidiRackAddMacroMapping(int trackId, int midiIndex, int macro, int chain, int device, int param, float lo, float hi);+ int MidiRackMappingCount(int trackId, int midiIndex);+ int MidiRackMappingInfo(int trackId, int midiIndex, int index, out int macro, out int chain, out int device, out int param, out float lo, out float hi, out int curve);+ bool MidiRackRemoveMapping(int trackId, int midiIndex, int index);+ bool MidiRackSetMappingRange(int trackId, int midiIndex, int index, float lo, float hi);+ bool MidiRackSetMappingCurve(int trackId, int midiIndex, int index, int curve);+ int RackDevDuplicateChain(int trackId, int deviceIndex, int chain);float RackDevDryWet(int trackId, int deviceIndex);void RackDevSetDryWet(int trackId, int deviceIndex, float v);bool RackDevPdc(int trackId, int deviceIndex);diff --git a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.csindex 11ebb06f..1e4ab017 100644--- a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs+++ b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs@@ -196,6 +196,9 @@ public static class BuiltinDeviceCatalognew("Nota Random", M, 5, "random transpose", D("random", "humanize chance","evolving", "", "synth", "", "","Random transposition, timing and dropouts.")),+ new("Nota MIDI Effect Rack", M, 6, "chains of MIDI effects", D("rack", "midirack split layer zones",+ "", "", "keys synth", "", "",+ "Splits notes across chains of MIDI effects by key, velocity or a selector.")),};public static IEnumerable<BuiltinDevice> OfType(BuiltinDeviceType t) => All.Where(d => d.Type == t);diff --git a/src/managed/Nota.Application/Palette/DeviceCategories.cs b/src/managed/Nota.Application/Palette/DeviceCategories.csindex 80956dad..2142f0db 100644--- a/src/managed/Nota.Application/Palette/DeviceCategories.cs+++ b/src/managed/Nota.Application/Palette/DeviceCategories.cs@@ -42,6 +42,7 @@ public static class DeviceCategories{new("Generate", ["Nota Arp", "Nota Chord", "Nota Random"]),new("Shape", ["Nota Scale", "Nota Length", "Nota Velocity"]),+ new("Racks", ["Nota MIDI Effect Rack"]),};/// <summary>The categories of one tab, in display order, with their built-in members.</summary>diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.csindex 6d867623..8ebbab8b 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs@@ -134,6 +134,12 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_midi_effect_scope")]internal static partial int MidiEffectScope(IntPtr engine, int trackId, int index, [Out] float[] outv, int maxN);+ [LibraryImport(Lib, EntryPoint = "nota_midi_effect_get_state")]+ internal static partial int MidiEffectGetState(IntPtr engine, int trackId, int index, [Out] byte[]? outBuffer, int capacity);++ [LibraryImport(Lib, EntryPoint = "nota_midi_effect_set_state")]+ internal static partial NotaResult MidiEffectSetState(IntPtr engine, int trackId, int index, [In] byte[] data, int size, int checkpoint);+[LibraryImport(Lib, EntryPoint = "nota_midi_effect_command")]internal static partial void MidiEffectCommand(IntPtr engine, int trackId, int index, int cmd);[LibraryImport(Lib, EntryPoint = "nota_midi_effect_name")]diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.MidiRack.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.MidiRack.csnew file mode 100644index 00000000..e768a473--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.MidiRack.cs@@ -0,0 +1,233 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++using System.Runtime.InteropServices;++namespace Nota.Infrastructure;++/// <summary>MIDI Effect Rack (MIDI kind 6, specs/040) and the MIDI effects in an Instrument Rack chain (#329).</summary>+/// <remarks>Part of <see cref="NotaEngine"/>'s P/Invoke surface; see nota_engine.h. Boolean ABI calls return 1/0.</remarks>+internal static partial class NativeMethods+{+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_count")]+ internal static partial int RackChainMidiCount(IntPtr engine, int trackId, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_add")]+ internal static partial int RackChainMidiAdd(IntPtr engine, int trackId, int chain, int midiKind);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_remove")]+ internal static partial int RackChainMidiRemove(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_move")]+ internal static partial int RackChainMidiMove(IntPtr engine, int trackId, int chain, int fromIndex, int toIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_kind")]+ internal static partial int RackChainMidiKind(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_name")]+ internal static partial IntPtr RackChainMidiName(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_param_count")]+ internal static partial int RackChainMidiParamCount(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_param_name")]+ internal static partial IntPtr RackChainMidiParamName(IntPtr engine, int trackId, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_param_min")]+ internal static partial float RackChainMidiParamMin(IntPtr engine, int trackId, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_param_max")]+ internal static partial float RackChainMidiParamMax(IntPtr engine, int trackId, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_param_get")]+ internal static partial float RackChainMidiParamGet(IntPtr engine, int trackId, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_param_set")]+ internal static partial void RackChainMidiParamSet(IntPtr engine, int trackId, int chain, int index, int param, float value);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_set_bypassed")]+ internal static partial void RackChainMidiSetBypassed(IntPtr engine, int trackId, int chain, int index, int bypassed);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_bypassed")]+ internal static partial int RackChainMidiBypassed(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_last_in")]+ internal static partial int RackChainMidiLastIn(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_last_out")]+ internal static partial int RackChainMidiLastOut(IntPtr engine, int trackId, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_scope")]+ internal static partial int RackChainMidiScope(IntPtr engine, int trackId, int chain, int index, [Out] float[] outv, int maxN);++ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_midi_command")]+ internal static partial void RackChainMidiCommand(IntPtr engine, int trackId, int chain, int index, int cmd);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_count")]+ internal static partial int MidiRackChainDeviceCount(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_add")]+ internal static partial int MidiRackChainDeviceAdd(IntPtr engine, int trackId, int midiIndex, int chain, int midiKind);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_remove")]+ internal static partial int MidiRackChainDeviceRemove(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_move")]+ internal static partial int MidiRackChainDeviceMove(IntPtr engine, int trackId, int midiIndex, int chain, int fromIndex, int toIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_kind")]+ internal static partial int MidiRackChainDeviceKind(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_name")]+ internal static partial IntPtr MidiRackChainDeviceName(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_param_count")]+ internal static partial int MidiRackChainDeviceParamCount(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_param_name")]+ internal static partial IntPtr MidiRackChainDeviceParamName(IntPtr engine, int trackId, int midiIndex, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_param_min")]+ internal static partial float MidiRackChainDeviceParamMin(IntPtr engine, int trackId, int midiIndex, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_param_max")]+ internal static partial float MidiRackChainDeviceParamMax(IntPtr engine, int trackId, int midiIndex, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_param_get")]+ internal static partial float MidiRackChainDeviceParamGet(IntPtr engine, int trackId, int midiIndex, int chain, int index, int param);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_param_set")]+ internal static partial void MidiRackChainDeviceParamSet(IntPtr engine, int trackId, int midiIndex, int chain, int index, int param, float value);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_set_bypassed")]+ internal static partial void MidiRackChainDeviceSetBypassed(IntPtr engine, int trackId, int midiIndex, int chain, int index, int bypassed);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_bypassed")]+ internal static partial int MidiRackChainDeviceBypassed(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_last_in")]+ internal static partial int MidiRackChainDeviceLastIn(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_last_out")]+ internal static partial int MidiRackChainDeviceLastOut(IntPtr engine, int trackId, int midiIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_scope")]+ internal static partial int MidiRackChainDeviceScope(IntPtr engine, int trackId, int midiIndex, int chain, int index, [Out] float[] outv, int maxN);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_device_command")]+ internal static partial void MidiRackChainDeviceCommand(IntPtr engine, int trackId, int midiIndex, int chain, int index, int cmd);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_count")]+ internal static partial int MidiRackChainCount(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_add_chain")]+ internal static partial int MidiRackAddChain(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_remove_chain")]+ internal static partial int MidiRackRemoveChain(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_duplicate_chain")]+ internal static partial int MidiRackDuplicateChain(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_checkpoint")]+ internal static partial int MidiRackCheckpoint(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_name")]+ internal static partial IntPtr MidiRackChainName(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_name", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial void MidiRackSetChainName(IntPtr engine, int trackId, int midiIndex, int chain, string name);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_mute")]+ internal static partial void MidiRackSetChainMute(IntPtr engine, int trackId, int midiIndex, int chain, int on);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_mute")]+ internal static partial int MidiRackChainMute(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_solo")]+ internal static partial void MidiRackSetChainSolo(IntPtr engine, int trackId, int midiIndex, int chain, int on);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_solo")]+ internal static partial int MidiRackChainSolo(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_zone")]+ internal static partial void MidiRackSetChainZone(IntPtr engine, int trackId, int midiIndex, int chain, int keyLo, int keyHi, int velLo, int velHi);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_zone")]+ internal static partial void MidiRackChainZone(IntPtr engine, int trackId, int midiIndex, int chain, out int keyLo, out int keyHi, out int velLo, out int velHi);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_select")]+ internal static partial void MidiRackSetChainSelect(IntPtr engine, int trackId, int midiIndex, int chain, int lo, int hi);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_select_range")]+ internal static partial void MidiRackChainSelectRange(IntPtr engine, int trackId, int midiIndex, int chain, out int lo, out int hi);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_transpose")]+ internal static partial void MidiRackSetChainTranspose(IntPtr engine, int trackId, int midiIndex, int chain, int semitones);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_transpose")]+ internal static partial int MidiRackChainTranspose(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_chain_vel_scale")]+ internal static partial void MidiRackSetChainVelScale(IntPtr engine, int trackId, int midiIndex, int chain, float scale);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_vel_scale")]+ internal static partial float MidiRackChainVelScale(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_chain_activity")]+ internal static partial float MidiRackChainActivity(IntPtr engine, int trackId, int midiIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_mode")]+ internal static partial void MidiRackSetMode(IntPtr engine, int trackId, int midiIndex, int mode);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_mode")]+ internal static partial int MidiRackMode(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_selector")]+ internal static partial void MidiRackSetSelector(IntPtr engine, int trackId, int midiIndex, float v);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_selector")]+ internal static partial float MidiRackSelector(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_merge")]+ internal static partial void MidiRackSetMerge(IntPtr engine, int trackId, int midiIndex, int on);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_merge")]+ internal static partial int MidiRackMerge(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_thru")]+ internal static partial void MidiRackSetThru(IntPtr engine, int trackId, int midiIndex, int on);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_thru")]+ internal static partial int MidiRackThru(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_macro_get")]+ internal static partial float MidiRackMacroGet(IntPtr engine, int trackId, int midiIndex, int macro);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_macro_set")]+ internal static partial void MidiRackMacroSet(IntPtr engine, int trackId, int midiIndex, int macro, float v);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_macro_name")]+ internal static partial IntPtr MidiRackMacroName(IntPtr engine, int trackId, int midiIndex, int macro);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_macro_name", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial void MidiRackSetMacroName(IntPtr engine, int trackId, int midiIndex, int macro, string name);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_add_macro_mapping")]+ internal static partial int MidiRackAddMacroMapping(IntPtr engine, int trackId, int midiIndex, int macro, int chain, int device, int param, float lo, float hi);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_mapping_count")]+ internal static partial int MidiRackMappingCount(IntPtr engine, int trackId, int midiIndex);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_mapping_info")]+ internal static partial int MidiRackMappingInfo(IntPtr engine, int trackId, int midiIndex, int index, out int macro, out int chain, out int device, out int param, out float lo, out float hi, out int curve);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_remove_mapping")]+ internal static partial int MidiRackRemoveMapping(IntPtr engine, int trackId, int midiIndex, int index);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_mapping_range")]+ internal static partial int MidiRackSetMappingRange(IntPtr engine, int trackId, int midiIndex, int index, float lo, float hi);++ [LibraryImport(Lib, EntryPoint = "nota_midirack_set_mapping_curve")]+ internal static partial int MidiRackSetMappingCurve(IntPtr engine, int trackId, int midiIndex, int index, int curve);+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.csindex d6a66421..596ebb5b 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs@@ -219,6 +219,15 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_rack_set_glide")]internal static partial void RackSetGlide(IntPtr engine, int trackId, float v);+ [LibraryImport(Lib, EntryPoint = "nota_rack_duplicate_chain")]+ internal static partial int RackDuplicateChain(IntPtr engine, int trackId, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rack_set_mono")]+ internal static partial void RackSetMono(IntPtr engine, int trackId, int on);++ [LibraryImport(Lib, EntryPoint = "nota_rack_mono")]+ internal static partial int RackMono(IntPtr engine, int trackId);+[LibraryImport(Lib, EntryPoint = "nota_rack_set_mapping_range")]internal static partial int RackSetMappingRange(IntPtr engine, int trackId, int index, float rangeMin, float rangeMax);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.csindex df5f2dde..eaf32b03 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs@@ -191,6 +191,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_rackdev_set_mode")]internal static partial void RackDevSetMode(IntPtr engine, int trackId, int deviceIndex, int mode);+ [LibraryImport(Lib, EntryPoint = "nota_rackdev_duplicate_chain")]+ internal static partial int RackDevDuplicateChain(IntPtr engine, int trackId, int deviceIndex, int chain);+[LibraryImport(Lib, EntryPoint = "nota_rackdev_drywet")]internal static partial float RackDevDryWet(IntPtr engine, int trackId, int deviceIndex);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.csindex 3937a6d6..65837610 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs@@ -179,6 +179,24 @@ public sealed partial class NotaEnginepublic int MidiEffectLastOut(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectLastOut(_handle, trackId, index); }public int MidiEffectScope(int trackId, int index, float[] outv) { ThrowIfDisposed(); return NativeMethods.MidiEffectScope(_handle, trackId, index, outv, outv.Length); }public void MidiEffectCommand(int trackId, int index, int cmd) { ThrowIfDisposed(); NativeMethods.MidiEffectCommand(_handle, trackId, index, cmd); }++ /// <summary>A MIDI effect's opaque state blob (the MIDI Effect Rack: its whole structure); empty for params-only effects.</summary>+ public byte[] MidiEffectGetState(int trackId, int index)+ {+ ThrowIfDisposed();+ int size = NativeMethods.MidiEffectGetState(_handle, trackId, index, null, 0);+ if (size <= 0) return Array.Empty<byte>();+ var buf = new byte[size];+ NativeMethods.MidiEffectGetState(_handle, trackId, index, buf, size);+ return buf;+ }++ /// <summary>Restores a MIDI effect's state blob; checkpoint makes it one undo step. False if it couldn't be applied.</summary>+ public bool MidiEffectSetState(int trackId, int index, byte[] data, bool checkpoint)+ {+ ThrowIfDisposed();+ return data.Length > 0 && NativeMethods.MidiEffectSetState(_handle, trackId, index, data, data.Length, checkpoint ? 1 : 0) == NativeMethods.NotaResult.Ok;+ }public string MidiEffectName(int trackId, int index) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiEffectName(_handle, trackId, index)) ?? ""; }public int MidiEffectParamCount(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectParamCount(_handle, trackId, index); }public string MidiEffectParamName(int trackId, int index, int paramIndex) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiEffectParamName(_handle, trackId, index, paramIndex)) ?? ""; }diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.MidiRack.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.MidiRack.csnew file mode 100644index 00000000..1a407b3a--- /dev/null+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.MidiRack.cs@@ -0,0 +1,234 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// NotaEngine — the MIDI Effect Rack (a MIDI effect, addressed by track + MIDI effect index)+// and the MIDI effects in an Instrument Rack chain (addressed by track + chain).++using System.Runtime.InteropServices;++namespace Nota.Infrastructure;++public sealed partial class NotaEngine+{+ public int RackChainMidiCount(int trackId, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiCount(_handle, trackId, chain); }++ public int RackChainMidiAdd(int trackId, int chain, int midiKind)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiAdd(_handle, trackId, chain, midiKind); }++ public bool RackChainMidiRemove(int trackId, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiRemove(_handle, trackId, chain, index) != 0; }++ public bool RackChainMidiMove(int trackId, int chain, int fromIndex, int toIndex)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiMove(_handle, trackId, chain, fromIndex, toIndex) != 0; }++ public int RackChainMidiKind(int trackId, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiKind(_handle, trackId, chain, index); }++ public string RackChainMidiName(int trackId, int chain, int index)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.RackChainMidiName(_handle, trackId, chain, index)) ?? ""; }++ public int RackChainMidiParamCount(int trackId, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiParamCount(_handle, trackId, chain, index); }++ public string RackChainMidiParamName(int trackId, int chain, int index, int param)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.RackChainMidiParamName(_handle, trackId, chain, index, param)) ?? ""; }++ public float RackChainMidiParamMin(int trackId, int chain, int index, int param)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiParamMin(_handle, trackId, chain, index, param); }++ public float RackChainMidiParamMax(int trackId, int chain, int index, int param)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiParamMax(_handle, trackId, chain, index, param); }++ public float RackChainMidiParamGet(int trackId, int chain, int index, int param)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiParamGet(_handle, trackId, chain, index, param); }++ public void RackChainMidiParamSet(int trackId, int chain, int index, int param, float value)+ { ThrowIfDisposed(); NativeMethods.RackChainMidiParamSet(_handle, trackId, chain, index, param, value); }++ public void RackChainMidiSetBypassed(int trackId, int chain, int index, bool bypassed)+ { ThrowIfDisposed(); NativeMethods.RackChainMidiSetBypassed(_handle, trackId, chain, index, bypassed ? 1 : 0); }++ public bool RackChainMidiBypassed(int trackId, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiBypassed(_handle, trackId, chain, index) != 0; }++ public int RackChainMidiLastIn(int trackId, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiLastIn(_handle, trackId, chain, index); }++ public int RackChainMidiLastOut(int trackId, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiLastOut(_handle, trackId, chain, index); }++ public int RackChainMidiScope(int trackId, int chain, int index, float[] outv)+ { ThrowIfDisposed(); return NativeMethods.RackChainMidiScope(_handle, trackId, chain, index, outv, outv.Length); }++ public void RackChainMidiCommand(int trackId, int chain, int index, int cmd)+ { ThrowIfDisposed(); NativeMethods.RackChainMidiCommand(_handle, trackId, chain, index, cmd); }++ public int MidiRackChainDeviceCount(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceCount(_handle, trackId, midiIndex, chain); }++ public int MidiRackChainDeviceAdd(int trackId, int midiIndex, int chain, int midiKind)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceAdd(_handle, trackId, midiIndex, chain, midiKind); }++ public bool MidiRackChainDeviceRemove(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceRemove(_handle, trackId, midiIndex, chain, index) != 0; }++ public bool MidiRackChainDeviceMove(int trackId, int midiIndex, int chain, int fromIndex, int toIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceMove(_handle, trackId, midiIndex, chain, fromIndex, toIndex) != 0; }++ public int MidiRackChainDeviceKind(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceKind(_handle, trackId, midiIndex, chain, index); }++ public string MidiRackChainDeviceName(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiRackChainDeviceName(_handle, trackId, midiIndex, chain, index)) ?? ""; }++ public int MidiRackChainDeviceParamCount(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceParamCount(_handle, trackId, midiIndex, chain, index); }++ public string MidiRackChainDeviceParamName(int trackId, int midiIndex, int chain, int index, int param)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiRackChainDeviceParamName(_handle, trackId, midiIndex, chain, index, param)) ?? ""; }++ public float MidiRackChainDeviceParamMin(int trackId, int midiIndex, int chain, int index, int param)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceParamMin(_handle, trackId, midiIndex, chain, index, param); }++ public float MidiRackChainDeviceParamMax(int trackId, int midiIndex, int chain, int index, int param)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceParamMax(_handle, trackId, midiIndex, chain, index, param); }++ public float MidiRackChainDeviceParamGet(int trackId, int midiIndex, int chain, int index, int param)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceParamGet(_handle, trackId, midiIndex, chain, index, param); }++ public void MidiRackChainDeviceParamSet(int trackId, int midiIndex, int chain, int index, int param, float value)+ { ThrowIfDisposed(); NativeMethods.MidiRackChainDeviceParamSet(_handle, trackId, midiIndex, chain, index, param, value); }++ public void MidiRackChainDeviceSetBypassed(int trackId, int midiIndex, int chain, int index, bool bypassed)+ { ThrowIfDisposed(); NativeMethods.MidiRackChainDeviceSetBypassed(_handle, trackId, midiIndex, chain, index, bypassed ? 1 : 0); }++ public bool MidiRackChainDeviceBypassed(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceBypassed(_handle, trackId, midiIndex, chain, index) != 0; }++ public int MidiRackChainDeviceLastIn(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceLastIn(_handle, trackId, midiIndex, chain, index); }++ public int MidiRackChainDeviceLastOut(int trackId, int midiIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceLastOut(_handle, trackId, midiIndex, chain, index); }++ public int MidiRackChainDeviceScope(int trackId, int midiIndex, int chain, int index, float[] outv)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainDeviceScope(_handle, trackId, midiIndex, chain, index, outv, outv.Length); }++ public void MidiRackChainDeviceCommand(int trackId, int midiIndex, int chain, int index, int cmd)+ { ThrowIfDisposed(); NativeMethods.MidiRackChainDeviceCommand(_handle, trackId, midiIndex, chain, index, cmd); }++ public int MidiRackChainCount(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainCount(_handle, trackId, midiIndex); }++ public int MidiRackAddChain(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackAddChain(_handle, trackId, midiIndex); }++ public bool MidiRackRemoveChain(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackRemoveChain(_handle, trackId, midiIndex, chain) != 0; }++ public int MidiRackDuplicateChain(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackDuplicateChain(_handle, trackId, midiIndex, chain); }++ public bool MidiRackCheckpoint(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackCheckpoint(_handle, trackId, midiIndex) != 0; }++ public string MidiRackChainName(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiRackChainName(_handle, trackId, midiIndex, chain)) ?? ""; }++ public void MidiRackSetChainName(int trackId, int midiIndex, int chain, string name)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainName(_handle, trackId, midiIndex, chain, name ?? ""); }++ public void MidiRackSetChainMute(int trackId, int midiIndex, int chain, bool on)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainMute(_handle, trackId, midiIndex, chain, on ? 1 : 0); }++ public bool MidiRackChainMute(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainMute(_handle, trackId, midiIndex, chain) != 0; }++ public void MidiRackSetChainSolo(int trackId, int midiIndex, int chain, bool on)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainSolo(_handle, trackId, midiIndex, chain, on ? 1 : 0); }++ public bool MidiRackChainSolo(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainSolo(_handle, trackId, midiIndex, chain) != 0; }++ public void MidiRackSetChainZone(int trackId, int midiIndex, int chain, int keyLo, int keyHi, int velLo, int velHi)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainZone(_handle, trackId, midiIndex, chain, keyLo, keyHi, velLo, velHi); }++ public void MidiRackChainZone(int trackId, int midiIndex, int chain, out int keyLo, out int keyHi, out int velLo, out int velHi)+ { ThrowIfDisposed(); NativeMethods.MidiRackChainZone(_handle, trackId, midiIndex, chain, out keyLo, out keyHi, out velLo, out velHi); }++ public void MidiRackSetChainSelect(int trackId, int midiIndex, int chain, int lo, int hi)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainSelect(_handle, trackId, midiIndex, chain, lo, hi); }++ public void MidiRackChainSelectRange(int trackId, int midiIndex, int chain, out int lo, out int hi)+ { ThrowIfDisposed(); NativeMethods.MidiRackChainSelectRange(_handle, trackId, midiIndex, chain, out lo, out hi); }++ public void MidiRackSetChainTranspose(int trackId, int midiIndex, int chain, int semitones)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainTranspose(_handle, trackId, midiIndex, chain, semitones); }++ public int MidiRackChainTranspose(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainTranspose(_handle, trackId, midiIndex, chain); }++ public void MidiRackSetChainVelScale(int trackId, int midiIndex, int chain, float scale)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetChainVelScale(_handle, trackId, midiIndex, chain, scale); }++ public float MidiRackChainVelScale(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainVelScale(_handle, trackId, midiIndex, chain); }++ public float MidiRackChainActivity(int trackId, int midiIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.MidiRackChainActivity(_handle, trackId, midiIndex, chain); }++ public void MidiRackSetMode(int trackId, int midiIndex, int mode)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetMode(_handle, trackId, midiIndex, mode); }++ public int MidiRackMode(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackMode(_handle, trackId, midiIndex); }++ public void MidiRackSetSelector(int trackId, int midiIndex, float v)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetSelector(_handle, trackId, midiIndex, v); }++ public float MidiRackSelector(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackSelector(_handle, trackId, midiIndex); }++ public void MidiRackSetMerge(int trackId, int midiIndex, bool on)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetMerge(_handle, trackId, midiIndex, on ? 1 : 0); }++ public bool MidiRackMerge(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackMerge(_handle, trackId, midiIndex) != 0; }++ public void MidiRackSetThru(int trackId, int midiIndex, bool on)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetThru(_handle, trackId, midiIndex, on ? 1 : 0); }++ public bool MidiRackThru(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackThru(_handle, trackId, midiIndex) != 0; }++ public float MidiRackMacroGet(int trackId, int midiIndex, int macro)+ { ThrowIfDisposed(); return NativeMethods.MidiRackMacroGet(_handle, trackId, midiIndex, macro); }++ public void MidiRackMacroSet(int trackId, int midiIndex, int macro, float v)+ { ThrowIfDisposed(); NativeMethods.MidiRackMacroSet(_handle, trackId, midiIndex, macro, v); }++ public string MidiRackMacroName(int trackId, int midiIndex, int macro)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiRackMacroName(_handle, trackId, midiIndex, macro)) ?? ""; }++ public void MidiRackSetMacroName(int trackId, int midiIndex, int macro, string name)+ { ThrowIfDisposed(); NativeMethods.MidiRackSetMacroName(_handle, trackId, midiIndex, macro, name ?? ""); }++ public int MidiRackAddMacroMapping(int trackId, int midiIndex, int macro, int chain, int device, int param, float lo, float hi)+ { ThrowIfDisposed(); return NativeMethods.MidiRackAddMacroMapping(_handle, trackId, midiIndex, macro, chain, device, param, lo, hi); }++ public int MidiRackMappingCount(int trackId, int midiIndex)+ { ThrowIfDisposed(); return NativeMethods.MidiRackMappingCount(_handle, trackId, midiIndex); }++ public int MidiRackMappingInfo(int trackId, int midiIndex, int index, out int macro, out int chain, out int device, out int param, out float lo, out float hi, out int curve)+ { ThrowIfDisposed(); return NativeMethods.MidiRackMappingInfo(_handle, trackId, midiIndex, index, out macro, out chain, out device, out param, out lo, out hi, out curve); }++ public bool MidiRackRemoveMapping(int trackId, int midiIndex, int index)+ { ThrowIfDisposed(); return NativeMethods.MidiRackRemoveMapping(_handle, trackId, midiIndex, index) != 0; }++ public bool MidiRackSetMappingRange(int trackId, int midiIndex, int index, float lo, float hi)+ { ThrowIfDisposed(); return NativeMethods.MidiRackSetMappingRange(_handle, trackId, midiIndex, index, lo, hi) != 0; }++ public bool MidiRackSetMappingCurve(int trackId, int midiIndex, int index, int curve)+ { ThrowIfDisposed(); return NativeMethods.MidiRackSetMappingCurve(_handle, trackId, midiIndex, index, curve) != 0; }+}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.csindex 198ea28c..d47b2159 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs@@ -246,6 +246,17 @@ public sealed partial class NotaEnginepublic void RackSetVolume(int trackId, float v){ ThrowIfDisposed(); NativeMethods.RackSetVolume(_handle, trackId, v); }+ /// <summary>Copies a chain after itself (children, controls, its mappings); the new index or <0. One undo step.</summary>+ public int RackDuplicateChain(int trackId, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDuplicateChain(_handle, trackId, chain); }++ /// <summary>Instrument Rack mono: one note at a time, last-note priority; glide bends between notes.</summary>+ public bool RackMono(int trackId)+ { ThrowIfDisposed(); return NativeMethods.RackMono(_handle, trackId) != 0; }++ public void RackSetMono(int trackId, bool on)+ { ThrowIfDisposed(); NativeMethods.RackSetMono(_handle, trackId, on ? 1 : 0); }+public float RackGlide(int trackId){ ThrowIfDisposed(); return NativeMethods.RackGlide(_handle, trackId); }diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.csindex 093171e9..c62ffa95 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs@@ -192,6 +192,10 @@ public sealed partial class NotaEngine{ ThrowIfDisposed(); return NativeMethods.RackDevMode(_handle, trackId, deviceIndex); }public void RackDevSetMode(int trackId, int deviceIndex, int mode){ ThrowIfDisposed(); NativeMethods.RackDevSetMode(_handle, trackId, deviceIndex, mode); }++ /// <summary>Copies an Audio Effect Rack chain after itself (devices, controls, its mappings); the new index or <0.</summary>+ public int RackDevDuplicateChain(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevDuplicateChain(_handle, trackId, deviceIndex, chain); }public float RackDevDryWet(int trackId, int deviceIndex){ ThrowIfDisposed(); return NativeMethods.RackDevDryWet(_handle, trackId, deviceIndex); }public void RackDevSetDryWet(int trackId, int deviceIndex, float v)diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.csindex 76b53ef8..d941b3d9 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs@@ -18,10 +18,14 @@ public static class PresetServicepublic const string Extension = ".notapreset";private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = true };+ /// <summary>Capture addresses a track's MIDI effect i as MidiEffectBase − i.</summary>+ public const int MidiEffectBase = -1000;+/// <summary>Snapshot a track's device (deviceIndex < 0 = its instrument) into a preset./// Returns null if the target has nothing capturable (e.g. a built-in synth).</summary>public static PresetDocument? Capture(IAudioEngine engine, int trackId, int deviceIndex, string displayName){+ if (deviceIndex <= MidiEffectBase) return CaptureMidiEffect(engine, trackId, MidiEffectBase - deviceIndex, displayName);var doc = new PresetDocument { DisplayName = displayName, DeviceName = engine.DeviceName(trackId, deviceIndex) };if (deviceIndex < 0){@@ -78,6 +82,32 @@ public static class PresetServicereturn string.IsNullOrEmpty(doc.PluginId) ? null : doc;}+ /// <summary>Snapshot a MIDI effect: its params by name, and its state blob when it has one+ /// (the MIDI Effect Rack's chains, devices and macros, specs/040).</summary>+ public static PresetDocument? CaptureMidiEffect(IAudioEngine engine, int trackId, int index, string displayName)+ {+ int kind = engine.MidiEffectKind(trackId, index);+ if (kind < 0) return null;+ var doc = new PresetDocument+ {+ DisplayName = displayName, DeviceName = engine.MidiEffectName(trackId, index),+ Type = "builtin-midi-effect", BuiltinKind = kind,+ };+ int pc = engine.MidiEffectParamCount(trackId, index);+ doc.NamedParams = new Dictionary<string, float>(pc);+ for (int i = 0; i < pc; i++) doc.NamedParams[engine.MidiEffectParamName(trackId, index, i)] = engine.MidiEffectGetParam(trackId, index, i);+ var state = engine.MidiEffectGetState(trackId, index);+ if (state.Length > 0) doc.StateBase64 = Convert.ToBase64String(state);+ return doc;+ }++ private static void ApplyMidiState(IAudioEngine engine, int trackId, int index, string base64, bool checkpoint)+ {+ if (string.IsNullOrEmpty(base64)) return;+ try { engine.MidiEffectSetState(trackId, index, Convert.FromBase64String(base64), checkpoint); }+ catch (FormatException) { /* a damaged preset keeps the params it had */ }+ }+/// <summary>Snapshot a rack chain's instrument (only hosted plugins carry recallable/// state) into a preset. Returns null for built-in chain instruments.</summary>public static PresetDocument? CaptureRackChainInstrument(IAudioEngine engine, int trackId, int chain, string displayName)@@ -206,6 +236,7 @@ public static class PresetServiceif (doc.BuiltinKind == 3 && doc.NamedParams.ContainsKey("Rate") && !doc.NamedParams.ContainsKey("Division")) LengthLegacy(engine, targetTrackId, mi);if (doc.BuiltinKind == 4 && !doc.NamedParams.ContainsKey("Random On")) VelocityLegacy(engine, targetTrackId, mi);}+ ApplyMidiState(engine, targetTrackId, mi, doc.StateBase64, false);return "";}case "builtin-instrument":@@ -397,6 +428,7 @@ public static class PresetServiceif (engine.MidiEffectKind(trackId, deviceIndex) == 4 && !doc.NamedParams.ContainsKey("Random On"))VelocityLegacy(engine, trackId, deviceIndex);}+ ApplyMidiState(engine, trackId, deviceIndex, doc.StateBase64, true);return "";}case "plugin-effect":diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.csindex 31721858..4240df47 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs@@ -97,6 +97,9 @@ public static class ProjectMigrations// v22 -> v23: devices, MIDI effects and instruments gain Folded (drawn as a strip in// the Devices panel, specs/022). Absent in v22 documents; false = unfolded — no-op.new Migration(22, _ => { }),+ // v23 -> v24: MIDI effects gain State (the MIDI Effect Rack's blob, specs/040). Absent in+ // v23 documents, which hold no MIDI Effect Rack; null = params only — no-op.+ new Migration(23, _ => { }),};/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex 3a8af9ab..63db8b5e 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -350,6 +350,9 @@ public sealed class MidiDeviceDtopublic int CcDestDevice { get; set; } = -2; // -2 = no routingpublic int CcDestParam { get; set; } = -1;public float CcDepth { get; set; } = 1.0f;+ // Opaque state blob (v24, specs/040): the MIDI Effect Rack's chains, devices, zones and+ // macros. Null for params-only MIDI effects.+ public string? State { get; set; }[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex db6a67ad..0fb1b4cd 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -33,7 +33,7 @@ public sealed class ProjectService/// v18 (Phase 3) adds CV modulation: per-track LFO modulators + CV links to device params./// v22 (specs/020) adds MIDI controller curves on MIDI clips and Session slot clips./// v23 (specs/022) adds the Devices-panel fold on devices, MIDI effects and instruments.- public const int CurrentFormatVersion = 23;+ public const int CurrentFormatVersion = 24;/// <summary>Manifest file name inside the bundle folder.</summary>public const string ManifestName = "project.json";@@ -179,6 +179,8 @@ public sealed class ProjectServicemdev.CcDestDevice = engine.MidiEffectCcDestDevice(ti.Id, m);mdev.CcDestParam = engine.MidiEffectCcDestParam(ti.Id, m);mdev.CcDepth = engine.MidiEffectCcDepth(ti.Id, m);+ var mstate = engine.MidiEffectGetState(ti.Id, m); // the MIDI Effect Rack's structure+ if (mstate.Length > 0) mdev.State = RegisterBlob(doc, mstate);t.MidiEffects.Add(mdev);}@@ -628,6 +630,11 @@ public sealed class ProjectServiceif (m.Kind == 1 && m.Params.Length <= 16) PresetService.ChordLegacySwitches(engine, id, mi); // pre-switch Nota Chordif (m.Kind == 3 && m.Params.Length <= 11) PresetService.LengthLegacy(engine, id, mi); // pre-Division Nota Lengthif (m.Kind == 4 && m.Params.Length <= 7) PresetService.VelocityLegacy(engine, id, mi); // pre-switch Nota Velocity+ if (m.State is { } ms)+ {+ var blob = ReadBlob(bundleDir, ms);+ if (blob.Length > 0) engine.MidiEffectSetState(id, mi, blob, false);+ }if (m.Bypassed) engine.SetMidiEffectBypassed(id, mi, true);if (m.Folded) engine.SetMidiEffectFolded(id, mi, true);if (m.CcDestDevice >= 0 && m.CcDestParam >= 0)diff --git a/src/managed/Nota.Mcp/Tools/EffectRackTools.cs b/src/managed/Nota.Mcp/Tools/EffectRackTools.csindex 8e0ffa17..0290a638 100644--- a/src/managed/Nota.Mcp/Tools/EffectRackTools.cs+++ b/src/managed/Nota.Mcp/Tools/EffectRackTools.cs@@ -20,8 +20,8 @@ public sealed class EffectRackTools(IAudioEngine engine, IEngineDispatch dispatcfloat Gain, float Pan, bool Mute, bool Solo, int DeviceCount);public sealed record RackSnapshot(int Mode, string ModeName, float DryWet, float Volume, float ChainSelect, ChainInfo[] Chains);public sealed record Param(int Index, string Name, float Value);- public sealed record MacroInfo(int Index, string Name, float Value);- public sealed record Mapping(int Index, int Macro, int Chain, int DeviceIndex, int ParamIndex, float RangeMin, float RangeMax);+ public sealed record MacroInfo(int Index, string Name, float Value, string Curve, int Targets);+ public sealed record Mapping(int Index, int Macro, int Chain, int DeviceIndex, int ParamIndex, float RangeMin, float RangeMax, string Curve);private static string ModeName(int m) => m switch { 1 => "series", 2 => "select", _ => "parallel" };@@ -92,7 +92,13 @@ public sealed class EffectRackTools(IAudioEngine engine, IEngineDispatch dispatcpublic Task<MacroInfo[]> GetEffectRackMacros(int trackId, int deviceIndex) => Read(() =>{var ms = new MacroInfo[8];- for (int i = 0; i < 8; i++) ms[i] = new MacroInfo(i, E.RackDevMacroName(trackId, deviceIndex, i), E.RackDevMacroGet(trackId, deviceIndex, i));+ int n = E.RackDevMappingCount(trackId, deviceIndex);+ (bool, int, int) Map(int i) => E.RackDevTryGetMapping(trackId, deviceIndex, i, out var m) ? (true, m.Macro, E.RackDevMappingCurve(trackId, deviceIndex, i)) : (false, 0, 0);+ for (int i = 0; i < 8; i++)+ {+ var (curve, targets) = RackTools.MacroCurve(n, Map, i);+ ms[i] = new MacroInfo(i, E.RackDevMacroName(trackId, deviceIndex, i), E.RackDevMacroGet(trackId, deviceIndex, i), curve, targets);+ }return ms;});@@ -107,16 +113,21 @@ public sealed class EffectRackTools(IAudioEngine engine, IEngineDispatch dispatcvar list = new List<Mapping>(n);for (int i = 0; i < n; i++)if (E.RackDevTryGetMapping(trackId, deviceIndex, i, out var m))- list.Add(new Mapping(i, m.Macro, m.Chain, m.DeviceIndex, m.ParamIndex, m.RangeMin, m.RangeMax));+ list.Add(new Mapping(i, m.Macro, m.Chain, m.DeviceIndex, m.ParamIndex, m.RangeMin, m.RangeMax, RackTools.CurveName(E.RackDevMappingCurve(trackId, deviceIndex, i))));return list.ToArray();});[McpServerTool(Name = "add_effect_rack_mapping"), Description(- "Map a macro (0..7) onto a chain parameter. targetDevice = the chain's device index (or -1 for its source instrument); "- + "range is the param's normalized 0..1 span the macro sweeps. Returns the mapping index.")]+ "Map a macro (0..7) onto a chain parameter. targetDevice = the chain's device index (or -1 for its source instrument), "+ + "or -3 for the Select-mode selector (paramIndex 0, range 0..1; chain is ignored). range is the span the macro sweeps, "+ + "in the target's units; min above max inverts. A parameter belongs to one macro: mapping it again moves its mapping. "+ + "Returns the mapping index.")]public Task<int> AddEffectRackMapping(int trackId, int deviceIndex, int macro, int chain, int targetDevice, int paramIndex, float rangeMin = 0f, float rangeMax = 1f)=> Mutate(() => E.RackDevAddMacroMapping(trackId, deviceIndex, macro, chain, targetDevice, paramIndex, rangeMin, rangeMax));+ [McpServerTool(Name = "duplicate_effect_rack_chain"), Description("Copy a chain right after itself: its devices, select range, mix and its macro mappings. Returns the new chain index.")]+ public Task<int> DuplicateEffectRackChain(int trackId, int deviceIndex, int chain) => Mutate(() => E.RackDevDuplicateChain(trackId, deviceIndex, chain));+[McpServerTool(Name = "remove_effect_rack_mapping"), Description("Remove a macro mapping by index.")]public Task<bool> RemoveEffectRackMapping(int trackId, int deviceIndex, int index) => Mutate(() => E.RackDevRemoveMapping(trackId, deviceIndex, index));}diff --git a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs b/src/managed/Nota.Mcp/Tools/MidiFxTools.csindex ed9a3a74..a04aa008 100644--- a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs+++ b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs@@ -15,7 +15,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I{private static readonly (int Kind, string Name)[] Kinds ={- (0, "Nota Arp"), (1, "Nota Chord"), (2, "Nota Scale"), (3, "Nota Length"), (4, "Nota Velocity"), (5, "Nota Random"),+ (0, "Nota Arp"), (1, "Nota Chord"), (2, "Nota Scale"), (3, "Nota Length"), (4, "Nota Velocity"), (5, "Nota Random"), (6, "Nota MIDI Effect Rack"),};public sealed record MidiFxKind(int Kind, string Name);@@ -34,7 +34,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, Ireturn arr;});- [McpServerTool(Name = "add_midi_fx"), Description("Add a built-in MIDI effect (see list_midi_fx_kinds) before the instrument. Returns the index (or -1).")]+ [McpServerTool(Name = "add_midi_fx"), Description("Add a built-in MIDI effect (see list_midi_fx_kinds) before the instrument; kind 6 is the MIDI Effect Rack (see get_midi_rack). Returns the index (or -1).")]public Task<int> AddMidiFx(int trackId, int kind) => Mutate(() => E.AddMidiEffect(trackId, kind));[McpServerTool(Name = "remove_midi_fx"), Description("Remove a MIDI effect from a track by index.")]diff --git a/src/managed/Nota.Mcp/Tools/MidiRackTools.cs b/src/managed/Nota.Mcp/Tools/MidiRackTools.csnew file mode 100644index 00000000..5e8b990f--- /dev/null+++ b/src/managed/Nota.Mcp/Tools/MidiRackTools.cs@@ -0,0 +1,225 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MCP tools — the MIDI Effect Rack (MIDI effect kind 6, specs/040): chains of built-in MIDI+// effects that take notes by key, velocity and (Select mode) select zone, each with transpose+// and a velocity-scaling volume, merged into the track's notes before the instrument.+// Every tool targets the rack at `midiIndex` among the track's MIDI effects (list_midi_fx).+// Chains, devices and macros are 0-based. Writes are one undo step each.++using System.ComponentModel;+using System.Globalization;+using ModelContextProtocol.Server;+using Nota.Application;++namespace Nota.Mcp.Tools;++[McpServerToolType]+public sealed class MidiRackTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh)+ : EngineTools(engine, dispatch, refresh)+{+ public sealed record Device(int Index, int Kind, string Name, bool Bypassed);+ public sealed record Chain(int Index, string Name, bool Mute, bool Solo, int KeyLo, int KeyHi, int VelLo, int VelHi,+ int SelLo, int SelHi, int Transpose, float VelScale, Device[] Devices);+ public sealed record Rack(string Mode, int Selector, bool Merge, bool Thru, Chain[] Chains);+ public sealed record Param(int Index, string Name, float Min, float Max, float Value);+ public sealed record Macro(int Index, string Name, float Value, string Curve, int Targets);+ public sealed record Mapping(int Index, int Macro, int Chain, int Device, int Param, float Min, float Max, string Curve);++ private static readonly string[] Names = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];++ // A key as a MIDI note number or a name ("C3", "F#4", "Bb2"; C4 = 60).+ private static int Note(string s)+ {+ s = s.Trim();+ if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) return Math.Clamp(n, 0, 127);+ int i = 1;+ int pc = Array.IndexOf(Names, char.ToUpperInvariant(s[0]).ToString());+ if (pc < 0) throw new ArgumentException($"Not a note: {s}");+ if (s.Length > 1 && s[1] == '#') { pc++; i = 2; }+ else if (s.Length > 1 && (s[1] == 'b' || s[1] == '♭')) { pc--; i = 2; }+ int oct = int.Parse(s[i..].Replace('−', '-'), NumberStyles.Integer, CultureInfo.InvariantCulture);+ return Math.Clamp((oct + 1) * 12 + pc, 0, 127);+ }++ [McpServerTool(Name = "get_midi_rack"), Description(+ "Snapshot of a MIDI Effect Rack: mode (parallel | select), selector 0..127, merge duplicate notes, pass through "+ + "notes outside every zone, and every chain (name, mute, solo, key zone, velocity zone, select range, transpose, "+ + "velocity scale 0..2 and its MIDI effects).")]+ public Task<Rack> GetMidiRack(int trackId, int midiIndex) => Read(() =>+ {+ int n = E.MidiRackChainCount(trackId, midiIndex);+ var chains = new Chain[n];+ for (int c = 0; c < n; c++)+ {+ E.MidiRackChainZone(trackId, midiIndex, c, out int kl, out int kh, out int vl, out int vh);+ E.MidiRackChainSelectRange(trackId, midiIndex, c, out int sl, out int sh);+ int dn = E.MidiRackChainDeviceCount(trackId, midiIndex, c);+ var devs = new Device[dn];+ for (int d = 0; d < dn; d++)+ devs[d] = new Device(d, E.MidiRackChainDeviceKind(trackId, midiIndex, c, d), E.MidiRackChainDeviceName(trackId, midiIndex, c, d),+ E.MidiRackChainDeviceBypassed(trackId, midiIndex, c, d));+ chains[c] = new Chain(c, E.MidiRackChainName(trackId, midiIndex, c), E.MidiRackChainMute(trackId, midiIndex, c),+ E.MidiRackChainSolo(trackId, midiIndex, c), kl, kh, vl, vh, sl, sh, E.MidiRackChainTranspose(trackId, midiIndex, c),+ E.MidiRackChainVelScale(trackId, midiIndex, c), devs);+ }+ return new Rack(E.MidiRackMode(trackId, midiIndex) == 2 ? "select" : "parallel", (int)Math.Round(E.MidiRackSelector(trackId, midiIndex) * 127),+ E.MidiRackMerge(trackId, midiIndex), E.MidiRackThru(trackId, midiIndex), chains);+ });++ [McpServerTool(Name = "add_midi_rack_chain"), Description("Add an empty chain (up to 16). Returns its index, or -1 at the limit.")]+ public Task<int> AddChain(int trackId, int midiIndex, string? name = null) => Mutate(() =>+ {+ int c = E.MidiRackAddChain(trackId, midiIndex);+ if (c >= 0 && !string.IsNullOrEmpty(name)) E.MidiRackSetChainName(trackId, midiIndex, c, name);+ return c;+ });++ [McpServerTool(Name = "remove_midi_rack_chain"), Description("Remove a chain (a rack keeps at least one); its macro mappings go with it.")]+ public Task<bool> RemoveChain(int trackId, int midiIndex, int chain) => Mutate(() => E.MidiRackRemoveChain(trackId, midiIndex, chain));++ [McpServerTool(Name = "duplicate_midi_rack_chain"), Description("Copy a chain right after itself, with its MIDI effects, zones and mappings. Returns the new index.")]+ public Task<int> DuplicateChain(int trackId, int midiIndex, int chain) => Mutate(() => E.MidiRackDuplicateChain(trackId, midiIndex, chain));++ [McpServerTool(Name = "set_midi_rack_chain_name"), Description("Rename a chain.")]+ public Task SetChainName(int trackId, int midiIndex, int chain, string name) => Mutate(() => E.MidiRackSetChainName(trackId, midiIndex, chain, name));++ [McpServerTool(Name = "add_midi_rack_chain_device"), Description("Append a built-in MIDI effect (kind 0..5, see list_midi_fx_kinds) to a chain. Returns its index.")]+ public Task<int> AddChainDevice(int trackId, int midiIndex, int chain, int kind) => Mutate(() => E.MidiRackChainDeviceAdd(trackId, midiIndex, chain, kind));++ [McpServerTool(Name = "remove_midi_rack_chain_device"), Description("Remove a MIDI effect from a chain.")]+ public Task<bool> RemoveChainDevice(int trackId, int midiIndex, int chain, int device) => Mutate(() => E.MidiRackChainDeviceRemove(trackId, midiIndex, chain, device));++ [McpServerTool(Name = "move_midi_rack_chain_device"), Description("Move a MIDI effect within its chain.")]+ public Task<bool> MoveChainDevice(int trackId, int midiIndex, int chain, int from, int to) => Mutate(() => E.MidiRackChainDeviceMove(trackId, midiIndex, chain, from, to));++ [McpServerTool(Name = "get_midi_rack_chain_params"), Description("List a chain MIDI effect's parameters (index, name, min, max, value).")]+ public Task<Param[]> GetChainParams(int trackId, int midiIndex, int chain, int device) => Read(() =>+ {+ int pc = E.MidiRackChainDeviceParamCount(trackId, midiIndex, chain, device);+ var ps = new Param[pc];+ for (int p = 0; p < pc; p++)+ ps[p] = new Param(p, E.MidiRackChainDeviceParamName(trackId, midiIndex, chain, device, p), E.MidiRackChainDeviceParamMin(trackId, midiIndex, chain, device, p),+ E.MidiRackChainDeviceParamMax(trackId, midiIndex, chain, device, p), E.MidiRackChainDeviceParamGet(trackId, midiIndex, chain, device, p));+ return ps;+ });++ [McpServerTool(Name = "set_midi_rack_chain_param"), Description("Set a chain MIDI effect's parameter (in its own min..max).")]+ public Task SetChainParam(int trackId, int midiIndex, int chain, int device, int param, float value)+ => Mutate(() => ChildInPlace(trackId, midiIndex, () => E.MidiRackChainDeviceParamSet(trackId, midiIndex, chain, device, param, value)));++ [McpServerTool(Name = "set_midi_rack_chain_bypass"), Description("Bypass or enable a chain MIDI effect.")]+ public Task SetChainBypass(int trackId, int midiIndex, int chain, int device, bool bypassed)+ => Mutate(() => ChildInPlace(trackId, midiIndex, () => E.MidiRackChainDeviceSetBypassed(trackId, midiIndex, chain, device, bypassed)));++ [McpServerTool(Name = "set_midi_rack_chain_mix"), Description("Set a chain's mute, solo, transpose (−48..+48 semitones) and velocity scale (\"Volume\", 0..2: 1 = unchanged, 0 = silent). Omitted fields stay.")]+ public Task SetChainMix(int trackId, int midiIndex, int chain, bool? mute = null, bool? solo = null, int? transpose = null, float? velScale = null) => Mutate(() => InPlace(trackId, midiIndex, () =>+ {+ if (mute is { } m) E.MidiRackSetChainMute(trackId, midiIndex, chain, m);+ if (solo is { } s) E.MidiRackSetChainSolo(trackId, midiIndex, chain, s);+ if (transpose is { } tr) E.MidiRackSetChainTranspose(trackId, midiIndex, chain, tr);+ if (velScale is { } v) E.MidiRackSetChainVelScale(trackId, midiIndex, chain, v);+ }));++ [McpServerTool(Name = "set_midi_rack_chain_zone"), Description(+ "Set a chain's zones; omitted ends stay. Keys take note numbers or names (\"C3\", \"F#4\"; C4 = 60); velocity and "+ + "select ranges are 0..127. In Select mode a chain plays while the selector is inside its select range.")]+ public Task SetChainZone(int trackId, int midiIndex, int chain, string? keyLo = null, string? keyHi = null,+ int? velLo = null, int? velHi = null, int? selLo = null, int? selHi = null) => Mutate(() => InPlace(trackId, midiIndex, () =>+ {+ E.MidiRackChainZone(trackId, midiIndex, chain, out int kl, out int kh, out int vl, out int vh);+ if (keyLo is not null) kl = Note(keyLo);+ if (keyHi is not null) kh = Note(keyHi);+ E.MidiRackSetChainZone(trackId, midiIndex, chain, kl, kh, velLo ?? vl, velHi ?? vh);+ E.MidiRackChainSelectRange(trackId, midiIndex, chain, out int sl, out int sh);+ if (selLo is not null || selHi is not null) E.MidiRackSetChainSelect(trackId, midiIndex, chain, selLo ?? sl, selHi ?? sh);+ }));++ [McpServerTool(Name = "set_midi_rack_mode"), Description("How chains run: parallel (every chain whose zone a note hits) or select (only chains whose select range holds the selector).")]+ public Task SetMode(int trackId, int midiIndex, [Description("parallel | select")] string mode)+ => Mutate(() => InPlace(trackId, midiIndex, () => E.MidiRackSetMode(trackId, midiIndex, mode.Trim().Equals("select", StringComparison.OrdinalIgnoreCase) ? 2 : 0)));++ [McpServerTool(Name = "set_midi_rack_selector"), Description("Set the Select-mode selector, 0..127.")]+ public Task SetSelector(int trackId, int midiIndex, int value)+ => Mutate(() => InPlace(trackId, midiIndex, () => E.MidiRackSetSelector(trackId, midiIndex, Math.Clamp(value, 0, 127) / 127f)));++ [McpServerTool(Name = "set_midi_rack_output"), Description("Merge duplicate notes from different chains into one; pass notes no chain takes through unchanged. Omitted fields stay.")]+ public Task SetOutput(int trackId, int midiIndex, bool? merge = null, bool? thru = null) => Mutate(() => InPlace(trackId, midiIndex, () =>+ {+ if (merge is { } m) E.MidiRackSetMerge(trackId, midiIndex, m);+ if (thru is { } t) E.MidiRackSetThru(trackId, midiIndex, t);+ }));++ [McpServerTool(Name = "get_midi_rack_macros"), Description("The rack's 8 macros: name, value 0..1, curve (lin/exp/log/s, \"mixed\" when targets differ, \"none\" without targets) and target count.")]+ public Task<Macro[]> GetMacros(int trackId, int midiIndex) => Read(() =>+ {+ int n = E.MidiRackMappingCount(trackId, midiIndex);+ (bool, int, int) Map(int i) => E.MidiRackMappingInfo(trackId, midiIndex, i, out int m, out _, out _, out _, out _, out _, out int cv) != 0 ? (true, m, cv) : (false, 0, 0);+ var ms = new Macro[8];+ for (int i = 0; i < 8; i++)+ {+ var (curve, targets) = RackTools.MacroCurve(n, Map, i);+ ms[i] = new Macro(i, E.MidiRackMacroName(trackId, midiIndex, i), E.MidiRackMacroGet(trackId, midiIndex, i), curve, targets);+ }+ return ms;+ });++ [McpServerTool(Name = "set_midi_rack_macro"), Description("Set a macro's value (0..1) and/or name.")]+ public Task SetMacro(int trackId, int midiIndex, int macro, float? value = null, string? name = null) => Mutate(() => InPlace(trackId, midiIndex, () =>+ {+ if (value is { } v) E.MidiRackMacroSet(trackId, midiIndex, macro, Math.Clamp(v, 0f, 1f));+ if (name is not null) E.MidiRackSetMacroName(trackId, midiIndex, macro, name);+ }));++ [McpServerTool(Name = "list_midi_rack_mappings"), Description("The rack's macro mappings (index, macro, chain, device — or -3 for the selector — param, range, curve).")]+ public Task<Mapping[]> ListMappings(int trackId, int midiIndex) => Read(() =>+ {+ int n = E.MidiRackMappingCount(trackId, midiIndex);+ var list = new List<Mapping>(n);+ for (int i = 0; i < n; i++)+ if (E.MidiRackMappingInfo(trackId, midiIndex, i, out int m, out int c, out int d, out int p, out float lo, out float hi, out int cv) != 0)+ list.Add(new Mapping(i, m, c, d, p, lo, hi, RackTools.CurveName(cv)));+ return list.ToArray();+ });++ [McpServerTool(Name = "add_midi_rack_mapping"), Description(+ "Map a macro (0..7) onto a chain MIDI effect's parameter (device = its index in the chain) or onto the selector "+ + "(device -3, param 0, range 0..1). Range is in the parameter's units; min above max inverts. A parameter belongs "+ + "to one macro: mapping it again moves its mapping. Returns the mapping index.")]+ public Task<int> AddMapping(int trackId, int midiIndex, int macro, int chain, int device, int param, float min = 0f, float max = 1f)+ => Mutate(() => E.MidiRackAddMacroMapping(trackId, midiIndex, macro, chain, device, param, min, max));++ [McpServerTool(Name = "remove_midi_rack_mapping"), Description("Remove a macro mapping by index.")]+ public Task<bool> RemoveMapping(int trackId, int midiIndex, int index) => Mutate(() => E.MidiRackRemoveMapping(trackId, midiIndex, index));++ [McpServerTool(Name = "set_midi_rack_mapping"), Description("Change a mapping's range (in the parameter's units) and/or curve (lin | exp | log | s).")]+ public Task SetMapping(int trackId, int midiIndex, int index, float? min = null, float? max = null, string? curve = null) => Mutate(() =>+ {+ if (min is not null || max is not null)+ {+ E.MidiRackMappingInfo(trackId, midiIndex, index, out _, out _, out _, out _, out float lo, out float hi, out _);+ E.MidiRackSetMappingRange(trackId, midiIndex, index, min ?? lo, max ?? hi);+ }+ if (curve is not null) E.MidiRackSetMappingCurve(trackId, midiIndex, index, RackTools.CurveId(curve));+ });++ // An edit the engine applies to the rack in place (a chain's mix, the mode, the selector, a+ // macro's value) as one undo step: the rack is forked first — sharing its MIDI effects, so+ // held notes play on — and the edit lands on the fork, so Undo brings back the rack as it was.+ // Inside the tool's Mutate group, so a call is still one step.+ private void InPlace(int trackId, int midiIndex, Action edit)+ {+ E.MidiRackCheckpoint(trackId, midiIndex);+ edit();+ }++ // A chain MIDI effect's own value (a parameter, its bypass) lives in the effect, which a fork+ // shares, so the step needs copies of the effects: an undoable write of the rack's own state+ // swaps them in. That ends the rack's held notes, as any change of its effects does.+ private void ChildInPlace(int trackId, int midiIndex, Action edit)+ {+ var before = E.MidiEffectGetState(trackId, midiIndex);+ if (before.Length > 0) E.MidiEffectSetState(trackId, midiIndex, before, checkpoint: true);+ edit();+ }+}diff --git a/src/managed/Nota.Mcp/Tools/RackTools.cs b/src/managed/Nota.Mcp/Tools/RackTools.csindex c4063b4e..c2ad3334 100644--- a/src/managed/Nota.Mcp/Tools/RackTools.cs+++ b/src/managed/Nota.Mcp/Tools/RackTools.cs@@ -20,10 +20,29 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr{public sealed record ChainInfo(int Index, int InstrumentKind, string InstrumentName, int TriggerNote,float Gain, float Pan, bool Mute, bool Solo, int DeviceCount, string Name);- public sealed record RackSnapshot(float Volume, ChainInfo[] Chains);+ public sealed record RackSnapshot(float Volume, ChainInfo[] Chains, bool Mono, float Glide);public sealed record Param(int Index, string Id, string Name, float Value);- public sealed record MacroInfo(int Index, string Name, float Value);- public sealed record Mapping(int Index, int Macro, int Chain, int DeviceIndex, int ParamIndex, float RangeMin, float RangeMax);+ public sealed record MacroInfo(int Index, string Name, float Value, string Curve, int Targets);+ public sealed record Mapping(int Index, int Macro, int Chain, int DeviceIndex, int ParamIndex, float RangeMin, float RangeMax, string Curve);++ private static readonly string[] CurveNames = ["lin", "exp", "log", "s"];+ internal static string CurveName(int curve) => curve >= 0 && curve < CurveNames.Length ? CurveNames[curve] : "lin";+ internal static int CurveId(string curve) => Math.Max(0, Array.IndexOf(CurveNames, curve.Trim().ToLowerInvariant()));++ // A macro's curve as the card shows it: its targets' common curve, "mixed" when they differ, "none" without targets.+ internal static (string Curve, int Targets) MacroCurve(int count, Func<int, (bool Ok, int Macro, int Curve)> mapping, int macro)+ {+ int curve = -1, n = 0;+ bool mixed = false;+ for (int i = 0; i < count; i++)+ {+ var (ok, m, c) = mapping(i);+ if (!ok || m != macro) continue;+ n++;+ if (curve < 0) curve = c; else if (curve != c) mixed = true;+ }+ return (n == 0 ? "none" : mixed ? "mixed" : CurveName(curve), n);+ }// ---- snapshot ---------------------------------------------------------@@ -39,7 +58,7 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IArE.RackChainTriggerNote(trackId, c), E.RackChainGain(trackId, c), E.RackChainPan(trackId, c),E.RackChainMute(trackId, c), E.RackChainSolo(trackId, c), E.RackChainDeviceCount(trackId, c),E.RackChainName(trackId, c));- return new RackSnapshot(E.RackVolume(trackId), chains);+ return new RackSnapshot(E.RackVolume(trackId), chains, E.RackMono(trackId), E.RackGlide(trackId));});// ---- chains -----------------------------------------------------------@@ -48,6 +67,9 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IArpublic Task<int> AddRackChain(int trackId, [Description("Instrument kind id, e.g. 6=Volt, 2=Physical, 5=Aurora")] int instrumentKind)=> Mutate(() => E.RackAddChain(trackId, instrumentKind));+ [McpServerTool(Name = "duplicate_rack_chain"), Description("Copy a chain right after itself: its instrument, devices, zone, mix and its macro mappings. Returns the new chain index.")]+ public Task<int> DuplicateRackChain(int trackId, int chain) => Mutate(() => E.RackDuplicateChain(trackId, chain));+[McpServerTool(Name = "remove_rack_chain"), Description("Remove a chain from the rack by index.")]public Task<bool> RemoveRackChain(int trackId, int chain) => Mutate(() => E.RackRemoveChain(trackId, chain));@@ -97,11 +119,17 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr// ---- macros ------------------------------------------------------------ [McpServerTool(Name = "get_macros"), Description("List the rack's 8 macro knobs (index, name, value 0..1).")]+ [McpServerTool(Name = "get_macros"), Description("List the rack's 8 macro knobs (index, name, value 0..1, response curve — lin/exp/log/s, \"mixed\" when its targets differ, \"none\" without targets — and target count).")]public Task<MacroInfo[]> GetMacros(int trackId) => Read(() =>{var ms = new MacroInfo[8];- for (int i = 0; i < 8; i++) ms[i] = new MacroInfo(i, E.RackMacroName(trackId, i), E.RackMacroGet(trackId, i));+ int n = E.RackMappingCount(trackId);+ (bool, int, int) Map(int i) => E.RackTryGetMapping(trackId, i, out var m) ? (true, m.Macro, E.RackMappingCurve(trackId, i)) : (false, 0, 0);+ for (int i = 0; i < 8; i++)+ {+ var (curve, targets) = MacroCurve(n, Map, i);+ ms[i] = new MacroInfo(i, E.RackMacroName(trackId, i), E.RackMacroGet(trackId, i), curve, targets);+ }return ms;});@@ -119,17 +147,53 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IArvar list = new List<Mapping>(n);for (int i = 0; i < n; i++)if (E.RackTryGetMapping(trackId, i, out var m))- list.Add(new Mapping(i, m.Macro, m.Chain, m.DeviceIndex, m.ParamIndex, m.RangeMin, m.RangeMax));+ list.Add(new Mapping(i, m.Macro, m.Chain, m.DeviceIndex, m.ParamIndex, m.RangeMin, m.RangeMax, CurveName(E.RackMappingCurve(trackId, i))));return list.ToArray();});[McpServerTool(Name = "add_macro_mapping"), Description("Map a macro (0..7) onto a parameter. deviceIndex = -1 targets the chain instrument, -2 the chain's own controls "+ "(a Drum Rack pad: paramIndex 0 Volume (linear gain), 1 Pan (-1..1), 2 Tune (semitones), 3 Decay (0..1, 1 = hold)), "- + "else the chain's device index (a built-in effect on the pad; range in the device's units). range is the span the "- + "macro sweeps, in the target's units (0..1 for an instrument param). Returns mapping index.")]+ + "-1000 - j the chain's MIDI effect j (#329), else the chain's device index (a built-in effect; range in the device's units). range is the span the "+ + "macro sweeps, in the target's units (0..1 for an instrument param); min above max inverts. A parameter belongs to "+ + "one macro: mapping it again moves its mapping (range and curve kept). A new target takes the macro's curve. "+ + "Returns mapping index.")]public Task<int> AddMacroMapping(int trackId, int macro, int chain, int deviceIndex, int paramIndex, float rangeMin = 0f, float rangeMax = 1f)- => Mutate(() => E.RackAddMacroMapping(trackId, macro, chain, deviceIndex, paramIndex, rangeMin, rangeMax));+ => Mutate(() =>+ {+ bool known = false;+ for (int i = 0; i < E.RackMappingCount(trackId); i++)+ if (E.RackTryGetMapping(trackId, i, out var m) && m.Chain == chain && m.DeviceIndex == deviceIndex && m.ParamIndex == paramIndex) known = true;+ var (curve, _) = MacroCurve(E.RackMappingCount(trackId), i => E.RackTryGetMapping(trackId, i, out var m) ? (true, m.Macro, E.RackMappingCurve(trackId, i)) : (false, 0, 0), macro);+ int idx = E.RackAddMacroMapping(trackId, macro, chain, deviceIndex, paramIndex, rangeMin, rangeMax);+ if (idx >= 0 && !known && curve is not ("none" or "mixed" or "lin")) E.RackSetMappingCurve(trackId, idx, CurveId(curve));+ return idx;+ });++ [McpServerTool(Name = "set_macro_curve"), Description(+ "Set a macro's response curve (lin | exp | log | s) on every one of its targets, as one undo step. "+ + "deviceIndex -1 = the track's Instrument Rack, else the Audio Effect Rack at that device index.")]+ public Task<int> SetMacroCurve(int trackId, int macro, [Description("lin | exp | log | s")] string curve, int deviceIndex = -1) => Mutate(() =>+ {+ int id = CurveId(curve), n = 0;+ bool rack = deviceIndex < 0;+ int count = rack ? E.RackMappingCount(trackId) : E.RackDevMappingCount(trackId, deviceIndex);+ for (int i = 0; i < count; i++)+ {+ RackMacroMapping m;+ bool ok = rack ? E.RackTryGetMapping(trackId, i, out m) : E.RackDevTryGetMapping(trackId, deviceIndex, i, out m);+ if (!ok || m.Macro != macro) continue;+ if (rack) E.RackSetMappingCurve(trackId, i, id); else E.RackDevSetMappingCurve(trackId, deviceIndex, i, id);+ n++;+ }+ return n;+ });++ [McpServerTool(Name = "set_mapping_range"), Description(+ "Set a macro mapping's range in the target's units (min above max inverts). "+ + "deviceIndex -1 = the track's Instrument Rack, else the Audio Effect Rack at that device index.")]+ public Task<bool> SetMappingRange(int trackId, int index, float rangeMin, float rangeMax, int deviceIndex = -1)+ => Mutate(() => deviceIndex < 0 ? E.RackSetMappingRange(trackId, index, rangeMin, rangeMax) : E.RackDevSetMappingRange(trackId, deviceIndex, index, rangeMin, rangeMax));[McpServerTool(Name = "remove_macro_mapping"), Description("Remove a macro mapping by index.")]public Task<bool> RemoveMacroMapping(int trackId, int index) => Mutate(() => E.RackRemoveMapping(trackId, index));@@ -139,11 +203,56 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr[McpServerTool(Name = "set_rack_volume"), Description("Set the rack's overall output volume (0..1 linear).")]public Task SetRackVolume(int trackId, float value) => Mutate(() => E.RackSetVolume(trackId, Math.Clamp(value, 0f, 1f)));- [McpServerTool(Name = "set_rack_glide"), Description("Set the rack glide/portamento amount (0..1).")]+ [McpServerTool(Name = "set_rack_glide"), Description("Set the rack glide (0..1 = 0..500 ms). Audible with mono on: each new note bends from the previous pitch on chain instruments that take per-note bend.")]public Task SetRackGlide(int trackId, float value) => Mutate(() => E.RackSetGlide(trackId, Math.Clamp(value, 0f, 1f)));// ---- Drum Rack extras -------------------------------------------------+ // ---- chain MIDI effects (issue #329) -------------------------------------++ public sealed record ChainMidiFx(int Index, int Kind, string Name, bool Bypassed);+ public sealed record MidiParam(int Index, string Name, float Min, float Max, float Value);++ [McpServerTool(Name = "list_rack_chain_midi_fx"), Description("List the MIDI effects in front of a chain's instrument (index, kind, name, bypass). They run in order on the notes the chain's zone takes.")]+ public Task<ChainMidiFx[]> ListChainMidiFx(int trackId, int chain) => Read(() =>+ {+ int n = E.RackChainMidiCount(trackId, chain);+ var a = new ChainMidiFx[n];+ for (int i = 0; i < n; i++) a[i] = new ChainMidiFx(i, E.RackChainMidiKind(trackId, chain, i), E.RackChainMidiName(trackId, chain, i), E.RackChainMidiBypassed(trackId, chain, i));+ return a;+ });++ [McpServerTool(Name = "add_rack_chain_midi_fx"), Description("Add a built-in MIDI effect (kind 0..5, see list_midi_fx_kinds) in front of a chain's instrument. Returns its index in the chain's MIDI section.")]+ public Task<int> AddChainMidiFx(int trackId, int chain, int kind) => Mutate(() => E.RackChainMidiAdd(trackId, chain, kind));++ [McpServerTool(Name = "remove_rack_chain_midi_fx"), Description("Remove a MIDI effect from a chain; its macro mappings go with it.")]+ public Task<bool> RemoveChainMidiFx(int trackId, int chain, int index) => Mutate(() => E.RackChainMidiRemove(trackId, chain, index));++ [McpServerTool(Name = "move_rack_chain_midi_fx"), Description("Move a MIDI effect within its chain's MIDI section.")]+ public Task<bool> MoveChainMidiFx(int trackId, int chain, int from, int to) => Mutate(() => E.RackChainMidiMove(trackId, chain, from, to));++ [McpServerTool(Name = "get_rack_chain_midi_fx_params"), Description("List a chain MIDI effect's parameters (index, name, min, max, value).")]+ public Task<MidiParam[]> GetChainMidiFxParams(int trackId, int chain, int index) => Read(() =>+ {+ int pc = E.RackChainMidiParamCount(trackId, chain, index);+ var ps = new MidiParam[pc];+ for (int p = 0; p < pc; p++)+ ps[p] = new MidiParam(p, E.RackChainMidiParamName(trackId, chain, index, p), E.RackChainMidiParamMin(trackId, chain, index, p),+ E.RackChainMidiParamMax(trackId, chain, index, p), E.RackChainMidiParamGet(trackId, chain, index, p));+ return ps;+ });++ [McpServerTool(Name = "set_rack_chain_midi_fx_param"), Description("Set a chain MIDI effect's parameter (in its own min..max).")]+ public Task SetChainMidiFxParam(int trackId, int chain, int index, int param, float value)+ => Mutate(() => E.RackChainMidiParamSet(trackId, chain, index, param, value));++ [McpServerTool(Name = "set_rack_chain_midi_fx_bypass"), Description("Bypass or enable a chain MIDI effect.")]+ public Task SetChainMidiFxBypass(int trackId, int chain, int index, bool bypassed)+ => Mutate(() => E.RackChainMidiSetBypassed(trackId, chain, index, bypassed));++ [McpServerTool(Name = "set_rack_mono"), Description("Instrument Rack mono: one note at a time, last-note priority, all chains share one voice.")]+ public Task SetRackMono(int trackId, bool on) => Mutate(() => E.RackSetMono(trackId, on));+[McpServerTool(Name = "set_pad_choke"), Description("Drum Rack: set a pad/chain's choke group (0 = none). Pads in the same group cut each other off.")]public Task SetPadChoke(int trackId, int chain, int group) => Mutate(() => E.RackSetChainChoke(trackId, chain, group));diff --git a/src/managed/Nota.Presentation/Racks/RackKeyParams.cs b/src/managed/Nota.Presentation/Racks/RackKeyParams.csnew file mode 100644index 00000000..c0aad43a--- /dev/null+++ b/src/managed/Nota.Presentation/Racks/RackKeyParams.cs@@ -0,0 +1,114 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The parameters a rack's compact device card shows (specs/040, research D8): up to three+// per device kind, the ones a player reaches for first. Listed by parameter NAME and+// resolved against the device's own names at run time, so a device that reorders or adds+// parameters keeps its key params. A kind without an entry, or whose names no longer+// match, falls back to its first parameters. While a macro is being mapped the card lists+// every parameter instead; this table is only what shows at rest.++namespace Nota.Presentation;++/// <summary>Which device list a kind number belongs to.</summary>+public enum RackDeviceFamily { Instrument, AudioEffect, MidiEffect }++public static class RackKeyParams+{+ public const int Max = 3;++ // Built-in instruments by instrument kind (chain instruments use the plugin-param names).+ private static readonly Dictionary<int, string[]> Instruments = new()+ {+ [0] = ["Cutoff", "Resonance", "Attack"], // Nota Synth+ [2] = ["Mallet Stiffness", "Res1 Decay", "Res1 Bright"], // Nota Physical+ [5] = ["Osc1 Position", "Cutoff", "Resonance"], // Nota Aurora+ [6] = ["Filter 1 Freq", "Filter 1 Reso", "Filter 1 Env"], // Nota Volt+ [7] = ["Filter Freq", "Filter Reso", "Drive"], // Nota Bass+ [8] = ["Motion Rate", "Voice Tone", "Voice Release"], // Nota Pendulum+ [9] = ["FM Depth", "Feedback", "Filter Freq"], // Nota Operator+ [10] = ["Position", "Grain Size", "Density"], // Nota Grain+ [11] = ["Vector X", "Vector Y", "Filter"], // Nota Flux+ [12] = ["Kick Level", "Snare Level", "Closed Hat Level"], // Nota Rhythm+ [13] = ["Filter Cutoff", "Filter Emphasis", "Filter Contour"], // Nota Monolith+ [14] = ["Filter Cutoff", "Filter Resonance", "Filter Env-Amount"], // Nota Pentad+ [15] = ["Filter Cutoff", "Filter Resonance", "Mixer Drive"], // Nota Consort+ [16] = ["Resonator Bright", "Hammer Hardness", "Tremolo Depth"], // Nota Keys+ };++ // Built-in audio effects by device kind.+ private static readonly Dictionary<int, string[]> AudioEffects = new()+ {+ [0] = ["1 Freq", "1 Gain", "Output"], // Nota EQ-8+ [1] = ["Thresh", "Ratio", "Makeup"], // Nota Compressor+ [2] = ["Size", "Decay", "Dry/Wet"], // Nota Reverb+ [3] = ["Time L", "Feedback", "Dry/Wet"], // Nota Delay+ [4] = ["Gain", "Width", "Balance"], // Nota Utility+ [6] = ["Gain", "Treble", "Mix"], // Nota Valve+ [7] = ["Freq", "Res", "Dry/Wet"], // Nota Auto Filter+ [8] = ["Drive", "Tone", "Mix"], // Nota Vintage+ [9] = ["Rate", "Amount", "Mix"], // Nota Orbit+ [10] = ["Amount", "Speed", "Mix"], // Nota Auto Shift+ [11] = ["Interval", "Gate", "Mix"], // Nota Beat Repeat+ [12] = ["Bits", "Rate", "Dry/Wet"], // Nota Crush+ [13] = ["1 Freq", "1 Thr", "1 Gain"], // Nota Dynamic EQ-8+ [14] = ["Ceiling", "Gain", "Release"], // Nota Ceiling+ [15] = ["Feedback", "InputGain", "Speed"], // Nota Strata+ [16] = ["Low", "Mid", "High"], // Nota EQ-3+ [17] = ["Amount", "Tone", "Wet"], // Nota Forge+ [18] = ["Target", "Trim", "Max Gain"], // Nota Level+ [19] = ["Threshold", "Attack", "Release"], // Nota Shutter+ [20] = ["Blend", "Algo Decay", "Dry/Wet"], // Nota Chamber+ [21] = ["Amount", "Output", "Mix"], // Nota Prism+ [22] = ["Scale Top", "Scale Range", "Freeze"], // Nota Lens+ [23] = ["Rate", "Depth", "Feedback"], // Nota Flanger+ [24] = ["Rate", "Depth", "Feedback"], // Nota Phaser+ [25] = ["Rate", "Amount", "Mix"], // Nota Chorus+ [26] = ["Formant", "Pitch", "Mix"], // Nota Vocoder+ };++ // Built-in MIDI effects by MIDI kind.+ private static readonly Dictionary<int, string[]> MidiEffects = new()+ {+ [0] = ["Rate", "Gate", "Octaves"], // Nota Arp+ [1] = ["Strum", "Spread", "Fold"], // Nota Chord+ [2] = ["Root", "Scale", "Transpose"], // Nota Scale+ [3] = ["Gate", "Percent", "Random"], // Nota Length+ [4] = ["Drive", "Random", "Out High"], // Nota Velocity+ [5] = ["Chance", "Note Range", "Vel Amt"], // Nota Random+ };++ private static Dictionary<int, string[]> Table(RackDeviceFamily family) => family switch+ {+ RackDeviceFamily.Instrument => Instruments,+ RackDeviceFamily.MidiEffect => MidiEffects,+ _ => AudioEffects,+ };++ /// <summary>The kinds with a curated entry in <paramref name="family"/>.</summary>+ public static IEnumerable<int> Kinds(RackDeviceFamily family) => Table(family).Keys;++ /// <summary>The curated names for a kind (empty when the kind has none).</summary>+ public static IReadOnlyList<string> Names(RackDeviceFamily family, int kind)+ => Table(family).TryGetValue(kind, out var n) ? n : [];++ /// <summary>The parameter indices a compact card shows for a device, at most <see cref="Max"/>:+ /// the curated names found on the device, in table order, topped up with the device's first+ /// parameters when a name is missing.</summary>+ public static int[] Resolve(RackDeviceFamily family, int kind, int paramCount, Func<int, string> paramName)+ {+ var picked = new List<int>(Max);+ foreach (var want in Names(family, kind))+ {+ for (int p = 0; p < paramCount; p++)+ {+ if (!string.Equals(paramName(p), want, StringComparison.OrdinalIgnoreCase) || picked.Contains(p)) continue;+ picked.Add(p);+ break;+ }+ }+ for (int p = 0; p < paramCount && picked.Count < Max; p++)+ if (!picked.Contains(p)) picked.Add(p);+ return picked.Count > Max ? picked.GetRange(0, Max).ToArray() : picked.ToArray();+ }+}diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex bed2833c..b2f4e64d 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -117,6 +117,7 @@ set(NOTA_ENGINE_SOURCESsrc/devices/racks/RackDevice.cpp # effect racksrc/devices/racks/RackInstrument.cpp # instrument racksrc/devices/racks/DrumRack.cpp # drum rack+ src/devices/racks/MidiRack.cpp # MIDI effect rack (specs/040)src/devices/midi_fx/Arpeggiator.cppsrc/devices/midi_fx/MidiChord.cppsrc/devices/midi_fx/MidiScale.cppdiff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 198289e8..12468fe7 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -1426,6 +1426,99 @@ NOTA_API int32_t nota_midi_effect_last_in(const NotaEngine* engine, int32_tNOTA_API int32_t nota_midi_effect_last_out(const NotaEngine* engine, int32_t track_id, int32_t index);/* Float scope buffer for a MIDI effect editor (Nota Velocity in/out pairs); returns count written. */NOTA_API int32_t nota_midi_effect_scope(const NotaEngine* engine, int32_t track_id, int32_t index, float* out, int32_t max_n);+/* Opaque state blob of a MIDI effect (the MIDI Effect Rack, kind 6: its chains, devices,+ * zones, macros and output). out == NULL returns the size; otherwise writes up to cap bytes and+ * returns the count written. 0 = no state (params-only effects). */+NOTA_API int32_t nota_midi_effect_get_state(const NotaEngine* engine, int32_t track_id, int32_t index, uint8_t* out, int32_t cap);+/* Restores a state blob by swapping in a restored copy; checkpoint != 0 makes it one undo step. */+NOTA_API NotaResult nota_midi_effect_set_state(NotaEngine* engine, int32_t track_id, int32_t index, const uint8_t* data, int32_t size, int32_t checkpoint);+/* ---- MIDI Effect Rack (specs/040) and chain MIDI effects (#329) ---------------+ * A MIDI Effect Rack is MIDI effect kind 6 (nota_track_add_midi_effect); its calls take+ * the track and its MIDI effect index `mi`. Its state blob (nota_midi_effect_get_state)+ * holds the whole rack. */+/* Instrument Rack chain MIDI effects (issue #329): a chain's MIDI effects (built-in kinds 0–5), run in order before the chain's sound. */+NOTA_API int32_t nota_rack_chain_midi_count(const NotaEngine* e, int32_t t, int32_t chain);+NOTA_API int32_t nota_rack_chain_midi_add(NotaEngine* e, int32_t t, int32_t chain, int32_t midi_kind);+NOTA_API int32_t nota_rack_chain_midi_remove(NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API int32_t nota_rack_chain_midi_move(NotaEngine* e, int32_t t, int32_t chain, int32_t from_index, int32_t to_index);+NOTA_API int32_t nota_rack_chain_midi_kind(const NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API const char* nota_rack_chain_midi_name(const NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API int32_t nota_rack_chain_midi_param_count(const NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API const char* nota_rack_chain_midi_param_name(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param);+NOTA_API float nota_rack_chain_midi_param_min(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param);+NOTA_API float nota_rack_chain_midi_param_max(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param);+NOTA_API float nota_rack_chain_midi_param_get(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param);+NOTA_API void nota_rack_chain_midi_param_set(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param, float value);+NOTA_API void nota_rack_chain_midi_set_bypassed(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t bypassed);+NOTA_API int32_t nota_rack_chain_midi_bypassed(const NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API int32_t nota_rack_chain_midi_last_in(const NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API int32_t nota_rack_chain_midi_last_out(const NotaEngine* e, int32_t t, int32_t chain, int32_t index);+NOTA_API int32_t nota_rack_chain_midi_scope(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, float* out, int32_t max_n);+NOTA_API void nota_rack_chain_midi_command(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t cmd);+/* MIDI Effect Rack (specs/040, MIDI kind 6; mi = its MIDI effect index): a chain's MIDI effects (built-in kinds 0–5), run in order before the chain's sound. */+NOTA_API int32_t nota_midirack_chain_device_count(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API int32_t nota_midirack_chain_device_add(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t midi_kind);+NOTA_API int32_t nota_midirack_chain_device_remove(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API int32_t nota_midirack_chain_device_move(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t from_index, int32_t to_index);+NOTA_API int32_t nota_midirack_chain_device_kind(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API const char* nota_midirack_chain_device_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API int32_t nota_midirack_chain_device_param_count(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API const char* nota_midirack_chain_device_param_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param);+NOTA_API float nota_midirack_chain_device_param_min(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param);+NOTA_API float nota_midirack_chain_device_param_max(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param);+NOTA_API float nota_midirack_chain_device_param_get(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param);+NOTA_API void nota_midirack_chain_device_param_set(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param, float value);+NOTA_API void nota_midirack_chain_device_set_bypassed(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t bypassed);+NOTA_API int32_t nota_midirack_chain_device_bypassed(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API int32_t nota_midirack_chain_device_last_in(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API int32_t nota_midirack_chain_device_last_out(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index);+NOTA_API int32_t nota_midirack_chain_device_scope(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, float* out, int32_t max_n);+NOTA_API void nota_midirack_chain_device_command(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t cmd);+/* MIDI Effect Rack structure. Up to 16 chains; add/duplicate return <0 at the limit. Edits are undoable. */+NOTA_API int32_t nota_midirack_chain_count(const NotaEngine* e, int32_t t, int32_t mi);+NOTA_API int32_t nota_midirack_add_chain(NotaEngine* e, int32_t t, int32_t mi);+NOTA_API int32_t nota_midirack_remove_chain(NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API int32_t nota_midirack_duplicate_chain(NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+/* One undo step for the in-place edits that follow (chain mix, mode, selector, output, macro+ values): the rack is forked now, keeping its MIDI effects and held notes. 1 = done. */+NOTA_API int32_t nota_midirack_checkpoint(NotaEngine* e, int32_t t, int32_t mi);+NOTA_API const char* nota_midirack_chain_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API void nota_midirack_set_chain_name(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, const char* name);+/* Chain controls: mute, solo, key/velocity zone, select range (0..127), transpose (−48..+48), velocity scale (0..2, 0 = silent), note activity (0..1). */+NOTA_API void nota_midirack_set_chain_mute(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t on);+NOTA_API int32_t nota_midirack_chain_mute(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API void nota_midirack_set_chain_solo(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t on);+NOTA_API int32_t nota_midirack_chain_solo(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API void nota_midirack_set_chain_zone(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t key_lo, int32_t key_hi, int32_t vel_lo, int32_t vel_hi);+NOTA_API void nota_midirack_chain_zone(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t* key_lo, int32_t* key_hi, int32_t* vel_lo, int32_t* vel_hi);+NOTA_API void nota_midirack_set_chain_select(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t lo, int32_t hi);+NOTA_API void nota_midirack_chain_select_range(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t* lo, int32_t* hi);+NOTA_API void nota_midirack_set_chain_transpose(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t semitones);+NOTA_API int32_t nota_midirack_chain_transpose(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API void nota_midirack_set_chain_vel_scale(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, float scale);+NOTA_API float nota_midirack_chain_vel_scale(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+NOTA_API float nota_midirack_chain_activity(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain);+/* Rack: chains run 0 Parallel / 2 Select; the selector (0..1); merge duplicate notes; pass notes outside every zone through. */+NOTA_API void nota_midirack_set_mode(NotaEngine* e, int32_t t, int32_t mi, int32_t mode);+NOTA_API int32_t nota_midirack_mode(const NotaEngine* e, int32_t t, int32_t mi);+NOTA_API void nota_midirack_set_selector(NotaEngine* e, int32_t t, int32_t mi, float v);+NOTA_API float nota_midirack_selector(const NotaEngine* e, int32_t t, int32_t mi);+NOTA_API void nota_midirack_set_merge(NotaEngine* e, int32_t t, int32_t mi, int32_t on);+NOTA_API int32_t nota_midirack_merge(const NotaEngine* e, int32_t t, int32_t mi);+NOTA_API void nota_midirack_set_thru(NotaEngine* e, int32_t t, int32_t mi, int32_t on);+NOTA_API int32_t nota_midirack_thru(const NotaEngine* e, int32_t t, int32_t mi);+/* Macros and mappings, as nota_rackdev_*; device = the chain's MIDI effect index, or NOTA_RACK_CONTROL (the selector). */+NOTA_API float nota_midirack_macro_get(const NotaEngine* e, int32_t t, int32_t mi, int32_t macro);+NOTA_API void nota_midirack_macro_set(NotaEngine* e, int32_t t, int32_t mi, int32_t macro, float v);+NOTA_API const char* nota_midirack_macro_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t macro);+NOTA_API void nota_midirack_set_macro_name(NotaEngine* e, int32_t t, int32_t mi, int32_t macro, const char* name);+NOTA_API int32_t nota_midirack_add_macro_mapping(NotaEngine* e, int32_t t, int32_t mi, int32_t macro, int32_t chain, int32_t device, int32_t param, float lo, float hi);+NOTA_API int32_t nota_midirack_mapping_count(const NotaEngine* e, int32_t t, int32_t mi);+NOTA_API int32_t nota_midirack_mapping_info(const NotaEngine* e, int32_t t, int32_t mi, int32_t index, int32_t* macro, int32_t* chain, int32_t* device, int32_t* param, float* lo, float* hi, int32_t* curve);+NOTA_API int32_t nota_midirack_remove_mapping(NotaEngine* e, int32_t t, int32_t mi, int32_t index);+NOTA_API int32_t nota_midirack_set_mapping_range(NotaEngine* e, int32_t t, int32_t mi, int32_t index, float lo, float hi);+NOTA_API int32_t nota_midirack_set_mapping_curve(NotaEngine* e, int32_t t, int32_t mi, int32_t index, int32_t curve);+/* An editor command to a MIDI effect (Nota Arp: 1 = restart the pattern). */NOTA_API void nota_midi_effect_command(NotaEngine* engine, int32_t track_id, int32_t index, int32_t cmd);/* Map/CC routing: the effect's CC lane modulates an audio-device param on the track. */@@ -1610,12 +1703,30 @@ NOTA_API int32_t nota_rack_chain_mute(const NotaEngine* engine, int32_t tracNOTA_API int32_t nota_rack_chain_solo(const NotaEngine* engine, int32_t track_id, int32_t chain);NOTA_API float nota_rack_macro_get(const NotaEngine* engine, int32_t track_id, int32_t macro);NOTA_API void nota_rack_macro_set(NotaEngine* engine, int32_t track_id, int32_t macro, float v);-/* Add a macro mapping. device_index < 0 targets the chain's instrument (param is- * a plugin-param index); >= 0 targets that device (param is a generic index).- * range_min/max are in the target's own units. Returns the mapping index or <0. */+/* Macro-mapping targets beside a chain's instrument (-1) and audio devices (>= 0), for every+ * rack's add_macro_mapping (specs/040): NOTA_RACK_CONTROL drives a rack-level control+ * (param 0 = the Select-mode selector, 0..1; the chain argument is ignored), and+ * NOTA_RACK_MIDI_DEVICE_BASE - j drives the chain's MIDI effect j (param = its generic index). */+#define NOTA_RACK_CONTROL (-3)+#define NOTA_RACK_MIDI_DEVICE_BASE (-1000)+/* Add a macro mapping. device_index -1 targets the chain's instrument (param is+ * a plugin-param index); >= 0 targets that device (param is a generic index); see+ * NOTA_RACK_CONTROL / NOTA_RACK_MIDI_DEVICE_BASE for the others.+ * range_min/max are in the target's own units. A target belongs to one macro: mapping a+ * target that is already mapped moves that mapping to `macro` (range and curve kept) and+ * returns its index. Returns the mapping index or <0. */NOTA_API int32_t nota_rack_add_macro_mapping(NotaEngine* engine, int32_t track_id, int32_t macro, int32_t chain,int32_t device_index, int32_t param_index, float range_min, float range_max);NOTA_API int32_t nota_rack_mapping_count(const NotaEngine* engine, int32_t track_id);+/* Copies a chain right after itself (children with all their state, controls, and copies of+ * its macro mappings), one undo step. Returns the new chain index or <0. */+NOTA_API int32_t nota_rack_duplicate_chain(NotaEngine* engine, int32_t track_id, int32_t chain);+NOTA_API int32_t nota_rackdev_duplicate_chain(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+/* Instrument Rack mono (specs/040): one note at a time, last-note priority; the rack's glide+ * (nota_rack_set_glide, 0..1 = 0..500 ms) bends each new note from the previous pitch on chain+ * instruments that take per-note bend. Off by default. */+NOTA_API void nota_rack_set_mono(NotaEngine* engine, int32_t track_id, int32_t on);+NOTA_API int32_t nota_rack_mono(const NotaEngine* engine, int32_t track_id);/* Fills the out params for mapping `index`; returns 1 on success, 0 otherwise. */NOTA_API int32_t nota_rack_mapping_info(const NotaEngine* engine, int32_t track_id, int32_t index,int32_t* macro, int32_t* chain, int32_t* device_index,diff --git a/src/native/nota.engine/src/abi/nota_engine_device.cpp b/src/native/nota.engine/src/abi/nota_engine_device.cppindex bfeecde6..db7320f5 100644--- a/src/native/nota.engine/src/abi/nota_engine_device.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_device.cpp@@ -189,6 +189,20 @@ int32_t nota_midi_effect_last_out(const NotaEngine* e, int32_t t, int32_t i) {int32_t nota_midi_effect_scope(const NotaEngine* e, int32_t t, int32_t i, float* out, int32_t max_n) {return e ? CENG(e)->midiEffectScope(t, i, out, max_n) : 0;}+int32_t nota_midi_effect_get_state(const NotaEngine* e, int32_t t, int32_t i, uint8_t* out, int32_t cap) {+ if (!e) return 0;+ const auto st = CENG(e)->midiEffectGetState(t, i);+ const int32_t n = static_cast<int32_t>(st.size());+ if (!out) return n;+ const int32_t w = std::min(n, cap);+ if (w > 0) std::memcpy(out, st.data(), static_cast<size_t>(w));+ return w;+}+NotaResult nota_midi_effect_set_state(+ NotaEngine* e, int32_t t, int32_t i, const uint8_t* data, int32_t size, int32_t checkpoint) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->midiEffectSetState(t, i, data, size, checkpoint != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}void nota_midi_effect_command(NotaEngine* e, int32_t t, int32_t i, int32_t cmd) {if (e) ENG(e)->midiEffectCommand(t, i, cmd);}diff --git a/src/native/nota.engine/src/abi/nota_engine_rack.cpp b/src/native/nota.engine/src/abi/nota_engine_rack.cppindex 28831c70..86573b1f 100644--- a/src/native/nota.engine/src/abi/nota_engine_rack.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_rack.cpp@@ -9,6 +9,7 @@// engine, valid until the next call), matching the other ABI slices.#include "nota_engine_internal.h"+#include "devices/racks/RackCore.h"#include <algorithm>#include <cstring>@@ -215,6 +216,18 @@ int32_t nota_rack_add_macro_mapping(NotaEngine* e, int32_t t, int32_t macro, int32_t chain, int32_t di, int32_t pi, float lo, float hi) {return e ? ENG(e)->rackAddMacroMapping(t, -1, macro, chain, di, pi, lo, hi) : -1;}+int32_t nota_rack_duplicate_chain(NotaEngine* e, int32_t t, int32_t chain) {+ return e ? ENG(e)->rackDuplicateChain(t, -1, chain) : -1;+}+int32_t nota_rackdev_duplicate_chain(NotaEngine* e, int32_t t, int32_t di, int32_t chain) {+ return e ? ENG(e)->rackDuplicateChain(t, di, chain) : -1;+}+void nota_rack_set_mono(NotaEngine* e, int32_t t, int32_t on) {+ if (e) ENG(e)->rackSetMono(t, on != 0);+}+int32_t nota_rack_mono(const NotaEngine* e, int32_t t) {+ return (e && CENG(e)->rackMono(t)) ? 1 : 0;+}int32_t nota_rack_mapping_count(const NotaEngine* e, int32_t t) {return e ? CENG(e)->rackMappingCount(t, -1) : 0;}@@ -549,4 +562,283 @@ float nota_rackdev_live_selector(const NotaEngine* e, int32_t t, int32_t di) {return e ? CENG(e)->rackLiveSelector(t, di) : 0.5f;}++// ---- MIDI Effect Rack (specs/040) and chain MIDI effects (#329) --------------------------+// A MIDI Effect Rack is the MIDI effect at index mi; the engine addresses it as kMidiRackBase − mi.+static int32_t MR(int32_t mi) { return nota::Engine::kMidiRackBase - mi; }++int32_t nota_rack_chain_midi_count(const NotaEngine* e, int32_t t, int32_t chain) {+ return e ? CENG(e)->rackChainMidiCount(t, -1, chain) : 0;+}+int32_t nota_rack_chain_midi_add(NotaEngine* e, int32_t t, int32_t chain, int32_t midi_kind) {+ return e ? ENG(e)->rackAddChainMidi(t, -1, chain, midi_kind) : -1;+}+int32_t nota_rack_chain_midi_remove(NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ return (e && ENG(e)->rackRemoveChainMidi(t, -1, chain, index)) ? 1 : 0;+}+int32_t nota_rack_chain_midi_move(NotaEngine* e, int32_t t, int32_t chain, int32_t from_index, int32_t to_index) {+ return (e && ENG(e)->rackMoveChainMidi(t, -1, chain, from_index, to_index)) ? 1 : 0;+}+int32_t nota_rack_chain_midi_kind(const NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->midiKind() : -1;+}+const char* nota_rack_chain_midi_name(const NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->displayName() : "";+}+int32_t nota_rack_chain_midi_param_count(const NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->paramCount() : 0;+}+const char* nota_rack_chain_midi_param_name(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->paramName(param) : "";+}+float nota_rack_chain_midi_param_min(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->paramMin(param) : 0.0f;+}+float nota_rack_chain_midi_param_max(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->paramMax(param) : 1.0f;+}+float nota_rack_chain_midi_param_get(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->getParam(param) : 0.0f;+}+void nota_rack_chain_midi_param_set(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t param, float value) {+ auto* m = e ? ENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ if (m) m->setParam(param, value);+}+void nota_rack_chain_midi_set_bypassed(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t bypassed) {+ if (e) ENG(e)->rackSetChainMidiBypassed(t, -1, chain, index, bypassed != 0);+}+int32_t nota_rack_chain_midi_bypassed(const NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return (m && m->bypassed()) ? 1 : 0;+}+int32_t nota_rack_chain_midi_last_in(const NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->midiLastIn() : -1;+}+int32_t nota_rack_chain_midi_last_out(const NotaEngine* e, int32_t t, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return m ? m->midiLastOut() : -1;+}+int32_t nota_rack_chain_midi_scope(const NotaEngine* e, int32_t t, int32_t chain, int32_t index, float* out, int32_t max_n) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ return (m && out) ? m->midiScope(out, max_n) : 0;+}+void nota_rack_chain_midi_command(NotaEngine* e, int32_t t, int32_t chain, int32_t index, int32_t cmd) {+ auto* m = e ? ENG(e)->rackChainMidiAt(t, -1, chain, index) : nullptr;+ if (m) m->midiCommand(cmd);+}+int32_t nota_midirack_chain_device_count(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return e ? CENG(e)->rackChainMidiCount(t, MR(mi), chain) : 0;+}+int32_t nota_midirack_chain_device_add(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t midi_kind) {+ return e ? ENG(e)->rackAddChainMidi(t, MR(mi), chain, midi_kind) : -1;+}+int32_t nota_midirack_chain_device_remove(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ return (e && ENG(e)->rackRemoveChainMidi(t, MR(mi), chain, index)) ? 1 : 0;+}+int32_t nota_midirack_chain_device_move(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t from_index, int32_t to_index) {+ return (e && ENG(e)->rackMoveChainMidi(t, MR(mi), chain, from_index, to_index)) ? 1 : 0;+}+int32_t nota_midirack_chain_device_kind(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->midiKind() : -1;+}+const char* nota_midirack_chain_device_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->displayName() : "";+}+int32_t nota_midirack_chain_device_param_count(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->paramCount() : 0;+}+const char* nota_midirack_chain_device_param_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->paramName(param) : "";+}+float nota_midirack_chain_device_param_min(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->paramMin(param) : 0.0f;+}+float nota_midirack_chain_device_param_max(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->paramMax(param) : 1.0f;+}+float nota_midirack_chain_device_param_get(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->getParam(param) : 0.0f;+}+void nota_midirack_chain_device_param_set(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t param, float value) {+ auto* m = e ? ENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ if (m) m->setParam(param, value);+}+void nota_midirack_chain_device_set_bypassed(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t bypassed) {+ if (e) ENG(e)->rackSetChainMidiBypassed(t, MR(mi), chain, index, bypassed != 0);+}+int32_t nota_midirack_chain_device_bypassed(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return (m && m->bypassed()) ? 1 : 0;+}+int32_t nota_midirack_chain_device_last_in(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->midiLastIn() : -1;+}+int32_t nota_midirack_chain_device_last_out(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return m ? m->midiLastOut() : -1;+}+int32_t nota_midirack_chain_device_scope(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, float* out, int32_t max_n) {+ auto* m = e ? CENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ return (m && out) ? m->midiScope(out, max_n) : 0;+}+void nota_midirack_chain_device_command(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t index, int32_t cmd) {+ auto* m = e ? ENG(e)->rackChainMidiAt(t, MR(mi), chain, index) : nullptr;+ if (m) m->midiCommand(cmd);+}+int32_t nota_midirack_chain_count(const NotaEngine* e, int32_t t, int32_t mi) {+ return e ? CENG(e)->rackChainCount(t, MR(mi)) : 0;+}+int32_t nota_midirack_add_chain(NotaEngine* e, int32_t t, int32_t mi) {+ return e ? ENG(e)->rackAddChain(t, MR(mi), -1) : -1;+}+int32_t nota_midirack_remove_chain(NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return (e && CENG(e)->rackChainCount(t, MR(mi)) > 1 && ENG(e)->rackRemoveChain(t, MR(mi), chain)) ? 1 : 0;+}+int32_t nota_midirack_duplicate_chain(NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return e ? ENG(e)->rackDuplicateChain(t, MR(mi), chain) : -1;+}+int32_t nota_midirack_checkpoint(NotaEngine* e, int32_t t, int32_t mi) {+ return (e && ENG(e)->rackCheckpoint(t, MR(mi))) ? 1 : 0;+}+const char* nota_midirack_chain_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ static std::string s;+ s = e ? CENG(e)->rackChainName(t, MR(mi), chain) : std::string{};+ return s.c_str();+}+void nota_midirack_set_chain_name(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, const char* name) {+ if (e) ENG(e)->rackSetChainName(t, MR(mi), chain, name ? name : "");+}+void nota_midirack_set_chain_mute(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t on) {+ if (e) ENG(e)->rackSetChainMute(t, MR(mi), chain, on != 0);+}+int32_t nota_midirack_chain_mute(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return (e && CENG(e)->rackChainMute(t, MR(mi), chain)) ? 1 : 0;+}+void nota_midirack_set_chain_solo(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t on) {+ if (e) ENG(e)->rackSetChainSolo(t, MR(mi), chain, on != 0);+}+int32_t nota_midirack_chain_solo(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return (e && CENG(e)->rackChainSolo(t, MR(mi), chain)) ? 1 : 0;+}+void nota_midirack_set_chain_zone(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t key_lo, int32_t key_hi, int32_t vel_lo, int32_t vel_hi) {+ if (e) ENG(e)->rackSetChainZone(t, MR(mi), chain, key_lo, key_hi, vel_lo, vel_hi);+}+void nota_midirack_chain_zone(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t* key_lo, int32_t* key_hi, int32_t* vel_lo, int32_t* vel_hi) {+ int32_t kl = 0, kh = 127, vl = 0, vh = 127;+ if (e) CENG(e)->rackChainZone(t, MR(mi), chain, kl, kh, vl, vh);+ if (key_lo) *key_lo = kl;+ if (key_hi) *key_hi = kh;+ if (vel_lo) *vel_lo = vl;+ if (vel_hi) *vel_hi = vh;+}+void nota_midirack_set_chain_select(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t lo, int32_t hi) {+ if (e) ENG(e)->rackSetChainSelectRange(t, MR(mi), chain, lo, hi);+}+void nota_midirack_chain_select_range(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t* lo, int32_t* hi) {+ int32_t l = 0, h = 127;+ if (e) CENG(e)->rackChainSelectRange(t, MR(mi), chain, l, h);+ if (lo) *lo = l;+ if (hi) *hi = h;+}+void nota_midirack_set_chain_transpose(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, int32_t semitones) {+ if (e) ENG(e)->rackSetChainTranspose(t, MR(mi), chain, semitones);+}+int32_t nota_midirack_chain_transpose(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return e ? CENG(e)->rackChainTranspose(t, MR(mi), chain) : 0;+}+void nota_midirack_set_chain_vel_scale(NotaEngine* e, int32_t t, int32_t mi, int32_t chain, float scale) {+ if (e) ENG(e)->rackSetChainVelScale(t, MR(mi), chain, scale);+}+float nota_midirack_chain_vel_scale(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return e ? CENG(e)->rackChainVelScale(t, MR(mi), chain) : 1.0f;+}+float nota_midirack_chain_activity(const NotaEngine* e, int32_t t, int32_t mi, int32_t chain) {+ return e ? CENG(e)->rackChainMeter(t, MR(mi), chain) : 0.0f;+}+void nota_midirack_set_mode(NotaEngine* e, int32_t t, int32_t mi, int32_t mode) {+ if (e && (mode == 0 || mode == 2)) ENG(e)->rackSetMode(t, MR(mi), mode);+}+int32_t nota_midirack_mode(const NotaEngine* e, int32_t t, int32_t mi) {+ return e ? CENG(e)->rackMode(t, MR(mi)) : 0;+}+void nota_midirack_set_selector(NotaEngine* e, int32_t t, int32_t mi, float v) {+ if (e) ENG(e)->rackSetChainSelect(t, MR(mi), v);+}+float nota_midirack_selector(const NotaEngine* e, int32_t t, int32_t mi) {+ return e ? CENG(e)->rackChainSelect(t, MR(mi)) : 0.5f;+}+void nota_midirack_set_merge(NotaEngine* e, int32_t t, int32_t mi, int32_t on) {+ if (e) ENG(e)->rackSetMerge(t, MR(mi), on != 0);+}+int32_t nota_midirack_merge(const NotaEngine* e, int32_t t, int32_t mi) {+ return (e && CENG(e)->rackMerge(t, MR(mi))) ? 1 : 0;+}+void nota_midirack_set_thru(NotaEngine* e, int32_t t, int32_t mi, int32_t on) {+ if (e) ENG(e)->rackSetThru(t, MR(mi), on != 0);+}+int32_t nota_midirack_thru(const NotaEngine* e, int32_t t, int32_t mi) {+ return (e && CENG(e)->rackThru(t, MR(mi))) ? 1 : 0;+}+float nota_midirack_macro_get(const NotaEngine* e, int32_t t, int32_t mi, int32_t macro) {+ return e ? CENG(e)->rackMacroGet(t, MR(mi), macro) : 0.0f;+}+void nota_midirack_macro_set(NotaEngine* e, int32_t t, int32_t mi, int32_t macro, float v) {+ if (e) ENG(e)->rackMacroSet(t, MR(mi), macro, v);+}+const char* nota_midirack_macro_name(const NotaEngine* e, int32_t t, int32_t mi, int32_t macro) {+ static std::string s;+ s = e ? CENG(e)->rackMacroName(t, MR(mi), macro) : std::string{};+ return s.c_str();+}+void nota_midirack_set_macro_name(NotaEngine* e, int32_t t, int32_t mi, int32_t macro, const char* name) {+ if (e) ENG(e)->rackSetMacroName(t, MR(mi), macro, name ? std::string(name) : std::string{});+}+int32_t nota_midirack_add_macro_mapping(NotaEngine* e, int32_t t, int32_t mi, int32_t macro, int32_t chain, int32_t device, int32_t param, float lo, float hi) {+ if (!e) return -1;+ const int32_t target = device >= 0 ? nota::RackCore::midiTarget(device) : device;+ return ENG(e)->rackAddMacroMapping(t, MR(mi), macro, chain, target, param, lo, hi);+}+int32_t nota_midirack_mapping_count(const NotaEngine* e, int32_t t, int32_t mi) {+ return e ? CENG(e)->rackMappingCount(t, MR(mi)) : 0;+}+int32_t nota_midirack_mapping_info(const NotaEngine* e, int32_t t, int32_t mi, int32_t index, int32_t* macro, int32_t* chain, int32_t* device, int32_t* param, float* lo, float* hi, int32_t* curve) {+ if (!e) return 0;+ int32_t mo, ch, dv, px;+ float rmin, rmax;+ if (!CENG(e)->rackMappingInfo(t, MR(mi), index, mo, ch, dv, px, rmin, rmax)) return 0;+ if (macro) *macro = mo;+ if (chain) *chain = ch;+ if (device) *device = nota::RackCore::isMidiTarget(dv) ? nota::RackCore::midiTargetIndex(dv) : dv;+ if (param) *param = px;+ if (lo) *lo = rmin;+ if (hi) *hi = rmax;+ if (curve) *curve = CENG(e)->rackMappingCurve(t, MR(mi), index);+ return 1;+}+int32_t nota_midirack_remove_mapping(NotaEngine* e, int32_t t, int32_t mi, int32_t index) {+ return (e && ENG(e)->rackRemoveMapping(t, MR(mi), index)) ? 1 : 0;+}+int32_t nota_midirack_set_mapping_range(NotaEngine* e, int32_t t, int32_t mi, int32_t index, float lo, float hi) {+ return (e && ENG(e)->rackSetMappingRange(t, MR(mi), index, lo, hi)) ? 1 : 0;+}+int32_t nota_midirack_set_mapping_curve(NotaEngine* e, int32_t t, int32_t mi, int32_t index, int32_t curve) {+ return (e && ENG(e)->rackSetMappingCurve(t, MR(mi), index, curve)) ? 1 : 0;+}+} // extern "C"diff --git a/src/native/nota.engine/src/devices/BuiltinDevices.cpp b/src/native/nota.engine/src/devices/BuiltinDevices.cppindex 4516d50d..8ffa0ffa 100644--- a/src/native/nota.engine/src/devices/BuiltinDevices.cpp+++ b/src/native/nota.engine/src/devices/BuiltinDevices.cpp@@ -33,6 +33,7 @@#include "devices/effects/Flanger.h"#include "devices/effects/Phaser.h"#include "devices/effects/Chorus.h"+#include "devices/effects/Vocoder.h"namespace nota {@@ -63,6 +64,7 @@ std::shared_ptr<Device> makeChainDevice(int32_t kind) {case 23: return std::make_shared<Flanger>();case 24: return std::make_shared<Phaser>();case 25: return std::make_shared<Chorus>();+ case 26: return std::make_shared<Vocoder>(); // in a chain: Saw / Noise carrier (no sidechain)default: return nullptr; // 5 = Effect Rack (nesting) / plugin: not via this factory}}diff --git a/src/native/nota.engine/src/devices/DeviceFactory.cpp b/src/native/nota.engine/src/devices/DeviceFactory.cppindex 047a4db7..7a396770 100644--- a/src/native/nota.engine/src/devices/DeviceFactory.cpp+++ b/src/native/nota.engine/src/devices/DeviceFactory.cpp@@ -38,6 +38,7 @@#include "devices/midi_fx/MidiChord.h"#include "devices/midi_fx/MidiNoteLength.h"#include "devices/midi_fx/MidiRandom.h"+#include "devices/racks/MidiRack.h"#include "devices/midi_fx/MidiScale.h"#include "devices/midi_fx/MidiVelocity.h"#include "devices/instruments/Monolith.h"@@ -125,6 +126,7 @@ std::shared_ptr<MidiDevice> makeMidiDevice(int32_t kind) {case 3: return std::make_shared<MidiNoteLength>();case 4: return std::make_shared<MidiVelocity>();case 5: return std::make_shared<MidiRandom>();+ case MidiRack::kKind: return std::make_shared<MidiRack>(); // the MIDI Effect Rack (specs/040)default: return nullptr;}}diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.hindex 4d288da1..3569bf7e 100644--- a/src/native/nota.engine/src/devices/Instrument.h+++ b/src/native/nota.engine/src/devices/Instrument.h@@ -21,12 +21,24 @@namespace nota {+struct MidiEv;+class Instrument {public:virtual ~Instrument() = default;virtual void setSampleRate(double sr) = 0;+ // MIDI effects inside the instrument (an Instrument Rack chain's, issue #329). An instrument+ // that wants the block's notes up front says so; the engine then hands it the block's sorted+ // events once, with the clock the track's own MIDI effects ran on (the arrangement's, or a+ // Session slot's loop), before driving it event by event as usual. The loop seam shifts+ // their clock like the track's own MIDI effects; allNotesOff flushes them.+ virtual bool takesBlockMidi() const { return false; }+ virtual void blockMidi(const MidiEv* /*evs*/, int /*n*/, int32_t /*frames*/, double /*beatStart*/, double /*spb*/,+ bool /*playing*/) {}+ virtual void midiTimeJump(double /*deltaBeats*/) {}+// Note events (applied at segment boundaries by the engine for sample accuracy).virtual void noteOn(int32_t pitch, float velocity) = 0;virtual void noteOff(int32_t pitch) = 0;diff --git a/src/native/nota.engine/src/devices/racks/MidiRack.cpp b/src/native/nota.engine/src/devices/racks/MidiRack.cppnew file mode 100644index 00000000..62eadaf4--- /dev/null+++ b/src/native/nota.engine/src/devices/racks/MidiRack.cpp@@ -0,0 +1,273 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MidiRack implementation — routing notes into chains, running each chain's MIDI effects,+// and merging their output (see MidiRack.h).++#include "MidiRack.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstring>++namespace nota {++namespace {++// Block order: by sample offset, a note-off before a note-on at the same offset (so a+// retriggered pitch ends before it starts again).+bool before(const MidiEv& a, const MidiEv& b) {+ if (a.off != b.off) return a.off < b.off;+ return !a.on && b.on;+}++} // namespace++MidiRack::MidiRack() {+ addChain(-1); // a new rack starts with one empty chain+ setRackMerge(true);+ setRackThru(true);+}++const char* MidiRack::paramName(int32_t index) const {+ if (index < 0 || index >= kNumMacros) return "";+ auto& buf = const_cast<std::array<char[24], kNumMacros>&>(paramNames_)[index];+ const std::string n = macroName(index); // message thread (editors, automation lanes)+ std::snprintf(buf, sizeof(buf), "%s", n.c_str());+ return buf;+}++std::shared_ptr<MidiDevice> MidiRack::clone() const {+ auto r = std::make_shared<MidiRack>();+ r->setRates(sampleRate_, maxBlock_);+ const auto blob = serialize();+ r->deserialize(blob.data(), static_cast<int32_t>(blob.size()));+ r->setBypassed(bypassed());+ return r;+}++uint64_t MidiRack::structureOf(const RackState& st) const {+ // Chains and their MIDI effects, by identity: a fork for an undoable edit shares the+ // devices, so it keeps the signature; adding, removing or moving anything changes it.+ uint64_t h = 1469598103934665603ull ^ static_cast<uint64_t>(st.chains.size());+ for (const auto& c : st.chains) {+ h = (h ^ static_cast<uint64_t>(c.midiDevices.size())) * 1099511628211ull;+ for (const auto& d : c.midiDevices) h = (h ^ reinterpret_cast<uintptr_t>(d.get())) * 1099511628211ull;+ }+ return h;+}++void MidiRack::emitMerged(const MidiEv& ev, MidiEv* out, int& nOut, int maxOut) {+ auto& rt = *rt_;+ const int32_t p = std::clamp(ev.pitch, 0, 127);+ if (ev.on) {+ // Merge: a pitch already sounding from another source isn't started again.+ if (rackMerge() && rt.held[p] > 0) {+ if (rt.held[p] < 255) ++rt.held[p];+ return;+ }+ if (rt.held[p] < 255) ++rt.held[p];+ } else {+ if (rt.held[p] == 0) return; // nothing of ours sounds there+ --rt.held[p];+ if (rackMerge() && rt.held[p] > 0) return; // another source still holds it+ }+ if (nOut < maxOut) out[nOut++] = ev;+}++void MidiRack::cutAll(const RackState& st, MidiEv* out, int& nOut, int maxOut) {+ auto& rt = *rt_;+ for (int32_t p = 0; p < 128; ++p) {+ while (rt.held[p] > 0) {+ if (nOut < maxOut) out[nOut++] = MidiEv{0, false, p, 0.0f};+ if (rackMerge()) rt.held[p] = 0;+ else --rt.held[p];+ }+ rt.route[p] = 0;+ rt.thru[p] = false;+ }+ rt.clearOut();+ for (const auto& c : st.chains)+ for (const auto& d : c.midiDevices)+ if (d) d->reset();+}++void MidiRack::process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut, int32_t frames, double beatStart,+ double spb, bool playing) {+ nOut = 0;+ const auto done = renderScope();+ RackState* st = live();+ if (!st) {+ for (int i = 0; i < nIn && nOut < maxOut; ++i) out[nOut++] = in[i];+ return;+ }+ auto& rt = *rt_;+ if (bypassed()) {+ // Switching off ends what the chains started (a transposed or generated pitch wouldn't+ // get its note-off from the raw input); then the notes pass untouched, counted, so+ // switching on again can end those.+ if (!rt.bypassed) {+ cutAll(*st, out, nOut, maxOut);+ rt.bypassed = true;+ }+ for (int i = 0; i < nIn && nOut < maxOut; ++i) {+ uint8_t& h = rt.rawHeld[std::clamp(in[i].pitch, 0, 127)];+ if (in[i].on) {+ if (h < 255) ++h;+ } else if (h > 0) {+ --h;+ }+ out[nOut++] = in[i];+ }+ return;+ }+ if (rt.bypassed) {+ for (int32_t p = 0; p < 128; ++p)+ for (; rt.rawHeld[p] > 0; --rt.rawHeld[p])+ if (nOut < maxOut) out[nOut++] = MidiEv{0, false, p, 0.0f};+ rt.bypassed = false;+ }++ // A different set of chains or devices: end what this rack holds rather than guess.+ const uint64_t sig = structureOf(*st);+ if (sig != rt.structure) {+ if (rt.structure != 0) cutAll(*st, out, nOut, maxOut);+ rt.structure = sig;+ }++ const int32_t nChains = std::min<int32_t>(static_cast<int32_t>(st->chains.size()), kMaxChains);+ bool anySolo = false;+ for (int32_t c = 0; c < nChains; ++c)+ if (st->chains[c].ctl->solo.load(std::memory_order_relaxed)) anySolo = true;+ const bool select = rackMode() == 2;+ const int32_t selector = static_cast<int32_t>(std::lround(chainSelect() * 127.0f));++ // 1. Route the input in time order (a note-off before a note-on at the same sample): a+ // note-on goes to every chain that takes it; its note-off follows it to the same chains,+ // whatever changed in between — and a key struck again keeps the new note's route.+ int nPool = 0;+ auto pool = [&](const MidiEv& ev, int16_t chain) {+ if (nPool < kPoolEvents) {+ pool_[nPool] = Tagged{ev, chain, nPool};+ ++nPool;+ }+ };+ const int nEv = std::min(nIn, static_cast<int>(kMaxEvents));+ for (int i = 0; i < nEv; ++i) order_[i] = static_cast<uint16_t>(i);+ std::sort(order_, order_ + nEv, [in](uint16_t x, uint16_t y) {+ if (before(in[x], in[y])) return true;+ if (before(in[y], in[x])) return false;+ return x < y;+ });+ for (int k = 0; k < nEv; ++k) {+ const int i = order_[k];+ const MidiEv& ev = in[i];+ const int32_t p = std::clamp(ev.pitch, 0, 127);+ if (ev.on) {+ const int32_t v = std::clamp(static_cast<int32_t>(std::lround(ev.vel * 127.0f)), 0, 127);+ uint16_t mask = 0;+ for (int32_t c = 0; c < nChains; ++c) {+ const auto& z = *st->chains[c].ctl;+ constexpr auto r = std::memory_order_relaxed;+ if (z.mute.load(r) || (anySolo && !z.solo.load(r))) continue;+ if (p < z.keyLo.load(r) || p > z.keyHi.load(r) || v < z.velLo.load(r) || v > z.velHi.load(r)) continue;+ if (select && (selector < z.selLo.load(r) || selector > z.selHi.load(r))) continue;+ mask |= static_cast<uint16_t>(1u << c);+ }+ rt.route[p] |= mask; // a second note-on before the note-off: one note-off ends both+ evMask_[i] = mask;+ if (mask == 0 && rackThru()) {+ rt.thru[p] = true;+ pool(ev, -1);+ }+ } else {+ // The note-off goes where its note-on went, even if the key comes back in this block.+ evMask_[i] = rt.route[p];+ rt.route[p] = 0;+ if (rt.thru[p]) {+ rt.thru[p] = false;+ pool(ev, -1);+ }+ }+ }++ // 2. Each chain: its share of the input through its MIDI effects, then transpose and+ // velocity scale on the way out.+ for (int32_t c = 0; c < nChains; ++c) {+ auto& chain = st->chains[c];+ const uint16_t bit = static_cast<uint16_t>(1u << c);+ int n = 0;+ for (int k = 0; k < nEv; ++k)+ if (evMask_[order_[k]] & bit) bufA_[n++] = in[order_[k]];+ MidiEv* a = bufA_;+ MidiEv* b = bufB_;+ for (auto& d : chain.midiDevices) {+ if (!d) continue;+ int m = 0;+ d->process(a, n, b, m, kMaxEvents, frames, beatStart, spb, playing);+ std::swap(a, b);+ n = m;+ }+ const int32_t tr = chain.ctl->transpose.load(std::memory_order_relaxed);+ const float vs = chain.ctl->velScale.load(std::memory_order_relaxed);+ float activity = chain.ctl->meter.load(std::memory_order_relaxed) * 0.85f;+ for (int i = 0; i < n; ++i) {+ MidiEv ev = a[i];+ const int32_t src = std::clamp(ev.pitch, 0, 127);+ if (ev.on) {+ if (vs <= 0.0f) continue; // Volume at 0: this chain sends nothing+ const int32_t q = std::clamp(src + tr, 0, 127);+ if (rt.outPitch[c][src] >= 0) { // a retrigger: end the one it replaces+ MidiEv off = ev;+ off.on = false;+ off.pitch = rt.outPitch[c][src];+ pool(off, static_cast<int16_t>(c));+ }+ rt.outPitch[c][src] = static_cast<int8_t>(q);+ ev.pitch = q;+ ev.vel = std::clamp(ev.vel * vs, 1.0f / 127.0f, 1.0f);+ activity = 1.0f;+ } else {+ const int32_t q = rt.outPitch[c][src];+ if (q < 0) continue; // never started (silent chain) or already ended+ rt.outPitch[c][src] = -1;+ ev.pitch = q;+ }+ pool(ev, static_cast<int16_t>(c));+ }+ chain.ctl->meter.store(activity, std::memory_order_relaxed);+ }++ // 3. Merge in time order.+ std::sort(pool_, pool_ + nPool, [](const Tagged& x, const Tagged& y) {+ if (before(x.ev, y.ev)) return true;+ if (before(y.ev, x.ev)) return false;+ return x.seq < y.seq;+ });+ for (int i = 0; i < nPool; ++i) emitMerged(pool_[i].ev, out, nOut, maxOut);+}++void MidiRack::reset() {+ auto& rt = *rt_;+ std::memset(rt.route, 0, sizeof(rt.route));+ std::memset(rt.thru, 0, sizeof(rt.thru));+ std::memset(rt.held, 0, sizeof(rt.held));+ std::memset(rt.rawHeld, 0, sizeof(rt.rawHeld));+ rt.clearOut();+ RackState* st = live();+ if (!st) return;+ for (auto& c : st->chains)+ for (auto& d : c.midiDevices)+ if (d) d->reset();+}++void MidiRack::timeJump(double deltaBeats) {+ RackState* st = live();+ if (!st) return;+ for (auto& c : st->chains)+ for (auto& d : c.midiDevices)+ if (d) d->timeJump(deltaBeats);+}++} // namespace notadiff --git a/src/native/nota.engine/src/devices/racks/MidiRack.h b/src/native/nota.engine/src/devices/racks/MidiRack.hnew file mode 100644index 00000000..fc074722--- /dev/null+++ b/src/native/nota.engine/src/devices/racks/MidiRack.h@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MidiRack — the MIDI Effect Rack (specs/040, MIDI kind 6). A MIDI effect whose chains each+// run a series of built-in MIDI effects on the notes their key / velocity zone (and, in+// Select mode, their select range around the selector) lets in; the chains' outputs merge+// into the track's note stream before the instrument. A chain transposes its output and+// scales its velocity ("Volume": 0 = silent). Notes no chain takes pass through when+// "pass through" is on; two chains sending one pitch play it once when "merge" is on.+//+// Structure, macros, mappings, persistence and undo come from RackCore. The note+// bookkeeping (which chains a key went to, which pitches each chain holds) lives in a+// Runtime shared by every fork of the rack, so an undoable edit that swaps the rack object+// keeps playing notes; a change of chains or devices cuts the held notes instead of leaving+// any hanging. Audio thread: fixed buffers only, no allocation (AR-6).++#pragma once++#include "RackCore.h"++#include <array>+#include <cstdint>+#include <memory>++namespace nota {++class MidiRack final : public MidiDevice, public RackCore {+ public:+ static constexpr int32_t kKind = 6;+ static constexpr int32_t kMaxChains = 16;+ static constexpr int32_t kMaxEvents = 1024; // per chain, as the track's MIDI chain+ static constexpr int32_t kPoolEvents = 4096; // every chain's output before the merge++ MidiRack();++ int32_t midiKind() const override { return kKind; }+ const char* displayName() const override { return "Nota MIDI Effect Rack"; }+ void setSampleRate(double sr, int32_t maxBlock) override { setRates(sr, maxBlock); }++ void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut, int32_t frames, double beatStart,+ double spb, bool playing) override;+ void reset() override;+ void timeJump(double deltaBeats) override;++ // The eight macros are the rack's parameters (automation, MIDI Learn, presets).+ int32_t paramCount() const override { return kNumMacros; }+ const char* paramName(int32_t index) const override;+ float paramMin(int32_t) const override { return 0.0f; }+ float paramMax(int32_t) const override { return 1.0f; }+ float getParam(int32_t index) const override { return macroGet(index); }+ void setParam(int32_t index, float value) override { macroSet(index, value); }++ std::vector<uint8_t> getState() const override { return serialize(); }+ void setState(const uint8_t* data, int32_t size) override { deserialize(data, size); }+ std::shared_ptr<MidiDevice> clone() const override;++ // A fork for an undoable edit plays on with the same held-note tables.+ void shareRuntimeWith(const MidiRack& o) { rt_ = o.rt_; }++ // Live note activity of a chain, 0..1 (decays), for the card's chain rows.+ float chainActivity(int32_t c) const { return chainMeter(c); }++ private:+ // Held-note bookkeeping, audio thread only.+ struct Runtime {+ uint16_t route[128] = {}; // input pitch → the chains its note-on went to+ bool thru[128] = {}; // input pitch passed through (no chain took it)+ int8_t outPitch[kMaxChains][128]; // chain c, device-output pitch → transposed pitch sent (−1 none)+ uint8_t held[128] = {}; // merged output: how many sources hold each pitch+ uint8_t rawHeld[128] = {}; // notes passed on untouched while bypassed+ bool bypassed = false; // the last block ran bypassed+ uint64_t structure = 0; // chains + devices the tables were filled for+ Runtime() { clearOut(); }+ void clearOut() {+ for (auto& row : outPitch)+ for (auto& p : row) p = -1;+ }+ };+ struct Tagged {+ MidiEv ev;+ int16_t chain; // −1 = pass-through+ int32_t seq; // arrival order: equal times keep it (std::sort, no allocation)+ };++ uint64_t structureOf(const RackState& st) const;+ void cutAll(const RackState& st, MidiEv* out, int& nOut, int maxOut);+ void emitMerged(const MidiEv& ev, MidiEv* out, int& nOut, int maxOut);++ std::shared_ptr<Runtime> rt_ = std::make_shared<Runtime>();+ MidiEv bufA_[kMaxEvents];+ MidiEv bufB_[kMaxEvents];+ Tagged pool_[kPoolEvents];+ uint16_t evMask_[kMaxEvents] = {}; // per input event: the chains it goes to+ uint16_t order_[kMaxEvents] = {}; // the input events in time order+ std::array<char[24], kNumMacros> paramNames_{};+};++} // namespace notadiff --git a/src/native/nota.engine/src/devices/racks/RackCore.cpp b/src/native/nota.engine/src/devices/racks/RackCore.cppindex 465bc128..9c0cd6ce 100644--- a/src/native/nota.engine/src/devices/racks/RackCore.cpp+++ b/src/native/nota.engine/src/devices/racks/RackCore.cpp@@ -22,6 +22,7 @@#include "devices/instruments/Keys.h"#include "devices/instruments/GrainSynth.h"#include "devices/instruments/Sampler.h"+#include "devices/DeviceFactory.h"#include <cmath>@@ -67,6 +68,8 @@ void RackCore::setRates(double sr, int32_t maxBlock) {if (c.instrument) c.instrument->setSampleRate(sampleRate_);for (auto& d : c.devices)if (d) d->setSampleRate(sampleRate_, maxBlock_);+ for (auto& m : c.midiDevices)+ if (m) m->setSampleRate(sampleRate_, maxBlock_);}}@@ -90,6 +93,10 @@ void RackCore::forkFrom(const RackCore& o) {ctl->tune.store(s.tune.load(r), r);ctl->decay.store(s.decay.load(r), r);ctl->ampEnv.store(s.ampEnv.load(r), r); // a ringing pad keeps its level+ ctl->selLo.store(s.selLo.load(r), r);+ ctl->selHi.store(s.selHi.load(r), r);+ ctl->transpose.store(s.transpose.load(r), r);+ ctl->velScale.store(s.velScale.load(r), r);}c.ctl = std::move(ctl);}@@ -109,6 +116,9 @@ void RackCore::forkFrom(const RackCore& o) {chainSelect_.store(o.chainSelect_.load(r), r);selFollow_.store(o.selFollow_.load(r), r);liveSel_.store(o.liveSel_.load(r), r);+ mono_.store(o.mono_.load(r), r);+ merge_.store(o.merge_.load(r), r);+ thru_.store(o.thru_.load(r), r);sampleRate_ = o.sampleRate_;maxBlock_ = o.maxBlock_;}@@ -167,6 +177,32 @@ bool RackCore::removeChain(int32_t chain) {return true;}+int32_t RackCore::duplicateChain(int32_t chain) {+ if (chain < 0 || chain >= chainCount()) return -1;+ // Rebuild the chain from this rack's own blob in a scratch rack: the blob already knows+ // how to recreate every child kind with all of its state.+ RackCore tmp;+ tmp.setRates(sampleRate_, maxBlock_);+ const auto blob = serialize();+ tmp.deserialize(blob.data(), static_cast<int32_t>(blob.size()));+ if (!tmp.authoring_ || chain >= static_cast<int32_t>(tmp.authoring_->chains.size())) return -1;+ auto ns = copyState();+ const int32_t at = chain + 1;+ ns->chains.insert(ns->chains.begin() + at, std::move(tmp.authoring_->chains[chain]));+ std::vector<MacroMapping> copies;+ for (auto& m : ns->mappings) {+ if (m.chainIndex == chain) {+ MacroMapping c = m;+ c.chainIndex = at;+ copies.push_back(c);+ } else if (m.chainIndex >= at)+ ++m.chainIndex;+ }+ ns->mappings.insert(ns->mappings.end(), copies.begin(), copies.end());+ commit(ns);+ return at;+}+bool RackCore::setChainInstrument(int32_t chain, int32_t instKind) {auto inst = makeInstrument(instKind);if (!inst) return false;@@ -265,6 +301,88 @@ Device* RackCore::chainDeviceAt(int32_t chain, int32_t dev) const {return d[dev].get();}+std::shared_ptr<MidiDevice> RackCore::makeChainMidiDevice(int32_t kind) {+ // Built-in MIDI effects only; kind 6 is the MIDI Effect Rack itself, which never nests.+ if (kind < 0 || kind > 5) return nullptr;+ return makeMidiDevice(kind);+}++int32_t RackCore::chainMidiDeviceCount(int32_t chain) const {+ RackState* st = live();+ if (!st || chain < 0 || chain >= static_cast<int32_t>(st->chains.size())) return 0;+ return static_cast<int32_t>(st->chains[chain].midiDevices.size());+}++int32_t RackCore::addChainMidiDevice(int32_t chain, int32_t midiKind) {+ return addChainMidiDeviceInstance(chain, makeChainMidiDevice(midiKind));+}++int32_t RackCore::addChainMidiDeviceInstance(int32_t chain, std::shared_ptr<MidiDevice> dev) {+ if (!dev || dev->midiKind() < 0 || dev->midiKind() > 5) return -1;+ auto ns = copyState();+ if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return -1;+ dev->setSampleRate(sampleRate_, maxBlock_);+ ns->chains[chain].midiDevices.push_back(std::move(dev));+ const int32_t idx = static_cast<int32_t>(ns->chains[chain].midiDevices.size()) - 1;+ commit(ns);+ return idx;+}++bool RackCore::removeChainMidiDevice(int32_t chain, int32_t idx) {+ auto ns = copyState();+ if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return false;+ auto& d = ns->chains[chain].midiDevices;+ if (idx < 0 || idx >= static_cast<int32_t>(d.size())) return false;+ d.erase(d.begin() + idx);+ // Mappings follow their MIDI effect: the removed one's go, the ones after it shift down.+ auto& mv = ns->mappings;+ for (auto it = mv.begin(); it != mv.end();) {+ if (it->chainIndex == chain && isMidiTarget(it->deviceIndex)) {+ const int32_t j = midiTargetIndex(it->deviceIndex);+ if (j == idx) {+ it = mv.erase(it);+ continue;+ }+ if (j > idx) it->deviceIndex = midiTarget(j - 1);+ }+ ++it;+ }+ commit(ns);+ return true;+}++bool RackCore::moveChainMidiDevice(int32_t chain, int32_t from, int32_t to) {+ auto ns = copyState();+ if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return false;+ auto& d = ns->chains[chain].midiDevices;+ const int32_t n = static_cast<int32_t>(d.size());+ if (from < 0 || from >= n) return false;+ to = std::clamp(to, 0, n - 1);+ if (to == from) return true;+ auto x = d[from];+ d.erase(d.begin() + from);+ d.insert(d.begin() + to, x);+ for (auto& m : ns->mappings) {+ if (m.chainIndex != chain || !isMidiTarget(m.deviceIndex)) continue;+ const int32_t j = midiTargetIndex(m.deviceIndex);+ if (j == from) m.deviceIndex = midiTarget(to);+ else if (from < to && j > from && j <= to)+ m.deviceIndex = midiTarget(j - 1);+ else if (to < from && j >= to && j < from)+ m.deviceIndex = midiTarget(j + 1);+ }+ commit(ns);+ return true;+}++MidiDevice* RackCore::chainMidiDeviceAt(int32_t chain, int32_t idx) const {+ RackState* st = live();+ if (!st || chain < 0 || chain >= static_cast<int32_t>(st->chains.size())) return nullptr;+ auto& d = st->chains[chain].midiDevices;+ if (idx < 0 || idx >= static_cast<int32_t>(d.size())) return nullptr;+ return d[idx].get();+}+RackCore::ChainControls* RackCore::chainControls(int32_t chain) const {RackState* st = live();if (!st || chain < 0 || chain >= static_cast<int32_t>(st->chains.size())) return nullptr;@@ -273,13 +391,30 @@ RackCore::ChainControls* RackCore::chainControls(int32_t chain) const {void RackCore::setChainZone(int32_t c, int32_t keyLo, int32_t keyHi, int32_t velLo, int32_t velHi) {if (auto* x = chainControls(c)) {- x->keyLo.store(std::clamp(keyLo, 0, 127), std::memory_order_relaxed);- x->keyHi.store(std::clamp(keyHi, 0, 127), std::memory_order_relaxed);- x->velLo.store(std::clamp(velLo, 0, 127), std::memory_order_relaxed);- x->velHi.store(std::clamp(velHi, 0, 127), std::memory_order_relaxed);+ // An edge never crosses the other: lo is held at or below hi.+ keyHi = std::clamp(keyHi, 0, 127);+ velHi = std::clamp(velHi, 0, 127);+ x->keyLo.store(std::clamp(keyLo, 0, keyHi), std::memory_order_relaxed);+ x->keyHi.store(keyHi, std::memory_order_relaxed);+ x->velLo.store(std::clamp(velLo, 0, velHi), std::memory_order_relaxed);+ x->velHi.store(velHi, std::memory_order_relaxed);+ }+}++void RackCore::setChainSelectRange(int32_t c, int32_t lo, int32_t hi) {+ if (auto* x = chainControls(c)) {+ hi = std::clamp(hi, 0, 127);+ x->selLo.store(std::clamp(lo, 0, hi), std::memory_order_relaxed);+ x->selHi.store(hi, std::memory_order_relaxed);}}+void RackCore::chainSelectRange(int32_t c, int32_t& lo, int32_t& hi) const {+ auto* x = chainControls(c);+ lo = x ? x->selLo.load(std::memory_order_relaxed) : 0;+ hi = x ? x->selHi.load(std::memory_order_relaxed) : 127;+}+void RackCore::chainZone(int32_t c, int32_t& keyLo, int32_t& keyHi, int32_t& velLo, int32_t& velHi) const {auto* x = chainControls(c);keyLo = x ? x->keyLo.load(std::memory_order_relaxed) : 0;@@ -299,7 +434,20 @@ int32_t RackCore::addMacroMapping(int32_t macro, int32_t chain, int32_t deviceIndex, int32_t paramIndex, float rangeMin, float rangeMax) {if (macro < 0 || macro >= kNumMacros) return -1;auto ns = copyState();- if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return -1;+ if (deviceIndex == kRackControl) {+ if (paramIndex < 0 || paramIndex >= kRackParams) return -1;+ chain = -1;+ } else if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size()))+ return -1;+ // One macro per target: an existing mapping of the same target moves to this macro.+ for (size_t i = 0; i < ns->mappings.size(); ++i) {+ auto& m = ns->mappings[i];+ if (m.chainIndex != chain || m.deviceIndex != deviceIndex || m.paramIndex != paramIndex) continue;+ m.macro = macro;+ commit(ns);+ applyMacro(macro, macros_[macro].load(std::memory_order_relaxed));+ return static_cast<int32_t>(i);+ }ns->mappings.push_back({macro, chain, deviceIndex, paramIndex, rangeMin, rangeMax});const int32_t idx = static_cast<int32_t>(ns->mappings.size()) - 1;commit(ns);@@ -362,6 +510,10 @@ std::vector<uint8_t> RackCore::serialize() const {putU8(b, static_cast<uint8_t>(pdc_.load(std::memory_order_relaxed)));putF32(b, chainSelect_.load(std::memory_order_relaxed));putU8(b, static_cast<uint8_t>(selFollow_.load(std::memory_order_relaxed)));+ // v9: Instrument Rack mono, MIDI Effect Rack output.+ putU8(b, static_cast<uint8_t>(mono_.load(std::memory_order_relaxed)));+ putU8(b, static_cast<uint8_t>(merge_.load(std::memory_order_relaxed)));+ putU8(b, static_cast<uint8_t>(thru_.load(std::memory_order_relaxed)));if (!st) {putU32(b, 0);putU32(b, 0);@@ -429,6 +581,22 @@ std::vector<uint8_t> RackCore::serialize() const {putU32(b, static_cast<uint32_t>(pc));for (int32_t p = 0; p < pc; ++p) putF32(b, d->getParam(p));}+ // v9: select range, transpose, velocity scale, then the chain's MIDI effects.+ putI32(b, c.ctl->selLo.load(std::memory_order_relaxed));+ putI32(b, c.ctl->selHi.load(std::memory_order_relaxed));+ putI32(b, c.ctl->transpose.load(std::memory_order_relaxed));+ putF32(b, c.ctl->velScale.load(std::memory_order_relaxed));+ putU32(b, static_cast<uint32_t>(c.midiDevices.size()));+ for (auto& m : c.midiDevices) {+ putI32(b, m ? m->midiKind() : -1);+ putU8(b, (m && m->bypassed()) ? 1 : 0);+ const int32_t pc = m ? m->paramCount() : 0;+ putU32(b, static_cast<uint32_t>(pc));+ for (int32_t p = 0; p < pc; ++p) putF32(b, m->getParam(p));+ std::vector<uint8_t> ms = m ? m->getState() : std::vector<uint8_t>{};+ putU32(b, static_cast<uint32_t>(ms.size()));+ b.insert(b.end(), ms.begin(), ms.end());+ }}return b;}@@ -455,6 +623,10 @@ void RackCore::deserialize(const uint8_t* data, int32_t size) {chainSelect_.store(getF32(cur), std::memory_order_relaxed);selFollow_.store(getU8(cur), std::memory_order_relaxed);}+ // v9 (older blobs: the defaults — mono off, merge and pass-through on).+ mono_.store(ver >= 9 ? getU8(cur) : 0, std::memory_order_relaxed);+ merge_.store(ver >= 9 ? getU8(cur) : 1, std::memory_order_relaxed);+ thru_.store(ver >= 9 ? getU8(cur) : 1, std::memory_order_relaxed);auto ns = std::make_shared<RackState>();const uint32_t mapN = getU32(cur);for (uint32_t i = 0; i < mapN && cur.ok(); ++i) {@@ -543,6 +715,33 @@ void RackCore::deserialize(const uint8_t* data, int32_t size) {c.devices.push_back(dev);}}+ if (ver >= 9) {+ const int32_t sl = getI32(cur), sh = getI32(cur);+ c.ctl->selHi.store(std::clamp(sh, 0, 127), std::memory_order_relaxed);+ c.ctl->selLo.store(std::clamp(sl, 0, std::clamp(sh, 0, 127)), std::memory_order_relaxed);+ c.ctl->transpose.store(std::clamp(getI32(cur), -48, 48), std::memory_order_relaxed);+ const float vs = getF32(cur);+ c.ctl->velScale.store(std::isfinite(vs) ? std::clamp(vs, 0.0f, 2.0f) : 1.0f, std::memory_order_relaxed);+ const uint32_t midiN = getU32(cur);+ for (uint32_t j = 0; j < midiN && cur.ok(); ++j) {+ const int32_t mk = getI32(cur);+ const bool byp = getU8(cur) != 0;+ const uint32_t pc = getU32(cur);+ auto md = makeChainMidiDevice(mk);+ if (md) md->setSampleRate(sampleRate_, maxBlock_);+ for (uint32_t p = 0; p < pc && cur.ok(); ++p) {+ const float pv = getF32(cur);+ if (md) md->setParam(static_cast<int32_t>(p), pv);+ }+ const uint32_t msLen = getU32(cur);+ const uint8_t* msPtr = cur.take(msLen);+ if (md) {+ if (msPtr && msLen > 0) md->setState(msPtr, static_cast<int32_t>(msLen));+ md->setBypassed(byp);+ c.midiDevices.push_back(std::move(md));+ }+ }+ }ns->chains.push_back(std::move(c));}commit(ns);@@ -601,6 +800,10 @@ void RackCore::applyMacro(int32_t macro, float value) {for (auto& m : st->mappings) {if (m.macro != macro) continue;const float target = m.rangeMin + applyCurve(value, m.curve) * (m.rangeMax - m.rangeMin);+ if (m.deviceIndex == kRackControl) { // rack-level control, no chain+ if (m.paramIndex == RackSelector) chainSelect_.store(std::clamp(target, 0.0f, 1.0f), std::memory_order_relaxed);+ continue;+ }if (m.chainIndex < 0 || m.chainIndex >= static_cast<int32_t>(st->chains.size())) continue;auto& c = st->chains[m.chainIndex];if (m.deviceIndex == kPadControls) {@@ -614,6 +817,10 @@ void RackCore::applyMacro(int32_t macro, float value) {case PadDecay: k.decay.store(std::clamp(target, 0.0f, 1.0f), std::memory_order_relaxed); break;default: break;}+ } else if (isMidiTarget(m.deviceIndex)) {+ const int32_t j = midiTargetIndex(m.deviceIndex);+ if (j < static_cast<int32_t>(c.midiDevices.size()) && c.midiDevices[j])+ c.midiDevices[j]->setParam(m.paramIndex, target);} else if (m.deviceIndex < 0) {if (c.instrument) c.instrument->pluginParamSet(m.paramIndex, target);} else if (m.deviceIndex < static_cast<int32_t>(c.devices.size())) {diff --git a/src/native/nota.engine/src/devices/racks/RackCore.h b/src/native/nota.engine/src/devices/racks/RackCore.hindex 64a8a915..4cc76a4f 100644--- a/src/native/nota.engine/src/devices/racks/RackCore.h+++ b/src/native/nota.engine/src/devices/racks/RackCore.h@@ -20,6 +20,7 @@#include "devices/Instrument.h"#include "engine/SnapshotHistory.h"#include "devices/Device.h"+#include "devices/MidiDevice.h"#include "media/SampleBuffer.h"#include "devices/BuiltinDevices.h"@@ -59,11 +60,20 @@ class RackCore {std::atomic<float> ampEnv{0.0f}; // pad decay VCA state: written on the audio thread only;// relaxed so a rack fork can carry it overbool retrig = false; // audio-thread only: noteOn asks for an env kick+ // v9 (specs/040): the MIDI Effect Rack's select range (the Audio Effect Rack keeps+ // using velLo/velHi for it, so its v7/v8 blobs keep their meaning), and a MIDI+ // chain's transpose and velocity scale (its "Volume": 1 = unchanged, 0 = silent).+ std::atomic<int32_t> selLo{0}, selHi{127};+ std::atomic<int32_t> transpose{0}; // semitones, -48..+48+ std::atomic<float> velScale{1.0f}; // 0..2};struct RackChain {std::shared_ptr<Instrument> instrument; // null for effect-rack chainsstd::vector<std::shared_ptr<Device>> devices; // insert chain+ // MIDI effects in front of the chain (v9): a MIDI Effect Rack chain is only these;+ // an Instrument Rack chain runs them before its instrument (issue #329).+ std::vector<std::shared_ptr<MidiDevice>> midiDevices;std::shared_ptr<ChainControls> ctl = std::make_shared<ChainControls>();// Display name (v8). Message thread only — the audio thread never reads it.// Empty means "fall back to the chain instrument's name": a Drum Rack pad that@@ -87,6 +97,16 @@ class RackCore {// A mapping with this deviceIndex targets the chain's own controls (a Drum Rack pad's// strip) rather than a child: paramIndex is a PadParam, in the control's own units.static constexpr int32_t kPadControls = -2;+ // A mapping with this deviceIndex drives a rack-level control (paramIndex RackParam), not a+ // chain child; its chainIndex is -1. v9.+ static constexpr int32_t kRackControl = -3;+ enum RackParam : int32_t { RackSelector = 0, kRackParams };+ // Chain MIDI effect j is addressed as deviceIndex kMidiDeviceBase - j, so the audio-device+ // indices (>= 0) keep their meaning in every rack kind. v9.+ static constexpr int32_t kMidiDeviceBase = -1000;+ static bool isMidiTarget(int32_t deviceIndex) { return deviceIndex <= kMidiDeviceBase; }+ static int32_t midiTargetIndex(int32_t deviceIndex) { return kMidiDeviceBase - deviceIndex; }+ static int32_t midiTarget(int32_t midiIndex) { return kMidiDeviceBase - midiIndex; }enum PadParam : int32_t { PadVolume = 0, PadPan, PadTune, PadDecay, kPadParams };static const char* padParamName(int32_t p) {static const char* n[kPadParams] = {"Volume", "Pan", "Tune", "Decay"};@@ -160,6 +180,10 @@ class RackCore {// + devices. Publishes a fresh Sampler via a state swap (thread-safe, no in-place mutate).bool setChainInstrumentSample(int32_t chain, std::shared_ptr<SampleBuffer> buf, int32_t root, bool loop);bool removeChain(int32_t chain);+ // Copies a chain right after itself: children rebuilt from the rack blob (so hosted plugins,+ // Sampler audio and MIDI effects come along), its controls, and copies of its mappings.+ // Returns the new chain index or -1.+ int32_t duplicateChain(int32_t chain);bool setChainInstrument(int32_t chain, int32_t instKind);int32_t chainInstrumentKind(int32_t chain) const;Instrument* chainInstrument(int32_t chain) const;@@ -173,6 +197,14 @@ class RackCore {bool moveChainDevice(int32_t chain, int32_t from, int32_t to);Device* chainDeviceAt(int32_t chain, int32_t dev) const;+ // Chain MIDI effects (v9): built-in kinds 0..5 only (a MIDI Effect Rack never nests).+ int32_t chainMidiDeviceCount(int32_t chain) const;+ int32_t addChainMidiDevice(int32_t chain, int32_t midiKind);+ int32_t addChainMidiDeviceInstance(int32_t chain, std::shared_ptr<MidiDevice> dev);+ bool removeChainMidiDevice(int32_t chain, int32_t idx);+ bool moveChainMidiDevice(int32_t chain, int32_t from, int32_t to);+ MidiDevice* chainMidiDeviceAt(int32_t chain, int32_t idx) const;+ChainControls* chainControls(int32_t chain) const;void setChainTriggerNote(int32_t c, int32_t note) {if (auto* x = chainControls(c)) x->triggerNote.store(note, std::memory_order_relaxed);@@ -236,6 +268,24 @@ class RackCore {// Key/velocity zone (Instrument Rack): only notes inside the range reach this chain.void setChainZone(int32_t c, int32_t keyLo, int32_t keyHi, int32_t velLo, int32_t velHi);void chainZone(int32_t c, int32_t& keyLo, int32_t& keyHi, int32_t& velLo, int32_t& velHi) const;+ // MIDI Effect Rack select range (v9), 0..127, lo <= hi.+ void setChainSelectRange(int32_t c, int32_t lo, int32_t hi);+ void chainSelectRange(int32_t c, int32_t& lo, int32_t& hi) const;+ void setChainTranspose(int32_t c, int32_t st) {+ if (auto* x = chainControls(c)) x->transpose.store(std::clamp(st, -48, 48), std::memory_order_relaxed);+ }+ int32_t chainTranspose(int32_t c) const {+ auto* x = chainControls(c);+ return x ? x->transpose.load(std::memory_order_relaxed) : 0;+ }+ void setChainVelScale(int32_t c, float v) {+ if (auto* x = chainControls(c))+ x->velScale.store(std::isfinite(v) ? std::clamp(v, 0.0f, 2.0f) : 1.0f, std::memory_order_relaxed);+ }+ float chainVelScale(int32_t c) const {+ auto* x = chainControls(c);+ return x ? x->velScale.load(std::memory_order_relaxed) : 1.0f;+ }float chainMeter(int32_t c) const {auto* x = chainControls(c);return x ? x->meter.load(std::memory_order_relaxed) : 0.0f;@@ -271,6 +321,15 @@ class RackCore {void setSelFollow(bool b) { selFollow_.store(b ? 1 : 0, std::memory_order_relaxed); }float liveSelector() const { return liveSel_.load(std::memory_order_relaxed); }+ // v9 (specs/040): Instrument Rack mono (last-note priority); MIDI Effect Rack output —+ // merge duplicate notes from different chains, pass notes outside every zone through.+ bool rackMono() const { return mono_.load(std::memory_order_relaxed) != 0; }+ void setRackMono(bool b) { mono_.store(b ? 1 : 0, std::memory_order_relaxed); }+ bool rackMerge() const { return merge_.load(std::memory_order_relaxed) != 0; }+ void setRackMerge(bool b) { merge_.store(b ? 1 : 0, std::memory_order_relaxed); }+ bool rackThru() const { return thru_.load(std::memory_order_relaxed) != 0; }+ void setRackThru(bool b) { thru_.store(b ? 1 : 0, std::memory_order_relaxed); }+// ---- macros -----------------------------------------------------------float macroGet(int32_t i) const {return (i >= 0 && i < kNumMacros) ? macros_[i].load(std::memory_order_relaxed) : 0.0f;@@ -298,6 +357,9 @@ class RackCore {}// ---- mappings ---------------------------------------------------------+ // A (chain, device, param) target belongs to one macro: adding a mapping for a target that+ // is already mapped moves it to `macro` (keeping its range and curve) and returns its index.+ // deviceIndex kRackControl targets the rack itself (chain is ignored and stored as -1).int32_t addMacroMapping(int32_t macro, int32_t chain, int32_t deviceIndex, int32_t paramIndex, float rangeMin, float rangeMax);int32_t mappingCount() const {@@ -314,6 +376,13 @@ class RackCore {return (st && i >= 0 && i < static_cast<int32_t>(st->mappings.size())) ? st->mappings[i].curve : 0;}+ // Drive every mapped target from its macro again. After an undo or redo swaps in another+ // copy of the rack, the children it shares with the copy still hold the values the other+ // copy's mappings gave them (specs/040). Message thread.+ void reapplyMacros() {+ for (int32_t i = 0; i < kNumMacros; ++i) applyMacro(i, macros_[i].load(std::memory_order_relaxed));+ }+// ---- undoable edits ---------------------------------------------------// Take over another rack's content (#236). The engine edits a copy of the rack instead// of the rack itself, so the graph snapshot on the undo stack keeps the old rack intact:@@ -358,6 +427,9 @@ class RackCore {std::atomic<int32_t> pdc_{1}; // PDC compensation on(1)/off(0)std::atomic<float> chainSelect_{0.5f}; // Select-mode manual selector 0..1std::atomic<int32_t> selFollow_{0}; // Select follows input level+ std::atomic<int32_t> mono_{0}; // Instrument Rack mono / last note (v9)+ std::atomic<int32_t> merge_{1}; // MIDI Effect Rack: merge duplicate notes (v9)+ std::atomic<int32_t> thru_{1}; // MIDI Effect Rack: pass notes outside every zone (v9)std::atomic<float> liveSel_{0.5f}; // runtime selector position (audio writes, UI reads)double sampleRate_ = 44100.0;int32_t maxBlock_ = kMaxBlock;@@ -371,6 +443,7 @@ class RackCore {states_.publish(std::move(ns));}static void pruneMappings(std::shared_ptr<RackState>& ns, int32_t removedChain);+ static std::shared_ptr<MidiDevice> makeChainMidiDevice(int32_t kind);static void putU8(std::vector<uint8_t>& b, uint8_t v) { b.push_back(v); }static void putU32(std::vector<uint8_t>& b, uint32_t v) {@@ -472,7 +545,7 @@ class RackCore {static constexpr uint32_t kMagic = 0x314B524E; // 'NRK1'static constexpr uint32_t kBlobVersion =- 8; // v2 triggerNote; v3 Sampler; v4 plugins; v5 zones/names/rack-out/curve; v6 drum pad shaping + swing/humanize; v7 effect-rack mode/dry-wet/pdc/select; v8 chain name+ 9; // v2 triggerNote; v3 Sampler; v4 plugins; v5 zones/names/rack-out/curve; v6 drum pad shaping + swing/humanize; v7 effect-rack mode/dry-wet/pdc/select; v8 chain name; v9 chain MIDI effects + select range/transpose/vel scale, mono/merge/thru (specs/040)std::shared_ptr<RackState> authoring_;SnapshotHistory<RackState> states_;diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp b/src/native/nota.engine/src/devices/racks/RackInstrument.cppindex 0684ee6e..63b95f4e 100644--- a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.cpp@@ -5,38 +5,313 @@#include "RackInstrument.h"+#include "engine/NoteExpression.h"+#include <algorithm>#include <cmath>#include <cstring>namespace nota {-void RackInstrument::noteOn(int32_t pitch, float velocity) {+RackInstrument::RackInstrument() : evStore_(new MidiEv[kMaxMidiChains * kChainEvents + 2048]) {+ chainEvs_ = evStore_.get();+ scratchA_ = chainEvs_ + kMaxMidiChains * kChainEvents;+ scratchB_ = scratchA_ + 1024;+}++namespace {+bool evBefore(const MidiEv& a, const MidiEv& b) {+ if (a.off != b.off) return a.off < b.off;+ return !a.on && b.on; // a note-off before a note-on at the same sample+}++// A chain's MIDI effects by identity (0 = none): a fork for an undoable edit shares them, so+// it keeps the signature; adding, removing or replacing one changes it.+template <class Chain> uint64_t midiSig(const Chain& c) {+ if (c.midiDevices.empty()) return 0;+ uint64_t h = 1469598103934665603ull ^ static_cast<uint64_t>(c.midiDevices.size());+ for (const auto& d : c.midiDevices) h = (h ^ reinterpret_cast<uintptr_t>(d.get())) * 1099511628211ull;+ return h | 1; // never 0+}+} // namespace++bool RackInstrument::takesBlockMidi() const {+ RackState* st = live();+ if (!st) return false;+ for (const auto& c : st->chains)+ if (!c.midiDevices.empty()) return true;+ return false;+}++bool RackInstrument::midiChainAt(int32_t c) const {+ RackState* st = live();+ return st && c >= 0 && c < kMaxMidiChains && c < static_cast<int32_t>(st->chains.size()) && !st->chains[c].midiDevices.empty();+}++void RackInstrument::syncChains() {+ RackState* st = live();+ if (!st) return;+ auto& m = *mono_;+ const int32_t n = static_cast<int32_t>(st->chains.size());+ uint64_t h = 1469598103934665603ull ^ static_cast<uint64_t>(n);+ for (int32_t c = 0; c < n; ++c) {+ const auto& ch = st->chains[c];+ h = (h ^ reinterpret_cast<uintptr_t>(ch.instrument.get())) * 1099511628211ull;+ h = (h ^ (c < kMaxMidiChains ? midiSig(ch) : 0)) * 1099511628211ull;+ }+ if (h == m.structure) return;+ const bool first = m.structure == 0;+ m.structure = h;++ // Old index of each chain still here (by its instrument), then the tables at the new places.+ uint16_t route[128] = {};+ uint8_t held[kMaxMidiChains][128] = {};+ const void* ids[kMaxMidiChains] = {};+ uint64_t sigs[kMaxMidiChains] = {};+ for (int32_t c = 0; c < n; ++c) {+ auto& ch = st->chains[c];+ if (!ch.instrument) continue;+ const uint64_t sig = c < kMaxMidiChains ? midiSig(ch) : 0;+ int32_t o = -1;+ for (int32_t k = 0; k < kMaxMidiChains && !first; ++k)+ if (m.chainId[k] == ch.instrument.get()) o = k;+ if (o >= 0 && m.chainSig[o] != 0) {+ if (m.chainSig[o] == sig && c < kMaxMidiChains) {+ // The same MIDI effects at a new place: its held keys and notes move with it.+ std::memcpy(held[c], m.outHeld[o], 128);+ for (int32_t p = 0; p < 128; ++p)+ if (m.midiRoute[p] & (1u << o)) route[p] |= static_cast<uint16_t>(1u << c);+ } else {+ // Its MIDI effects changed (or it's a plain chain now): end the notes they started+ // and what the remaining ones still hold; a held key plays again when struck again.+ for (int32_t p = 0; p < 128; ++p)+ if (m.outHeld[o][p]) ch.instrument->noteOff(p);+ for (auto& d : ch.midiDevices)+ if (d) d->reset();+ }+ } else if (o >= 0 && sig != 0) {+ // A plain chain took MIDI effects: the held keys it played directly end now (its+ // ordinary note-offs skip MIDI chains).+ for (int32_t i = 0; i < m.heldN; ++i) ch.instrument->noteOff(m.held[i]);+ }+ if (c < kMaxMidiChains) {+ ids[c] = ch.instrument.get();+ sigs[c] = sig;+ }+ }+ std::memcpy(m.midiRoute, route, sizeof(route));+ std::memcpy(m.outHeld, held, sizeof(held));+ std::memcpy(m.chainId, ids, sizeof(ids));+ std::memcpy(m.chainSig, sigs, sizeof(sigs));+}++void RackInstrument::deliver(int32_t c, Instrument& inst, const MidiEv& ev) {+ uint8_t& h = mono_->outHeld[c][std::clamp(ev.pitch, 0, 127)];+ if (ev.on) {+ if (h < 255) ++h;+ inst.noteOn(ev.pitch, ev.vel);+ } else {+ if (h > 0) --h;+ inst.noteOff(ev.pitch);+ }+}++void RackInstrument::blockMidi(const MidiEv* evs, int n, int32_t frames, double beatStart, double spb, bool playing) {+ blockPos_ = 0;+ syncChains();+ RackState* st = live();+ const int32_t nc = st ? std::min<int32_t>(static_cast<int32_t>(st->chains.size()), kMaxMidiChains) : 0;+ for (int32_t c = 0; c < kMaxMidiChains; ++c) chainCount_[c] = chainCursor_[c] = 0;+ // Route in block order: a note-on goes to the MIDI chains whose zone holds it, its note-off to+ // the chains its note-on went to — even when the key is played again within the block.+ auto& route = mono_->midiRoute;+ n = std::min(n, 1024);+ for (int i = 0; i < n; ++i) {+ const MidiEv& ev = evs[i];+ const int32_t p = std::clamp(ev.pitch, 0, 127);+ if (ev.on) {+ const int32_t v = std::clamp(static_cast<int32_t>(std::lround(ev.vel * 127.0f)), 0, 127);+ uint16_t mask = 0;+ for (int32_t c = 0; c < nc; ++c) {+ const auto& chain = st->chains[c];+ if (chain.midiDevices.empty() || !chain.instrument) continue;+ const auto& z = *chain.ctl;+ constexpr auto r = std::memory_order_relaxed;+ if (p < z.keyLo.load(r) || p > z.keyHi.load(r) || v < z.velLo.load(r) || v > z.velHi.load(r)) continue;+ mask |= static_cast<uint16_t>(1u << c);+ }+ route[p] |= mask;+ evMask_[i] = mask;+ } else {+ evMask_[i] = route[p];+ route[p] = 0;+ }+ }+ for (int32_t c = 0; c < nc; ++c) {+ auto& chain = st->chains[c];+ if (chain.midiDevices.empty() || !chain.instrument) continue;+ const uint16_t bit = static_cast<uint16_t>(1u << c);+ int m = 0;+ for (int i = 0; i < n; ++i)+ if (evMask_[i] & bit) scratchA_[m++] = evs[i];+ MidiEv* a = scratchA_;+ MidiEv* b = scratchB_;+ for (auto& d : chain.midiDevices) {+ if (!d) continue;+ int out = 0;+ d->process(a, m, b, out, 1024, frames, beatStart, spb, playing);+ std::swap(a, b);+ m = out;+ }+ std::sort(a, a + m, evBefore);+ m = std::min(m, kChainEvents);+ std::copy_n(a, m, chainEvs_ + c * kChainEvents);+ chainCount_[c] = m;+ }+}++void RackInstrument::midiTimeJump(double deltaBeats) {+ RackState* st = live();+ if (!st) return;+ for (auto& c : st->chains)+ for (auto& d : c.midiDevices)+ if (d) d->timeJump(deltaBeats);+}++void RackInstrument::fanOn(int32_t pitch, float velocity, int32_t glideFrom) {RackState* st = live();if (!st) return;const int32_t v = std::clamp((int32_t)std::lround(velocity * 127.0f), 0, 127);- for (auto& c : st->chains) {- if (!c.instrument) continue;+ const float bend = glideFrom >= 0 ? static_cast<float>(glideFrom - pitch) : 0.0f;+ syncChains();+ const int32_t n = static_cast<int32_t>(st->chains.size());+ for (int32_t ci = 0; ci < n; ++ci) {+ auto& c = st->chains[ci];+ if (!c.instrument || midiChainAt(ci)) continue; // a MIDI chain plays its effects' notes (blockMidi)auto* z = c.ctl.get();if (pitch < z->keyLo.load(std::memory_order_relaxed) || pitch > z->keyHi.load(std::memory_order_relaxed) ||v < z->velLo.load(std::memory_order_relaxed) || v > z->velHi.load(std::memory_order_relaxed))continue;c.instrument->noteOn(pitch, velocity);+ // Right after the note-on a bend lands without smoothing: the note starts at the old pitch.+ if (bend != 0.0f && c.instrument->supportsMpe())+ c.instrument->noteExpression(pitch, ExprBend, bend);}}-void RackInstrument::noteOff(int32_t pitch) {+void RackInstrument::fanOff(int32_t pitch) {RackState* st = live();if (!st) return;- for (auto& c : st->chains)- if (c.instrument) c.instrument->noteOff(pitch);+ // Plain chains only: a MIDI chain's effects decide when its notes end (a Length may hold one+ // past the key). A chain that turned into a MIDI chain or back is reconciled by syncChains.+ syncChains();+ const int32_t n = static_cast<int32_t>(st->chains.size());+ for (int32_t ci = 0; ci < n; ++ci)+ if (st->chains[ci].instrument && !midiChainAt(ci)) st->chains[ci].instrument->noteOff(pitch);+}++void RackInstrument::endGlide() {+ auto& m = *mono_;+ if (m.glideLeft > 0 && m.sounding >= 0)+ if (RackState* st = live()) {+ const int32_t n = static_cast<int32_t>(st->chains.size());+ for (int32_t ci = 0; ci < n; ++ci) {+ auto& c = st->chains[ci];+ if (c.instrument && !midiChainAt(ci) && c.instrument->supportsMpe())+ c.instrument->noteExpression(m.sounding, ExprBend, 0.0f);+ }+ }+ m.glideLeft = 0;+}++void RackInstrument::monoRemove(int32_t pitch) {+ auto& m = *mono_;+ for (int32_t i = 0; i < m.heldN; ++i)+ if (m.held[i] == pitch) {+ for (int32_t j = i; j + 1 < m.heldN; ++j) m.held[j] = m.held[j + 1];+ --m.heldN;+ return;+ }+}++void RackInstrument::syncMono() {+ auto& m = *mono_;+ const bool mono = rackMono();+ if (mono == m.wasMono) return;+ m.wasMono = mono;+ endGlide();+ if (mono) {+ // Poly → mono: only the last held key keeps sounding.+ for (int32_t i = 0; i + 1 < m.heldN; ++i) fanOff(m.held[i]);+ m.sounding = m.heldN > 0 ? m.held[m.heldN - 1] : -1;+ } else {+ m.sounding = -1; // mono → poly: the sounding key plays on as a poly note+ }+}++void RackInstrument::noteOn(int32_t pitch, float velocity) {+ if (pitch < 0 || pitch > 127) return;+ syncMono();+ auto& m = *mono_;+ monoRemove(pitch);+ if (m.heldN < 128) m.held[m.heldN++] = static_cast<int8_t>(pitch);+ m.heldVel[pitch] = velocity;+ if (!rackMono()) {+ fanOn(pitch, velocity, -1);+ return;+ }+ // Mono, last-note priority: the new key takes over from the sounding one.+ const int32_t prev = m.sounding;+ if (prev >= 0) fanOff(prev);+ const double ms = rackGlide() * 500.0;+ const bool glide = prev >= 0 && prev != pitch && ms > 0.5;+ fanOn(pitch, velocity, glide ? prev : -1);+ m.sounding = pitch;+ m.glideBend = glide ? static_cast<float>(prev - pitch) : 0.0f;+ m.glideTotal = m.glideLeft = glide ? std::max<int64_t>(1, std::llround(ms * 0.001 * sampleRate_)) : 0;+}++void RackInstrument::noteOff(int32_t pitch) {+ if (pitch < 0 || pitch > 127) return;+ syncMono();+ auto& m = *mono_;+ monoRemove(pitch);+ if (!rackMono() || pitch != m.sounding) {+ // Poly, or a key that isn't sounding (superseded, or pressed before mono was on):+ // let it go everywhere — a note-off for a silent pitch is harmless.+ fanOff(pitch);+ if (pitch == m.sounding) m.sounding = -1;+ return;+ }+ fanOff(pitch);+ m.sounding = -1;+ m.glideLeft = 0;+ if (m.heldN > 0) { // fall back to the key still held last, gliding from the released one+ const int32_t back = m.held[m.heldN - 1];+ const double ms = rackGlide() * 500.0;+ const bool glide = ms > 0.5;+ fanOn(back, m.heldVel[back], glide ? pitch : -1);+ m.sounding = back;+ m.glideBend = glide ? static_cast<float>(pitch - back) : 0.0f;+ m.glideTotal = m.glideLeft = glide ? std::max<int64_t>(1, std::llround(ms * 0.001 * sampleRate_)) : 0;+ }}void RackInstrument::allNotesOff() {+ auto& m = *mono_;+ m.heldN = 0;+ m.sounding = -1;+ m.glideLeft = 0;+ std::memset(m.midiRoute, 0, sizeof(m.midiRoute));+ std::memset(m.outHeld, 0, sizeof(m.outHeld));+ for (int32_t c = 0; c < kMaxMidiChains; ++c) chainCount_[c] = 0; // nothing queued plays after thisRackState* st = live();if (!st) return;- for (auto& c : st->chains)+ for (auto& c : st->chains) {if (c.instrument) c.instrument->allNotesOff();+ for (auto& d : c.midiDevices)+ if (d) d->reset(); // flush an Arp's held / pending notes+ }}void RackInstrument::noteExpression(int32_t pitch, int32_t dim, float value) {@@ -72,16 +347,58 @@ void RackInstrument::render(float* out, int32_t frames) {break;}const float rv = rackVolume_.load(std::memory_order_relaxed);+ // Mono glide: the sounding note's bend ramps back to 0 (block rate; the voices smooth it).+ syncMono();+ syncChains();+ auto& m = *mono_;+ if (m.glideLeft > 0 && m.sounding >= 0) {+ m.glideLeft = std::max<int64_t>(0, m.glideLeft - frames);+ const float bend = m.glideBend * static_cast<float>(m.glideLeft) / static_cast<float>(m.glideTotal);+ const int32_t n = static_cast<int32_t>(st->chains.size());+ for (int32_t ci = 0; ci < n; ++ci) {+ auto& c = st->chains[ci];+ if (c.instrument && !midiChainAt(ci) && c.instrument->supportsMpe())+ c.instrument->noteExpression(m.sounding, ExprBend, bend);+ }+ }for (auto& c : st->chains) {if (!c.instrument) continue;const bool solo = c.ctl->solo.load(std::memory_order_relaxed);const bool mute = c.ctl->mute.load(std::memory_order_relaxed);if (mute || (anySolo && !solo)) {c.ctl->meter.store(0.0f, std::memory_order_relaxed);+ // A silent MIDI chain still takes its notes, so a note held across an unmute ends.+ const int32_t ci = static_cast<int32_t>(&c - st->chains.data());+ if (midiChainAt(ci)) {+ int32_t& k = chainCursor_[ci];+ const MidiEv* evs = chainEvs_ + ci * kChainEvents;+ for (; k < chainCount_[ci] && evs[k].off < blockPos_ + frames; ++k) deliver(ci, *c.instrument, evs[k]);+ }continue;}std::memset(scratch_, 0, sizeof(float) * frames * 2);- c.instrument->render(scratch_, frames);+ const int32_t ci = static_cast<int32_t>(&c - st->chains.data());+ if (midiChainAt(ci)) {+ // Play this chain's MIDI-effect output into its instrument at the exact samples.+ int32_t cursor = 0;+ const int32_t end = blockPos_ + frames;+ int32_t& k = chainCursor_[ci];+ const MidiEv* evs = chainEvs_ + ci * kChainEvents;+ while (k < chainCount_[ci]) {+ const MidiEv& ev = evs[k];+ if (ev.off >= end) break;+ const int32_t at = std::clamp(ev.off - blockPos_, 0, frames);+ if (at > cursor) {+ c.instrument->render(&scratch_[cursor * 2], at - cursor);+ cursor = at;+ }+ deliver(ci, *c.instrument, ev);+ ++k;+ }+ if (cursor < frames) c.instrument->render(&scratch_[cursor * 2], frames - cursor);+ } else {+ c.instrument->render(scratch_, frames);+ }for (auto& d : c.devices)if (d && !d->bypassed()) d->process(scratch_, frames);const float g = c.ctl->gain.load(std::memory_order_relaxed);@@ -98,6 +415,7 @@ void RackInstrument::render(float* out, int32_t frames) {}c.ctl->meter.store(peak * g, std::memory_order_relaxed);}+ blockPos_ += frames; // the next segment of this block starts here}std::shared_ptr<Instrument> RackInstrument::clone() const {diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.h b/src/native/nota.engine/src/devices/racks/RackInstrument.hindex 346e89ff..f1fa6358 100644--- a/src/native/nota.engine/src/devices/racks/RackInstrument.h+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.h@@ -3,8 +3,9 @@//// RackInstrument — a parallel-chain Instrument Rack. A container Instrument whose// parallel chains each hold a built-in instrument followed by an insert chain of-// built-in devices. Every note is fanned to every chain (no key/velocity zones in-// v1) and the chain outputs are summed. All the chain/macro/snapshot/persistence+// built-in devices. A note reaches every chain whose key/velocity zone holds it and the+// chain outputs are summed. With mono on (specs/040) the rack plays one note at a time,+// last-note priority, and glides between notes by per-note pitch bend. All the chain/macro/snapshot/persistence// machinery lives in RackCore; this class only adds the Instrument interface.//// Because a RackInstrument is just an Instrument, it slots onto an instrument@@ -23,6 +24,7 @@ namespace nota {class RackInstrument : public Instrument, public RackCore {public:+ RackInstrument();int32_t kind() const override { return 3; } // built-in Instrument Rack (project compat)const char* displayName() const override { return "Nota Instrument Rack"; }bool hostsPlugin() const override { return chainsHostPlugin(); } // Drum Rack too@@ -33,6 +35,15 @@ class RackInstrument : public Instrument, public RackCore {void setTransportInfo(const TransportInfo& ti) override { forwardTransport(ti); }void setTransport(double beatStart, double spb, bool playing) override { forwardTempo(beatStart, spb, playing); }+ // Chain MIDI effects (issue #329): a chain with any runs them on its share of the block's+ // notes up front; render then plays their output into that chain's instrument, sample-accurate.+ bool takesBlockMidi() const override;+ void blockMidi(const MidiEv* evs, int n, int32_t frames, double beatStart, double spb, bool playing) override;+ void midiTimeJump(double deltaBeats) override;+ // MIDI effects run in the first 16 chains; the engine refuses one further down, and a chain+ // with effects moved past them plays its notes as a plain chain.+ static constexpr int32_t kMaxMidiChains = 16;+// ---- note fan-out: a note reaches a chain only if it's inside its key/vel zone --void noteOn(int32_t pitch, float velocity) override;void noteOff(int32_t pitch) override;@@ -49,6 +60,9 @@ class RackInstrument : public Instrument, public RackCore {int32_t latencySamples() const override { return maxChainLatency(); }+ // A fork for an undoable edit plays on with the same held keys, sounding note and glide.+ void shareMonoWith(const RackInstrument& o) { mono_ = o.mono_; }+// ---- macros over the plugin-param surface (automation-free) -------------int32_t pluginParamCount() const override { return kNumMacros; }std::string pluginParamId(int32_t i) const override { return macroParamId(i); }@@ -64,6 +78,57 @@ class RackInstrument : public Instrument, public RackCore {protected:float scratch_[kMaxBlock * 2]; // per-chain render buffer (DrumRack reuses it)++ private:+ // Fan a note-on out to the chains whose zone holds it; with glideFrom >= 0 the chains+ // that take per-note bend start bent to the previous pitch and glide back (mono).+ void fanOn(int32_t pitch, float velocity, int32_t glideFrom);+ void fanOff(int32_t pitch);+ void monoRemove(int32_t pitch);+ void syncMono(); // mono switched since the last call: reconcile the sounding keys+ void endGlide(); // a glide stops half-way: the sounding note returns to its own pitch+ // The chains or their MIDI effects changed since the last call: carry the held routes over+ // to the chains' new places and end the notes whose MIDI effects went away.+ void syncChains();+ void deliver(int32_t c, Instrument& inst, const MidiEv& ev); // a MIDI chain's event into its instrument++ // Note state (audio thread only), shared by every fork of the rack so an edit that swaps+ // the rack object keeps it: held keys in press order (poly too, so switching mono on knows+ // them), their velocities, the sounding pitch in mono, and the glide ramp (bend in+ // semitones from start to 0 over total samples).+ struct MonoState {+ int8_t held[128] = {};+ int32_t heldN = 0;+ float heldVel[128] = {};+ int32_t sounding = -1;+ float glideBend = 0.0f;+ int64_t glideTotal = 0, glideLeft = 0;+ bool wasMono = false;+ // MIDI chains (#329): the chains each held key went to, and the pitches each chain's+ // MIDI effects started in its instrument and haven't ended. They are kept for the chains+ // as they were at `structure`: chain c is the one playing `chainId[c]` (its instrument)+ // with MIDI effects `chainSig[c]` (0 = a plain chain).+ uint16_t midiRoute[128] = {};+ uint8_t outHeld[kMaxMidiChains][128] = {};+ const void* chainId[kMaxMidiChains] = {};+ uint64_t chainSig[kMaxMidiChains] = {};+ uint64_t structure = 0;+ };+ std::shared_ptr<MonoState> mono_ = std::make_shared<MonoState>();++ // Chain MIDI effects (audio thread): each MIDI chain's processed events for this block (its+ // own kChainEvents slots, sorted — a chain's effects emit at most that many per block, so+ // nothing, a release least of all, is dropped), the render position within the block, and+ // the chains each input event goes to.+ static constexpr int32_t kChainEvents = 1024;+ MidiEv* chainEvs_ = nullptr; // kMaxMidiChains × kChainEvents, allocated once in the ctor+ MidiEv* scratchA_ = nullptr; // 1024+ MidiEv* scratchB_ = nullptr; // 1024+ std::unique_ptr<MidiEv[]> evStore_;+ int32_t chainCount_[kMaxMidiChains] = {}, chainCursor_[kMaxMidiChains] = {};+ int32_t blockPos_ = 0;+ uint16_t evMask_[1024] = {}; // per input event: the MIDI chains it goes to (in block order)+ bool midiChainAt(int32_t c) const;};} // namespace notadiff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex f97509ba..3149da76 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -4,6 +4,7 @@// Engine — lifecycle, audio/MIDI device config, preview, tone/transport setters, immutable-graph publish/clone/undo/reset, post-fader meters. Definitions of the rest of the class live in the sibling Engine_*.cpp slices.#include "Engine.h"+#include "devices/racks/RackCore.h"#include "audio_io/AudioBackendFactory.h"#include "media/AudioFile.h"#include "bridge/PluginHostBridge.h"@@ -688,6 +689,7 @@ bool Engine::undo() {if (e.graph) {publishRaw(std::move(e.graph));recomputePdc();+ reapplyRackMacros();applied = true;}for (const auto& c : e.mix) applied |= applyMix(c, false);@@ -696,6 +698,22 @@ bool Engine::undo() {return false;}+// The restored racks drive their mapped targets again: the children they share with the+// copies an edit made still hold what those copies' mappings gave them (specs/040).+void Engine::reapplyRackMacros() {+ if (!authoring_) return;+ auto each = [](const std::shared_ptr<Track>& t) {+ if (!t) return;+ if (auto* r = dynamic_cast<RackCore*>(t->instrument.get())) r->reapplyMacros();+ for (auto& d : t->devices)+ if (auto* r = dynamic_cast<RackCore*>(d.get())) r->reapplyMacros();+ for (auto& m : t->midiEffects)+ if (auto* r = dynamic_cast<RackCore*>(m.get())) r->reapplyMacros();+ };+ for (auto& t : authoring_->tracks) each(t);+ each(authoring_->masterTrack);+}+bool Engine::redo() {while (!redoStack_.empty()) {UndoEntry e = std::move(redoStack_.back());@@ -705,6 +723,7 @@ bool Engine::redo() {if (e.graph) {publishRaw(std::move(e.graph));recomputePdc();+ reapplyRackMacros();applied = true;}for (const auto& c : e.mix) applied |= applyMix(c, true);diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 91f25f65..3f8180da 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -818,6 +818,10 @@ class Engine {int32_t midiEffectScope(int32_t trackId, int32_t index, float* out,int32_t maxN) const; // float scope (Nota Velocity in/out pairs)void midiEffectCommand(int32_t trackId, int32_t index, int32_t cmd); // editor command (Nota Arp: 1 = restart)+ // Opaque state blob of a MIDI effect (the MIDI Effect Rack: its whole structure). Setting+ // it swaps in a restored copy, so the old one stays on the undo stack when checkpoint.+ std::vector<uint8_t> midiEffectGetState(int32_t trackId, int32_t index) const;+ bool midiEffectSetState(int32_t trackId, int32_t index, const uint8_t* data, int32_t size, bool checkpoint);const char* midiEffectName(int32_t trackId, int32_t index) const;int32_t midiEffectParamCount(int32_t trackId, int32_t index) const;const char* midiEffectParamName(int32_t trackId, int32_t index, int32_t paramIndex) const;@@ -874,6 +878,32 @@ class Engine {std::string rackChainName(int32_t trackId, int32_t deviceIndex, int32_t chain) const;void rackSetChainName(int32_t trackId, int32_t deviceIndex, int32_t chain, const std::string& name);int32_t rackChainCount(int32_t trackId, int32_t deviceIndex) const;+ int32_t rackDuplicateChain(int32_t trackId, int32_t deviceIndex, int32_t chain);+ // One undo step for edits the rack takes in place (a chain mix, the mode, the selector, a+ // macro value): fork the rack now, sharing its children and held notes, so the edits that+ // follow land on the fork and Undo brings back the rack as it was.+ bool rackCheckpoint(int32_t trackId, int32_t deviceIndex);+ // A MIDI Effect Rack is addressed as deviceIndex kMidiRackBase − its MIDI effect index.+ static constexpr int32_t kMidiRackBase = -1000;+ // Chain MIDI effects (MIDI Effect Rack chains; Instrument Rack chains, #329).+ int32_t rackChainMidiCount(int32_t trackId, int32_t deviceIndex, int32_t chain) const;+ int32_t rackAddChainMidi(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t kind);+ bool rackRemoveChainMidi(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index);+ bool rackMoveChainMidi(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t from, int32_t to);+ MidiDevice* rackChainMidiAt(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index) const;+ void rackSetChainMidiBypassed(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index, bool b);+ void rackChainSelectRange(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t& lo, int32_t& hi) const;+ void rackSetChainSelectRange(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t lo, int32_t hi);+ int32_t rackChainTranspose(int32_t trackId, int32_t deviceIndex, int32_t chain) const;+ void rackSetChainTranspose(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t st);+ float rackChainVelScale(int32_t trackId, int32_t deviceIndex, int32_t chain) const;+ void rackSetChainVelScale(int32_t trackId, int32_t deviceIndex, int32_t chain, float v);+ bool rackMerge(int32_t trackId, int32_t deviceIndex) const;+ void rackSetMerge(int32_t trackId, int32_t deviceIndex, bool on);+ bool rackThru(int32_t trackId, int32_t deviceIndex) const;+ void rackSetThru(int32_t trackId, int32_t deviceIndex, bool on);+ bool rackMono(int32_t trackId) const;+ void rackSetMono(int32_t trackId, bool on);int32_t rackAddChain(int32_t trackId, int32_t deviceIndex, int32_t instKind); // 0=Synth, 2=Physical, <0=nonebool rackRemoveChain(int32_t trackId, int32_t deviceIndex, int32_t chain);bool rackSetChainInstrument(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t instKind);@@ -1228,6 +1258,7 @@ class Engine {void republishWithTrack(int32_t trackId, std::shared_ptr<Track> nt); // checkpointsvoid republishWithTrackRaw(int32_t trackId, std::shared_ptr<Track> nt); // no undo entryvoid pushUndo(); // snapshot authoring_ onto the undo stack, clear redo+ void reapplyRackMacros(); // after undo/redo: racks drive their shared children againstatic int32_t trackLatency(const Track& t);std::shared_ptr<Instrument> cloneInstrument(const Track& src) const; // duplicateTrack helperstd::shared_ptr<Device> cloneDevice(const Device& src) const;diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cppindex 96c93092..aaaef910 100644--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp@@ -5,6 +5,7 @@#include "Engine.h"#include "devices/DeviceFactory.h"+#include "devices/racks/MidiRack.h"#include "devices/effects/Amp.h"#include "devices/effects/AutoFilter.h"#include "media/AudioFile.h"@@ -913,6 +914,27 @@ void Engine::midiEffectSetParam(int32_t t, int32_t i, int32_t p, float v) {routeCvBaseEdit(2, t, i, p, v);if (auto* m = midiDeviceAt(t, i)) m->setParam(p, v);}+std::vector<uint8_t> Engine::midiEffectGetState(int32_t t, int32_t i) const {+ auto* m = midiDeviceAt(t, i);+ return m ? m->getState() : std::vector<uint8_t>{};+}+bool Engine::midiEffectSetState(int32_t t, int32_t i, const uint8_t* data, int32_t size, bool checkpoint) {+ auto old = findTrackAuthoring(t);+ if (!old || !data || size <= 0 || i < 0 || i >= static_cast<int32_t>(old->midiEffects.size()) || !old->midiEffects[i])+ return false;+ auto fresh = cloneMidiDevice(*old->midiEffects[i]);+ if (!fresh) return false;+ fresh->setState(data, size);+ // A MIDI Effect Rack's copy plays on with the held-note tables, so it ends what the old one+ // started instead of leaving it hanging.+ if (auto* to = dynamic_cast<MidiRack*>(fresh.get()))+ if (auto* from = dynamic_cast<const MidiRack*>(old->midiEffects[i].get())) to->shareRuntimeWith(*from);+ auto nt = cloneTrack(*old);+ nt->midiEffects[i] = std::move(fresh);+ if (checkpoint) republishWithTrack(t, nt);+ else republishWithTrackRaw(t, nt);+ return true;+}void Engine::setMidiEffectBypassed(int32_t t, int32_t i, bool b) {if (auto* m = midiDeviceAt(t, i)) m->setBypassed(b);}diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cppindex 30ab5dbd..3b80eaef 100644--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp@@ -1,10 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Engine — Instrument / Audio-Effect Rack (nested device containers). Resolves a-// (trackId, deviceIndex) pair to the shared RackCore (deviceIndex < 0 = the-// track's instrument rack; >= 0 = the effect-rack device at that chain position)-// and delegates to its editing API. Rack-internal edits publish the rack's OWN+// Engine — Instrument / Audio-Effect / MIDI-Effect Rack (nested device containers). Resolves a+// (trackId, deviceIndex) pair to the shared RackCore (deviceIndex −1 = the track's instrument+// rack; >= 0 = the effect-rack device at that chain position; <= kMidiRackBase = the MIDI+// effect rack at MIDI index kMidiRackBase − deviceIndex, specs/040) and delegates to its+// editing API. Rack-internal edits publish the rack's OWN// snapshot (thread-safe) and don't republish the graph — the rack object is// stable across graph snapshots.@@ -15,6 +16,7 @@#include "devices/racks/RackInstrument.h"#include "devices/racks/RackDevice.h"#include "devices/racks/DrumRack.h"+#include "devices/racks/MidiRack.h"#include "devices/instruments/Sampler.h"#include "SnapshotHistory.h"@@ -129,6 +131,11 @@ bool Engine::rackSetChainSamplerSample(RackCore* Engine::rackCoreAt(int32_t trackId, int32_t deviceIndex) const {auto t = findTrackAuthoring(trackId);if (!t) return nullptr;+ if (deviceIndex <= kMidiRackBase) {+ const int32_t mi = kMidiRackBase - deviceIndex;+ if (mi >= static_cast<int32_t>(t->midiEffects.size()) || !t->midiEffects[mi]) return nullptr;+ return dynamic_cast<RackCore*>(dynamic_cast<MidiRack*>(t->midiEffects[mi].get()));+ }if (deviceIndex < 0) return t->instrument ? dynamic_cast<RackCore*>(t->instrument.get()) : nullptr;if (deviceIndex < static_cast<int32_t>(t->devices.size()))return t->devices[deviceIndex] ? dynamic_cast<RackCore*>(t->devices[deviceIndex].get()) : nullptr;@@ -144,6 +151,20 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {if (!old || !rackCoreAt(trackId, deviceIndex)) return nullptr;auto nt = cloneTrack(*old);RackCore* fresh = nullptr;+ if (deviceIndex <= kMidiRackBase) {+ const int32_t mi = kMidiRackBase - deviceIndex;+ auto* src = dynamic_cast<MidiRack*>(old->midiEffects[mi].get());+ if (!src) return nullptr;+ auto r = std::make_shared<MidiRack>();+ r->forkFrom(*src);+ r->shareRuntimeWith(*src); // held notes play on through the swap+ r->setBypassed(src->bypassed());+ r->setFolded(src->folded());+ fresh = r.get();+ nt->midiEffects[mi] = std::move(r);+ republishWithTrack(trackId, nt);+ return fresh;+ }if (deviceIndex < 0) {auto* src = dynamic_cast<RackInstrument*>(old->instrument.get());if (!src) return nullptr;@@ -151,6 +172,7 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {if (dynamic_cast<DrumRack*>(src)) r = std::make_shared<DrumRack>();else r = std::make_shared<RackInstrument>();r->forkFrom(*src);+ r->shareMonoWith(*src); // held keys, the sounding note and a glide in progress play onr->setBypassed(src->bypassed());r->folded = src->folded;// Playback state the audio thread owns: relaxed atomics, carried over so a held pedal@@ -256,7 +278,29 @@ int32_t Engine::rackChainCount(int32_t t, int32_t di) const {auto* r = rackCoreAt(t, di);return r ? r->chainCount() : 0;}+int32_t Engine::rackDuplicateChain(int32_t t, int32_t di, int32_t c) {+ auto* r = rackCoreAt(t, di);+ if (!r || c < 0 || c >= r->chainCount()) return -1;+ if (di <= kMidiRackBase && r->chainCount() >= MidiRack::kMaxChains) return -1;+ if (di == -1) {+ // The copy goes in after the source and the chains below move down: refuse when that+ // would push a chain's MIDI effects past the first 16 chains, where they don't run.+ const int32_t n = r->chainCount();+ for (int32_t j = c; j < n; ++j)+ if (r->chainMidiDeviceCount(j) > 0 && j + 1 >= RackInstrument::kMaxMidiChains) return -1;+ }+ return rackForEdit(t, di)->duplicateChain(c);+}+bool Engine::rackCheckpoint(int32_t t, int32_t di) { return rackForEdit(t, di) != nullptr; }+bool Engine::rackMono(int32_t t) const {+ auto* r = rackCoreAt(t, -1);+ return r && r->rackMono();+}+void Engine::rackSetMono(int32_t t, bool on) {+ if (auto* r = rackCoreAt(t, -1)) r->setRackMono(on);+}int32_t Engine::rackAddChain(int32_t t, int32_t di, int32_t k) {+ if (auto* cur = rackCoreAt(t, di); cur && di <= kMidiRackBase && cur->chainCount() >= MidiRack::kMaxChains) return -1;auto* r = rackForEdit(t, di);return r ? r->addChain(k) : -1;}@@ -444,6 +488,74 @@ float Engine::rackChainDeviceParamGet(int32_t t, int32_t di, int32_t c, int32_tDevice* dev = r ? r->chainDeviceAt(c, d) : nullptr;return dev ? dev->getParam(p) : 0.0f;}+// ---- chain MIDI effects (MIDI Effect Rack chains; Instrument Rack chains, #329) ----------+int32_t Engine::rackChainMidiCount(int32_t t, int32_t di, int32_t c) const {+ auto* r = rackCoreAt(t, di);+ return r ? r->chainMidiDeviceCount(c) : 0;+}+int32_t Engine::rackAddChainMidi(int32_t t, int32_t di, int32_t c, int32_t kind) {+ auto* r = rackCoreAt(t, di);+ if (!r || c < 0 || c >= r->chainCount() || kind < 0 || kind > 5) return -1;+ if (dynamic_cast<DrumRack*>(r)) return -1; // pads keep their own note handling+ if (di == -1 && c >= RackInstrument::kMaxMidiChains) return -1; // MIDI effects run in the first 16 chains+ return rackForEdit(t, di)->addChainMidiDevice(c, kind);+}+bool Engine::rackRemoveChainMidi(int32_t t, int32_t di, int32_t c, int32_t i) {+ auto* r = rackCoreAt(t, di);+ if (!r || i < 0 || i >= r->chainMidiDeviceCount(c)) return false;+ return rackForEdit(t, di)->removeChainMidiDevice(c, i);+}+bool Engine::rackMoveChainMidi(int32_t t, int32_t di, int32_t c, int32_t from, int32_t to) {+ auto* r = rackCoreAt(t, di);+ if (!r || from < 0 || from >= r->chainMidiDeviceCount(c)) return false;+ return rackForEdit(t, di)->moveChainMidiDevice(c, from, to);+}+MidiDevice* Engine::rackChainMidiAt(int32_t t, int32_t di, int32_t c, int32_t i) const {+ auto* r = rackCoreAt(t, di);+ return r ? r->chainMidiDeviceAt(c, i) : nullptr;+}+void Engine::rackSetChainMidiBypassed(int32_t t, int32_t di, int32_t c, int32_t i, bool b) {+ if (auto* m = rackChainMidiAt(t, di, c, i)) m->setBypassed(b);+}++// ---- chain select range / transpose / velocity scale, rack merge / pass-through (v9) ----+void Engine::rackChainSelectRange(int32_t t, int32_t di, int32_t c, int32_t& lo, int32_t& hi) const {+ lo = 0;+ hi = 127;+ if (auto* r = rackCoreAt(t, di)) r->chainSelectRange(c, lo, hi);+}+void Engine::rackSetChainSelectRange(int32_t t, int32_t di, int32_t c, int32_t lo, int32_t hi) {+ if (auto* r = rackCoreAt(t, di)) r->setChainSelectRange(c, lo, hi);+}+int32_t Engine::rackChainTranspose(int32_t t, int32_t di, int32_t c) const {+ auto* r = rackCoreAt(t, di);+ return r ? r->chainTranspose(c) : 0;+}+void Engine::rackSetChainTranspose(int32_t t, int32_t di, int32_t c, int32_t st) {+ if (auto* r = rackCoreAt(t, di)) r->setChainTranspose(c, st);+}+float Engine::rackChainVelScale(int32_t t, int32_t di, int32_t c) const {+ auto* r = rackCoreAt(t, di);+ return r ? r->chainVelScale(c) : 1.0f;+}+void Engine::rackSetChainVelScale(int32_t t, int32_t di, int32_t c, float v) {+ if (auto* r = rackCoreAt(t, di)) r->setChainVelScale(c, v);+}+bool Engine::rackMerge(int32_t t, int32_t di) const {+ auto* r = rackCoreAt(t, di);+ return !r || r->rackMerge();+}+void Engine::rackSetMerge(int32_t t, int32_t di, bool on) {+ if (auto* r = rackCoreAt(t, di)) r->setRackMerge(on);+}+bool Engine::rackThru(int32_t t, int32_t di) const {+ auto* r = rackCoreAt(t, di);+ return !r || r->rackThru();+}+void Engine::rackSetThru(int32_t t, int32_t di, bool on) {+ if (auto* r = rackCoreAt(t, di)) r->setRackThru(on);+}+void Engine::rackChainDeviceParamSet(int32_t t, int32_t di, int32_t c, int32_t d, int32_t p, float v) {auto* r = rackCoreAt(t, di);Device* dev = r ? r->chainDeviceAt(c, d) : nullptr;@@ -605,7 +717,8 @@ void Engine::rackMacroSet(int32_t t, int32_t di, int32_t m, float v) {int32_t Engine::rackAddMacroMapping(int32_t t, int32_t di, int32_t macro, int32_t chain, int32_t targetDevice,int32_t paramIndex, float rangeMin, float rangeMax) {auto* r = rackCoreAt(t, di);- if (!r || macro < 0 || macro >= RackCore::kNumMacros || chain < 0 || chain >= r->chainCount()) return -1;+ if (!r || macro < 0 || macro >= RackCore::kNumMacros) return -1;+ if (targetDevice != RackCore::kRackControl && (chain < 0 || chain >= r->chainCount())) return -1;return rackForEdit(t, di)->addMacroMapping(macro, chain, targetDevice, paramIndex, rangeMin, rangeMax);}int32_t Engine::rackMappingCount(int32_t t, int32_t di) const {@@ -662,7 +775,9 @@ std::string Engine::rackMacroName(int32_t t, int32_t di, int32_t m) const {return r ? r->macroName(m) : std::string{};}void Engine::rackSetMacroName(int32_t t, int32_t di, int32_t m, const std::string& name) {- if (auto* r = rackCoreAt(t, di)) r->setMacroName(m, name);+ auto* r = rackCoreAt(t, di);+ if (!r || m < 0 || m >= RackCore::kNumMacros || r->macroName(m) == name) return;+ rackForEdit(t, di)->setMacroName(m, name); // undoable (specs/040)}float Engine::rackVolume(int32_t t, int32_t di) const {auto* r = rackCoreAt(t, di);@@ -678,9 +793,14 @@ float Engine::rackGlide(int32_t t, int32_t di) const {void Engine::rackSetGlide(int32_t t, int32_t di, float v) {if (auto* r = rackCoreAt(t, di)) r->setRackGlide(v);}+// Range and curve edits fork the rack like any other rack edit, so they undo (specs/040);+// a range drag brackets itself in an undo group so the whole gesture is one step.bool Engine::rackSetMappingRange(int32_t t, int32_t di, int32_t i, float lo, float hi) {auto* r = rackCoreAt(t, di);- return r && r->setMappingRange(i, lo, hi);+ RackCore::MacroMapping m;+ if (!r || !r->mappingInfo(i, m)) return false;+ if (m.rangeMin == lo && m.rangeMax == hi) return true;+ return rackForEdit(t, di)->setMappingRange(i, lo, hi);}int32_t Engine::rackMappingCurve(int32_t t, int32_t di, int32_t i) const {auto* r = rackCoreAt(t, di);@@ -688,7 +808,10 @@ int32_t Engine::rackMappingCurve(int32_t t, int32_t di, int32_t i) const {}bool Engine::rackSetMappingCurve(int32_t t, int32_t di, int32_t i, int32_t curve) {auto* r = rackCoreAt(t, di);- return r && r->setMappingCurve(i, curve);+ RackCore::MacroMapping m;+ if (!r || !r->mappingInfo(i, m)) return false;+ if (m.curve == std::clamp(curve, 0, 3)) return true;+ return rackForEdit(t, di)->setMappingCurve(i, curve);}// Device-free self-test for the rack core (kept from Phase 1; now exercises thediff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex 9c060848..6c3a910c 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -160,15 +160,17 @@ inline void deliverExpr(Instrument& inst, int32_t pitch, int32_t dim, float valu// An instrument switched off (#148) renders its first block off once more, without the block's// events, fading what was sounding to silence, then releases every voice and held controller;// after that it isn't rendered at all (no CPU) until it is switched back on, so `dst` stays-// silent. The MIDI before it keeps running.+// silent. The MIDI before it keeps running. `beat` / `spb` / `rolling` is the clock the track's+// MIDI effects ran on, for the MIDI effects inside the instrument.template <class Live>-void playEvents(- Instrument& inst, float* dst, int32_t frames, const MidiEv* evs, int n, const ExprEv* xev, int xn, Live&& live) {+void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs, int n, const ExprEv* xev, int xn,+ double beat, double spb, bool rolling, Live&& live) {const bool off = inst.bypassed();if (!off) inst.offSettled.store(false, std::memory_order_relaxed);else if (inst.offSettled.load(std::memory_order_relaxed))return;if (off) n = xn = 0; // nothing new starts on the way out+ if (inst.takesBlockMidi()) inst.blockMidi(evs, n, frames, beat, spb, rolling); // a rack's chain MIDI effects (#329)int32_t cursor = 0;bool liveDone = false;auto renderTo = [&](int32_t to) {@@ -1334,7 +1336,7 @@ void Engine::renderInstrumentRaw(std::sort(evs, evs + n, midiEvLess);std::stable_sort(xev, xev + xn, [](const ExprEv& a, const ExprEv& b) { return a.off < b.off; });- playEvents(*inst, dst, frames, evs, n, xev, xn, [&] {+ playEvents(*inst, dst, frames, evs, n, xev, xn, spb > 0.0 ? blockStart / spb : 0.0, spb, playing, [&] {if (liveExprCount_ > 0) applyLiveExpression(g, t, *inst);});@@ -1435,7 +1437,7 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double s}// The monitored live expression, after the offset-0 notes (as in renderInstrumentRaw).- playEvents(*inst, dst, frames, evs, n, xev, xn, [&] {+ playEvents(*inst, dst, frames, evs, n, xev, xn, p, spb, true, [&] { // the slot's own loop clockif (!monitoring) return;for (int i = 0; i < liveExprCount_; ++i)if (liveExpr_[i].trackId < 0 || liveExpr_[i].trackId == t.id())@@ -1641,9 +1643,11 @@ void Engine::onLoopWrap(Graph* g, double loopStartBeat, double loopEndBeat) {const double jump = loopStartBeat - loopEndBeat;if (g)for (auto& tptr : g->tracks)- if (tptr && tptr->instrument && !sessionActiveOf(*tptr))+ if (tptr && tptr->instrument && !sessionActiveOf(*tptr)) {for (auto& md : tptr->midiEffects)if (md) md->timeJump(jump);+ tptr->instrument->midiTimeJump(jump); // MIDI effects in a rack's chains (#329)+ }if (!recording_.load(std::memory_order_relaxed) || recordSlotPlayer_.load(std::memory_order_acquire)) return;constexpr double kMinHead = 1.0 / 64.0;diff --git a/tests/Nota.SmokeTest/DesignTokenCheck.Browser.cs b/tests/Nota.SmokeTest/DesignTokenCheck.Browser.csindex e0d54d4b..395612fe 100644--- a/tests/Nota.SmokeTest/DesignTokenCheck.Browser.cs+++ b/tests/Nota.SmokeTest/DesignTokenCheck.Browser.cs@@ -16,7 +16,7 @@ internal static partial class DesignTokenCheckvar types = new[] { BuiltinDeviceType.Instrument, BuiltinDeviceType.AudioEffect, BuiltinDeviceType.MidiEffect };var expected = new Dictionary<BuiltinDeviceType, int>{- [BuiltinDeviceType.Instrument] = 16, [BuiltinDeviceType.AudioEffect] = 27, [BuiltinDeviceType.MidiEffect] = 6,+ [BuiltinDeviceType.Instrument] = 16, [BuiltinDeviceType.AudioEffect] = 27, [BuiltinDeviceType.MidiEffect] = 7, // + the MIDI Effect Rack (specs/040)};foreach (var type in types){diff --git a/tests/Nota.SmokeTest/DeviceFoldTests.cs b/tests/Nota.SmokeTest/DeviceFoldTests.csindex 43a99a83..013d7279 100644--- a/tests/Nota.SmokeTest/DeviceFoldTests.cs+++ b/tests/Nota.SmokeTest/DeviceFoldTests.cs@@ -74,10 +74,12 @@ internal static class DeviceFoldTeststry { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { }}- // A v22 document has no folds: it migrates to v23 and every device opens unfolded.+ // A v22 document has no folds: it migrates past v23 (to the current format) and every+ // device opens unfolded.var old = ProjectMigrations.Migrate(new JsonObject { ["formatVersion"] = 22 });- yield return (ProjectService.CurrentFormatVersion == 23 && old["formatVersion"]?.GetValue<int>() == 23,- "fold: a v22 project migrates to v23");+ int migrated = old["formatVersion"]?.GetValue<int>() ?? 0;+ yield return (migrated >= 23 && migrated == ProjectService.CurrentFormatVersion,+ "fold: a v22 project migrates to v23 and on");yield return (!new DeviceDto().Folded && !new MidiDeviceDto().Folded && !new InstrumentDto().Folded,"fold: absent means unfolded");}diff --git a/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.bin b/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.binnew file mode 100644index 00000000..430a7d32Binary files /dev/null and b/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.bin differdiff --git a/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.f32 b/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.f32new file mode 100644index 00000000..cb803801Binary files /dev/null and b/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.f32 differdiff --git a/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.txt b/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.txtnew file mode 100644index 00000000..0d1bb6ee--- /dev/null+++ b/tests/Nota.SmokeTest/Fixtures/racks-v8/effect.txt@@ -0,0 +1,15 @@+chains 2+chain 0 gain=1 pan=-0.3 mute=False solo=False select=0-63+ dev 0 kind=4 -6 0 100 0 120 0 0 0 0 0 0 0 0 -14 0 0 -1+chain 1 gain=0.7 pan=0 mute=False solo=False select=30-127+ dev 0 kind=16 1 0.8 0 0 0 0 0.4363 0.4491 0 0.5 1+macro 0 'Tone' 0.4+macro 1 'Macro 2' 0+macro 2 'Macro 3' 0+macro 3 'Macro 4' 0+macro 4 'Macro 5' 0+macro 5 'Macro 6' 0+macro 6 'Macro 7' 0+macro 7 'Macro 8' 0+map 0 m0 c1 d0 p2 -12..12 curve=3+mode 2 select 0.3 drywet 0.7 pdc True volume 0.9diff --git a/tests/Nota.SmokeTest/Fixtures/racks-v8/instrument.bin b/tests/Nota.SmokeTest/Fixtures/racks-v8/instrument.binnew file mode 100644index 00000000..e8819bb9Binary files /dev/null and b/tests/Nota.SmokeTest/Fixtures/racks-v8/instrument.bin differdiff --git a/tests/Nota.SmokeTest/Fixtures/racks-v8/instrument.txt b/tests/Nota.SmokeTest/Fixtures/racks-v8/instrument.txtnew file mode 100644index 00000000..b7797424--- /dev/null+++ b/tests/Nota.SmokeTest/Fixtures/racks-v8/instrument.txt@@ -0,0 +1,43 @@+chains 3+chain 0 name='Low' inst=0 gain=0.8 pan=0 mute=False solo=False keys=0-70 vel=0-127+ inst p0=0.66+ inst p1=0.02+ inst p2=0.25+ inst p3=0.7+ inst p4=0.2+ inst p5=0.62+ inst p6=0.12+ inst p7=0.8+ dev 0 kind=16 0 0.8 0.8 0 0 0 0.4363 0.4491 0 0.5 1+chain 1 name='' inst=2 gain=1 pan=0.2 mute=True solo=False keys=58-127 vel=0-127+ inst p0=0.85+ inst p1=0.66476+ inst p2=0.1+ inst p3=0.4+ inst p4=0+ inst p5=0.5+ inst p6=0+ inst p7=0.5+chain 2 name='Hard hits' inst=6 gain=1 pan=-0.15 mute=False solo=True keys=36-84 vel=96-127+ inst p0=0+ inst p1=0.5+ inst p2=0.5+ inst p3=0.5+ inst p4=0.85+ inst p5=0+ inst p6=0+ inst p7=0.5+ dev 0 kind=2 0.5265 0.5 0.1 0.6 0.6 0 0.85 0.6 0.3 0.25 0 0 0.3 0.5 0.70711 1 1 0 0 0 1+macro 0 'Bright' 0.6+macro 1 'Space' 0.35+macro 2 'Macro 3' 0+macro 3 'Macro 4' 0.25+macro 4 'Macro 5' 0+macro 5 'Macro 6' 0+macro 6 'Macro 7' 0+macro 7 'Macro 8' 0+map 0 m0 c0 d-1 p0 0.3..0.9 curve=0+map 1 m0 c1 d-1 p1 0.2..0.8 curve=2+map 2 m1 c2 d0 p0 0.6..0 curve=1+map 3 m3 c0 d0 p0 -6..6 curve=3+volume 0.8 glide 0.3diff --git a/tests/Nota.SmokeTest/MidiRackTests.cs b/tests/Nota.SmokeTest/MidiRackTests.csnew file mode 100644index 00000000..db5d2884--- /dev/null+++ b/tests/Nota.SmokeTest/MidiRackTests.cs@@ -0,0 +1,415 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MIDI Effect Rack (specs/040, US4): notes routed by key, velocity and select zones through+// chains of MIDI effects, merged into the instrument — routing, no stuck notes under edits,+// and persistence (blob, undo, copies).+// The rig: a Pentad track whose MIDI chain is [MIDI Effect Rack, Nota Velocity]. What reaches+// the instrument is read from Pentad's held keys; Nota Velocity reports the last note-on's+// velocity and counts the note-ons that pass it.+// Runs with the other rack sections: `dotnet run --project tests/Nota.SmokeTest -- --racks`.++using System.Globalization;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class MidiRackTests+{+ private const int RackKind = 6, VelocityKind = 4, ArpKind = 0, ChordKind = 1;+ private const int Rate = 48000, Block = 256;++ /// <summary>The smoke-test sections, in run order.</summary>+ public static IEnumerable<(string title, Func<IEnumerable<(bool ok, string label)>> run)> Sections()+ {+ yield return ("racks: midi rack routing", Routing);+ yield return ("racks: midi rack no stuck notes", NoStuckNotes);+ yield return ("racks: midi rack persistence", Persistence);+ yield return ("racks: midi rack MCP", Mcp);+ }++ private sealed class Rig : IDisposable+ {+ public readonly NotaEngine E = new();+ public readonly int T;+ public const int Mi = 0, Vel = 1;+ private readonly float[] _buf = new float[Block * 2];++ public Rig()+ {+ T = E.AddPentadTrack();+ E.AddMidiEffect(T, RackKind);+ E.AddMidiEffect(T, VelocityKind);+ }++ public void Render(int blocks = 2) { for (int i = 0; i < blocks; i++) E.RenderOffline(_buf, Block, Rate); }++ public string Held()+ {+ var n = new int[32];+ int k = E.InstrumentHeldNotes(T, n);+ return string.Join(",", n.Take(Math.Max(0, k)).OrderBy(x => x));+ }++ public int NoteOns()+ {+ var s = new float[25];+ return E.MidiEffectScope(T, Vel, s) == 25 ? (int)s[24] : -1;+ }++ public string Play(int pitch, float vel = 0.8f)+ {+ E.TrackNoteOn(T, pitch, vel);+ Render();+ string held = Held();+ E.TrackNoteOff(T, pitch);+ Render(4);+ return held;+ }++ public void Dispose() => E.Dispose();+ }++ private static IEnumerable<(bool, string)> Routing()+ {+ using var r = new Rig();+ var e = r.E;+ int t = r.T, mi = Rig.Mi;+ yield return (e.MidiEffectKind(t, mi) == RackKind && e.MidiRackChainCount(t, mi) == 1, "a new MIDI Effect Rack has one empty chain");+ e.MidiRackAddChain(t, mi);+ e.MidiRackSetChainZone(t, mi, 0, 60, 127, 0, 127);+ e.MidiRackSetChainZone(t, mi, 1, 0, 59, 0, 127);+ e.MidiRackSetChainTranspose(t, mi, 0, 12);+ yield return (r.Play(72) == "84" && r.Play(48) == "48", "a note goes to the chain whose key zone holds it (C5 → +12 on the upper chain, C3 untouched)");+ yield return (r.Held() == "", "a transposed note ends on its transposed pitch");++ e.MidiRackSetChainVelScale(t, mi, 0, 0.5f);+ r.Play(72, 100 / 127f);+ int half = e.MidiEffectLastIn(t, Rig.Vel);+ e.MidiRackSetChainVelScale(t, mi, 0, 0f);+ string silent = r.Play(72);+ e.MidiRackSetChainVelScale(t, mi, 0, 1f);+ yield return (Math.Abs(half - 50) <= 1 && silent == "", $"Volume scales velocity (100 → {half} at 50 %) and 0 % sends nothing ({(silent == "" ? "silent" : silent)})");++ e.MidiRackSetChainMute(t, mi, 0, true);+ string thru = r.Play(72);+ e.MidiRackSetThru(t, mi, false);+ string dropped = r.Play(72);+ e.MidiRackSetChainMute(t, mi, 0, false);+ yield return (thru == "72" && dropped == "", $"a note no chain takes passes through, or not with pass-through off ({thru} / {(dropped == "" ? "dropped" : dropped)})");+ e.MidiRackSetThru(t, mi, true);++ e.MidiRackSetChainSolo(t, mi, 1, true);+ yield return (r.Play(72) == "72" && r.Play(48) == "48", "solo: only the soloed chain takes notes (the rest pass through)");+ e.MidiRackSetChainSolo(t, mi, 1, false);++ e.MidiRackSetChainZone(t, mi, 0, 60, 127, 110, 127);+ e.MidiRackSetThru(t, mi, false);+ string soft = r.Play(72, 100 / 127f), hard = r.Play(72, 120 / 127f);+ yield return (soft == "" && hard == "84", $"a velocity zone takes only hard hits (vel 100: {(soft == "" ? "none" : soft)}, vel 120: {hard})");+ e.MidiRackSetThru(t, mi, true);++ // Select mode: the selector picks the chain whose select range holds it.+ e.MidiRackSetChainZone(t, mi, 0, 0, 127, 0, 127);+ e.MidiRackSetChainZone(t, mi, 1, 0, 127, 0, 127);+ e.MidiRackSetChainTranspose(t, mi, 1, -12);+ e.MidiRackSetChainSelect(t, mi, 0, 0, 63);+ e.MidiRackSetChainSelect(t, mi, 1, 64, 127);+ e.MidiRackSetMode(t, mi, 2);+ e.MidiRackSetSelector(t, mi, 0.2f);+ string low = r.Play(60);+ e.MidiRackSetSelector(t, mi, 0.8f);+ string high = r.Play(60);+ yield return (e.MidiRackMode(t, mi) == 2 && low == "72" && high == "48", $"Select mode: the selector picks the chain ({low} at 25, {high} at 102)");+ e.MidiRackSetMode(t, mi, 1);+ yield return (e.MidiRackMode(t, mi) == 2, "a MIDI Effect Rack has no Serial mode");+ e.MidiRackSetMode(t, mi, 0);++ // Merge: two chains sending one pitch play it once.+ e.MidiRackSetChainTranspose(t, mi, 0, 0);+ e.MidiRackSetChainTranspose(t, mi, 1, 0);+ int before = r.NoteOns();+ r.Play(64);+ int merged = r.NoteOns() - before;+ e.MidiRackSetMerge(t, mi, false);+ before = r.NoteOns();+ r.Play(64);+ int both = r.NoteOns() - before;+ e.MidiRackSetMerge(t, mi, true);+ yield return (merged == 1 && both == 2 && r.Held() == "", $"merge duplicate notes: one note-on with merge, {both} without, none left");++ // A chain's MIDI effects run on its notes: a Chord on the lower chain stacks its notes.+ e.MidiRackSetChainZone(t, mi, 0, 60, 127, 0, 127);+ e.MidiRackSetChainZone(t, mi, 1, 0, 59, 0, 127);+ int chord = e.MidiRackChainDeviceAdd(t, mi, 1, ChordKind);+ for (int p = 0; p < e.MidiRackChainDeviceParamCount(t, mi, 1, chord); p++)+ if (e.MidiRackChainDeviceParamName(t, mi, 1, chord, p) == "Strum") e.MidiRackChainDeviceParamSet(t, mi, 1, chord, p, 0f); // all at once+ string stacked = r.Play(48), plain = r.Play(72);+ yield return (chord == 0 && stacked.Split(',').Length > 1 && plain == "72",+ $"a chain's MIDI effects shape only its notes (C3 → {stacked}, C5 → {plain})");+ e.SetMidiEffectBypassed(t, mi, true);+ yield return (r.Play(48) == "48", "a bypassed rack passes notes straight through");+ e.SetMidiEffectBypassed(t, mi, false);++ // Bypass switched while notes sound: what the chains sent ends, and so does a note held+ // through the bypass once the rack is back on.+ e.MidiRackSetChainTranspose(t, mi, 0, 12);+ e.TrackNoteOn(t, 72, 0.8f);+ r.Render();+ string sounding = r.Held();+ e.SetMidiEffectBypassed(t, mi, true);+ r.Render();+ e.TrackNoteOff(t, 72);+ r.Render(4);+ string afterOff = r.Held();+ e.TrackNoteOn(t, 72, 0.8f);+ r.Render();+ e.SetMidiEffectBypassed(t, mi, false);+ r.Render();+ e.TrackNoteOff(t, 72);+ r.Render(4);+ yield return (sounding.Contains("84") && afterOff == "" && r.Held() == "",+ $"switching bypass with notes held leaves none hanging ({sounding} → {(afterOff == "" ? "none" : afterOff)} / {(r.Held() == "" ? "none" : r.Held())})");++ // A key struck again within one block keeps sounding, then ends.+ e.TrackNoteOn(t, 72, 0.8f);+ r.Render();+ e.TrackNoteOff(t, 72);+ e.TrackNoteOn(t, 72, 0.8f);+ r.Render();+ string again = r.Held();+ e.TrackNoteOff(t, 72);+ r.Render(4);+ yield return (again != "" && r.Held() == "", $"a key struck again in the same block keeps its route ({again}, then {(r.Held() == "" ? "none" : r.Held())})");+ e.MidiRackSetChainTranspose(t, mi, 0, 0);+ }++ private static IEnumerable<(bool, string)> NoStuckNotes()+ {+ using var r = new Rig();+ var e = r.E;+ int t = r.T, mi = Rig.Mi;+ e.MidiRackAddChain(t, mi);+ e.MidiRackAddChain(t, mi);+ e.MidiRackChainDeviceAdd(t, mi, 0, ChordKind);+ e.MidiRackChainDeviceAdd(t, mi, 1, ArpKind);+ var rng = new Random(4040);+ var down = new HashSet<int>();+ int edits = 0;+ for (int step = 0; step < 1000; step++)+ {+ int p = 36 + rng.Next(48);+ if (down.Contains(p)) { e.TrackNoteOff(t, p); down.Remove(p); }+ else { e.TrackNoteOn(t, p, (float)rng.NextDouble()); down.Add(p); }+ if (rng.Next(10) == 0)+ {+ int c = rng.Next(e.MidiRackChainCount(t, mi));+ switch (rng.Next(7))+ {+ case 0: { int lo = rng.Next(100); e.MidiRackSetChainZone(t, mi, c, lo, lo + rng.Next(27), rng.Next(60), 127); break; }+ case 1: e.MidiRackSetMode(t, mi, rng.Next(2) * 2); break;+ case 2: e.MidiRackSetChainMute(t, mi, c, rng.Next(2) == 0); break;+ case 3: e.MidiRackSetChainTranspose(t, mi, c, rng.Next(25) - 12); break;+ case 4: e.MidiRackSetSelector(t, mi, (float)rng.NextDouble()); break;+ case 5: if (e.MidiRackChainCount(t, mi) > 1) e.MidiRackRemoveChain(t, mi, c); else e.MidiRackAddChain(t, mi); break;+ default: e.MidiRackAddChain(t, mi); break;+ }+ edits++;+ }+ r.Render(1);+ }+ foreach (int p in down) e.TrackNoteOff(t, p);+ r.Render(Rate / Block); // a second for releases and the Arp to stop+ string left = r.Held();+ yield return (left == "", $"1000 random notes under {edits} zone / mode / mute / transpose / chain edits leave no note hanging ({(left == "" ? "none" : left)})");+ }++ private static string Dump(NotaEngine e, int t, int mi)+ {+ var s = new System.Text.StringBuilder();+ string F(float v) => v.ToString("0.###", CultureInfo.InvariantCulture);+ int n = e.MidiRackChainCount(t, mi);+ s.Append($"mode {e.MidiRackMode(t, mi)} sel {F(e.MidiRackSelector(t, mi))} merge {e.MidiRackMerge(t, mi)} thru {e.MidiRackThru(t, mi)} chains {n}\n");+ for (int c = 0; c < n; c++)+ {+ e.MidiRackChainZone(t, mi, c, out int kl, out int kh, out int vl, out int vh);+ e.MidiRackChainSelectRange(t, mi, c, out int sl, out int sh);+ s.Append($" {c} '{e.MidiRackChainName(t, mi, c)}' {kl}-{kh}/{vl}-{vh} sel {sl}-{sh} tr {e.MidiRackChainTranspose(t, mi, c)} vs {F(e.MidiRackChainVelScale(t, mi, c))} m {e.MidiRackChainMute(t, mi, c)} s {e.MidiRackChainSolo(t, mi, c)}\n");+ for (int d = 0; d < e.MidiRackChainDeviceCount(t, mi, c); d++)+ {+ s.Append($" dev {e.MidiRackChainDeviceKind(t, mi, c, d)} byp {e.MidiRackChainDeviceBypassed(t, mi, c, d)}");+ for (int p = 0; p < e.MidiRackChainDeviceParamCount(t, mi, c, d); p++) s.Append(' ').Append(F(e.MidiRackChainDeviceParamGet(t, mi, c, d, p)));+ s.Append('\n');+ }+ }+ for (int m = 0; m < 8; m++) s.Append($" macro {m} '{e.MidiRackMacroName(t, mi, m)}' {F(e.MidiRackMacroGet(t, mi, m))}\n");+ for (int i = 0; i < e.MidiRackMappingCount(t, mi); i++)+ {+ e.MidiRackMappingInfo(t, mi, i, out int mm, out int ch, out int dv, out int pp, out float lo, out float hi, out int cv);+ s.Append($" map {mm} c{ch} d{dv} p{pp} {F(lo)}..{F(hi)} curve {cv}\n");+ }+ return s.ToString();+ }++ // A rack with a bit of everything, for the round trips.+ private static void Furnish(NotaEngine e, int t, int mi)+ {+ e.MidiRackAddChain(t, mi);+ e.MidiRackSetChainName(t, mi, 0, "Arp lead");+ e.MidiRackSetChainZone(t, mi, 0, 60, 127, 0, 127);+ e.MidiRackSetChainZone(t, mi, 1, 0, 59, 10, 120);+ e.MidiRackSetChainSelect(t, mi, 1, 64, 127);+ e.MidiRackSetChainTranspose(t, mi, 1, -7);+ e.MidiRackSetChainVelScale(t, mi, 1, 0.75f);+ e.MidiRackSetChainSolo(t, mi, 0, true);+ int arp = e.MidiRackChainDeviceAdd(t, mi, 0, ArpKind);+ e.MidiRackChainDeviceParamSet(t, mi, 0, arp, 3, 0.4f);+ e.MidiRackChainDeviceAdd(t, mi, 1, ChordKind);+ e.MidiRackChainDeviceSetBypassed(t, mi, 1, 0, true);+ e.MidiRackSetMode(t, mi, 2);+ e.MidiRackSetSelector(t, mi, 0.7f);+ e.MidiRackSetMerge(t, mi, false);+ e.MidiRackSetMacroName(t, mi, 0, "Rate");+ e.MidiRackMacroSet(t, mi, 0, 0.3f);+ int m = e.MidiRackAddMacroMapping(t, mi, 0, 0, arp, 0, 0.2f, 0.9f);+ e.MidiRackSetMappingCurve(t, mi, m, 1);+ e.MidiRackAddMacroMapping(t, mi, 1, 0, -3, 0, 0f, 1f); // the selector+ }++ private static IEnumerable<(bool, string)> Persistence()+ {+ using var e = new NotaEngine();+ int t = e.AddPentadTrack();+ int mi = e.AddMidiEffect(t, RackKind);+ Furnish(e, t, mi);+ string want = Dump(e, t, mi);++ byte[] blob = e.MidiEffectGetState(t, mi);+ int t2 = e.AddPentadTrack();+ int mi2 = e.AddMidiEffect(t2, RackKind);+ bool set = e.MidiEffectSetState(t2, mi2, blob, false);+ string got = Dump(e, t2, mi2);+ yield return (blob.Length > 0 && set && got == want, "the state blob carries every chain, device, zone, macro and output setting" + (got == want ? "" : $"\n--- want\n{want}--- got\n{got}"));++ int dupTrack = e.DuplicateTrack(t);+ yield return (dupTrack > 0 && Dump(e, dupTrack, 0) == want, "duplicating the track copies the rack");++ e.CopyMidiEffect(t, mi);+ int pasted = e.PasteMidiEffect(t2, -1);+ yield return (pasted >= 0 && Dump(e, t2, pasted) == want, "copy / paste of the rack keeps it all");++ int chains = e.MidiRackChainCount(t, mi);+ e.MidiRackAddChain(t, mi);+ bool added = e.MidiRackChainCount(t, mi) == chains + 1;+ e.Undo();+ bool undone = Dump(e, t, mi) == want;+ e.Redo();+ yield return (added && undone && e.MidiRackChainCount(t, mi) == chains + 1, "adding a chain is one undo step");+ e.Undo();++ e.MidiRackChainDeviceAdd(t, mi, 1, ArpKind);+ e.Undo();+ string afterDev = Dump(e, t, mi);+ e.MidiRackSetChainName(t, mi, 1, "Chords");+ e.Undo();+ string afterName = Dump(e, t, mi);+ e.MidiRackSetMappingCurve(t, mi, 0, 3);+ e.Undo();+ string afterCurve = Dump(e, t, mi);+ string bad = afterDev != want ? $"device\n{want}---\n{afterDev}" : afterName != want ? $"name\n{afterName}" : afterCurve != want ? $"curve\n{afterCurve}" : "";+ yield return (bad == "", "device, name and curve edits each undo back to where they were" + (bad == "" ? "" : $" — differs after {bad}"));++ // Project save → reopen, and a user preset save → load on another track.+ string dir = Path.Combine(Path.GetTempPath(), $"nota-midirack-{Guid.NewGuid():N}");+ try+ {+ var transport = new TransportState(120.0, 1.0, false, false);+ ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), dir, e);+ using var dst = new NotaEngine();+ var warn = ProjectService.Apply(ProjectService.Load(dir), dst, dir);+ int lt = -1;+ for (int i = 0; i < dst.TrackCount && lt < 0; i++)+ {+ if (!dst.TryGetTrackInfo(i, out var info)) continue;+ if (dst.TrackMidiEffectCount(info.Id) > 0 && dst.MidiEffectKind(info.Id, 0) == RackKind) lt = info.Id;+ }+ yield return (warn.Count == 0 && lt > 0 && Dump(dst, lt, 0) == want, $"the rack survives a project save and reopen ({warn.Count} warnings)");++ var preset = PresetService.CaptureMidiEffect(e, t, mi, "Split arp");+ int pt = e.AddPentadTrack();+ string err = preset is null ? "no preset" : PresetService.Apply(preset, e, pt);+ yield return (err == "" && Dump(e, pt, 0) == want, "a rack preset brings back the whole rack" + (err == "" ? "" : $" ({err})"));+ }+ finally { try { Directory.Delete(dir, true); } catch (IOException) { } }++ for (int i = 0; i < 20; i++) e.MidiRackAddChain(t, mi);+ yield return (e.MidiRackChainCount(t, mi) == 16 && e.MidiRackAddChain(t, mi) < 0, "a MIDI Effect Rack holds up to 16 chains");+ }++ // The quickstart's MCP walkthrough: an arp above C3, chords below, accents on hard hits.+ private static IEnumerable<(bool, string)> Mcp()+ {+ using var r = new Rig();+ var e = r.E;+ int t = r.T;+ var fx = new Nota.Mcp.Tools.MidiFxTools(e, new SyncDispatch(), new NoRefresh());+ var rack = new Nota.Mcp.Tools.MidiRackTools(e, new SyncDispatch(), new NoRefresh());+ yield return (fx.ListMidiFxKinds().Any(k => k.Kind == RackKind), "list_midi_fx_kinds lists the MIDI Effect Rack");+ int mi = Rig.Mi;+ rack.AddChain(t, mi, "Chords").Wait();+ rack.AddChain(t, mi, "Accents").Wait();+ rack.SetChainName(t, mi, 0, "Arp lead").Wait();+ rack.SetChainZone(t, mi, 0, keyLo: "C3").Wait();+ rack.SetChainZone(t, mi, 1, keyHi: "B2").Wait();+ rack.SetChainZone(t, mi, 2, velLo: 110).Wait();+ rack.SetChainMix(t, mi, 0, transpose: 12).Wait();+ rack.SetChainMix(t, mi, 1, transpose: -12).Wait();+ rack.SetChainMix(t, mi, 2, transpose: 7).Wait();+ rack.SetOutput(t, mi, merge: false).Wait();+ var snap = rack.GetMidiRack(t, mi).Result;+ yield return (snap.Chains.Length == 3 && snap.Chains[0].KeyLo == 48 && snap.Chains[1].KeyHi == 47 && snap.Chains[2].VelLo == 110 && !snap.Merge,+ "zones by note name and output switches land (C3 = 48)");+ string low = r.Play(36), mid = r.Play(64), hard = r.Play(64, 120 / 127f);+ yield return (low == "24" && mid == "76" && hard == "71,76", $"notes follow the zones (C2 → {low}, E4 → {mid}, a hard E4 → {hard})");+ rack.SetMode(t, mi, "select").Wait();+ rack.SetChainZone(t, mi, 0, selLo: 0, selHi: 63).Wait();+ rack.SetSelector(t, mi, 100).Wait();+ string sel = r.Play(64);+ yield return (rack.GetMidiRack(t, mi).Result.Mode == "select" && sel == "64", $"Select mode with the selector outside the chain's range passes the note through ({sel})");+ int map = rack.AddMapping(t, mi, 0, 0, -3, 0, 0f, 1f).Result;+ rack.SetMacro(t, mi, 0, value: 0.2f, name: "Section").Wait();+ var macros = rack.GetMacros(t, mi).Result;+ yield return (map >= 0 && macros[0].Name == "Section" && macros[0].Targets == 1 && Math.Abs(rack.GetMidiRack(t, mi).Result.Selector - 25) <= 1,+ "a macro mapped to the selector drives it");++ // Value edits over MCP keep a held note sounding.+ e.TrackNoteOn(t, 72, 0.8f);+ r.Render();+ string heldBefore = r.Held();+ rack.SetSelector(t, mi, 30).Wait();+ rack.SetMacro(t, mi, 3, value: 0.3f).Wait();+ rack.SetChainMix(t, mi, 2, velScale: 1.2f).Wait();+ r.Render();+ string heldAfter = r.Held();+ e.TrackNoteOff(t, 72);+ r.Render(4);+ yield return (heldBefore != "" && heldAfter == heldBefore && r.Held() == "",+ $"selector, macro and mix edits over MCP leave held notes playing ({heldBefore} → {(heldAfter == "" ? "cut" : heldAfter)})");++ // In-place edits over MCP undo one call at a time.+ int tr = e.MidiRackChainTranspose(t, mi, 0), mode = e.MidiRackMode(t, mi);+ float macro = e.MidiRackMacroGet(t, mi, 3);+ rack.SetChainMix(t, mi, 0, transpose: tr + 5).Wait();+ rack.SetMode(t, mi, mode == 2 ? "parallel" : "select").Wait();+ rack.SetMacro(t, mi, 3, value: macro > 0.5f ? 0.1f : 0.9f).Wait();+ bool changed = e.MidiRackChainTranspose(t, mi, 0) == tr + 5 && e.MidiRackMode(t, mi) != mode;+ e.Undo();+ bool macroBack = Math.Abs(e.MidiRackMacroGet(t, mi, 3) - macro) < 1e-4;+ e.Undo();+ bool modeBack = e.MidiRackMode(t, mi) == mode && e.MidiRackChainTranspose(t, mi, 0) == tr + 5;+ e.Undo();+ yield return (changed && macroBack && modeBack && e.MidiRackChainTranspose(t, mi, 0) == tr,+ "set_midi_rack_chain_mix / _mode / _macro each undo as one step");+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 7a7266a4..0b0c01a9 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -411,6 +411,23 @@ if (args.Length >= 1 && args[0] == "--warp-split")Console.WriteLine(failures == 0 ? "WARP SPLIT PASSED" : $"WARP SPLIT FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Writes the racks-redesign v8 fixtures (run on the engine from before specs/040 only).+if (args.Length >= 1 && args[0] == "--rack-fixtures")+{+ RackRedesignTests.WriteFixtures();+ return 0;+}+// Racks redesign (specs/040) alone: `--racks`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--racks")+{+ foreach (var (title, run) in RackSections())+ {+ Console.WriteLine($"-- {title} --");+ foreach (var (ok, label) in run()) Check(ok, label);+ }+ Console.WriteLine(failures == 0 ? "RACKS PASSED" : $"RACKS FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Device copy / duplicate audit + rack undo alone: `--device-copy`. Also part of the full run.if (args.Length >= 1 && args[0] == "--device-copy"){@@ -15120,6 +15137,13 @@ Console.WriteLine("-- device remove undo --");foreach (var (ok, label) in DeviceRemoveUndoTests.Run()) Check(ok, label);Console.WriteLine("-- device copy + rack undo --");foreach (var (ok, label) in DeviceCopyTests.Run()) Check(ok, label);++// --- racks redesign (specs/040): v8 compatibility, mapping rules, MIDI racks, chain MIDI effects ---+foreach (var (title, run) in RackSections())+{+ Console.WriteLine($"-- {title} --");+ foreach (var (ok, label) in run()) Check(ok, label);+}Console.WriteLine("-- pads + warp toggle --");foreach (var (ok, label) in PadAndWarpTests.Run()) Check(ok, label);@@ -15165,3 +15189,6 @@ foreach (var (ok, label) in AppUpdaterTests.Run()) Check(ok, label);Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");return failures == 0 ? 0 : 1;++static IEnumerable<(string title, Func<IEnumerable<(bool ok, string label)>> run)> RackSections() =>+ RackRedesignTests.Sections().Concat(MidiRackTests.Sections()).Concat(RackChainMidiTests.Sections());diff --git a/tests/Nota.SmokeTest/RackChainMidiTests.cs b/tests/Nota.SmokeTest/RackChainMidiTests.csnew file mode 100644index 00000000..7bbc59bd--- /dev/null+++ b/tests/Nota.SmokeTest/RackChainMidiTests.cs@@ -0,0 +1,225 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MIDI effects inside Instrument Rack chains (specs/040, US6, issue #329): a chain runs MIDI+// effects → instrument → audio effects, sample-accurate and on the same clock as a track's MIDI+// effects, and keeps them through save, copy and undo.+// Timing is checked by sound: a Sampler on a generated sine is deterministic, so an Arp in a+// rack chain must render the same samples as the same Arp on a plain Sampler track, across a+// loop seam.+// Runs with the other rack sections: `dotnet run --project tests/Nota.SmokeTest -- --racks`.++using System.Globalization;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class RackChainMidiTests+{+ private const int Rate = 48000, Block = 512, Arp = 0, Chord = 1, Length = 3, Pentad = 14;++ /// <summary>The smoke-test sections, in run order.</summary>+ public static IEnumerable<(string title, Func<IEnumerable<(bool ok, string label)>> run)> Sections()+ {+ yield return ("racks: chain MIDI effects", ChainMidi);+ }++ private static string Sine()+ {+ string path = Path.Combine(Path.GetTempPath(), "nota-rack-chain-midi-sine.wav");+ WavWriter.WriteSine(path, 2.0, 220.0, Rate);+ return path;+ }++ private static readonly NotaNote[] Chord3 = [new(60, 0, 3.5, 0.8f), new(64, 0, 3.5, 0.8f), new(67, 0, 3.5, 0.8f)];++ // Render seconds of a track playing a held chord from beat 0, looping beats 0–2.+ private static float[] Play(NotaEngine e, int t, double seconds)+ {+ int clip = e.AddMidiClip(t, 0, 4);+ e.SetClipNotes(t, clip, Chord3);+ e.SetLoop(true, 0, 2);+ e.Seek(0);+ e.Play();+ int frames = (int)(seconds * Rate);+ var all = new float[frames * 2];+ var buf = new float[Block * 2];+ for (int done = 0; done < frames; done += Block)+ {+ int n = Math.Min(Block, frames - done);+ e.RenderOffline(buf, n, Rate);+ Array.Copy(buf, 0, all, done * 2, n * 2);+ }+ e.Stop();+ return all;+ }++ private static string Held(NotaEngine e, int t, int c)+ {+ var b = new int[32];+ int n = e.RackChainInstrumentHeldNotes(t, c, b);+ return string.Join(",", b.Take(Math.Max(0, n)).OrderBy(x => x));+ }++ private static void Render(NotaEngine e, int blocks)+ {+ var buf = new float[Block * 2];+ for (int i = 0; i < blocks; i++) e.RenderOffline(buf, Block, Rate);+ }++ private static IEnumerable<(bool, string)> ChainMidi()+ {+ string wav = Sine();++ // 1. Same Arp, same notes, same samples: on a track vs in a rack chain, over a loop seam.+ float[] track, rack;+ using (var e = new NotaEngine())+ {+ int t = e.AddSamplerTrack(wav, 60, false);+ e.AddMidiEffect(t, Arp);+ track = Play(e, t, 3.0);+ }+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int c = e.RackAddSamplerChain(t, wav, 60, false);+ e.RackChainMidiAdd(t, c, Arp);+ rack = Play(e, t, 3.0);+ }+ double diff = 0, peak = 0;+ for (int i = 0; i < Math.Min(track.Length, rack.Length); i++) { diff = Math.Max(diff, Math.Abs(track[i] - rack[i])); peak = Math.Max(peak, Math.Abs(track[i])); }+ yield return (peak > 0.01 && diff < 1e-4,+ string.Create(CultureInfo.InvariantCulture, $"an Arp in a rack chain plays the samples it plays on a track, across a loop seam (max diff {diff:E1}, peak {peak:F2})"));++ // The same through a MIDI Effect Rack chain: a key played again on the loop seam keeps+ // its route, so the Arp in the chain lets go of the old one.+ float[] viaMidiRack;+ using (var e = new NotaEngine())+ {+ int t = e.AddSamplerTrack(wav, 60, false);+ int mi = e.AddMidiEffect(t, 6);+ e.MidiRackChainDeviceAdd(t, mi, 0, Arp);+ viaMidiRack = Play(e, t, 3.0);+ }+ double d2 = 0;+ for (int i = 0; i < Math.Min(track.Length, viaMidiRack.Length); i++) d2 = Math.Max(d2, Math.Abs(track[i] - viaMidiRack[i]));+ yield return (d2 < 1e-4, string.Create(CultureInfo.InvariantCulture, $"an Arp in a MIDI Effect Rack chain plays what it plays on the track, across the seam (max diff {d2:E1})"));++ // 2. A chain's MIDI effects shape only that chain; zones come first.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int a = e.RackAddChain(t, Pentad), b = e.RackAddChain(t, Pentad);+ int ch = e.RackChainMidiAdd(t, a, Chord);+ for (int p = 0; p < e.RackChainMidiParamCount(t, a, ch); p++)+ if (e.RackChainMidiParamName(t, a, ch, p) == "Strum") e.RackChainMidiParamSet(t, a, ch, p, 0f);+ e.TrackNoteOn(t, 60, 0.8f);+ Render(e, 4);+ string stacked = Held(e, t, a), plain = Held(e, t, b);+ e.TrackNoteOff(t, 60);+ Render(e, 8);+ yield return (stacked.Split(',').Length > 1 && plain == "60", $"a chain's Chord stacks only that chain's notes ({stacked} | {plain})");++ e.RackSetChainZone(t, a, 0, 59, 0, 127);+ e.TrackNoteOn(t, 72, 0.8f);+ Render(e, 4);+ string outside = Held(e, t, a);+ e.TrackNoteOff(t, 72);+ Render(e, 8);+ yield return (outside == "" && Held(e, t, a) == "", "the chain's zone picks the notes before its MIDI effects run");++ // A macro drives a chain MIDI effect's parameter (deviceIndex −1000 − j).+ e.RackSetChainZone(t, a, 0, 127, 0, 127);+ int spread = -1;+ for (int p = 0; p < e.RackChainMidiParamCount(t, a, ch); p++) if (e.RackChainMidiParamName(t, a, ch, p) == "Spread") spread = p;+ float lo = e.RackChainMidiParamMin(t, a, ch, spread), hi = e.RackChainMidiParamMax(t, a, ch, spread);+ e.RackAddMacroMapping(t, 0, a, RackMacroMapping.MidiDeviceBase - ch, spread, lo, hi);+ e.RackMacroSet(t, 0, 1f);+ yield return (spread >= 0 && Math.Abs(e.RackChainMidiParamGet(t, a, ch, spread) - hi) < 1e-3, "a macro drives a chain MIDI effect's parameter");++ // A held key survives an undoable edit: its note-off still reaches the chain.+ e.TrackNoteOn(t, 62, 0.8f);+ Render(e, 4);+ e.RackSetMacroName(t, 0, "Spread");+ e.RackChainMidiAdd(t, b, Chord); // b becomes a MIDI chain too+ e.TrackNoteOff(t, 62);+ Render(e, 16);+ yield return (Held(e, t, a) == "" && Held(e, t, b) == "", "no note hangs when the rack is edited while a key is held");++ // 3. The rack blob, duplication and undo keep the chain MIDI effects.+ byte[] blob = e.GetPluginState(t, -1);+ int t2 = e.AddInstrumentRackTrack();+ e.SetPluginState(t2, -1, blob);+ yield return (e.RackChainMidiCount(t2, 0) == 1 && e.RackChainMidiKind(t2, 0, 0) == Chord && e.RackChainMidiCount(t2, 1) == 1,+ "chain MIDI effects ride the rack blob (project and preset)");+ int dup = e.DuplicateTrack(t);+ yield return (dup > 0 && e.RackChainMidiCount(dup, 0) == 1, "duplicating the track keeps chain MIDI effects");+ int n = e.RackChainMidiCount(t, a);+ e.RackChainMidiAdd(t, a, Arp);+ e.Undo();+ yield return (e.RackChainMidiCount(t, a) == n, "adding a chain MIDI effect is one undo step");+ int dc = e.RackDuplicateChain(t, a);+ yield return (dc >= 0 && e.RackChainMidiCount(t, dc) == 1, "duplicating a chain copies its MIDI effects");++ // 4. MCP.+ var tools = new Nota.Mcp.Tools.RackTools(e, new SyncDispatch(), new NoRefresh());+ int added = tools.AddChainMidiFx(t, b, 2).Result;+ var list = tools.ListChainMidiFx(t, b).Result;+ yield return (added == 1 && list.Length == 2 && list[1].Kind == 2, "add_rack_chain_midi_fx / list_rack_chain_midi_fx");+ }++ // 5. A chain's MIDI effects decide when its notes end, and edits carry held notes along.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int a = e.RackAddChain(t, Pentad), b = e.RackAddChain(t, Pentad);+ e.RackChainMidiAdd(t, b, Length); // Sync 1/8: at 120 BPM a note lasts 0.25 s+ e.TrackNoteOn(t, 60, 0.8f);+ Render(e, 2);+ e.TrackNoteOff(t, 60); // released after ~20 ms+ Render(e, 3);+ string held = Held(e, t, b), plain = Held(e, t, a);+ Render(e, 40);+ yield return (held == "60" && plain == "" && Held(e, t, b) == "",+ $"a Length in a chain holds its note past the key and then ends it ({held} | plain chain {(plain == "" ? "released" : plain)})");++ // A key held into an Arp; the chain in front goes away, the Arp's chain moves up.+ e.RackChainMidiRemove(t, b, 0);+ e.RackChainMidiAdd(t, b, Arp);+ e.TrackNoteOn(t, 64, 0.8f);+ Render(e, 8);+ e.RackRemoveChain(t, a); // the Arp's chain is chain 0 now+ e.TrackNoteOff(t, 64);+ Render(e, 40);+ yield return (Held(e, t, 0) == "", "removing a chain while a key is held still ends its notes in the chains that moved");++ // Removing the last MIDI effect ends what it started.+ e.TrackNoteOn(t, 67, 0.8f);+ Render(e, 8);+ e.RackChainMidiRemove(t, 0, 0);+ Render(e, 2);+ string afterRemove = Held(e, t, 0);+ e.TrackNoteOff(t, 67);+ Render(e, 8);+ yield return (afterRemove == "" && Held(e, t, 0) == "", $"removing a chain's last MIDI effect ends the notes it was playing ({(afterRemove == "" ? "none" : afterRemove)})");++ // MIDI effects run in the first 16 chains only.+ while (e.RackChainCount(t) < 17) e.RackAddChain(t, Pentad);+ yield return (e.RackChainMidiAdd(t, 16, Arp) < 0 && e.RackChainMidiAdd(t, 15, Arp) >= 0, "MIDI effects go into the first 16 chains only");+ int count = e.RackChainCount(t);+ yield return (e.RackDuplicateChain(t, 0) < 0 && e.RackChainCount(t) == count && e.RackChainMidiCount(t, 15) == 1,+ "duplicating a chain that would push MIDI effects past chain 16 is refused");+ }++ // 6. A Drum Rack keeps its pads' note handling: no MIDI effects in pads.+ using (var e = new NotaEngine())+ {+ int t = e.AddDrumRackTrack();+ yield return (e.RackChainCount(t) == 0 || e.RackChainMidiAdd(t, 0, Arp) < 0, "a Drum Rack pad takes no MIDI effects");+ }+ }+}diff --git a/tests/Nota.SmokeTest/RackRedesignTests.cs b/tests/Nota.SmokeTest/RackRedesignTests.csnew file mode 100644index 00000000..9e583e3c--- /dev/null+++ b/tests/Nota.SmokeTest/RackRedesignTests.cs@@ -0,0 +1,654 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Racks redesign (specs/040-racks-redesign): what the reworked rack engine must keep and add.+// - v8 compatibility: rack blobs saved before the change (Fixtures/racks-v8) load into the+// same settings, and the Audio Effect Rack renders the same samples (FR-029, SC-004).+// The Instrument Rack is compared by its settings, not its audio: the built-in synths+// free-run their oscillators, so two renders of the same notes never match sample for sample.+// - mapping rules, the selector as a macro target, the key-parameter table.+// Fixtures are written once, on the engine from before the change:+// `dotnet run --project tests/Nota.SmokeTest -- --rack-fixtures`.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --racks`.++using System.Globalization;+using System.Text;+using Nota.Application;+using Nota.Infrastructure;+using Nota.Presentation;++namespace Nota.SmokeTest;++internal static class RackRedesignTests+{+ private const int Rate = 48000, Block = 512, EffectFrames = 24 * Block; // ~0.26 s of audio+ private const int Synth = 0, Physical = 2, Volt = 6, Pentad = 14; // instrument kinds+ private const int Eq3 = 16, Reverb = 2, Utility = 4, EffectRack = 5; // device kinds+ private const int RackControl = -3, Selector = 0; // NOTA_RACK_CONTROL target++ /// <summary>The smoke-test sections, in run order.</summary>+ public static IEnumerable<(string title, Func<IEnumerable<(bool ok, string label)>> run)> Sections()+ {+ yield return ("racks: v8 compatibility", V8Compatibility);+ yield return ("racks: instrument mono/glide", MonoGlide);+ yield return ("racks: duplicate chain", DuplicateChain);+ yield return ("racks: edits keep playing state", EditsKeepState);+ yield return ("racks: mapping rules", MappingRules);+ yield return ("racks: macro curves and ranges", CurvesAndRanges);+ yield return ("racks: audio rack select", AudioSelect);+ yield return ("racks: key params table", KeyParamsTable);+ }++ // ---- fixtures -------------------------------------------------------------------++ private static string FixtureDir()+ {+ var d = new DirectoryInfo(AppContext.BaseDirectory);+ while (d is not null && !File.Exists(Path.Combine(d.FullName, "Nota.sln"))) d = d.Parent;+ if (d is null) throw new InvalidOperationException("repo root not found");+ return Path.Combine(d.FullName, "tests", "Nota.SmokeTest", "Fixtures", "racks-v8");+ }++ /// <summary>Writes the v8 fixtures. Run on the engine from before the racks redesign only.</summary>+ public static void WriteFixtures()+ {+ string dir = FixtureDir();+ Directory.CreateDirectory(dir);++ using (var e = new NotaEngine())+ {+ int t = BuildInstrumentRack(e);+ File.WriteAllBytes(Path.Combine(dir, "instrument.bin"), e.GetPluginState(t, -1));+ File.WriteAllText(Path.Combine(dir, "instrument.txt"), DumpInstrumentRack(e, t));+ }++ string wav = ToneFile();+ using (var e = new NotaEngine())+ {+ var (t, d) = BuildEffectRack(e, wav);+ File.WriteAllBytes(Path.Combine(dir, "effect.bin"), e.GetPluginState(t, d));+ File.WriteAllText(Path.Combine(dir, "effect.txt"), DumpEffectRack(e, t, d));+ File.WriteAllBytes(Path.Combine(dir, "effect.f32"), FloatsToBytes(RenderEffect(e)));+ }+ Console.WriteLine($"rack fixtures written to {dir}");+ }++ // Three chains with zones, devices, names and mix; four macros, one of them with two+ // targets on different curves (the "Mixed" case), one inverted range; glide set.+ private static int BuildInstrumentRack(NotaEngine e)+ {+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int a = e.RackAddChain(t, Synth), b = e.RackAddChain(t, Physical), c = e.RackAddChain(t, Volt);+ e.RackSetChainZone(t, a, 0, 70, 0, 127);+ e.RackSetChainZone(t, b, 58, 127, 0, 127);+ e.RackSetChainZone(t, c, 36, 84, 96, 127);+ e.RackSetChainName(t, a, "Low");+ e.RackSetChainName(t, c, "Hard hits");+ e.RackSetChainGain(t, a, 0.8f);+ e.RackSetChainPan(t, b, 0.2f);+ e.RackSetChainPan(t, c, -0.15f);+ e.RackSetChainMute(t, b, true);+ e.RackSetChainSolo(t, c, true);+ e.RackChainInstrumentParamSet(t, a, 0, 0.62f);+ int eq = e.RackAddChainDevice(t, a, Eq3);+ e.RackChainDeviceParamSet(t, a, eq, 0, 3.5f);+ e.RackAddChainDevice(t, c, Reverb);++ e.RackSetMacroName(t, 0, "Bright");+ e.RackSetMacroName(t, 1, "Space");+ e.RackMacroSet(t, 0, 0.6f);+ e.RackMacroSet(t, 1, 0.35f);+ e.RackMacroSet(t, 3, 0.25f);+ int m0 = e.RackAddMacroMapping(t, 0, a, -1, 0, 0.3f, 0.9f);+ int m1 = e.RackAddMacroMapping(t, 0, b, -1, 1, 0.2f, 0.8f);+ e.RackSetMappingCurve(t, m0, 0); // Lin+ e.RackSetMappingCurve(t, m1, 2); // Log: macro 1 is "Mixed"+ int m2 = e.RackAddMacroMapping(t, 1, c, 0, 0, 0.6f, 0.0f); // inverted+ e.RackSetMappingCurve(t, m2, 1); // Exp+ int m3 = e.RackAddMacroMapping(t, 3, a, 0, 0, -6f, 6f);+ e.RackSetMappingCurve(t, m3, 3); // S+ e.RackSetVolume(t, 0.8f);+ e.RackSetGlide(t, 0.3f);+ return t;+ }++ // Select mode, two deterministic chains (Utility gain, EQ-3), select ranges that overlap+ // around the selector, dry/wet, latency compensation, one macro target.+ private static (int t, int d) BuildEffectRack(NotaEngine e, string wav)+ {+ int t = e.AddAudioTrack();+ e.AddAudioClip(t, wav, 0);+ int d = e.AddBuiltinDevice(t, EffectRack);+ while (e.RackDevChainCount(t, d) > 0) e.RackDevRemoveChain(t, d, 0);+ int a = e.RackDevAddChain(t, d, -1), b = e.RackDevAddChain(t, d, -1);+ int u = e.RackDevAddChainDevice(t, d, a, Utility);+ e.RackDevChainDeviceParamSet(t, d, a, u, 0, -6f);+ int q = e.RackDevAddChainDevice(t, d, b, Eq3);+ e.RackDevChainDeviceParamSet(t, d, b, q, 0, 6f);+ e.RackDevSetChainZone(t, d, a, 0, 63);+ e.RackDevSetChainZone(t, d, b, 30, 127);+ e.RackDevSetChainGain(t, d, b, 0.7f);+ e.RackDevSetChainPan(t, d, a, -0.3f);+ e.RackDevSetMode(t, d, 2);+ e.RackDevSetChainSelect(t, d, 0.3f);+ e.RackDevSetDryWet(t, d, 0.7f);+ e.RackDevSetPdc(t, d, true);+ e.RackDevSetVolume(t, d, 0.9f);+ e.RackDevSetMacroName(t, d, 0, "Tone");+ e.RackDevMacroSet(t, d, 0, 0.4f);+ int m = e.RackDevAddMacroMapping(t, d, 0, b, q, 2, -12f, 12f);+ e.RackDevSetMappingCurve(t, d, m, 3);+ return (t, d);+ }++ private static string ToneFile()+ {+ string path = Path.Combine(Path.GetTempPath(), "nota-rack-fixture-tones.wav");+ WavWriter.WriteTones(path, 2.0, new[] { 110.0, 880.0, 5000.0 }, 0.2, Rate);+ return path;+ }++ private static float[] RenderEffect(NotaEngine e)+ {+ var all = new float[EffectFrames * 2];+ var buf = new float[Block * 2];+ e.Seek(0);+ e.Play();+ for (int done = 0; done < EffectFrames; done += Block)+ {+ int n = Math.Min(Block, EffectFrames - done);+ e.RenderOffline(buf, n, Rate);+ Array.Copy(buf, 0, all, done * 2, n * 2);+ }+ e.Stop();+ return all;+ }++ // ---- settings dumps (the comparison key for v8 loads) ----------------------------++ private static string F(float v) => v.ToString("0.#####", CultureInfo.InvariantCulture);++ public static string DumpInstrumentRack(NotaEngine e, int t)+ {+ var s = new StringBuilder();+ int n = e.RackChainCount(t);+ s.Append($"chains {n}").Append('\n');+ for (int c = 0; c < n; c++)+ {+ e.RackChainZone(t, c, out int kl, out int kh, out int vl, out int vh);+ s.Append($"chain {c} name='{e.RackChainName(t, c)}' inst={e.RackChainInstrumentKind(t, c)} " ++ $"gain={F(e.RackChainGain(t, c))} pan={F(e.RackChainPan(t, c))} mute={e.RackChainMute(t, c)} " ++ $"solo={e.RackChainSolo(t, c)} keys={kl}-{kh} vel={vl}-{vh}").Append('\n');+ int ip = Math.Min(8, e.RackChainInstrumentParamCount(t, c));+ for (int p = 0; p < ip; p++) s.Append($" inst p{p}={F(e.RackChainInstrumentParamGet(t, c, p))}").Append('\n');+ for (int d = 0; d < e.RackChainDeviceCount(t, c); d++)+ {+ s.Append($" dev {d} kind={e.RackChainDeviceBuiltinKind(t, c, d)}");+ for (int p = 0; p < e.RackChainDeviceParamCount(t, c, d); p++) s.Append(' ').Append(F(e.RackChainDeviceParamGet(t, c, d, p)));+ s.Append('\n');+ }+ }+ for (int m = 0; m < 8; m++) s.Append($"macro {m} '{e.RackMacroName(t, m)}' {F(e.RackMacroGet(t, m))}").Append('\n');+ for (int i = 0; i < e.RackMappingCount(t); i++)+ if (e.RackTryGetMapping(t, i, out var mm))+ s.Append($"map {i} m{mm.Macro} c{mm.Chain} d{mm.DeviceIndex} p{mm.ParamIndex} {F(mm.RangeMin)}..{F(mm.RangeMax)} curve={e.RackMappingCurve(t, i)}").Append('\n');+ s.Append($"volume {F(e.RackVolume(t))} glide {F(e.RackGlide(t))}").Append('\n');+ return s.ToString();+ }++ public static string DumpEffectRack(NotaEngine e, int t, int d)+ {+ var s = new StringBuilder();+ int n = e.RackDevChainCount(t, d);+ s.Append($"chains {n}").Append('\n');+ for (int c = 0; c < n; c++)+ {+ e.RackDevChainZone(t, d, c, out int lo, out int hi);+ s.Append($"chain {c} gain={F(e.RackDevChainGain(t, d, c))} pan={F(e.RackDevChainPan(t, d, c))} " ++ $"mute={e.RackDevChainMute(t, d, c)} solo={e.RackDevChainSolo(t, d, c)} select={lo}-{hi}").Append('\n');+ for (int k = 0; k < e.RackDevChainDeviceCount(t, d, c); k++)+ {+ s.Append($" dev {k} kind={e.RackDevChainDeviceBuiltinKind(t, d, c, k)}");+ for (int p = 0; p < e.RackDevChainDeviceParamCount(t, d, c, k); p++) s.Append(' ').Append(F(e.RackDevChainDeviceParamGet(t, d, c, k, p)));+ s.Append('\n');+ }+ }+ for (int m = 0; m < 8; m++) s.Append($"macro {m} '{e.RackDevMacroName(t, d, m)}' {F(e.RackDevMacroGet(t, d, m))}").Append('\n');+ for (int i = 0; i < e.RackDevMappingCount(t, d); i++)+ if (e.RackDevTryGetMapping(t, d, i, out var mm))+ s.Append($"map {i} m{mm.Macro} c{mm.Chain} d{mm.DeviceIndex} p{mm.ParamIndex} {F(mm.RangeMin)}..{F(mm.RangeMax)} curve={e.RackDevMappingCurve(t, d, i)}").Append('\n');+ s.Append($"mode {e.RackDevMode(t, d)} select {F(e.RackDevChainSelect(t, d))} drywet {F(e.RackDevDryWet(t, d))} " ++ $"pdc {e.RackDevPdc(t, d)} volume {F(e.RackDevVolume(t, d))}").Append('\n');+ return s.ToString();+ }++ private static byte[] FloatsToBytes(float[] f)+ {+ var b = new byte[f.Length * 4];+ Buffer.BlockCopy(f, 0, b, 0, b.Length);+ return b;+ }++ private static float[] BytesToFloats(byte[] b)+ {+ var f = new float[b.Length / 4];+ Buffer.BlockCopy(b, 0, f, 0, f.Length * 4);+ return f;+ }++ // ---- sections -------------------------------------------------------------------++ private static IEnumerable<(bool, string)> V8Compatibility()+ {+ string dir = FixtureDir();+ if (!File.Exists(Path.Combine(dir, "instrument.bin")))+ {+ yield return (false, $"v8 fixtures missing in {dir}");+ yield break;+ }++ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ e.SetPluginState(t, -1, File.ReadAllBytes(Path.Combine(dir, "instrument.bin")));+ string want = File.ReadAllText(Path.Combine(dir, "instrument.txt")).ReplaceLineEndings("\n"), got = DumpInstrumentRack(e, t);+ yield return (got == want, "v8 Instrument Rack blob loads with every setting (zones, mix, macros, per-target curves, glide)"+ + (got == want ? "" : $"\n--- want\n{want}--- got\n{got}"));+ }++ using (var e = new NotaEngine())+ {+ int t = e.AddAudioTrack();+ e.AddAudioClip(t, ToneFile(), 0);+ int d = e.AddBuiltinDevice(t, EffectRack);+ e.SetPluginState(t, d, File.ReadAllBytes(Path.Combine(dir, "effect.bin")));+ string want = File.ReadAllText(Path.Combine(dir, "effect.txt")).ReplaceLineEndings("\n"), got = DumpEffectRack(e, t, d);+ yield return (got == want, "v8 Audio Effect Rack blob loads with every setting (Select mode, select ranges, dry/wet, PDC)"+ + (got == want ? "" : $"\n--- want\n{want}--- got\n{got}"));+ var refAudio = BytesToFloats(File.ReadAllBytes(Path.Combine(dir, "effect.f32")));+ var audio = RenderEffect(e);+ double maxDiff = 0, peak = 0;+ for (int i = 0; i < Math.Min(audio.Length, refAudio.Length); i++)+ {+ maxDiff = Math.Max(maxDiff, Math.Abs(audio[i] - refAudio[i]));+ peak = Math.Max(peak, Math.Abs(refAudio[i]));+ }+ yield return (audio.Length == refAudio.Length && peak > 0.01 && maxDiff < 1e-5,+ string.Create(CultureInfo.InvariantCulture, $"v8 Audio Effect Rack renders the same samples as before (max diff {maxDiff:E1}, peak {peak:F3})"));+ }+ }++ private static bool Near(float a, float b) => Math.Abs(a - b) < 1e-4f;++ private static IEnumerable<(bool, string)> MappingRules()+ {+ using var e = new NotaEngine();++ // One macro per target: mapping a mapped parameter again moves it, range kept.+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int a = e.RackAddChain(t, Synth), b = e.RackAddChain(t, Physical);+ int m = e.RackAddMacroMapping(t, 0, a, -1, 5, 0.2f, 0.7f);+ int again = e.RackAddMacroMapping(t, 3, a, -1, 5, 0f, 1f);+ e.RackTryGetMapping(t, again, out var moved);+ yield return (again == m && e.RackMappingCount(t) == 1 && moved.Macro == 3 && Near(moved.RangeMin, 0.2f) && Near(moved.RangeMax, 0.7f),+ $"mapping a mapped parameter moves it to the new macro and keeps its range ({e.RackMappingCount(t)} mapping, macro {moved.Macro})");+ yield return (e.Undo() && e.RackTryGetMapping(t, 0, out var back) && back.Macro == 0, "moving a mapping to another macro is one undo step");++ // Deleting a chain drops its mappings and re-indexes the rest.+ e.RackAddMacroMapping(t, 1, b, -1, 0, 0f, 1f);+ e.RackRemoveChain(t, a);+ e.RackTryGetMapping(t, 0, out var left);+ yield return (e.RackMappingCount(t) == 1 && left.Chain == 0 && left.Macro == 1,+ $"deleting a chain drops its mappings and shifts the others ({e.RackMappingCount(t)} left, on chain {left.Chain})");++ // The selector as a macro target (Audio Effect Rack): the chain argument is ignored.+ int at = e.AddAudioTrack();+ int d = e.AddBuiltinDevice(at, EffectRack);+ while (e.RackDevChainCount(at, d) < 2) e.RackDevAddChain(at, d, -1);+ int sm = e.RackDevAddMacroMapping(at, d, 1, 99, RackControl, Selector, 0.2f, 0.8f);+ e.RackDevMacroSet(at, d, 1, 1f);+ float hi = e.RackDevChainSelect(at, d);+ e.RackDevMacroSet(at, d, 1, 0f);+ float lo = e.RackDevChainSelect(at, d);+ yield return (sm >= 0 && Near(hi, 0.8f) && Near(lo, 0.2f),+ string.Create(CultureInfo.InvariantCulture, $"a macro mapped to the selector drives it over its range ({lo:0.##}–{hi:0.##})"));+ e.RackDevRemoveChain(at, d, 0);+ yield return (e.RackDevMappingCount(at, d) == 1, "the selector mapping survives deleting a chain");++ // Mappings, the selector target and curves survive the blob (v9 round trip).+ e.RackDevSetMappingCurve(at, d, sm, 2);+ string before = DumpEffectRack(e, at, d);+ int at2 = e.AddAudioTrack();+ int d2 = e.AddBuiltinDevice(at2, EffectRack);+ e.SetPluginState(at2, d2, e.GetPluginState(at, d));+ string after = DumpEffectRack(e, at2, d2);+ yield return (before == after, "a rack blob round-trips its selector mapping and curves" + (before == after ? "" : $"\n{before}\n{after}"));++ // A MIDI effect without a state blob reports none and refuses an empty one.+ int it = e.AddInstrumentTrack();+ int arp = e.AddMidiEffect(it, 0);+ yield return (e.MidiEffectGetState(it, arp).Length == 0 && !e.MidiEffectSetState(it, arp, Array.Empty<byte>(), true),+ "a params-only MIDI effect has no state blob");+ }++ private static IEnumerable<(bool, string)> KeyParamsTable()+ {+ using var e = new NotaEngine();+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);++ foreach (int k in RackKeyParams.Kinds(RackDeviceFamily.Instrument))+ {+ int c = e.RackAddChain(t, k);+ if (c < 0 || e.RackChainInstrumentKind(t, c) != k) { yield return (false, $"instrument kind {k} can be a rack chain"); continue; }+ int n = e.RackChainInstrumentParamCount(t, c);+ yield return Check(RackDeviceFamily.Instrument, k, e.RackChainInstrumentName(t, c), n, p => e.RackChainInstrumentParamName(t, c, p));+ }+ int host = e.RackAddChain(t, Synth);+ foreach (int k in RackKeyParams.Kinds(RackDeviceFamily.AudioEffect))+ {+ int d = e.RackAddChainDevice(t, host, k);+ if (d < 0) { yield return (false, $"audio effect kind {k} can be a chain device"); continue; }+ int n = e.RackChainDeviceParamCount(t, host, d);+ yield return Check(RackDeviceFamily.AudioEffect, k, e.RackChainDeviceName(t, host, d), n, p => e.RackChainDeviceParamName(t, host, d, p));+ }+ int it = e.AddInstrumentTrack();+ foreach (int k in RackKeyParams.Kinds(RackDeviceFamily.MidiEffect))+ {+ int m = e.AddMidiEffect(it, k);+ if (m < 0) { yield return (false, $"MIDI effect kind {k} exists"); continue; }+ int n = e.MidiEffectParamCount(it, m);+ yield return Check(RackDeviceFamily.MidiEffect, k, e.MidiEffectName(it, m), n, p => e.MidiEffectParamName(it, m, p));+ }++ // A kind without an entry (the Sampler) falls back to its first parameters.+ var fb = RackKeyParams.Resolve(RackDeviceFamily.Instrument, 1, 5, p => $"P{p}");+ yield return (fb.SequenceEqual(new[] { 0, 1, 2 }), "a kind without key params shows its first three");+ }++ // Every curated name is found on the device, and the picks are distinct and in range.+ private static (bool, string) Check(RackDeviceFamily f, int kind, string name, int count, Func<int, string> paramName)+ {+ var want = RackKeyParams.Names(f, kind);+ var got = RackKeyParams.Resolve(f, kind, count, paramName);+ var missing = want.Where(w => !Enumerable.Range(0, count).Any(p => string.Equals(paramName(p), w, StringComparison.OrdinalIgnoreCase))).ToList();+ bool ok = want.Count is > 0 and <= RackKeyParams.Max && missing.Count == 0 && got.Length == Math.Min(RackKeyParams.Max, count)+ && got.Distinct().Count() == got.Length && got.All(p => p >= 0 && p < count);+ return (ok, $"{name}: key params {string.Join(", ", got.Select(paramName))}" + (missing.Count > 0 ? $" (missing: {string.Join(", ", missing)})" : ""));+ }++ // ---- mono / glide (US1) -----------------------------------------------------------++ private static float[] RenderFrames(NotaEngine e, int frames)+ {+ var all = new float[frames * 2];+ var buf = new float[Block * 2];+ for (int done = 0; done < frames; done += Block)+ {+ int n = Math.Min(Block, frames - done);+ e.RenderOffline(buf, n, Rate);+ Array.Copy(buf, 0, all, done * 2, n * 2);+ }+ return all;+ }++ // Fundamental of the left channel by autocorrelation: the shortest lag within 90 % of the+ // best one (so a lag of two periods never wins), 60–600 Hz.+ private static double Pitch(float[] st, int from, int len)+ {+ int lo = Rate / 600, hi = Rate / 60;+ var x = new double[len];+ for (int i = 0; i < len; i++) x[i] = st[(from + i) * 2];+ var r = new double[hi + 1];+ double best = 0;+ for (int lag = lo; lag <= hi; lag++)+ {+ double sum = 0, e0 = 0, e1 = 0;+ for (int i = 0; i + lag < len; i++) { sum += x[i] * x[i + lag]; e0 += x[i] * x[i]; e1 += x[i + lag] * x[i + lag]; }+ r[lag] = e0 > 0 && e1 > 0 ? sum / Math.Sqrt(e0 * e1) : 0;+ best = Math.Max(best, r[lag]);+ }+ for (int lag = lo; lag <= hi; lag++)+ if (r[lag] >= 0.9 * best && (lag == lo || r[lag] >= r[lag - 1]) && (lag == hi || r[lag] >= r[lag + 1])) return (double)Rate / lag;+ return 0;+ }++ private static double Hz(int note) => 440.0 * Math.Pow(2, (note - 69) / 12.0);++ private static int Held(NotaEngine e, int t, int c, out string list)+ {+ var buf = new int[16];+ int n = e.RackChainInstrumentHeldNotes(t, c, buf);+ list = string.Join(",", buf.Take(Math.Max(0, n)));+ return n;+ }++ private static int PentadRack(NotaEngine e)+ {+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int c = e.RackAddChain(t, Pentad);+ for (int p = 0; p < e.RackChainInstrumentParamCount(t, c); p++)+ {+ string n = e.RackChainInstrumentParamName(t, c, p);+ if (n == "Amp-Env Release" || n == "Amp-Env Attack") e.RackChainInstrumentParamSet(t, c, p, 0f);+ if (n == "Glide Time") e.RackChainInstrumentParamSet(t, c, p, 0f); // the rack glides, not Pentad+ }+ return t;+ }++ private static IEnumerable<(bool, string)> MonoGlide()+ {+ string F2(double v) => v.ToString("0.#", CultureInfo.InvariantCulture);+ using (var e = new NotaEngine())+ {+ int t = PentadRack(e);+ e.TrackNoteOn(t, 48, 0.8f);+ e.TrackNoteOn(t, 60, 0.8f);+ RenderFrames(e, Block * 4);+ int poly = Held(e, t, 0, out var pl);+ e.TrackNoteOff(t, 48); e.TrackNoteOff(t, 60);+ RenderFrames(e, Block * 8);+ yield return (poly == 2 && !e.RackMono(t), $"poly by default: both keys sound ({pl})");++ e.RackSetMono(t, true);+ e.TrackNoteOn(t, 48, 0.8f);+ RenderFrames(e, Block * 4);+ e.TrackNoteOn(t, 60, 0.8f);+ RenderFrames(e, Block * 4);+ int mono = Held(e, t, 0, out var ml);+ yield return (e.RackMono(t) && mono == 1 && ml == "60", $"mono: the last key takes over ({ml})");+ e.TrackNoteOff(t, 60);+ RenderFrames(e, Block * 4);+ int back = Held(e, t, 0, out var bl);+ yield return (back == 1 && bl == "48", $"mono: releasing it returns to the key still held ({bl})");+ e.TrackNoteOff(t, 48);+ RenderFrames(e, Block * 8);+ yield return (Held(e, t, 0, out _) == 0, "mono: no note left hanging");+ }++ using (var e = new NotaEngine())+ {+ int t = PentadRack(e);+ e.RackSetMono(t, true);+ e.RackSetGlide(t, 0.6f); // 300 ms+ e.TrackNoteOn(t, 48, 0.8f);+ RenderFrames(e, Rate / 4);+ e.TrackNoteOn(t, 60, 0.8f);+ var a = RenderFrames(e, Rate / 2);+ double start = Pitch(a, 0, 2048), end = Pitch(a, Rate * 2 / 5, 2048);+ yield return (start > 0 && start < Hz(60) * 0.8 && Math.Abs(end - Hz(60)) < Hz(60) * 0.04,+ $"glide: the new note starts near the old pitch and arrives in time ({F2(start)} → {F2(end)} Hz, target {F2(Hz(60))})");+ e.TrackNoteOff(t, 60); e.TrackNoteOff(t, 48);+ RenderFrames(e, Block * 8);++ e.RackSetGlide(t, 0f);+ e.TrackNoteOn(t, 48, 0.8f);+ RenderFrames(e, Rate / 4);+ e.TrackNoteOn(t, 60, 0.8f);+ var b = RenderFrames(e, Rate / 10);+ double now = Pitch(b, 0, 2048);+ yield return (Math.Abs(now - Hz(60)) < Hz(60) * 0.04, $"no glide at 0 ms: the new note is in tune at once ({F2(now)} Hz)");+ }+ }++ private static IEnumerable<(bool, string)> DuplicateChain()+ {+ using var e = new NotaEngine();+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int a = e.RackAddChain(t, Synth), b = e.RackAddChain(t, Volt);+ e.RackSetChainZone(t, a, 10, 70, 5, 120);+ e.RackSetChainGain(t, a, 0.6f);+ e.RackSetChainName(t, a, "Low");+ e.RackChainInstrumentParamSet(t, a, 5, 0.3f);+ int eq = e.RackAddChainDevice(t, a, Eq3);+ e.RackChainDeviceParamSet(t, a, eq, 1, 0.37f);+ e.RackAddMacroMapping(t, 0, a, -1, 5, 0.1f, 0.9f);+ e.RackAddMacroMapping(t, 1, b, -1, 0, 0f, 1f);+ int d = e.RackDuplicateChain(t, a);+ e.RackChainZone(t, d, out int kl, out int kh, out int vl, out int vh);+ bool same = d == 1 && e.RackChainCount(t) == 3 && e.RackChainInstrumentKind(t, d) == Synth && e.RackChainName(t, d) == "Low"+ && kl == 10 && kh == 70 && vl == 5 && vh == 120 && Near(e.RackChainGain(t, d), 0.6f)+ && e.RackChainDeviceCount(t, d) == 1 && Near(e.RackChainDeviceParamGet(t, d, 0, 1), e.RackChainDeviceParamGet(t, a, eq, 1))+ && e.RackChainInstrumentKind(t, 2) == Volt;+ yield return (same, "duplicate chain: the copy sits after the original with its instrument, devices, zone and mix"+ + (same ? "" : $" [d={d} n={e.RackChainCount(t)} kind={e.RackChainInstrumentKind(t, d)} name='{e.RackChainName(t, d)}' zone={kl}-{kh}/{vl}-{vh} gain={e.RackChainGain(t, d)} devs={e.RackChainDeviceCount(t, d)} eq={(e.RackChainDeviceCount(t, d) > 0 ? e.RackChainDeviceParamGet(t, d, 0, 1) : -1)} k2={e.RackChainInstrumentKind(t, 2)}]"));+ int onCopy = 0, onVolt = 0;+ for (int i = 0; i < e.RackMappingCount(t); i++)+ if (e.RackTryGetMapping(t, i, out var m)) { if (m.Chain == d && m.Macro == 0) onCopy++; if (m.Chain == 2 && m.Macro == 1) onVolt++; }+ yield return (e.RackMappingCount(t) == 3 && onCopy == 1 && onVolt == 1, "duplicate chain: the copy gets the chain's mappings, later chains keep theirs");+ yield return (e.Undo() && e.RackChainCount(t) == 2 && e.RackMappingCount(t) == 2, "duplicate chain is one undo step");+ }++ // ---- curves, inverted ranges (US2) -------------------------------------------------++ private static IEnumerable<(bool, string)> CurvesAndRanges()+ {+ using var e = new NotaEngine();+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int c = e.RackAddChain(t, Synth);+ int a = e.RackAddMacroMapping(t, 0, c, -1, 5, 0f, 1f);+ int b = e.RackAddMacroMapping(t, 0, c, -1, 6, 0f, 1f);+ e.RackSetMappingCurve(t, a, 1);+ e.RackSetMappingCurve(t, b, 2);+ yield return (e.RackMappingCurve(t, a) != e.RackMappingCurve(t, b), "one macro can hold different curves per target (the Mixed case)");++ e.BeginUndoGroup();+ e.RackSetMappingCurve(t, a, 3);+ e.RackSetMappingCurve(t, b, 3);+ e.EndUndoGroup();+ yield return (e.RackMappingCurve(t, a) == 3 && e.RackMappingCurve(t, b) == 3, "picking a curve for the macro sets every target");+ yield return (e.Undo() && e.RackMappingCurve(t, a) == 1 && e.RackMappingCurve(t, b) == 2, "picking a curve is one undo step");++ // min above max inverts: the macro at its top drives the parameter to the range's min end.+ int inv = e.RackAddMacroMapping(t, 1, c, -1, 7, 0.8f, 0.2f);+ e.RackMacroSet(t, 1, 1f);+ float top = e.RackChainInstrumentParamGet(t, c, 7);+ e.RackMacroSet(t, 1, 0f);+ float bottom = e.RackChainInstrumentParamGet(t, c, 7);+ yield return (inv >= 0 && Near(top, 0.2f) && Near(bottom, 0.8f),+ string.Create(CultureInfo.InvariantCulture, $"a range with min above max inverts the response ({bottom:0.##} → {top:0.##})"));+ }++ // ---- Audio Effect Rack select (US3) -----------------------------------------------++ private static IEnumerable<(bool, string)> AudioSelect()+ {+ using var e = new NotaEngine();+ int t = e.AddAudioTrack();+ e.AddAudioClip(t, ToneFile(), 0);+ int d = e.AddBuiltinDevice(t, EffectRack);+ while (e.RackDevChainCount(t, d) > 0) e.RackDevRemoveChain(t, d, 0);+ int quiet = e.RackDevAddChain(t, d, -1), loud = e.RackDevAddChain(t, d, -1);+ int u = e.RackDevAddChainDevice(t, d, quiet, Utility);+ for (int p = 0; p < e.RackDevChainDeviceParamCount(t, d, quiet, u); p++)+ if (e.RackDevChainDeviceParamName(t, d, quiet, u, p) == "Mute") e.RackDevChainDeviceParamSet(t, d, quiet, u, p, 1f);+ e.RackDevSetChainZone(t, d, quiet, 0, 63);+ e.RackDevSetChainZone(t, d, loud, 64, 127);+ e.RackDevSetMode(t, d, 2);+ e.RackDevSetDryWet(t, d, 1f);+ e.RackDevAddMacroMapping(t, d, 0, 0, RackControl, Selector, 0f, 1f);++ float Level(float macro)+ {+ e.RackDevMacroSet(t, d, 0, macro);+ e.Seek(0); e.Play();+ var buf = RenderFrames(e, Rate / 4);+ e.Stop();+ double sum = 0;+ for (int i = Rate / 8 * 2; i < buf.Length; i++) sum += buf[i] * buf[i];+ return (float)Math.Sqrt(sum / (buf.Length - Rate / 8 * 2));+ }+ float low = Level(0f), high = Level(1f);+ yield return (low < 1e-4f && high > 0.02f,+ string.Create(CultureInfo.InvariantCulture, $"a macro on the selector switches which chain plays (rms {low:0.####} → {high:0.###})"));++ int dup = e.RackDevDuplicateChain(t, d, loud);+ e.RackDevChainZone(t, d, dup, out int lo, out int hi);+ yield return (dup == 2 && e.RackDevChainCount(t, d) == 3 && lo == 64 && hi == 127, "duplicate chain on an Audio Effect Rack keeps its select range");+ }++ // ---- review follow-ups: undo restores driven values, mono survives edits and switches ----++ private static IEnumerable<(bool, string)> EditsKeepState()+ {+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ while (e.RackChainCount(t) > 0) e.RackRemoveChain(t, 0);+ int c = e.RackAddChain(t, Synth);+ e.RackMacroSet(t, 0, 0f);+ e.RackMacroSet(t, 3, 1f);+ e.RackAddMacroMapping(t, 0, c, -1, 5, 0.2f, 0.7f);+ float before = e.RackChainInstrumentParamGet(t, c, 5);+ e.RackAddMacroMapping(t, 3, c, -1, 5, 0.2f, 0.7f); // moves it to macro 3, at its top+ float moved = e.RackChainInstrumentParamGet(t, c, 5);+ e.Undo();+ float undone = e.RackChainInstrumentParamGet(t, c, 5);+ e.Redo();+ float redone = e.RackChainInstrumentParamGet(t, c, 5);+ yield return (Near(before, 0.2f) && Near(moved, 0.7f) && Near(undone, 0.2f) && Near(redone, 0.7f),+ string.Create(CultureInfo.InvariantCulture, $"undo and redo restore what a macro drives ({before:0.##} → {moved:0.##}, undo {undone:0.##}, redo {redone:0.##})"));+ }++ using (var e = new NotaEngine())+ {+ int t = PentadRack(e);+ e.RackSetMono(t, true);+ e.TrackNoteOn(t, 48, 0.8f);+ RenderFrames(e, Block * 4);+ e.RackSetMacroName(t, 0, "Edited"); // an undoable edit swaps the rack object+ e.TrackNoteOn(t, 60, 0.8f);+ RenderFrames(e, Block * 4);+ Held(e, t, 0, out var afterEdit);+ e.TrackNoteOff(t, 60);+ RenderFrames(e, Block * 4);+ Held(e, t, 0, out var back);+ e.TrackNoteOff(t, 48);+ RenderFrames(e, Block * 8);+ yield return (afterEdit == "60" && back == "48" && Held(e, t, 0, out _) == 0,+ $"mono plays on through a rack edit (new key {afterEdit}, back to {back})");+ }++ using (var e = new NotaEngine())+ {+ int t = PentadRack(e);+ foreach (int p in new[] { 48, 52, 55 }) e.TrackNoteOn(t, p, 0.8f);+ RenderFrames(e, Block * 4);+ e.RackSetMono(t, true);+ RenderFrames(e, Block * 4);+ Held(e, t, 0, out var onSwitch);+ e.TrackNoteOn(t, 60, 0.8f);+ RenderFrames(e, Block * 4);+ Held(e, t, 0, out var next);+ foreach (int p in new[] { 48, 52, 55, 60 }) e.TrackNoteOff(t, p);+ RenderFrames(e, Block * 8);+ yield return (onSwitch == "55" && next == "60" && Held(e, t, 0, out _) == 0,+ $"switching mono on with a chord held keeps only the last key ({onSwitch}, then {next})");+ }+ }+}