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/rack nested instruments (#348)
Egor Khindikaynena85331bee68e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4c8914bf..0b58a8d6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,22 +20,6 @@ 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@@ -54,6 +38,27 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.- **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 thecard's menu or the Browser; inside a rack it uses its own Saw or Noise carrier.+- **Nota Mosaic and the Drum Rack in Instrument Rack chains**: drop either on a rack from the+ Browser or pick it in the card's chain menus. A Mosaic chain opens the full Mosaic editor+ (presets, zones, loading) and its program is saved with the rack; a Drum Rack chain opens+ the Drum Rack card in a window — pads, pad editor, macros and the factory kits — so one+ track can play a kit on one octave and an instrument on the rest. Outer macros can drive+ the Drum Rack's macros. Racks nest one level: a Drum Rack goes in an Instrument Rack chain+ only, and a Drum Rack inside a chain has no swing or humanize of its own. Drum Rack pads take+ Mosaic too. MCP: `set_chain_instrument` takes 17 and 4, `load_mosaic_preset` takes a chain,+ `get_rack` reads a nested Drum Rack.+- **Presets drop onto racks**: drag a preset from the Browser onto a rack — an instrument preset+ (a factory or user preset, a Mosaic pack preset or a drum kit) starts a new chain with it, or+ replaces a chain's instrument when dropped on that chain; an effect or MIDI-effect preset adds+ the device to the chain, preset applied, in one undo step. Plug-in presets don't go into a+ rack chain yet; a MIDI-effect preset brings its parameters.+- **Move, copy and paste devices in rack chains**: drag a device's header to reorder it in its+ chain (a drop bar shows where), or onto another chain's row to move it there with its macro+ mappings. Click one to select it, then Copy, Cut, Paste, Duplicate or Delete from its menu or+ with ⌘C / ⌘X / ⌘V / ⌘D / Delete. The clipboard is shared with the track's device chain, so a+ device copies between the track chain and any rack chain, settings and all (a sidechain key+ is dropped inside a rack). Each step is one undo step.+- **Duplicate a device with ⌘D** on the track's device chain (also in its right-click menu).- **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. Each@@ -74,6 +79,19 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.and the status line says why. ⌘G on tracks still groups tracks.### Changed+- **A new Instrument Rack starts empty** instead of with a Nota Volt chain: drop an instrument+ or a preset on it to add the first chain.+- **A Mosaic in a rack chain lists the presets a Mosaic track does** in its window — the factory+ multisamples, the pack presets, the program it holds and Init.+- **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.- **Splitting a long warped clip is instant** (nota-daw/nota#299, nota-daw/nota#259): a split,trim or range cut of a warped clip reuses the stretch the clip already has instead ofstretching both halves again on the UI thread (13 s for a 20-minute clip before), and the@@ -81,6 +99,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.at full detail instead of in blocks.### Fixed+- A rack card's faders, mode buttons and switches (and zone or select-range drags) undo one+ gesture at a time on every rack, the MIDI Effect Rack included; a nested Drum Rack's window+ follows its chain when chains in front of it are removed or moved.+- 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.- **Linux: file dialogs that never open** (nota-daw/nota#297): when xdg-desktop-portal has noworking FileChooser backend, Open / Save / Export / Import used to do nothing. Nota now noticeswithin 4 seconds (the request fails, answers without showing, or shows nothing) and opens itsdiff --git a/FEATURES.md b/FEATURES.mdindex 9b3ea8f4..484e3120 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -232,6 +232,9 @@ track count and closes with Escape.**+** at its end opens the browser on Audio effects with the cursor in the search.- Double-click a device's header (or Fold in its menu) to fold it into a narrow strip withits rotated name and on/off switch; double-click the strip to unfold. Saved with the project.+ - Click a device to select it: ⌘C / ⌘X / ⌘V copy, cut and paste it with all its settings+ (also into and out of rack chains), ⌘D duplicates it, Delete removes it; drag a header to+ reorder.---@@ -646,7 +649,8 @@ audio effects after it keep running and keep their settings; saved with the projon built-in multisamples (felt piano with release samples, mallets, nylon guitar, brass, pad,music box) rendered on first use; Init in the card's preset list empties the instrument; MCP `read_mosaic`, `set_mosaic`, `set_mosaic_zone`,`set_mosaic_group`, `import_sfz`, `create_multisample`, `list_mosaic_presets`,- `load_mosaic_preset`, `scan_sample_packs`.+ `load_mosaic_preset` (also into an Instrument Rack chain), `scan_sample_packs`. Also plays as+ an Instrument Rack chain or a Drum Rack pad, with the same editor.### Audio effects- **Nota EQ-8** (kind 0) — 8-band parametric: each band on / off, Low cut / Low shelf / Bell /@@ -886,21 +890,29 @@ audio effects after it keep running and keep their settings; saved with the proj- **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 summaryand 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** /+ parameters, Browser drops (devices and presets), + Chain, 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 eachtarget'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.+ place: click parameters on the chain's devices to add or remove them; Esc ends it. A chain's+ devices drag by their header to a new place in their section (a drop bar shows where) or+ onto another chain's row to move there with their macro mappings; click one to select it+ for Copy / Cut / Paste / Duplicate / Delete (menu or ⌘C ⌘X ⌘V ⌘D Delete). The clipboard is+ the device chain's too, so devices copy between the track chain and any rack chain.- **Nota Instrument Rack** — layered chains of MIDI effects → instrument → audio effects, eachwith **key and velocity zones**, gain, pan, M·S; Rack out: Volume, Glide and **Mono (lastnote)** — glide bends each new note from the last one on instruments that take per-note bend.+ A chain can hold **Nota Mosaic** (its full editor, program saved with the rack) or a **Drum+ Rack** — one level deep — whose card opens in a window with its pads, macros and factory kits;+ outer macros can drive its macros. MCP `get_rack` with `nestedChain` reads it.- **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 padoscillogram with a playhead, and each pad's own effect chain. Eight **macros** over the kitmap onto pad controls (Volume / Pan / Tune / Decay), pad instruments and the pads' effects,- with draggable ranges per receiver. A **kit picker** in the+ with draggable ranges per receiver. A pad plays Nota Sampler, a built-in synth or Nota Mosaic.+ A **kit picker** in thecard header loads any factory kit in place and names the kit a rack holds. Its clips canbe stepped in the detail panel's **Pattern** tab (see below).- **25 factory kits** under Nota Drum Rack and Nota Rhythm in the browser and in their cards' kit pickers:diff --git a/specs/041-rack-nested-instruments/checklists/requirements.md b/specs/041-rack-nested-instruments/checklists/requirements.mdnew file mode 100644index 00000000..d23d0ac7--- /dev/null+++ b/specs/041-rack-nested-instruments/checklists/requirements.md@@ -0,0 +1,35 @@+# Specification Quality Checklist: Mosaic and Drum Rack in Instrument Rack chains++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-27+**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++- Nesting depth settled as one level (Drum Rack only in a track Instrument Rack chain) without a clarification question: the task brief asked to settle it in the spec, and deeper nesting has no use the wider rack doesn't cover.+- FR-013 names the AR rules on purpose (project constitution), not as an implementation choice.diff --git a/specs/041-rack-nested-instruments/contracts/c-abi.md b/specs/041-rack-nested-instruments/contracts/c-abi.mdnew file mode 100644index 00000000..789b9225--- /dev/null+++ b/specs/041-rack-nested-instruments/contracts/c-abi.md@@ -0,0 +1,46 @@+# C ABI additions (`nota_engine.h`)++All take `device_index` like the other `nota_rackdev_*` calls: −1 the track's instrument+rack, ≥ 0 an Audio Effect Rack, `NOTA_RACK_NESTED_BASE − chain` a nested Drum Rack.++```c+/* The Drum Rack held by chain `chain` of the track's Instrument Rack (one level only). */+#define NOTA_RACK_NESTED_BASE (-100000)++/* Drum Rack pads / kit timing, Sampler pads, chain names (twins of nota_rack_*). */+int32_t nota_rackdev_add_sampler_chain(NotaEngine*, int32_t t, int32_t di, const char* path, int32_t root, int32_t loop);+int32_t nota_rackdev_set_chain_sampler_sample(NotaEngine*, int32_t t, int32_t di, int32_t chain, const char* path, int32_t root);+int32_t nota_rackdev_add_plugin_instrument_chain(NotaEngine*, int32_t t, int32_t di, int32_t catalog_index);+const char* nota_rackdev_chain_name(const NotaEngine*, int32_t t, int32_t di, int32_t chain);+void nota_rackdev_set_chain_name(NotaEngine*, int32_t t, int32_t di, int32_t chain, const char* name);+void nota_rackdev_set_chain_choke / _tune / _decay (…, int32_t chain, value);+… nota_rackdev_chain_choke / _tune / _decay (…, int32_t chain);+void nota_rackdev_set_swing / _set_humanize (…, float v); float nota_rackdev_swing / _humanize (…);+int32_t nota_rackdev_chain_sampler_info(const NotaEngine*, int32_t t, int32_t di, int32_t chain, NotaSamplerInfo* out);+int32_t nota_rackdev_set_chain_sampler_root(NotaEngine*, int32_t t, int32_t di, int32_t chain, int32_t root);+float nota_rackdev_chain_sampler_play_position(const NotaEngine*, int32_t t, int32_t di, int32_t chain);+/* Chain instrument surface (twins). */+const char* nota_rackdev_chain_instrument_param_id(…, int32_t chain, int32_t param);+float nota_rackdev_chain_instrument_param_default(…, int32_t chain, int32_t param);+int32_t nota_rackdev_chain_instrument_scope(…, int32_t chain, float* out, int32_t max_n);+int32_t nota_rackdev_chain_instrument_voice_count(…, int32_t chain);+int32_t nota_rackdev_chain_instrument_held_notes(…, int32_t chain, int32_t* out, int32_t max_n);+void nota_rackdev_chain_instrument_action(…, int32_t chain, int32_t id, int32_t iarg, float farg);++/* Nota Mosaic as a chain instrument. undoable = 1: one undo step (a fresh Mosaic swaps in);+ * 0: live, in place. Return 1 / 0 (not a Mosaic chain). */+int32_t nota_rackdev_chain_mosaic_set_program(NotaEngine*, int32_t t, int32_t di, int32_t chain, const char* text, int32_t undoable);+int32_t nota_rackdev_chain_mosaic_program(const NotaEngine*, int32_t t, int32_t di, int32_t chain, char* out, int32_t cap);+int32_t nota_rackdev_chain_mosaic_status(const NotaEngine*, int32_t t, int32_t di, int32_t chain, NotaMosaicStatus* out);+int64_t nota_rackdev_chain_mosaic_zone_sample_id(const NotaEngine*, int32_t t, int32_t di, int32_t chain, int32_t zone);+```++Behaviour changes of existing calls:++- `nota_rack_add_chain`, `nota_rack_set_chain_instrument` (+ `rackdev` twins): accept 17+ everywhere instrument chains exist and 4 only on a track's plain Instrument Rack+ (`device_index` −1); otherwise unchanged refusal (−1 / 0).+- All `nota_rackdev_*` calls accept the nested range.++The exact shape of each declaration follows the existing `nota_rack_*` twin; the program+getter follows the `nota_track_mosaic_program` buffer convention used today.diff --git a/specs/041-rack-nested-instruments/data-model.md b/specs/041-rack-nested-instruments/data-model.mdnew file mode 100644index 00000000..f4a44e25--- /dev/null+++ b/specs/041-rack-nested-instruments/data-model.md@@ -0,0 +1,41 @@+# Data model: Mosaic and Drum Rack in Instrument Rack chains++## Chain instrument kinds (`RackCore::makeInstrument`)++| Kind | Instrument | Where allowed as a chain instrument |+|---|---|---|+| 0, 1, 2, 5–16 | built-in synths, Sampler | every rack with instrument chains (unchanged) |+| 17 | Nota Mosaic (empty program) | Instrument Rack chains, Drum Rack pads (track or nested) |+| 4 | Nota Drum Rack (empty kit) | chains of a track's plain Instrument Rack only |+| 3 | Instrument Rack | never |+| −1 | hosted plug-in | unchanged |++## Rack blob (v9, unchanged layout)++A chain stores `instKind` then `u32 len + getState()` of its instrument:++- kind 17 → Mosaic state: parameters + program text (sample paths as written by the+ program; the audio is never in the blob).+- kind 4 → the nested Drum Rack's own complete rack blob (`NRK1`, v9), pads' Sampler+ audio included.++Deserialization depth: the outermost blob is depth 0; a rack instrument (kind 3/4) is+built only at depth 0 (so its chains are depth 1 and take no rack).++## Rack address `(trackId, deviceIndex)`++| deviceIndex | Rack |+|---|---|+| −1 | the track's instrument rack (Instrument / Drum Rack) |+| ≥ 0 | the Audio Effect Rack at that device position |+| −1000 − mi | the MIDI Effect Rack at MIDI effect index mi |+| −100000 − c (new) | the Drum Rack held by chain c of the track's Instrument Rack |++Validity: resolves to null (calls no-op / return defaults) when chain c is gone or holds+no rack — an open window on a removed nested rack goes inert.++## Undo++- Nested structural edits: outer fork + inner fork, one `pushUndo`.+- Chain Mosaic program (undoable): rack fork + chain instrument replaced with a clone+ holding the new program, one `pushUndo`.diff --git a/specs/041-rack-nested-instruments/plan.md b/specs/041-rack-nested-instruments/plan.mdnew file mode 100644index 00000000..ae2ffd8d--- /dev/null+++ b/specs/041-rack-nested-instruments/plan.md@@ -0,0 +1,151 @@+# Implementation Plan: Mosaic and Drum Rack in Instrument Rack chains++**Branch**: `feat/rack-nested-instruments` | **Date**: 2026-10-27 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/041-rack-nested-instruments/spec.md`++## Summary++A rack chain's instrument is built by `RackCore::makeInstrument`, which stops at kind 16, so+every path that adds a chain instrument by kind (Browser drop, card menus, MCP, the rack+blob) refuses Mosaic (17) and the Drum Rack (4). The plan:++1. **Engine — chain kinds.** `makeInstrument` learns 17 (an empty Mosaic) and 4 (an empty+ Drum Rack). The rack blob already stores a built-in chain instrument as kind + its+ `getState()`, and both instruments' state is complete (Mosaic: params + program text;+ Drum Rack: its own rack blob, Sampler audio included), so persistence, presets and+ chain duplication follow. The one-level rule is enforced in the engine: a Drum Rack is+ accepted only in a chain of a track's plain Instrument Rack, refused in Drum Rack pads,+ nested racks and effect/MIDI racks, and not built when a blob would nest deeper.+2. **Engine — nested rack address.** A nested Drum Rack is addressed like any other rack+ by `(trackId, deviceIndex)` with a new range: `deviceIndex = kNestedRackBase − chain`+ (`kNestedRackBase = −100000`), "the rack in chain `chain` of the track's Instrument+ Rack". `rackCoreAt` resolves it, `rackForEdit` forks the outer rack and then the inner+ one (one graph republish = one undo step) — so every existing `rack*` engine call and+ every `nota_rackdev_*` ABI call works on a nested rack unchanged.+3. **ABI — the missing `rackdev` twins.** The Drum Rack card talks to its rack through+ `nota_rack_*` (device index −1 implied). The calls it needs that have no+ `nota_rackdev_*` twin get one (pad shaping, kit timing, chain name, Sampler pads, chain+ instrument telemetry/defaults/ids). Mosaic in a chain gets four calls addressed by+ `(track, device_index, chain)`: set program (live or undoable), program, status, zone+ sample id. `findSampleById` also looks inside chains (Mosaic zones, nested pads).+4. **Managed — proxies, not new cards.** The chain-instrument editor already hosts a+ built-in instrument's real editor through `RackChainEngineProxy` (a `DispatchProxy`+ over `IAudioEngine`). It gains the four Mosaic calls, so the Mosaic card runs on a+ chain as it does on a track. A new `NestedRackEngineProxy` redirects every+ `Rack*(track, …)` call to `RackDev*(track, nestedIndex, …)` by name (plus the plugin+ param / instrument-kind / automation calls), so the existing Drum Rack card is built+ unchanged inside a `DeviceWindow` for the nested rack. Both proxies move to+ `Nota.Application` so the MCP server can apply a Mosaic preset to a chain too.+5. **UI menus and drops.** Add Nota Mosaic and Nota Drum Rack to the Instrument Rack's+ add-chain and chain-instrument menus, Mosaic to the Drum Rack pad menu; drops already+ route by kind and start working once the engine accepts them; the nested card hides+ swing/humanize and MIDI Learn on its macros.+ Audio Effect and MIDI Effect Rack chains never hold an instrument: `rackAddChain` ignores+ the kind asked for there. MCP `add_effect_rack_chain` used to pass 4 by default, which meant+ "no instrument" while kind 4 built nothing; now that 4 builds a Drum Rack, the engine drops+ the kind for those racks and the tool's default is −1 (found by the full smoke run).+6. **Tests, docs.** Smoke-test sections for both chain kinds; CHANGELOG, FEATURES,+ nota-docs (EN + RU).++## Nota: Read Before Planning++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): the rack edits keep the+ existing pattern — rack-internal snapshots published on the message thread+ (`SnapshotHistory`), fork + graph republish for undo (AR-5). Mosaic loads on its own+ loader threads and publishes through an atomic pointer (AR-6).+- **UI work** → [`DESIGN.md`](../../DESIGN.md): no new visual element; the two cards are+ reused as they are.+- **A built-in instrument** → `nota-instrument` skill: the kind registration checklist+ is already done for Mosaic (track instrument); only the rack factory missed it.++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 (app, MCP, smoke test)++**Primary Dependencies**: none new.++**Storage**: project files and presets — no format change: the rack blob (v9) already+carries "kind + instrument state" per chain. Older builds reading a blob with a kind-17+or kind-4 chain leave that chain without an instrument, the normal forward-compat story+for a new chain kind. No blob version bump.++**Audio-Thread Impact**: A nested Drum Rack renders inside its chain like any chain+instrument (its own `scratch_` buffer, its own snapshot `RenderScope`); a Mosaic in a+chain renders lock-free as on a track. Structural edits are message-thread snapshot+swaps; no new audio-thread allocation, lock or I/O.++**Testing**: `tests/Nota.SmokeTest` (end to end through the C ABI), `scripts/build.sh`.+UI checked with the headless Avalonia harness.++**Target Platform**: macOS / Linux / Windows desktop.++**Project Type**: desktop app (native engine + managed UI).++**Performance Goals**: no extra per-block cost for racks without these chains.++**Constraints**: one nesting level (spec FR-003).++**Scale/Scope**: ~4 engine files, 1 ABI file + header, P/Invoke + `IAudioEngine` ++`NotaEngine`, 3–4 UI files, MCP rack/mosaic tools, smoke test, docs.++## Constitution Check++| Principle | Status |+|---|---|+| I. Real-time safety | Pass — reuses the rack snapshot + fork pattern; Mosaic loads off the audio thread. |+| II. Boundary discipline | Pass — new calls are plain C functions in `nota_engine.h`; no JUCE. |+| III. Licensing | Pass — no dependency; new files carry the SPDX header. |+| IV. Verification gate | Pass — smoke-test sections planned (FR-014). |+| V. One logical change | Pass — two chain instrument kinds and the nested-rack address they need. |+| VI. Docs in sync | Planned — CHANGELOG, FEATURES, nota-docs. |+| VII. Spec first | Pass — this spec/plan/tasks. |+| VIII. Rules not weakened | Pass. |++Re-check after design: unchanged.++## Project Structure++### Documentation (this feature)++```text+specs/041-rack-nested-instruments/+├── plan.md+├── research.md+├── data-model.md+├── quickstart.md+├── contracts/c-abi.md+└── tasks.md+```++### Source Code++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # NOTA_RACK_NESTED_BASE, rackdev twins, chain Mosaic calls+├── nota_exports.txt / nota_exports.map # export lists for the new symbols+└── src/+ ├── devices/racks/RackCore.{h,cpp} # makeInstrument 4/17, nesting guard, replaceChainInstrument+ ├── engine/Engine.h # kNestedRackBase, new rack* methods+ ├── engine/Engine_Rack.cpp # rackCoreAt / rackForEdit for nested racks, chain Mosaic+ ├── engine/Engine_Tracks.cpp # findSampleById looks into chains+ └── abi/nota_engine_rack.cpp # new ABI wrappers++src/managed/+├── Nota.Application/Engine/IAudioEngine.cs # RackDev* twins, RackChainMosaic*+├── Nota.Application/Engine/RackEngineProxies.cs # chain-instrument + nested-rack proxies+├── Nota.Infrastructure/Interop/NativeMethods.Rack.cs, NotaEngine.Rack.cs+├── Nota.App/DeviceCards/Rack/RackCardView.cs # menus, nested Drum Rack window, proxy use+├── Nota.App/DeviceCards/Rack/RackCard.Chains.cs # chain instrument menu+├── Nota.App/DeviceCards/Rack/RackCardView.Drum.cs # pad menu + nested mode (no swing / learn)+└── Nota.Mcp/Tools/{RackTools,MosaicTools}.cs++tests/Nota.SmokeTest/Program.cs+CHANGELOG.md, FEATURES.md, ../nota-docs (rack pages EN + RU)+```++**Structure Decision**: extend the existing rack code paths; no new projects.++## Complexity Tracking++None.diff --git a/specs/041-rack-nested-instruments/quickstart.md b/specs/041-rack-nested-instruments/quickstart.mdnew file mode 100644index 00000000..160feab9--- /dev/null+++ b/specs/041-rack-nested-instruments/quickstart.md@@ -0,0 +1,27 @@+# Quickstart: validating Mosaic and Drum Rack chains++## Automated++```bash+scripts/build.sh+```++The smoke test's "Rack chains: Mosaic" and "Rack chains: nested Drum Rack" sections must+print PASS:++- Mosaic chain: add by kind 17, set a program over generated WAVs, wait for status ready,+ render a note inside the chain zone (audible) and outside (silent), save/reload the rack+ blob (program text equal), an undoable program set + undo restores the old text.+- Nested Drum Rack: add by kind 4 on an Instrument Rack (accepted) and on a Drum Rack pad+ (refused); add two Sampler pads through the nested address; pad note inside the zone+ audible, other note silent; choke/tune/decay round-trip; undo of a nested pad add;+ blob round-trip keeps pads and audio; an outer macro mapped to the nested macro moves a+ nested pad's decay.++## Manual / headless UI++1. New Instrument Rack track → card → add chain → Nota Mosaic; open its GUI → load a+ factory preset → zones fill in; play.+2. Drop "Nota Drum Rack" from the Browser on the add-chain area → chain appears; open its+ GUI → Drum Rack card in a window; drop a sample on a pad; play C1.+3. ⌘Z after each edit; save, reopen, check both chains.diff --git a/specs/041-rack-nested-instruments/research.md b/specs/041-rack-nested-instruments/research.mdnew file mode 100644index 00000000..5e34b8f6--- /dev/null+++ b/specs/041-rack-nested-instruments/research.md@@ -0,0 +1,75 @@+# Research: Mosaic and Drum Rack in Instrument Rack chains++## R1 — How a nested rack is addressed++- **Decision**: a new device-index range, `kNestedRackBase − chain` (`kNestedRackBase =+ −100000`), meaning "the rack instrument in chain `chain` of the track's Instrument Rack".+- **Rationale**: every engine `rack*` method and every `nota_rackdev_*` ABI call already+ takes `(trackId, deviceIndex)` and resolves it in one place (`rackCoreAt`) and forks in+ one place (`rackForEdit`). A new range there makes the whole existing surface work on a+ nested rack. −100000 keeps clear of the MIDI Effect Rack range (−1000 − mi) and of+ macro-target constants (−2, −3, −1000 − j).+- **Alternatives**: a handle/ID per nested rack (state to keep valid across forks and+ undo — rejected); encoding the chain into the track id (hidden coupling — rejected);+ a full `nota_nested_*` ABI family (duplicates 70 calls — rejected).++## R2 — Undo for nested edits++- **Decision**: `rackForEdit(t, nested(c))` = `rackForEdit(t, −1)` (fork the outer rack,+ republish the track: one undo checkpoint), then fork the inner Drum Rack (chain children+ shared, mono/pedal state carried as for a track Drum Rack) and swap it into the forked+ outer's chain `c` with a rack-internal commit.+- **Rationale**: the graph snapshot on the undo stack still holds the old outer rack,+ which still holds the old inner rack — undo restores both. Voices survive because pad+ instruments are shared.+- **Alternatives**: forking only the inner rack in place (the shared outer rack would+ point at it from the undo snapshot too — no undo; rejected).++## R3 — Nesting depth++- **Decision**: one level. `rackSetChainInstrument` / `rackAddChain` accept kind 4 only+ when the address is −1 and the track instrument is a plain `RackInstrument` (not a Drum+ Rack); kind 3 is never a chain instrument. `RackCore::deserialize` keeps a thread-local+ depth and builds no rack instrument below depth 1 (a hand-made blob can't nest deeper).+- **Rationale**: covers drums + bass/keys splits; deeper nesting adds UI addressing+ complexity with no musical gain.++## R4 — Mosaic persistence inside a rack++- **Decision**: nothing new — `Mosaic::getState()` holds params + program text and the+ rack blob stores built-in chain instrument state. `deserialize` → `setState` →+ `setProgram` starts the async load.+- **Undoable program edits** in a chain clone the chain's Mosaic (the clone keeps decoded+ buffers, so a zone edit is ready at once), set the program, and swap it into a forked+ rack via a new `RackCore::replaceChainInstrument(chain, inst)` (keeps the chain's+ devices, MIDI effects, controls and mappings). Live (non-undoable) edits set the+ program in place, as on a track.+- **Samples by id** (`ReadSample` for the editor waveforms): `findSampleById` walks rack+ chains — Sampler and Mosaic chain instruments and, for a nested Drum Rack, its pads.++## R5 — The editors in the UI++- **Mosaic**: `RackChainEngineProxy` gains `MosaicSetProgram / MosaicProgram /+ TryGetMosaicStatus / MosaicZoneSampleId` → chain calls; `MosaicInstrumentCard` then runs+ unchanged in the chain device window (it already reads only via `engine.*(track)`).+- **Drum Rack**: `NestedRackEngineProxy` maps by name — `RackFoo(t, args…)` →+ `RackDevFoo(t, nested, args…)` when such a method exists (cached reflection), and+ `RackDevFoo(t, −1, …)` → `RackDevFoo(t, nested, …)`; `PluginParamGet/Set/Count/Id(t,+ −1, i)` → the nested rack's macros; `TrackInstrumentKind` → 4; automation writes →+ no-ops. A few Rack* calls whose RackDev twin has another shape (zones) are mapped+ explicitly. The Drum Rack card is built with a `DeviceCardContext` over that proxy in a+ `DeviceWindow`, so pads, pad editor, pad Sampler editor and macros all address the+ nested rack.+- **Why proxies**: two existing cards (≈2000 lines) stay single-source; a nested card+ can't drift from the track card.+- **Placement**: both proxies move to `Nota.Application` (public), so `Nota.Mcp` applies a+ Mosaic preset to a chain with the same `IFactoryPresets.ApplyInPlace(engine, …)` path.++## R6 — Kit timing and MIDI Learn in the nested card++- Swing/humanize are applied to the track's event list in `computeInstrumentMidi`, which+ only sees the track instrument; applying a nested rack's value would shift every chain.+ The nested card hides them (`E is NestedRackEngineProxy`), the engine ignores them.+- `MidiLearn.Bind(PluginParam(track, −1, m))` would learn the outer macro; the nested card+ skips MIDI Learn on its macros. Outer macros map to the nested macros (chain instrument+ params) instead.diff --git a/specs/041-rack-nested-instruments/spec.md b/specs/041-rack-nested-instruments/spec.mdnew file mode 100644index 00000000..36aca55f--- /dev/null+++ b/specs/041-rack-nested-instruments/spec.md@@ -0,0 +1,171 @@+# Feature Specification: Mosaic and Drum Rack in Instrument Rack chains++**Feature Branch**: `feat/rack-nested-instruments`++**Created**: 2026-10-27++**Status**: Draft++**Input**: User description: "Let an Instrument Rack chain host Nota Mosaic (built-in instrument kind 17) and a Nota Drum Rack (kind 4). Today the Browser drop and the chain-instrument picker refuse both. Both must be addable from the Browser and the rack card, play with zones and macros, survive save/reopen, presets and undo, and have their own editors inside the chain (the Mosaic editor; the Drum Rack's pads and macros). A Drum Rack in a chain is a rack inside a rack: settle the nesting depth (one level)." Reported during the review of the racks redesign ([nota-daw/nota#331](https://github.com/nota-daw/nota/pull/331), specs/040).++## 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: Engine (a rack chain gains two new instrument kinds, one of them a rack), with+the rack card and its device windows on top.++**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).++## User Scenarios & Testing *(mandatory)*++### User Story 1 - A multisampled piano as one layer of an Instrument Rack (Priority: P1)++A producer layers a pad over a grand piano. They drop Nota Mosaic from the Browser onto+an Instrument Rack (as a new chain, or onto an existing chain to replace its instrument),+or pick Nota Mosaic in the card's "add chain" / instrument menus. They open the chain's+instrument and get the full Mosaic editor: they load a multisample preset, see the zones+fill in as the samples load, edit a zone, and play. The chain's key and velocity zone+splits the keyboard between the piano and the pad, and a rack macro mapped to the Mosaic's+filter cutoff moves it.++**Why this priority**: Mosaic is the instrument for realistic keys and orchestral sounds;+layering it is the most common reason to put it in a rack, and it needs no rack nesting.++**Independent Test**: Add Mosaic to an Instrument Rack chain, load a program in its+editor, play notes inside and outside the chain's zone, move a mapped macro, save and+reopen the project — everything works without the Drum Rack story.++**Acceptance Scenarios**:++1. **Given** an Instrument Rack, **When** the user drops Nota Mosaic from the Browser on the "add chain" area, **Then** a new chain holding an empty Mosaic appears and is chosen.+2. **Given** a chain holding Nota Volt, **When** the user drops Nota Mosaic on that chain (or picks it in the chain's instrument menu), **Then** the chain's instrument becomes Mosaic and its effects, zone, mix and MIDI effects stay.+3. **Given** a Mosaic chain, **When** the user opens its editor and loads a multisample preset, **Then** the editor shows the program, its loading progress and then its zones, and notes in the chain's zone play the samples.+4. **Given** a Mosaic chain with a program, **When** the user edits a zone in the editor and then undoes, **Then** the zone goes back, and each step is one undo step.+5. **Given** a rack macro mapped to a Mosaic parameter, **When** the user moves the macro, **Then** the parameter follows within the mapping's range.+6. **Given** a project with a Mosaic chain, **When** it is saved and reopened, or the rack is saved as a preset and loaded on another track, **Then** the chain comes back with the same program (its samples load again from where they are) and the same parameters.++---++### User Story 2 - A Drum Rack inside an Instrument Rack (Priority: P2)++A beat-maker wants one instrument track that plays a drum kit on the low octave and a+bass on the rest of the keyboard. They add a Nota Drum Rack to an Instrument Rack chain+(Browser drop or the card's menus), set that chain's key zone to C1–B1, and open the+chain's instrument: the Drum Rack's own card opens in a device window with its pads, pad+editor and macros. They drop samples on pads, set choke groups and pad tune, map a Drum+Rack macro to a pad's decay, and map an Instrument Rack macro to that Drum Rack macro.++**Why this priority**: Splitting drums and a bass or keys across one track is a familiar+rack use, but it needs a rack inside a rack, so it builds on the chain work of story 1.++**Independent Test**: Put a Drum Rack in a chain, load two pads, play their notes, edit+pads and macros in its window, undo each edit, save and reopen.++**Acceptance Scenarios**:++1. **Given** an Instrument Rack, **When** the user adds a Nota Drum Rack chain, **Then** the chain shows "Nota Drum Rack" as its instrument and starts with an empty kit.+2. **Given** a Drum Rack chain, **When** the user opens its instrument, **Then** a device window shows the Drum Rack card (pads, pad editor, macros) working on that nested Drum Rack, not on the track's rack.+3. **Given** the nested Drum Rack card, **When** the user drops a sample on a pad and plays that pad's note inside the chain's key zone, **Then** the pad sounds; a note outside the chain's zone does not reach the Drum Rack.+4. **Given** the nested Drum Rack card, **When** the user changes a pad's choke group, tune, decay, volume or name, adds or removes a pad, or changes a macro or a mapping, **Then** the nested rack changes and Undo reverts that step without touching the rest of the Instrument Rack.+5. **Given** an Instrument Rack macro, **When** the user maps it to the nested Drum Rack's macro 2, **Then** moving the outer macro moves macro 2 and whatever it drives.+6. **Given** a project with a nested Drum Rack, **When** it is saved and reopened, or the Instrument Rack is saved as a preset and loaded, **Then** the nested kit comes back: pads, samples, pad shaping, macros and mappings.++---++### User Story 3 - Agents and tests reach the nested instruments (Priority: P3)++An MCP client builds the same layered rack: it sets a chain's instrument to Mosaic or a+Drum Rack, loads a Mosaic preset into the chain, and lists the rack. The engine smoke+test covers both chain kinds end to end.++**Why this priority**: Keeps the MCP surface honest about what a chain can hold, and the+smoke test guards the feature; it adds no new UI.++**Independent Test**: Call the MCP rack tools on a scratch project and run the smoke test.++**Acceptance Scenarios**:++1. **Given** an Instrument Rack track, **When** an MCP client sets chain 0's instrument to kind 17 or 4, **Then** the call succeeds and the rack listing names the new instrument.+2. **Given** the smoke test, **When** it runs, **Then** it covers a Mosaic chain (program, playback, persistence, undo) and a nested Drum Rack (pads, playback inside the zone, persistence, undo, the nesting refusal).++---++### Edge Cases++- **Nesting depth.** Only one level: a Drum Rack may sit in a chain of a track's Instrument Rack. A Drum Rack's pads, a nested Drum Rack's pads, an Audio Effect Rack and a MIDI Effect Rack never take a rack; an Instrument Rack never goes in a chain. Such a drop or menu pick is refused (the menu doesn't offer it; a drop shows the not-allowed cursor) and nothing changes.+- **A Drum Rack chain and its MIDI effects.** A Drum Rack chain of an Instrument Rack can still hold MIDI effects in front of it, like any chain; the nested Drum Rack's own pads take none, as on a track.+- **Kit timing.** Swing and humanize shift the notes of the whole track, so they are a track-level Drum Rack's controls only; the nested Drum Rack card hides them and the engine ignores them for a nested Drum Rack.+- **Mosaic in a Drum Rack pad.** A Drum Rack pad (on a track or nested) may hold Mosaic too, through the same pad instrument menu: the editor and persistence are the same chain editor.+- **Missing samples.** A reopened Mosaic chain whose sample files moved reports them as missing in its editor, like a Mosaic track; the rest of the rack plays.+- **Loading while playing.** While a chain's Mosaic loads its samples it is silent; other chains keep playing and nothing glitches.+- **Replacing the instrument.** Turning a Mosaic or Drum Rack chain into another instrument drops the chain's mappings onto that instrument's parameters like any instrument change does today (and keeps the rest); undo brings the old instrument back with its program or kit.+- **Removing / duplicating a chain.** Duplicating a Mosaic or Drum Rack chain copies its program or whole kit; removing it removes the nested rack and its window closes or shows nothing.+- **Old projects.** Projects and presets saved before this feature load unchanged.+- **Audition.** Clicking a pad in the nested Drum Rack card plays the pad through the track, so other chains whose zone holds that note also sound.+- **Open window, structural change.** If the chain behind an open nested-Drum-Rack or Mosaic window changes its instrument or goes away, the window stops driving it (shows the new state or nothing) and never edits another chain by accident.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: An Instrument Rack chain MUST accept Nota Mosaic and Nota Drum Rack as its instrument, both as a new chain and as a replacement of a chain's instrument, from the Browser (drop) and from the rack card's add-chain and chain-instrument menus.+- **FR-002**: A Drum Rack pad MUST accept Nota Mosaic as its instrument from the pad instrument menu and a Browser drop.+- **FR-003**: Rack nesting MUST be at most one level deep: a Drum Rack only inside a chain of a track's Instrument Rack; every other rack-in-rack combination is refused by the engine and not offered by the UI.+- **FR-004**: A chain's Mosaic MUST play its program's zones (key, velocity, round robin, release) for the notes the chain's zone and MIDI effects let through, and its parameters MUST be reachable by rack macro mappings.+- **FR-005**: Opening a Mosaic chain's instrument MUST show the full Mosaic editor working on that chain: program loading (presets, SFZ, packs as on a track), loading status and missing-file count, zone editing, waveforms, telemetry.+- **FR-006**: A Mosaic program change from the chain editor MUST be one undo step; a drag inside the editor MUST be live and then one step, as on a track.+- **FR-007**: A nested Drum Rack MUST route a note to the pads assigned to it with choke groups, pad tune and pad decay, as on a track, for the notes its chain lets through.+- **FR-008**: Opening a Drum Rack chain's instrument MUST show the Drum Rack card (pads grid, pad editor with its instrument and effects, macros and macro mapping) driving the nested rack; every structural edit there MUST be one undo step of the project, as on a track.+- **FR-009**: The nested Drum Rack's eight macros MUST be visible to the Instrument Rack's macro mapping as the chain instrument's parameters, so an outer macro can drive them.+- **FR-010**: Project save/reopen, Instrument Rack presets, chain duplication and undo/redo MUST keep a chain's Mosaic (parameters and program) and a nested Drum Rack (pads, pad instruments and their state including Sampler audio, pad effects, pad shaping, macros, macro names and mappings).+- **FR-011**: Factory presets for Mosaic MUST apply to a Mosaic chain from its editor's preset picker, as they do for other chain instruments; the factory kits MUST load into a nested Drum Rack from its window's preset picker.+- **FR-012**: The MCP rack tools MUST accept kind 17 and kind 4 as a chain instrument and report them; setting a Mosaic chain's preset MUST be possible through MCP.+- **FR-013**: Nothing on the audio thread may allocate, lock or wait because of these chains; program loading stays on the message and loader threads (AR-4, AR-5, AR-6).+- **FR-014**: The smoke test MUST cover both chain kinds: adding, playback, persistence round trip, undo and the nesting refusal.+- **FR-015**: CHANGELOG `[Unreleased]`, FEATURES.md and the nota-docs rack pages (EN + RU) MUST describe the new chain instruments and the one-level nesting rule.++### Key Entities++- **Chain instrument**: the instrument at the head of a rack chain; now one of the built-in synths, Sampler, Mosaic, a hosted plug-in, or (Instrument Rack chains only) a Drum Rack.+- **Nested Drum Rack**: a Drum Rack living in an Instrument Rack chain; addressed through the track and the chain that holds it; has its own pads, macros and mappings; stored inside the Instrument Rack's saved state.+- **Mosaic program**: the text description of a Mosaic's zones and groups plus where its sample files live; stored with the instrument's parameters wherever the instrument is stored.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: A user can put a playable multisampled piano in an Instrument Rack chain in under 30 seconds (drop Mosaic, pick a preset in its editor).+- **SC-002**: A user can build a split track — a drum kit on one octave, a synth on the rest — inside one Instrument Rack without leaving the rack card and its device windows.+- **SC-003**: 100% of Mosaic programs and nested kits come back identical after save/reopen, preset load and chain duplication (checked by the smoke test comparing the program text and every pad's state).+- **SC-004**: Every edit made in a chain's Mosaic editor or nested Drum Rack card undoes in one step, and undoing it changes nothing else in the project.+- **SC-005**: No dropout or audio-thread stall when a chain's Mosaic loads a large program while the transport plays.++## Assumptions++- The racks redesign (specs/040, nota-daw/nota#331) is the base; this work extends its shared rack card and Drum Rack card rather than drawing new UI. The nested card reuses the Drum Rack card as is, in a device window.+- Instrument Rack inside an Instrument Rack chain is out of scope (a nested Instrument Rack adds nothing a wider rack doesn't); so is any rack inside an Audio Effect or MIDI Effect Rack.+- The factory drum kits load into a nested Drum Rack from its window's preset picker; a kit dropped from the Browser onto a nested Drum Rack, and a Mosaic pack preset dropped onto a chain, are follow-ups. A chain Mosaic's editor window lists the factory Mosaic presets; pack presets reach a chain through MCP `load_mosaic_preset` (and the editor's own source controls).+- Nested Drum Rack macros and Mosaic chain parameters are not directly automatable or MIDI-learnable (chain parameters never are); the outer rack's macros are the way to automate and learn them.+- Mosaic samples are referenced by path, as on a track; a rack preset carries the program text, not the audio.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [x] 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)+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`+- [x] 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)+- [x] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/041-rack-nested-instruments/tasks.md b/specs/041-rack-nested-instruments/tasks.mdnew file mode 100644index 00000000..20d25441--- /dev/null+++ b/specs/041-rack-nested-instruments/tasks.md@@ -0,0 +1,110 @@+---++description: "Tasks: Mosaic and Drum Rack in Instrument Rack chains"+---++# Tasks: Mosaic and Drum Rack in Instrument Rack chains++**Input**: Design documents from `specs/041-rack-nested-instruments/`++**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/c-abi.md, quickstart.md++**Tests**: the smoke test is required by the spec (FR-014) and the constitution (IV).++## Format: `[ID] [P?] [Story] Description`++## Phase 1: Setup++- [X] T001 Build the engine in the worktree (`src/native/nota.engine/build`, Release) so later steps can link++---++## Phase 2: Foundational (blocking)++- [X] T002 Add `RackCore::replaceChainInstrument(int32_t chain, std::shared_ptr<Instrument>)` (keeps devices, MIDI effects, controls, mappings; sets the rack's sample rate on the instrument) in `src/native/nota.engine/src/devices/racks/RackCore.{h,cpp}`+- [X] T003 Teach `RackCore::makeInstrument` kind 17 (`Mosaic`, empty) and kind 4 (`DrumRack`, empty) in `src/native/nota.engine/src/devices/racks/RackCore.cpp`; guard `deserialize` with a thread-local depth so a rack instrument (kind 3/4) is built only at depth 0 ("a rack instrument (kind 3/4) is built only at depth 0")+- [X] T004 Add `Engine::kNestedRackBase = -100000` and resolve `deviceIndex <= kNestedRackBase` in `Engine::rackCoreAt` (the RackCore of the `RackInstrument` in chain `kNestedRackBase - di` of the track's plain Instrument Rack; null otherwise) and `Engine::rackForEdit` (fork the outer via `rackForEdit(t, -1)`, fork the inner `DrumRack` with mono/pedal/ctl state as for a track Drum Rack, `replaceChainInstrument`) in `src/native/nota.engine/src/engine/{Engine.h,Engine_Rack.cpp}`; test the nested range before the MIDI-rack range everywhere `kMidiRackBase` is compared+- [X] T005 Enforce one nesting level in `Engine::rackAddChain` / `rackSetChainInstrument`: kind 3 never; kind 4 only for `di == -1` on a plain `RackInstrument` (not `DrumRack`) in `src/native/nota.engine/src/engine/Engine_Rack.cpp`+- [X] T006 Extend `Engine::findSampleById` to chain Mosaic zones and nested Drum Rack pads (Sampler / Mosaic) in `src/native/nota.engine/src/engine/Engine_Tracks.cpp`++**Checkpoint**: engine accepts both kinds; nested address resolves.++---++## Phase 3: User Story 1 — Mosaic in a chain (P1) 🎯 MVP++**Goal**: Mosaic as a chain instrument with its full editor, undo and persistence.++**Independent Test**: smoke "Rack chains: Mosaic" section + headless shot of the chain editor.++- [X] T007 [US1] Engine: `rackChainMosaicSetProgram(t, di, c, text, undoable)` (undoable: `rackForEdit` + clone + `setProgram` + `replaceChainInstrument`), `rackChainMosaicProgram`, `rackChainMosaicStatus`, `rackChainMosaicZoneSampleId` in `src/native/nota.engine/src/engine/{Engine.h,Engine_Rack.cpp}`+- [X] T008 [US1] ABI: `nota_rackdev_chain_mosaic_set_program / _program / _status / _zone_sample_id` (contracts/c-abi.md) in `include/nota/nota_engine.h`, `src/abi/nota_engine_rack.cpp`, `nota_exports.txt`, `nota_exports.map`+- [X] T009 [P] [US1] Managed interop: `IAudioEngine.RackChainMosaicSetProgram/Program/TryGetStatus/ZoneSampleId(trackId, deviceIndex, chain, …)` in `src/managed/Nota.Application/Engine/IAudioEngine.cs`, `src/managed/Nota.Infrastructure/Interop/{NativeMethods.Rack.cs,NotaEngine.Rack.cs}`+- [X] T010 [US1] Move `RackChainEngineProxy` to `src/managed/Nota.Application/Engine/RackEngineProxies.cs` (public, with a `Create(engine, chain, deviceIndex = -1)` factory) and map `MosaicSetProgram / MosaicProgram / TryGetMosaicStatus / MosaicZoneSampleId` to the chain calls; update `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs`+- [X] T011 [US1] Add "Nota Mosaic" to the add-chain menu (`RackCardView.cs` `ShowAddChainMenu`), the chain instrument menu (`RackCard.Chains.cs`) and the Drum Rack pad instrument menu (`RackCardView.Drum.cs`)+- [X] T012 [US1] MCP: `load_mosaic_preset` gains `chain` (≥0: apply to that Instrument Rack chain via the chain proxy) in `src/managed/Nota.Mcp/Tools/MosaicTools.cs`; the `set_chain_instrument` description lists 17 and 4 in `src/managed/Nota.Mcp/Tools/RackTools.cs`+- [X] T013 [US1] Smoke test "racks: Mosaic chain" (`tests/Nota.SmokeTest/RackNestingTests.cs`): generated WAVs → program → status ready → note in zone audible / outside silent → macro mapped to a Mosaic param → blob round-trip keeps program text → undoable set + undo restores text, in `tests/Nota.SmokeTest/Program.cs`++**Checkpoint**: US1 works on its own.++---++## Phase 4: User Story 2 — Drum Rack in a chain (P2)++**Goal**: a nested Drum Rack with its card in a device window, undo, persistence.++**Independent Test**: smoke "Rack chains: nested Drum Rack" + headless shot of the nested card.++- [X] T014 [US2] Engine: honour `di` in the Drum-Rack-only engine calls already taking it (they all did); swing/humanize are applied only for the track instrument in `computeInstrumentMidi`, so a nested rack's are ignored — verified, no change in `src/native/nota.engine/src/engine/Engine_Rack.cpp`+- [X] T015 [US2] ABI twins (contracts/c-abi.md): `nota_rackdev_add_sampler_chain`, `_set_chain_sampler_sample`, `_add_plugin_instrument_chain`, `_chain_name`, `_set_chain_name`, `_chain_choke/_tune/_decay` + setters, `_swing/_humanize` + setters, `_chain_sampler_info`, `_set_chain_sampler_root`, `_chain_sampler_play_position`, `_chain_instrument_param_id`, `_param_default`, `_scope`, `_voice_count`, `_held_notes`, `_action`; `#define NOTA_RACK_NESTED_BASE (-100000)` in `include/nota/nota_engine.h`, `src/abi/nota_engine_rack.cpp`, export lists+- [X] T016 [P] [US2] Managed interop for T015 as `RackDev*` twins in `IAudioEngine.cs`, `NativeMethods.Rack.cs`, `NotaEngine.Rack.cs`; `RackMacroMapping.NestedRackBase` constant+- [X] T017 [US2] `NestedRackEngineProxy` in `src/managed/Nota.Application/Engine/RackEngineProxies.cs`: `Rack<Name>(t, …)` → `RackDev<Name>(t, nested, …)` by cached reflection, explicit maps for differently-shaped twins (`RackChainZone`, `RackSetChainZone`, `RackTryGetMapping`), `RackDev*(t, -1, …)` → nested, `PluginParam*(t, -1, i)` → nested macros, `TrackInstrumentKind` → 4, automation writes → no-op+- [X] T018 [US2] Open a Drum Rack chain's GUI as the Drum Rack card over the proxy in a `DeviceWindow` (`OpenChainInstrumentGui`, kind 4) in `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs`; in nested mode the Drum card hides swing/humanize and skips MIDI Learn on macros (`RackCardView.Drum.cs`, `RackCardView.cs` `MacroCell`, `RackCard.Macros.cs`/`MacroPanel.cs` where learn is bound)+- [X] T019 [US2] Add "Nota Drum Rack" to the Instrument Rack add-chain and chain instrument menus only (not pads) in `RackCardView.cs`, `RackCard.Chains.cs`+- [X] T020 [US2] Smoke test "racks: nested Drum Rack" (`RackNestingTests.cs`): accept on Instrument Rack, refuse on a Drum Rack pad and deeper; two Sampler pads via the nested address; pad note in zone audible / other note silent; choke/tune/decay round-trip; undo of a nested pad add; blob round-trip keeps pads and audio; outer macro → nested macro → pad decay, in `tests/Nota.SmokeTest/Program.cs`++---++## Phase 5: User Story 3 — MCP / listing (P3)++- [X] T021 [US3] `get_rack` gains `nestedChain` (reads the nested Drum Rack through `NestedRackEngineProxy`); chain kinds 17/4 already show in its chain list, in `src/managed/Nota.Mcp/Tools/RackTools.cs`++---++## Phase 6: Polish++- [X] T022 Headless UI check: chain Mosaic editor and nested Drum Rack card render and edit (scratch harness, not committed)+- [X] T023 [P] CHANGELOG `[Unreleased]` Added entry in `CHANGELOG.md`+- [X] T024 [P] FEATURES.md via the nota-features skill+- [X] T025 [P] nota-docs rack pages EN + RU via the nota-docs skill (`../nota-docs`: devices/racks/instrument-rack, drum-rack; build + check pass, left uncommitted)+- [X] T026 `scripts/build.sh` green+- [X] T027 `/speckit-converge` reports Converged (after T028)++## Dependencies++- T002–T006 before every story. US1 (T007–T013) and US2 (T014–T020) are independent of+ each other after Phase 2, except that T010 (proxy file) precedes T017.+- T026 after all code tasks.++## Parallel examples++- T009 ∥ T008 once T007's signatures are fixed; T016 ∥ T015.+- T023 ∥ T024 ∥ T025.++## Implementation strategy++MVP = Phase 2 + US1 (Mosaic chains). Then US2 (nesting), US3, polish.++## Nota Compliance Re-check++- [X] SPDX header on the new `RackEngineProxies.cs`+- [X] No new dependency+- [X] No audio-thread allocation/lock/I/O added (rack snapshot pattern only)+- [X] All new crossings are C ABI functions in `nota_engine.h`+- [X] Smoke test extended (T013, T020)+- [X] CHANGELOG / FEATURES / docs (T023–T025)+- [X] UI reuses existing cards (DESIGN.md)++## Phase 7: Convergence++- [X] T028 Record why Audio Effect / MIDI Effect Rack chains now ignore the instrument kind in `Engine::rackAddChain` and why MCP `add_effect_rack_chain` defaults to −1 (kind 4 used to mean "no instrument" there and is now the Drum Rack) per plan: nesting rule (unrequested)diff --git a/specs/042-rack-device-clipboard/checklists/requirements.md b/specs/042-rack-device-clipboard/checklists/requirements.mdnew file mode 100644index 00000000..9947c0f9--- /dev/null+++ b/specs/042-rack-device-clipboard/checklists/requirements.md@@ -0,0 +1,37 @@+# Specification Quality Checklist: Move, copy and paste devices in rack chains++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-27+**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++- The Nota Context and Nota Compliance sections name repo areas and AR rules on purpose (the+ Nota template asks for them); the user-facing sections stay implementation-free.+- Scope decisions recorded under Assumptions and Clarifications: Duplicate / ⌘D added to both+ chains (clarified); drag within a chain and onto another chain's row of the same rack (clarified); instruments not copied.diff --git a/specs/042-rack-device-clipboard/contracts/c-abi.md b/specs/042-rack-device-clipboard/contracts/c-abi.mdnew file mode 100644index 00000000..60dddfb1--- /dev/null+++ b/specs/042-rack-device-clipboard/contracts/c-abi.md@@ -0,0 +1,57 @@+# Contract: C ABI additions (`nota_engine.h`)++All calls run on the message thread.++**Rack address.** `device_index` addresses the rack the same way as the other `nota_rackdev_*` calls:+- −1 = the track's Instrument (or Drum) Rack;+- ≥0 = an Audio Effect Rack at that device index;+- −1000 − mi = the MIDI Effect Rack at MIDI effect index mi;+- `NOTA_RACK_NESTED_BASE` − c = the Drum Rack nested in Instrument Rack chain c.++**Undo.** Every editing call is one undo step: one rack fork.++**Clipboard.** It is the engine's existing device clipboard, the one `nota_track_copy_device`, `nota_track_paste_device`, `nota_track_copy_midi_effect` and `nota_track_paste_midi_effect` use.++```c+/* Copy chain `chain`'s audio effect `index` (or MIDI effect) to the device clipboard.+ 1 = copied, 0 = no such device. */+NOTA_API int32_t nota_rackdev_chain_device_copy(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);+NOTA_API int32_t nota_rackdev_chain_midi_copy(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);++/* Paste a fresh clone of the clipboard into chain `chain`'s audio-effect (or MIDI-effect)+ section at `at_index` (−1 or past the end = at the end). A pasted audio effect loses its+ sidechain key. Returns the new index, or:+ −1 nothing to paste / bad address+ −2 the clipboard holds the other family (or this rack has no such section)+ −3 a rack inside a rack+ −5 a MIDI effect past chain 16 of an Instrument Rack */+NOTA_API int32_t nota_rackdev_chain_device_paste(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t at_index);+NOTA_API int32_t nota_rackdev_chain_midi_paste(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t at_index);++/* Duplicate a chain device right after itself (the clipboard is untouched). New index or < 0. */+NOTA_API int32_t nota_rackdev_chain_device_duplicate(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);+NOTA_API int32_t nota_rackdev_chain_midi_duplicate(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);++/* Move a chain device to the end of another chain's matching section of the same rack; its+ macro mappings follow it. New index in `to_chain`, or −1 bad address / same chain, −5 as above. */+NOTA_API int32_t nota_rackdev_chain_device_move_to(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t index, int32_t to_chain);+NOTA_API int32_t nota_rackdev_chain_midi_move_to(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t chain, int32_t index, int32_t to_chain);++/* 1 when the clipboard holds an audio effect keyed from another track (its key won't survive+ a paste into a rack chain). */+NOTA_API int32_t nota_device_clipboard_sidechain(const NotaEngine* e);+```++**Managed mirror** (`IAudioEngine`):+- `RackDevChainDeviceCopy` / `RackDevChainMidiCopy` → bool;+- `RackDevChainDevicePaste` / `RackDevChainMidiPaste` → int;+- `RackDevChainDeviceDuplicate` / `RackDevChainMidiDuplicate` → int;+- `RackDevChainDeviceMoveTo` / `RackDevChainMidiMoveTo` → int;+- `DeviceClipboardSidechain` → bool.++The Instrument Rack's `IRackAccess` passes −1, the Audio Effect Rack passes its device index, and the MIDI Effect Rack passes −1000 − mi.++**Existing calls used as they are**:+- `nota_rack_move_chain_device`, `nota_rackdev_move_chain_device`, `nota_rack_chain_midi_move`, `nota_midirack_chain_device_move` (move within a section);+- `nota_track_duplicate_device`, `nota_track_duplicate_midi_effect` (track-chain Duplicate);+- `nota_device_clipboard_kind`.diff --git a/specs/042-rack-device-clipboard/contracts/ui.md b/specs/042-rack-device-clipboard/contracts/ui.mdnew file mode 100644index 00000000..57bfdd46--- /dev/null+++ b/specs/042-rack-device-clipboard/contracts/ui.md@@ -0,0 +1,40 @@+# Contract: UI behaviour++## Rack card (Chains tab, device lane)++| Gesture | Result |+|---|---|+| Left-click a device's header | selects it: the track chain's selected-device look (accent outline); clears any other selection on the track |+| Drag a device's header (or its grip) ≥ 5 px | the card dims to 0.55 and an `AccentBright` 3-px drop bar shows at the gap under the pointer, only among the same section's cards |+| Release over a gap | moves there: one undo step; the device stays selected |+| Drag over a chain row in the chain list | the row gets the drop outline (as for Browser drops) if that chain can take the device; else no drop is offered |+| Release on a chain row | moves the device to the end of that chain's section, and chooses that chain |+| Right-click a device's header | menu: Open · Turn on/off · ─ · Move left · Move right · ─ · Copy ⌘C · Cut ⌘X · Paste ⌘V · Duplicate ⌘D · ─ · Delete ⌫ |+| Right-click a chain row | the chain menu gains **Paste** (at the end of the clipboard's family section), disabled when the clipboard is empty or doesn't fit |+| Click the lane's dashed "+" target | its add menu gains **Paste** at the top when the clipboard fits that section |+| Right-click the instrument card | as now (no copy or paste of instruments) |++## Keys (device panel focused)++| Key | Rack device selected | Track device selected | Nothing selected |+|---|---|---|---|+| ⌘C | copy it | copy it (as now) | — |+| ⌘X | cut it | cut it (as now) | — |+| ⌘V | paste after it, same chain and section | paste after it (as now) | paste at the end of the track chain (as now) |+| ⌘D | duplicate after it | duplicate after it (new) | — |+| Delete / ⌫ | delete it | delete it (as now) | — |++A paste that's refused leaves everything as it was and puts the reason on the status line (data-model.md). A pasted keyed effect adds "· sidechain dropped".++## Track chain++- The device menu gains **Duplicate ⌘D** between Paste and the rack group items.+- ⌘V pastes a rack chain copy as it pastes any copy. A rack device (kind 5) pasted onto the track chain is fine (existing behaviour).++## Shortcuts list (Preferences → Shortcuts, "Devices (after a click on a device)")++- Add: `⌘ D` — "Duplicate the device". Existing rows ⌘C / ⌘X / ⌘V / Delete now also say "(track or rack chain)" where the text names the chain.++## Themes++The selection outline, drop bar, dimmed card and row drop outline use the track chain's tokens (`Accent`, `AccentBright`, `Teal` washes). They are checked on a 4-theme render.diff --git a/specs/042-rack-device-clipboard/data-model.md b/specs/042-rack-device-clipboard/data-model.mdnew file mode 100644index 00000000..02fade82--- /dev/null+++ b/specs/042-rack-device-clipboard/data-model.md@@ -0,0 +1,57 @@+# Data Model: Move, copy and paste devices in rack chains++Nothing new is saved: no rack blob or project format change. The entities below live for the+app session.++## Device clipboard (engine, existing)++| Field | Meaning |+|---|---|+| `clipDevice_` | a full clone of a copied audio effect (built-in, hosted plug-in or rack), or empty |+| `clipMidi_` | a full clone of a copied MIDI effect, or empty |++- **Invariant**: at most one of them is set (copying one clears the other).+- **Filled by**: track `copyDevice` / `copyMidiEffect` (existing), and rack `rackChainDeviceCopy` / `rackChainMidiCopy` (new).+- **Read by**: track `pasteDevice` / `pasteMidiEffect` (existing), and rack `rackChainDevicePaste` / `rackChainMidiPaste` (new).++ Every paste clones the clipboard again, so it can be pasted many times.+- **Kind** (`nota_device_clipboard_kind`, existing): 0 empty, 1 audio effect, 2 MIDI effect.+- **Sidechain** (`nota_device_clipboard_sidechain`, new): 1 when `clipDevice_` has a sidechain source track.++## Rack chain device address++| Field | Values |+|---|---|+| rack | −1 = the track's Instrument Rack (or Drum Rack); ≥0 = Audio Effect Rack at device index; −1000 − mi = MIDI Effect Rack at MIDI effect index mi; `NOTA_RACK_NESTED_BASE` − c = the Drum Rack nested in Instrument Rack chain c (specs/041) |+| chain | 0..chainCount−1 |+| section | audio effect, or MIDI effect |+| index | position within the section |++## Rack device selection (managed, new)++`RackDeviceSel(int Rack, int Chain, bool Midi, int Index)` is held by `DeviceChainView`.++- **Exclusive** with the track-chain selection (`_selChainKind` / `_selDeviceIndex`): setting one clears the other.+- **Clearing**: cleared on `Show(track)`, on a rebuild whose rack or chain no longer has that index, and when the chosen chain changes on that rack.+- **Keys**: drives the ⌘C / ⌘X / ⌘V / ⌘D / Delete routing and the card's selected look.++## State transitions (one rack fork each = one undo step)++| Action | Rack change | Mappings |+|---|---|---|+| Move within section (from → to) | reorder | the device's follow it; between from and to shift by one (existing) |+| Move to another chain (c1, i → c2, end) | remove from c1, append to c2 | the device's rewrite to (c2, new index); c1's after i shift down |+| Paste at `at` (c) | insert clone at `at` | c's at or after `at` shift up; the clone has none |+| Duplicate (c, i) | insert clone at i+1 | as Paste at i+1 |+| Cut (c, i) | copy to the clipboard, then remove | removed with it (undo restores them) |+| Delete (c, i) | remove | removed with it (undo restores them) |++## Paste result codes (engine → UI)++| Code | Meaning | Status line |+|---|---|---|+| ≥0 | index of the pasted device | "Pasted <name>" (+ " · sidechain dropped" when the clipboard was keyed) |+| −1 | nothing on the clipboard / bad address | (Paste disabled) |+| −2 | the wrong family for this section (MIDI effect into effects, or the other way round; an audio effect into a MIDI Effect Rack) | "A <section> takes <family> only." |+| −3 | a rack inside a rack | "A rack can't go inside a rack." |+| −5 | a MIDI effect past chain 16 of an Instrument Rack | "MIDI effects run in the first 16 chains." |diff --git a/specs/042-rack-device-clipboard/plan.md b/specs/042-rack-device-clipboard/plan.mdnew file mode 100644index 00000000..2ef78ae1--- /dev/null+++ b/specs/042-rack-device-clipboard/plan.md@@ -0,0 +1,126 @@+# Implementation Plan: Move, copy and paste devices in rack chains++**Branch**: `feat/rack-nested-instruments` (spec 042 follows 040 and 041 on the same branch) | **Date**: 2026-10-27 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/042-rack-device-clipboard/spec.md`++## Summary++Rack chains get the track chain's device handling:+- **header drag** with a drop bar to reorder within a section;+- **drop on another chain's row** to move a device there, mappings and all;+- **selection, with Copy / Cut / Paste / Duplicate / Delete** from the menu and from ⌘C / ⌘X / ⌘V / ⌘D / Delete.++The track chain gains Duplicate (⌘D) too.++The clipboard is the engine's existing one (`clipDevice_` / `clipMidi_`), so a copy taken on the track chain pastes into a rack chain and the other way round.++Engine work is small and structural (no DSP):+- rack copy, paste at a position, duplicate, and move to another chain;+- each as one rack fork, so each is one undo step.++The bulk is managed UI: the rack lane's drag, selection, menus and key routing in `DeviceChainView`. See [research.md](research.md).++## Nota: Read Before Planning++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-5 (rack edits are immutable snapshots via `rackForEdit`), AR-6 (nothing new on the audio thread), AR-7 (new C ABI functions only).+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill: the drop bar and selection reuse the track chain's tokens (`AccentBright` bar, the selected-device look).+- **Shortcuts** → the `nota-shortcuts` skill (⌘D in Preferences → Shortcuts).+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).++## Technical Context++**Language/Version**: C++20 (engine: `RackCore`, `Engine_Rack.cpp`, `abi/nota_engine_rack.cpp`); C# / .NET 10 (`Nota.Infrastructure` interop, `Nota.Application` `IAudioEngine`, `Nota.App` rack card and device chain view).++**Primary Dependencies**: none new (Avalonia as today).++**Storage**: none new. Moves and pastes change the rack blob through existing persistence; no format change.++**Audio-Thread Impact**: none new. Every operation is a structural rack edit on the message thread: `rackForEdit` forks the rack (AR-5) and republishes; the audio thread sees a new snapshot. Instrument Rack MIDI chains reconcile held notes in `syncChains` when a chain's MIDI effects change (specs/040 review fix); MIDI Effect Racks cut held notes on a structure change. No allocation or lock is added on the audio thread (AR-6).++**Testing**: `tests/Nota.SmokeTest`, a new section `racks: chain device clipboard`. It covers:+- move within a chain and to another chain, with mappings and undo;+- copy and paste between the track chain and rack chains (audio effect, MIDI effect, hosted plug-in where available), checking params and state;+- every refusal code;+- sidechain stripping;+- duplicate on both chains;+- one undo step each.++The UI (drag, selection, menu, keys) is checked headlessly by driving the card's handlers, plus a theme sheet.++**Target Platform**: macOS / Windows / Linux desktop (as the app).++**Project Type**: desktop app (native engine + managed UI).++**Performance Goals**: an edit lands within one UI frame plus the snapshot publish (well under 50 ms on a 16-chain rack).++**Constraints**:+- one undo step per user action;+- no change to rack blob v9 or the project format;+- the track chain's existing behaviour stays as it is, apart from the added Duplicate.++**Scale/Scope**: about 8 C ABI functions, 4 `RackCore` methods, and the rack card and device chain view (around 400 lines of C#).++## Constitution Check++| Principle | Status |+|---|---|+| I. Real-time audio safety | Pass: structural edits via snapshots only; nothing on the audio thread |+| II. Boundary discipline | Pass: new calls are pure C ABI in `nota_engine.h`; no JUCE outside `pluginhost/` |+| III. Licensing hygiene | Pass: no new dependency; new files (if any) get the SPDX header |+| IV. Verification gate | Planned: `scripts/build.sh` plus the new smoke section |+| V. One logical change per PR | Note: lands on the 041 branch per the user's flow; can be split into its own PR at review time |+| VI. Docs in sync | Planned: CHANGELOG, FEATURES, nota-docs rack pages (EN + RU), Shortcuts list |+| VII. Spec-first | Pass: spec 042 with clarifications |+| VIII. Safety rules not weakened | Pass |++No violations, so no Complexity Tracking entries. Re-checked after Phase 1: unchanged.++## Project Structure++### Documentation (this feature)++```text+specs/042-rack-device-clipboard/+├── spec.md+├── research.md+├── plan.md+├── data-model.md+├── quickstart.md+├── contracts/+│ ├── c-abi.md+│ └── ui.md+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # new nota_rackdev_chain_* clipboard/move calls, nota_device_clipboard_sidechain+├── src/devices/racks/RackCore.h/.cpp # insertChainDeviceInstance, insertChainMidiDeviceInstance,+│ # moveChainDeviceToChain, moveChainMidiDeviceToChain+├── src/engine/Engine.h, Engine_Rack.cpp # rackChain{Device,Midi}{Copy,Paste,Duplicate,MoveTo}+├── src/engine/Engine_Devices.cpp # deviceClipboardSidechain()+└── src/abi/nota_engine_rack.cpp, nota_engine_device.cpp++src/managed/+├── Nota.Infrastructure/Interop/NativeMethods.Rack.cs, NotaEngine.Rack.cs # P/Invoke + wrappers+├── Nota.Application/Engine/IAudioEngine.cs # the new calls+├── Nota.App/DeviceCards/Rack/IRackAccess.cs # Copy/Paste/Duplicate/MoveToChain per rack kind+├── Nota.App/DeviceCards/DeviceCardContext.cs # SelectRackDevice / RackSelection+├── Nota.App/DeviceCards/Rack/RackCard.Chains.cs # header drag + drop bar, chain-row drop,+│ # selection look, card menu, chain-row Paste+├── Nota.App/DeviceChainView.Clipboard.cs # rack selection routing, ⌘D, Duplicate item+├── Nota.App/MenuKit.cs # DuplicateKey+└── Nota.App/PreferencesWindow.cs # ⌘D row++tests/Nota.SmokeTest/RackClipboardTests.cs (new), Program.cs (section hook)+```++**Structure Decision**: The engine keeps the clipboard and does every structural edit as one rack fork. The managed side holds only the selection and routes keys and menus. The rack card is the only UI that draws rack chain devices, so the drag, selection and menus live in `RackCard.Chains.cs`, and `DeviceChainView` stays the single key handler.++## Complexity Tracking++None.diff --git a/specs/042-rack-device-clipboard/quickstart.md b/specs/042-rack-device-clipboard/quickstart.mdnew file mode 100644index 00000000..d7042a0f--- /dev/null+++ b/specs/042-rack-device-clipboard/quickstart.md@@ -0,0 +1,23 @@+# Quickstart: validating spec 042++## Build and smoke++```bash+scripts/build.sh+dotnet run --project tests/Nota.SmokeTest -c Release -- --racks+```++Expect the `racks: chain device clipboard` section to pass:+- move within a chain and to another chain (mappings follow, one undo each);+- track → rack and rack → track paste with equal params and state;+- every refusal code, sidechain stripping, and Duplicate on both chains.++## In the app++1. **Q1 — reorder (US1)**: an Audio Effect Rack, chain 1 with EQ-3 · Compressor · Reverb. Drag Reverb's header in front of EQ-3. A drop bar shows while dragging; the order becomes Reverb · EQ-3 · Compressor. ⌘Z restores it.+2. **Q2 — move to a chain (FR-003a)**: map Macro 1 to the Compressor's Threshold, then drag the Compressor onto chain 2's row. It now sits in chain 2 and chain 2 is chosen. Macro 1 still drives it, as the M1 tag on its card shows. ⌘Z puts it back in chain 1, still mapped.+3. **Q3 — clipboard inside a rack (US2)**: click the Reverb, ⌘C, choose chain 2, ⌘V. Chain 2 has a Reverb with the same values. ⌘D adds another right after it. Delete removes it. Each step undoes on its own.+4. **Q4 — across (US3)**: tune a Delay on the track chain, ⌘C. Click a device in an Instrument Rack chain and press ⌘V: the Delay lands after it with the same values. Copy it back from the rack, click a track device, ⌘V. Repeat with an Arp from the track's MIDI effects into an Instrument Rack chain and into a MIDI Effect Rack chain.+5. **Q5 — refusals**: copy an Arp and paste into an Audio Effect Rack chain. Copy an Audio Effect Rack and paste into another rack's chain. Paste a MIDI effect into chain 17 of an Instrument Rack. Each time nothing changes and the status line gives the reason.+6. **Q6 — sidechain**: key a Compressor from another track, copy it, paste into a rack chain. The status line ends with "sidechain dropped" and the pasted compressor runs on the chain's signal.+7. **Q7 — themes**: repeat Q1–Q3 in Studio Light, Ember Graphite and Ember Paper. The selection, drop bar and row drop outline must be readable.diff --git a/specs/042-rack-device-clipboard/research.md b/specs/042-rack-device-clipboard/research.mdnew file mode 100644index 00000000..a6879229--- /dev/null+++ b/specs/042-rack-device-clipboard/research.md@@ -0,0 +1,54 @@+# Research: Move, copy and paste devices in rack chains++Findings from the code as it stands on `feat/rack-nested-instruments` (after specs/040 and 041).++## D1 — Why moving a rack chain device doesn't work today++- **Decision**: Replace the rack lane's grip-only reorder with header drag and a drop bar, matching the track chain.+- **Rationale**: `RackCard.Chains.cs` `RcGripReorder` hangs the move on the 8-px grip glyph in the card footer. It shows no drop bar and moves by `round(dx / (card width + 14))` steps on release. The grip is easy to miss and gives no feedback, which matches the report ("can't move effects"). The track chain (`DeviceChainView.Clipboard.cs` `HookDeviceDrag`) drags by the header, dims the card, shows `_devDropBar` at the gap under the pointer, and moves on release by the gap index.+- **Alternatives considered**: keeping the grip and adding a drop bar. Rejected: the header is the handle on the track chain; two handles would differ for no gain. The grip glyph stays as a visual cue and also starts a drag.++## D2 — Engine primitives that already exist++- **Move within a chain**: `RackCore::moveChainDevice` and `moveChainMidiDevice` (rack fork, undoable) already remap mappings by index. ABI: `nota_rack_move_chain_device`, `nota_rackdev_move_chain_device`, `nota_rack_chain_midi_move`, `nota_midirack_chain_device_move`. US1 within a chain needs no engine work.+- **The clipboard**: the engine owns one device clipboard: `Engine::clipDevice_` (an audio effect clone) / `clipMidi_` (a MIDI effect clone), filled by `copyDevice` / `copyMidiEffect` and read by `pasteDevice` / `pasteMidiEffect`, with `nota_device_clipboard_kind`. It holds full clones (`cloneDevice` copies params, state blob, bypass, fold and sidechain; hosted plug-ins and racks clone themselves).+- **Duplicate on the track chain**: `duplicateDevice` / `duplicateMidiEffect` exist in the engine and `IAudioEngine` but no UI uses them.+- **Mappings on remove**: `removeChainDevice` / `removeChainMidiDevice` drop the device's mappings and shift the rest. Undo restores them because the whole rack forks.++## D3 — One clipboard for track and rack chains++- **Decision**: Rack copy writes the same `clipDevice_` / `clipMidi_`, and rack paste reads them. New ABI: `nota_rackdev_chain_device_copy` / `_paste`, `nota_rackdev_chain_midi_copy` / `_paste`, addressed like other `rackdev` calls (−1 Instrument Rack, ≥0 Audio Effect Rack, −1000 − mi for a MIDI Effect Rack (the engine's `kMidiRackBase` address), `NOTA_RACK_NESTED_BASE − chain`).+- **Rationale**: FR-009 asks for one shared clipboard. Reusing the engine's means the track chain's existing ⌘V already pastes a rack copy (and the other way round) with no new managed state. The managed `DeviceChainView._clip` (`DeviceClip`) only carries preset labels for the A/B extras; it gains a "came from a rack" flag so Paste is enabled.+- **Alternatives considered**: a managed clipboard holding a preset document. Rejected: it loses state that isn't in params (hosted plug-in state, Arp lanes beyond params) and duplicates the engine's clone logic.++## D4 — Paste at a position, and mappings++- **Decision**: New `RackCore::insertChainDeviceInstance(chain, dev, at)` / `insertChainMidiDeviceInstance(chain, dev, at)`. They insert the clone and shift mappings at or after `at` up by one, like `insertDeviceClone` remaps automation on the track. A pasted device has no mappings (FR-011).+- **Rationale**: `addChainDeviceInstance` only appends. Add-then-move would make two forks (two undo steps) unless grouped, and is harder to reason about.++## D5 — Moving to another chain (drag onto a chain row)++- **Decision**: New `RackCore::moveChainDeviceToChain(fromChain, idx, toChain)` and a MIDI twin, in one fork. They take the device object out of `fromChain`, append it to `toChain`, rewrite the device's own mappings to `(toChain, newIdx)`, and shift `fromChain`'s later mappings down. ABI: `nota_rackdev_chain_device_move_to` / `nota_rackdev_chain_midi_move_to`.+- **Rationale**: FR-003a needs mappings to follow (FR-012). Cut and paste would drop them, so a real move is needed.+- **Audio-thread note**: the instance moves between chains in a new snapshot. Instrument Rack MIDI chains are reconciled by `syncChains` (specs/040 review fix): a MIDI effect that changes chain changes both chains' signatures, so held notes there end cleanly.++## D6 — Refusals and the sidechain++- **Decision**: Paste returns the new index or a negative reason code:+ - −2: the clipboard is empty, or holds the wrong family for the section;+ - −3: a rack inside a rack (`RackDevice` kind 5, `MidiRack` kind 6);+ - −5: a MIDI effect past chain 16 of an Instrument Rack.+ A sidechain key is cleared on the clone pasted into a chain (`setSidechainSourceTrackId(−1)`). `nota_device_clipboard_sidechain(e)` tells the UI beforehand so the status line can say the sidechain was dropped (FR-015).+- **No −4.** Every rack the clipboard reaches (Instrument, Drum, Audio Effect) hosts plug-ins and a MIDI Effect Rack has no audio section (−2), so the planned "can't host a plug-in" code never arises; it was dropped.+- **Rationale**: the engine is where the clone's type is known; the codes map 1:1 to the spec's status messages. Chain devices have no sidechain input (the chain device proxy already reports `DeviceAcceptsSidechain` false).++## D7 — Selection and keys++- **Decision**: `DeviceChainView` owns one selection that is either a track-chain device (as now: `_selChainKind` / `_selDeviceIndex`) or a rack chain device: a new `RackDeviceSel(int Rack, int Chain, bool Midi, int Index)` set through `DeviceCardContext.SelectRackDevice`. `OnKeyDown` routes ⌘C / ⌘X / ⌘V / ⌘D / Delete to the rack commands when a rack device is selected. Selecting either kind clears the other (FR-005).+- **Rationale**: Keys already reach `DeviceChainView.OnKeyDown`, and the rack card is built inside it. One owner keeps "paste goes where you last clicked" simple.+- **Paste with no device selected in the chosen chain**: the chain row's menu and the lane's "+" target menu get **Paste** (at the end of the matching section), so FR-008's "end of the chosen chain" is reachable without a selection.++## D8 — ⌘D++- **Decision**: ⌘D in `DeviceChainView.OnKeyDown` duplicates the selected device (track or rack) while the panel has focus, and its menu gains **Duplicate**. `MenuKit` gets a `DuplicateKey` hint; Preferences → Shortcuts lists "⌘D Duplicate the selected device" in the Devices group.+- **Check**: ⌘D elsewhere (piano roll duplicate notes, arrangement) is handled by those views while they have focus. The device panel handles only its own focus, so there is no conflict.diff --git a/specs/042-rack-device-clipboard/spec.md b/specs/042-rack-device-clipboard/spec.mdnew file mode 100644index 00000000..7ec0440c--- /dev/null+++ b/specs/042-rack-device-clipboard/spec.md@@ -0,0 +1,174 @@+# Feature Specification: Move, copy and paste devices in rack chains++**Feature Branch**: `feat/rack-nested-instruments` (follows specs/040 and specs/041)++**Created**: 2026-10-27++**Status**: Draft++**Input**: User description: "Move, copy and paste devices inside rack chains, the same way as in a track's device chain. On the shared rack card (Instrument, Audio Effect and MIDI Effect Racks; the chosen chain's devices shown left to right as compact cards in the Chains tab), the user can: (1) drag a chain's audio effect (or MIDI effect) to a new position within its section of that chain, with the same drag gesture, drop indicator and undo as reordering devices on the track's own device chain; (2) select a device in a rack chain and copy, cut, paste, duplicate and delete it from its right-click menu and with the same shortcuts as the track chain (⌘C / ⌘X / ⌘V, ⌘D, Delete); (3) copy a device from the track's device chain and paste it into a rack chain, and copy a device from a rack chain and paste it onto a track's device chain (or into another rack's chain), keeping its parameters and state — audio effects into audio-effect slots, MIDI effects into MIDI-effect slots, refusing what a slot can't take (an instrument, a rack inside a rack except the nested Drum Rack rules of specs/041, a plug-in where the rack can't host plug-ins) with a status-line reason. Paste goes after the selected device, or at the end of the chain. Each move / paste / cut / duplicate is one undo step. Mappings to a moved device follow it; a pasted device carries no macro mappings. The Preferences → Shortcuts list and docs stay in sync. Works in all four themes."++User's words (Russian, 2026-10-27): "не могу перемещать эффекты внутри цепочки устройств внутри рэков (менять их положение). Нужно реализовать такую же логику как в основной цепочке + копировать / вставить (через контекстное меню и горячей клавишей). При этом я хотел бы копировать устройства из основной цепочки сюда и наоборот."++## Clarifications++### Session 2026-10-27++- Q: Should rack chain devices (and the track chain, so both stay the same) get a Duplicate command with ⌘D, or is Copy then Paste enough? → A: Add Duplicate (⌘D, plus a menu item) to both the rack chains and the main device chain.+- Q: When dragging a device, should it be able to go only within its own chain, or also into another chain of the same rack and between the track chain and a rack? → A: Within its chain, plus onto another chain's row in the same rack's chain list (the device moves there, to the end). To and from the track chain or another rack stays Cut + Paste.+- Q: When an effect that listens to a sidechain is pasted into a rack chain, where there's no sidechain input, what should happen? → A: Paste it without the key; the status line says the sidechain was dropped.++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [ ] 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++Engine work is likely small: the rack already moves a chain's devices and MIDI effects (with undo). Copying a device's full state between a track chain and a rack chain may need an engine path that takes a device's state across. The plan decides.++**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).++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Reorder a chain's effects (Priority: P1)++On a rack card, with a chain chosen, the user drags one of its audio effects by its header and drops it before or after another effect in the same chain. A drop indicator shows where it will land, as it does on the track's device chain. The chain plays in the new order. The same works for a chain's MIDI effects, within the MIDI section. The device's right-click menu also offers **Move left** and **Move right**, as the track chain's does.++**Why this priority**: The user can't reorder devices inside a rack today. Order changes the sound (a compressor before or after a reverb), so a rack chain is hard to work with without it.++**Independent Test**: Put an EQ, a compressor and a reverb in a chain. Drag the reverb in front of the EQ, then play: the reverb now comes first. One Undo brings the old order back.++**Acceptance Scenarios**:++1. **Given** a chain with effects A, B, C, **When** the user drags C onto the gap before A, **Then** the chain reads C, A, B, plays in that order, and one Undo restores A, B, C.+2. **Given** a chain with MIDI effects Arp then Chord, **When** the user drags Chord before Arp, **Then** the order is Chord, Arp.+3. **Given** a macro mapped to B's parameter, **When** B is moved, **Then** the macro still drives that same parameter on B.+4. **Given** a drag of an audio effect, **When** it hovers the chain's MIDI section or its instrument slot, **Then** no drop is offered there.+6. **Given** a drag of an effect from chain 1, **When** it is dropped on chain 2's row in the chain list, **Then** it leaves chain 1 and lands at the end of chain 2's matching section (effects or MIDI effects), keeps its settings and its macro mappings, and chain 2 becomes the chosen chain; one Undo puts it back in chain 1.+7. **Given** a drag of a MIDI effect, **When** it hovers the row of a chain that can't take it (chain 17+ of an Instrument Rack), **Then** no drop is offered there.+5. **Given** a device, **When** the user picks **Move left** or **Move right** in its menu, **Then** it swaps with its neighbour. At the first or last position the item is disabled.++---++### User Story 2 - Copy, cut, paste and delete inside rack chains (Priority: P1)++The user clicks a device in a rack chain to select it; the selection looks the same as on the track chain. **Copy**, **Cut**, **Paste**, **Duplicate** and **Delete** are in its right-click menu and on the same keys as on the track chain: ⌘C, ⌘X, ⌘V, ⌘D, and Delete or Backspace. Duplicate is new on the track chain too, so both chains offer the same commands. Paste puts the copy right after the selected device, or at the end of the section when nothing in that chain is selected. The copy keeps every parameter and the device's state.++**Why this priority**: The user asked for it explicitly. It is the everyday way to build variations across chains, such as the same compressor on every layer.++**Independent Test**: Copy a compressor on chain 1, choose chain 2, paste. Chain 2 now has a compressor with the same settings. Cut it and paste it on chain 3; delete it. Each step undoes on its own.++**Acceptance Scenarios**:++1. **Given** a selected effect in chain 1, **When** the user presses ⌘C, chooses chain 2 and presses ⌘V, **Then** chain 2 gains a copy with identical parameter values, at the end of its effects.+2. **Given** a selected effect in chain 2, **When** the user pastes, **Then** the copy lands right after the selected effect.+3. **Given** a selected effect, **When** the user presses ⌘X, **Then** it leaves the chain and the clipboard holds it; ⌘V elsewhere puts it back with its settings.+4. **Given** a selected device, **When** the user presses Delete, **Then** it is removed; one Undo brings it back with its macro mappings.+6. **Given** a selected device in a rack chain or on the track chain, **When** the user presses ⌘D (or picks **Duplicate**), **Then** a copy with the same settings lands right after it and is selected; the clipboard is left as it was; one Undo removes the copy.+5. **Given** a copied MIDI effect, **When** the user pastes into a chain of an Audio Effect Rack, **Then** nothing is pasted and the status line says why.++---++### User Story 3 - Copy between the track chain and rack chains (Priority: P2)++The user copies a device from the track's own device chain and pastes it into a rack chain, or the other way round, or from one rack into another rack's chain. It arrives with its settings and state. One clipboard serves all of these.++**Why this priority**: The user asked for it. It saves rebuilding a sound by hand when moving a tuned effect into a parallel chain, or pulling one out of a rack.++**Independent Test**: On a track, tune a reverb on the main chain and copy it. Select a chain in an Audio Effect Rack on the same track (or another track) and paste. The reverb in the chain has the same values. Copy it back out of the rack and paste it onto the main chain.++**Acceptance Scenarios**:++1. **Given** a reverb copied from the track chain, **When** the user pastes into a rack chain, **Then** the chain gains a reverb with the same values.+2. **Given** an effect copied from a rack chain, **When** the user selects a device on the track chain and pastes, **Then** the effect lands after it on the track chain with the same values.+3. **Given** an Arp copied from the track's MIDI effects, **When** pasted into an Instrument Rack chain or a MIDI Effect Rack chain, **Then** it lands among that chain's MIDI effects with its settings.+4. **Given** something a slot can't take (an instrument, a rack, a plug-in into a rack that can't host plug-ins, a MIDI effect into an audio-effect slot), **When** pasted, **Then** nothing changes and the status line names the reason.+5. **Given** a rack chain device copied while the track chain had keyboard focus elsewhere, **When** the user pastes, **Then** the paste goes to where the user last clicked: the selected rack chain device, or the selected track-chain device.++---++### Edge Cases++- **Paste with nothing selected anywhere on the track:** it lands at the end of the track's own chain, as today.+- **Paste into a full MIDI Effect Rack chain section, or into chain 17+ of an Instrument Rack** (MIDI effects run only in the first 16 chains): refused, with the reason.+- **Copy a device, then delete its chain or track before pasting:** the clipboard still holds the copy, which pastes normally.+- **Cut from a rack chain, then Undo:** the device returns to its place with its macro mappings.+- **A pasted device carries no macro mappings.** A mapping belongs to the rack it was made in.+- **Moving a device while it is being mapped (Map mode):** the move works, and its mapping highlights follow it.+- **A sidechained effect** (a compressor keyed from another track) copied into a rack chain: the chain has no sidechain, so it pastes without its key and the status line says so.+- **A Vocoder with a Track carrier** copied into a rack chain: it pastes and passes sound through, as specs/040's Vocoder note says.+- **A device inside a nested Drum Rack's pad** (specs/041): its pad window follows the same rules inside the Drum Rack card.+- **Keyboard focus:** the shortcuts act only while the device panel has focus. Typing in a rename box never copies or deletes a device.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: Users MUST be able to reorder a rack chain's audio effects by dragging a device's header within that chain's effect section. A drop indicator shows the landing spot, matching the track chain's drag.+- **FR-002**: Users MUST be able to reorder a rack chain's MIDI effects the same way, within the chain's MIDI section, for Instrument Rack and MIDI Effect Rack chains.+- **FR-003**: A drag MUST NOT drop a device into another section (audio effect ↔ MIDI effect ↔ instrument slot), and MUST NOT leave its rack: dropping onto the track chain or another rack offers no drop.+- **FR-003a**: Dropping a dragged device on another chain's row in the same rack's chain list MUST move it to the end of that chain's matching section, keeping its settings, state and macro mappings, and choose that chain. A row whose chain can't take it (FR-013) offers no drop.+- **FR-004**: A rack chain device's right-click menu MUST offer **Move left** and **Move right**, disabled at the section's ends.+- **FR-005**: Users MUST be able to select a rack chain device by clicking it, shown with the track chain's selection look in every theme. Selecting a rack chain device deselects any track-chain device, and the other way round.+- **FR-006**: A rack chain device's right-click menu MUST offer **Copy**, **Cut**, **Paste**, **Duplicate** and **Delete**, with the same names, icons, key hints and order as the track chain's menu.+- **FR-007**: ⌘C, ⌘X, ⌘V, ⌘D and Delete / Backspace MUST act on the selected rack chain device while the device panel has focus.+- **FR-007a**: The track's own device chain MUST gain **Duplicate** (menu item and ⌘D) for its effects and MIDI effects: a copy with the same settings lands right after the selected device and is selected, without touching the clipboard. A device that can't be copied (the track's instrument) offers it disabled.+- **FR-008**: Paste MUST land right after the selected device in its section, or at the end of the chosen chain's matching section when no device in that chain is selected.+- **FR-009**: The track chain and every rack chain on every track MUST share one device clipboard. A copy taken in either place pastes in the other.+- **FR-010**: A pasted device MUST keep its parameter values and its state (for example an Arp's steps or an EQ's bands), so it sounds the same as its source.+- **FR-011**: A pasted device MUST carry no macro mappings, and its source's mappings MUST stay unchanged.+- **FR-012**: Moving a device, within its chain or to another chain of the same rack, MUST keep every macro mapping on that device. Removing (cut or delete) a device removes its mappings, and undo brings them back.+- **FR-013**: A paste MUST be refused, with a status-line reason and nothing changed, when the target can't take the device. That covers:+ - an instrument;+ - an Audio Effect Rack or MIDI Effect Rack into a rack chain;+ - a plug-in into a rack that can't host plug-ins;+ - a MIDI effect into an audio-effect section, or the other way round;+ - a MIDI effect into an Instrument Rack chain past the first 16;+ - an audio effect into a MIDI Effect Rack.+- **FR-014**: Each move, cut, paste, duplicate and delete MUST be one undo step.+- **FR-015**: An effect with a sidechain key pasted into a rack chain MUST paste without the key (it then works on the chain's own signal), and the status line MUST say the sidechain was dropped. The source keeps its key.+- **FR-016**: Preferences → Shortcuts MUST list ⌘D (Duplicate device) and the rack chain behaviour if it adds anything else the list doesn't already say. The user docs (EN + RU) MUST describe moving and copying devices in rack chains.+- **FR-017**: The selection, drop indicator and menus MUST follow Studio design tokens and read correctly in Studio Dark, Studio Light, Ember Graphite and Ember Paper.++### Key Entities++- **Device clipboard**: the one copied device: its kind (audio effect, MIDI effect, plug-in effect), its parameter values and state, and where it was copied from (for the status line only). It is shared by the track chain and every rack chain.+- **Rack chain device selection**: which rack (track, rack address), chain, section (audio effect or MIDI effect) and index the user selected last. It is mutually exclusive with the track-chain selection.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: A user can reorder an effect inside a rack chain, or move it to another chain of the rack, in one drag under 3 seconds, without opening any window.+- **SC-002**: A device copied from a track chain and pasted into a rack chain renders the same audio as the original, bit for bit or within 1e-4 of each sample, on the same input.+- **SC-003**: Every move, cut, paste, duplicate and delete in a rack chain (and duplicate on the track chain) undoes in exactly one step, verified for each operation by the smoke test.+- **SC-004**: All the refusals in FR-013 leave the project unchanged and show a reason, verified by the smoke test or a headless UI check.+- **SC-005**: The selection and drop indicator are legible in all four themes (checked on rendered cards).++## Assumptions++- **⌘D belongs to the device panel while it has focus.** Elsewhere ⌘D keeps whatever it does there (for example in the piano roll or arrangement); the device panel only handles it while focused, as with ⌘C / ⌘X / ⌘V.+- **Drag stays inside its rack.** A drag reorders within a chain or moves to another chain of the same rack (onto its row). Moving to the track chain or another rack is Cut + Paste.+- **Instruments are not copied or pasted by this feature.** A chain's instrument is swapped from the Browser or the chain menu, and the track chain's own clipboard doesn't copy instruments either.+- **Plug-in effects** copy with their state where the target hosts plug-ins (the Audio Effect Rack and Instrument Rack chains, per specs/040).+- **The nested Drum Rack's pad chains** (specs/041) behave like other rack chains inside the Drum Rack card's pad editor, as far as that card already shows pad effects.+- **The clipboard is in-app only.** It lives for the app session and isn't the system clipboard, as today.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency+- [x] Audio-thread impact considered: moves and pastes are structural rack edits through the rack's immutable snapshots (AR-5), so nothing new happens on the audio thread+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); any new copy path is a C ABI function+- [x] Smoke-test impact assessed: copy/paste between track and rack chains and every undo step get smoke checks+- [x] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned, plus FEATURES.md and nota-docs (rack pages, EN + RU)+- [x] UI change → follows `DESIGN.md` (Studio design language); the selection uses the track chain's selection lookdiff --git a/specs/042-rack-device-clipboard/tasks.md b/specs/042-rack-device-clipboard/tasks.mdnew file mode 100644index 00000000..ceff16f7--- /dev/null+++ b/specs/042-rack-device-clipboard/tasks.md@@ -0,0 +1,204 @@+---++description: "Tasks for spec 042: move, copy and paste devices in rack chains"+---++# Tasks: Move, copy and paste devices in rack chains++**Input**: Design documents from `specs/042-rack-device-clipboard/`:+- [spec.md](spec.md), [plan.md](plan.md), [research.md](research.md), [data-model.md](data-model.md);+- the contracts [c-abi.md](contracts/c-abi.md) and [ui.md](contracts/ui.md);+- [quickstart.md](quickstart.md).++**Tests**: The smoke test is the project's gate (constitution IV), and the plan asks for a section `racks: chain device clipboard`. So each story gets smoke tasks, written before its implementation where the engine is involved.++**Organization**: by user story: US1 reorder and move between chains (P1), US2 the clipboard inside racks (P1), US3 across the track and rack chains (P2).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: can run in parallel (different files, no dependency on an unfinished task)+- **[Story]**: US1 / US2 / US3++---++## Phase 1: Setup++- [X] T001 Create `tests/Nota.SmokeTest/RackClipboardTests.cs`:+ - AGPL-3.0-only SPDX two-line header;+ - an `internal static class RackClipboardTests` with `Sections()` yielding `("racks: chain device clipboard", …)`, following `RackChainMidiTests.cs`;+ - register it in the `--racks` list in `tests/Nota.SmokeTest/Program.cs` (`RackSections()`).+- [X] T002 [P] Add `MenuKit.DuplicateKey` (`Cmd(Key.D)`) next to `CopyKey` / `CutKey` / `PasteKey` in `src/managed/Nota.App/MenuKit.cs`.++---++## Phase 2: Foundational (blocks US1 cross-chain, US2, US3)++**Purpose**: the engine primitives and the managed selection every story uses.++- [X] T003 In `src/native/nota.engine/src/devices/racks/RackCore.h/.cpp`, add `int32_t insertChainDeviceInstance(int32_t chain, std::shared_ptr<Device> dev, int32_t at, bool prepare = true)` and `int32_t insertChainMidiDeviceInstance(int32_t chain, std::shared_ptr<MidiDevice> dev, int32_t at)`.+ - Each is one `copyState` / `commit`, and returns the new index.+ - Insert at `at`; −1 or past the end means the end.+ - Shift that chain's mappings at or after `at` up by one: for audio, `deviceIndex >= at`; for MIDI, `isMidiTarget` with `midiTargetIndex >= at`, rewritten with `midiTarget(j+1)`.+ - The MIDI variant refuses kinds outside 0..5, like `addChainMidiDeviceInstance`.+- [X] T004 In `RackCore.h/.cpp`, add `int32_t moveChainDeviceToChain(int32_t chain, int32_t idx, int32_t toChain)` and `int32_t moveChainMidiDeviceToChain(…)`.+ - Each is one fork: erase from `chain`, append to `toChain`'s matching section.+ - The device's mappings are rewritten to `(toChain, newIndex)`; `chain`'s mappings after `idx` shift down.+ - Returns the new index, or −1 for a bad address or `toChain == chain`.+- [X] T005 In `src/native/nota.engine/src/engine/Engine.h` and `Engine_Rack.cpp`, add these on top of `rackCoreAt` / `rackForEdit` and the shared clipboard `clipDevice_` / `clipMidi_`:+ - `rackChainDeviceCopy` / `rackChainMidiCopy` set the clipboard to `cloneDevice` / `cloneMidiDevice` of the chain device, and clear the other slot.+ - `rackChainDevicePaste(t, di, c, at)` / `rackChainMidiPaste` return codes per data-model.md:+ - −1: nothing to paste or a bad address;+ - −2: the wrong family, or the rack has no such section — a MIDI Effect Rack has no audio effects; an Audio Effect Rack and a Drum Rack pad have no MIDI effects;+ - −3: a `RackDevice` or `MidiRack` clone;+ - −4: a hosted plug-in where `!chainsHostPlugin`-style hosting isn't allowed (match `IRackAccess.HostsPlugins` per rack kind);+ - −5: MIDI past `RackInstrument::kMaxMidiChains` for `di == -1`.+ - An audio clone gets `setSidechainSourceTrackId(-1)` before the insert.+ - `rackChainDeviceDuplicate` / `rackChainMidiDuplicate` insert a clone at idx+1 without touching the clipboard.+ - `rackChainDeviceMoveTo` / `rackChainMidiMoveTo` keep the 16-chain rule for MIDI in Instrument Racks.+ - After any insert into an Audio Effect Rack, call `recomputePdc()` as the existing chain-device add does.+- [X] T006 Add `bool deviceClipboardSidechain() const` in `src/native/nota.engine/src/engine/Engine_Devices.cpp` and `Engine.h`: true when `clipDevice_` has `sidechainSourceTrackId() >= 0`.+- [X] T007 Add the C ABI functions exactly as in contracts/c-abi.md, with comments:+ - declare them in `src/native/nota.engine/include/nota/nota_engine.h`;+ - implement them in `src/native/nota.engine/src/abi/nota_engine_rack.cpp` (`nota_rackdev_chain_*`) and `src/native/nota.engine/src/abi/nota_engine_device.cpp` (`nota_device_clipboard_sidechain`).+- [X] T008 [P] Add the P/Invoke declarations and wrappers listed in contracts/c-abi.md ("Managed mirror") in:+ - `src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs`;+ - `src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs`;+ - `src/managed/Nota.Application/Engine/IAudioEngine.cs`.+- [X] T009 Extend `IRackAccess` in `src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs`:+ - add default members `CopyChainDevice` / `CopyChainMidi`, `PasteChainDevice` / `PasteChainMidi` (`int at`), `DuplicateChainDevice` / `DuplicateChainMidi`, `MoveChainDeviceTo` / `MoveChainMidiTo` (default −1/false);+ - implement them for `InstrumentRackAccess` (di −1), `EffectRackAccess` (di) and `MidiRackAccess` (−1000 − mi, MIDI only);+ - the Rhythm / Drum accesses keep the defaults unless their pad strip already shows effects.+- [X] T010 Add the rack device selection to `src/managed/Nota.App/DeviceCards/DeviceCardContext.cs` and `src/managed/Nota.App/DeviceChainView.cs` / `DeviceChainView.Clipboard.cs`:+ - a `RackDeviceSel(int Rack, int Chain, bool Midi, int Index)` record;+ - `DeviceCardContext.RackSelection` (get) and `SelectRackDevice(RackDeviceSel?)`;+ - in `DeviceChainView`, setting a rack selection clears `_selDeviceIndex`, and selecting a track device clears the rack selection (FR-005);+ - `Show(track)` clears both.++**Checkpoint**: the engine and interop build, and `scripts/build.sh` passes with no behaviour change.++---++## Phase 3: User Story 1 — Reorder and move a chain's effects (P1) 🎯 MVP++**Goal**: drag by the header with a drop bar inside a section; drop on another chain's row to move there; **Move left** / **Move right** in the menu.++**Independent Test**: quickstart Q1 + Q2; the smoke checks below.++### Smoke for US1++- [X] T011 [US1] In `tests/Nota.SmokeTest/RackClipboardTests.cs`:+ - Audio Effect Rack chain 0 = EQ-3, Compressor, Reverb. Move Reverb to 0, check the order, check that Undo restores it. Map a macro to the Compressor's Threshold, move the Compressor, and check that the macro still drives it.+ - Move the Compressor to chain 1 with `RackDevChainDeviceMoveTo`. Check it is at the end of chain 1 with its params, that the macro still drives it, and that one Undo puts it back in chain 0.+ - The same for a MIDI effect between Instrument Rack chains. A move into chain 16 returns −5.++### Implementation for US1++- [X] T012 [US1] Replace `RcGripReorder` with header drag in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs`, modelled on `DeviceChainView.HookDeviceDrag`.+ - On header press, capture; after 5 px, dim the card to 0.55 and show a 3-px `NotaPalette.AccentBright` drop bar at the gap among the same section's cards in the lane strip (tag the cards with `(chain, slot, idx)`).+ - On release, `MoveChainDevice` / `MoveChainMidi` to the gap (`to = gap > from ? gap - 1 : gap`), keep the device selected, then `DeferRebuild()`.+ - The grip glyph starts the same drag.+ - The instrument card never drags.+- [X] T013 [US1] Add chain-row drop for a dragged lane device in `RackCard.Chains.cs`.+ - While a lane drag is active, the pointer over a chain row (hit-test the chain list rows) shows that row's drop outline (`NotaPalette.AccentBright` border, as for Browser drops) only if the chain can take it.+ - "Can take it" means a different chain; a MIDI effect needs `_rp.TakesMidiEffects`, and for the Instrument Rack chain index < 16.+ - On release over the row, call `MoveChainDeviceTo` / `MoveChainMidiTo`, set `Sel` to that chain, select the moved device, and `DeferRebuild()`.+- [X] T014 [US1] Add **Move left** / **Move right** (`GlyphKind.StepLeft` / `StepRight`, disabled at the ends) to `RcCardMenu` in `RackCard.Chains.cs` for effect and MIDI cards, calling `MoveChainDevice` / `MoveChainMidi`.++**Checkpoint**: US1 works on its own: quickstart Q1, Q2, and T011 passing.++---++## Phase 4: User Story 2 — Copy, cut, paste, duplicate and delete inside racks (P1)++**Goal**: rack chain devices can be selected, with Copy / Cut / Paste / Duplicate / Delete in the menu and on ⌘C / ⌘X / ⌘V / ⌘D / Delete.++**Independent Test**: quickstart Q3 + Q5; the smoke checks below.++### Smoke for US2++- [X] T015 [US2] In `RackClipboardTests.cs`:+ - Copy chain 0's Reverb with `RackDevChainDeviceCopy`, then `RackDevChainDevicePaste` into chain 1 at −1. Check the params are equal and the copy has no mappings.+ - Paste at 0 lands first and shifts chain 1's mapping indices. Check with a mapping on chain 1's first device.+ - Duplicate lands at idx+1 and leaves the clipboard kind unchanged.+ - Each step is one Undo.+ - Refusals: −2 for a MIDI effect into an Audio Effect Rack chain, −3 for a rack, −5 for MIDI into Instrument Rack chain 16.+ - A MIDI rack: copy and paste an Arp between its chains, comparing params and `MidiEffectGetState`-equivalent params.++### Implementation for US2++- [X] T016 [US2] In `RackCard.Chains.cs`:+ - A left-click on an effect or MIDI card header selects it through `_ctx.SelectRackDevice(new(rackIndex, c, slot == RcSlot.Midi, idx))`, keeping the rack index from `BuildRackCard`.+ - Draw the selected card with the track chain's selected look (`NotaPalette.Accent` border, 1.5 px, as `DeviceChainView` draws `_selDeviceIndex`).+ - Clear the rack selection when the chosen chain changes.+- [X] T017 [US2] Add the rack-device commands (Copy, Cut, Paste, Duplicate, Delete) in a new partial `src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs` (SPDX header).+ - Work on the selection through `IRackAccess`. Each runs inside `E.BeginUndoGroup()` / `EndUndoGroup()`, so Cut (copy + remove) is one step.+ - Paste goes after the selected index in the same chain and section, and goes to the MIDI section when the clipboard kind is 2.+ - Map refusal codes to the data-model.md status messages through `_ctx.Status`, and add " · sidechain dropped" when `E.DeviceClipboardSidechain` was true before the paste.+ - Select the pasted or duplicated device, then `DeferRebuild()`.+- [X] T018 [US2] Extend `RcCardMenu` in `RackCard.Chains.cs` with groups via `MenuKit.AddGroups`: Copy / Cut / Paste (enabled when `E.DeviceClipboardKind` fits) / Duplicate, then Delete as `MenuKit.Danger`, with `MenuKit` key hints. The existing **Remove** item becomes **Delete**.+- [X] T019 [US2] Add **Paste** to the chain row menu (`RcChainMenu`) and to the lane "+" target's add menus (`ShowAddDeviceMenu` / `RcAddMidiMenu`). It pastes at the end of the matching section and is disabled when the clipboard is empty or doesn't fit. Files: `RackCard.Chains.cs` and `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs`.+- [X] T020 [US2] Route keys in `src/managed/Nota.App/DeviceChainView.Clipboard.cs` `OnKeyDown`: when `_rackSel` is set, ⌘C / ⌘X / ⌘V / ⌘D / Delete / Backspace call the selected rack card's commands, through a delegate the card registers on the context (`DeviceCardContext.SetRackCommands`). Typing in a TextBox never reaches it (the existing focus guard).++**Checkpoint**: US1 and US2 both work: quickstart Q1–Q3 and Q5 inside racks.++---++## Phase 5: User Story 3 — Copy between the track chain and rack chains (P2)++**Goal**: one clipboard both ways, plus Duplicate on the track chain.++**Independent Test**: quickstart Q4 + Q6; the smoke checks below.++### Smoke for US3++- [X] T021 [US3] In `RackClipboardTests.cs`:+ - Track Delay → `TrackCopyDevice` (existing) → `RackDevChainDevicePaste` into an Instrument Rack chain: the params are equal, and the rendered output of a test tone through both is equal within 1e-4 (SC-002).+ - Rack chain EQ → `RackDevChainDeviceCopy` → `TrackPasteDevice`: it lands on the track with equal params.+ - Track Arp → MIDI Effect Rack chain and Instrument Rack chain.+ - A keyed Compressor: `DeviceClipboardSidechain` is true; the pasted chain copy has `DeviceSidechainSource` −1 (read through the chain); the track source keeps its key.+ - Track `TrackDuplicateDevice` / `TrackDuplicateMidiEffect` are one Undo each.++### Implementation for US3++- [X] T022 [US3] In `src/managed/Nota.App/DeviceChainView.Clipboard.cs`:+ - Paste is enabled when the engine clipboard has something (`_engine.DeviceClipboardKind != 0`), not only when `_clip` is set, so a rack copy pastes onto the track chain.+ - Keep `_clip`'s preset label only when it came from the track.+ - Selecting a track device clears the rack selection (T010).+- [X] T023 [US3] Add **Duplicate ⌘D** to the track device menu (between Paste and the rack group) and ⌘D to `OnKeyDown`, calling `DuplicateDevice` / `DuplicateMidiEffect`. Then `ExtrasMoved`-style bookkeeping for the A/B extras, select the copy, and `Rebuild()`. File: `DeviceChainView.Clipboard.cs`.+- [X] T024 [US3] When the rack selection is set and the clipboard came from the track (or the other way round), paste goes to where the user last clicked (FR / US3-5). Verify in `DeviceChainView.Clipboard.cs` that the routing from T020 covers it with no extra state.++**Checkpoint**: all three stories work: quickstart Q1–Q6.++---++## Phase 6: Polish & Cross-Cutting++- [X] T025 [P] Shortcuts (nota-shortcuts skill): in `src/managed/Nota.App/PreferencesWindow.cs` "Devices (after a click on a device)", add `⌘ D` "Duplicate the device". Mention that the copy / cut / paste rows work in rack chains too.+- [X] T026 [P] `CHANGELOG.md` `[Unreleased]`: under Added, moving, copying, cutting, pasting and duplicating devices in rack chains, plus copy between track and rack chains; under Added or Changed, Duplicate ⌘D on the track chain.+- [X] T027 [P] `FEATURES.md` (nota-features): extend the racks bullet and the device chain bullet.+- [X] T028 nota-docs (EN + RU) in the docs repo: the rack pages (instrument-rack, audio-effect-rack, midi-effect-rack) get a "Move and copy devices" paragraph; the device chain page mentions Duplicate ⌘D; regenerate the shortcuts page.+- [X] T029 Theme check: render the rack card with a selected device, a drag in progress (drop bar) and a row drop outline in all four themes with the headless harness; fix any token issue (quickstart Q7, FR-017).+- [X] T030 Run `scripts/build.sh` (native, managed, full smoke). Confirm the `racks: chain device clipboard` section prints and passes.+- [X] T031 Remove the obsolete `RcGripReorder` code path and the "drag the grip" wording in comments. Re-check the Nota Compliance list in spec.md.++---++## Dependencies & Execution Order++- **Setup (T001–T002)** → **Foundational (T003–T010)** → the stories.+- **US1** within a chain (T012, T014) needs only existing engine calls and could start right after Setup. The cross-chain move (T013) needs T004, T005, T007–T009.+- **US2** needs T003, T005–T010.+- **US3** needs US2's selection and commands (T016–T020), because paste routing is shared.+- **Polish** comes after the stories are done.++## Parallel Opportunities++- T002 runs alongside T001. T008 (interop) can run alongside T003–T007 once the ABI signatures are fixed (contracts/c-abi.md).+- Within US1: T014 alongside T012 (different methods, same file: run them one after the other if one agent edits).+- In Polish: T025, T026 and T027 together.++## Implementation Strategy++1. **MVP**: Setup, then T012 + T014 (reorder inside a chain with the existing engine calls). That fixes "can't move" first.+2. Foundational engine and interop, then T013 (move to another chain), then US2, then US3.+3. Polish: docs, shortcuts, themes, the full build.diff --git a/src/managed/Nota.App/DeviceCards/DeviceCardContext.cs b/src/managed/Nota.App/DeviceCards/DeviceCardContext.csindex 2a900c0c..b239f972 100644--- a/src/managed/Nota.App/DeviceCards/DeviceCardContext.cs+++ b/src/managed/Nota.App/DeviceCards/DeviceCardContext.cs@@ -29,7 +29,10 @@ internal sealed class DeviceCardContext(Action<int> requestRackPresetSave,Action hideDropGlow,IFactoryPresets? factory = null,- Action<string>? status = null)+ Action<string>? status = null,+ Func<RackDeviceSel?>? rackSelection = null,+ Action<RackDeviceSel?, RackDeviceCommands?>? selectRackDevice = null,+ Action? rackCopied = null){public IAudioEngine Engine => engine;public int TrackId => trackId;@@ -79,4 +82,22 @@ internal sealed class DeviceCardContext(/// <summary>Show a one-line message in the app's status bar (e.g. a plug-in window that/// failed to open). A no-op where the card isn't hosted by the chain view.</summary>public void Status(string message) => status?.Invoke(message);++ /// <summary>The selected rack chain device (specs/042), or null. The device panel keeps one+ /// selection: a rack chain device or a track-chain device, never both.</summary>+ public RackDeviceSel? RackSelection => rackSelection?.Invoke();++ /// <summary>Select a rack chain device (null clears it) and hand the panel the commands its+ /// keys run on it. A no-op where the card isn't hosted by the chain view.</summary>+ public void SelectRackDevice(RackDeviceSel? sel, RackDeviceCommands? commands) => selectRackDevice?.Invoke(sel, commands);++ /// <summary>A rack chain device went onto the shared device clipboard.</summary>+ public void RackCopied() => rackCopied?.Invoke();}++/// <summary>A device in a rack chain: the rack (its RackDev address), the chain, the section+/// (audio effects or MIDI effects) and the index in it (specs/042).</summary>+internal sealed record RackDeviceSel(int Rack, int Chain, bool Midi, int Index);++/// <summary>What the device panel's keys do to the selected rack chain device.</summary>+internal sealed record RackDeviceCommands(Action Copy, Action Cut, Action Paste, Action Duplicate, Action Delete);diff --git a/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs b/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.csindex dc8a5bfb..2e0bdaf4 100644--- a/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/IRackAccess.cs@@ -19,6 +19,12 @@ internal interface IRackAccessint AutomationDeviceIndex { get; }/// <summary>The rack in a MIDI Learn rack target (MidiTarget.DeviceIndex).</summary>int LearnDeviceIndex => AutomationDeviceIndex;+ /// <summary>The rack's address for the engine's RackDev* calls (−1 the track's Instrument or+ /// Drum Rack, ≥0 an Audio Effect Rack, −1000 − mi a MIDI Effect Rack), used by the chain+ /// device clipboard (specs/042); null for a strip that isn't a rack (Nota Rhythm's voices).</summary>+ int? RackAddress => null;+ /// <summary>Make the in-place edits that follow one undo step (fork the rack now).</summary>+ void Checkpoint() { }int ChainCount();int AddChain(int instKind);bool RemoveChain(int chain);@@ -139,6 +145,8 @@ internal interface IRackAccessinternal sealed class InstrumentRackAccess(IAudioEngine e, int t) : IRackAccess{+ public int? RackAddress => -1;+ public void Checkpoint() => e.RackDevCheckpoint(t, -1);public bool HasInstrumentChains => true;public int AutomationDeviceIndex => -1;public int ChainCount() => e.RackChainCount(t);@@ -226,6 +234,8 @@ internal sealed class InstrumentRackAccess(IAudioEngine e, int t) : IRackAccessinternal sealed class EffectRackAccess(IAudioEngine e, int t, int di) : IRackAccess{+ public int? RackAddress => di;+ public void Checkpoint() => e.RackDevCheckpoint(t, di);public bool HasInstrumentChains => false;public int AutomationDeviceIndex => di;public int ChainCount() => e.RackDevChainCount(t, di);@@ -366,6 +376,8 @@ internal sealed class RhythmVoiceAccess(IAudioEngine e, int t) : IRackAccess// are the MIDI effect's parameters 0..7 (automation, MIDI Learn).internal sealed class MidiRackAccess(IAudioEngine e, int t, int mi) : IRackAccess{+ public int? RackAddress => -1000 - mi; // the engine's MIDI Effect Rack address+ public void Checkpoint() => e.MidiRackCheckpoint(t, mi);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;diff --git a/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.cs b/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.csindex caf17643..e2ce7197 100644--- a/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.cs@@ -161,7 +161,8 @@ internal static class MacroPanelif (!sel) select(m); // the macro you turned is the one whose receivers show (after the drag)};tick.Add(() => { if (!knob.Dragging) { float v = Value(e, s, m); if (Math.Abs(v - knob.Value) > 1e-4) { knob.Value = v; value.Text = Pct(v); } } });- MidiLearn.Bind(knob, MidiTarget.PluginParam(track, di, pi), $"Macro {m + 1} · {s.MacroName(m)}");+ // A Drum Rack nested in a chain isn't a learn target of its own: map an outer macro to it.+ if (e is not NestedRackEngineProxy) MidiLearn.Bind(knob, MidiTarget.PluginParam(track, di, pi), $"Macro {m + 1} · {s.MacroName(m)}");// ⌥-click types, double-click resets; right-click stays the macro's own menu (the cell's).ValueEntry.Attach(knob, $"Macro {m + 1}", value, menu: false);diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.csindex f5ff0164..4c43448b 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs@@ -160,12 +160,14 @@ internal sealed partial class RackCardViewChild = new StackPanel { Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { top, bottom } },};if (!audible) row.AttachedToVisualTree += (_, _) => Inactive.Set(row, true, interactive: true);+ _rcRows.Add((row, c)); // a lane device dragged onto the row moves to this chainrow.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; }+ RcSelectChain(c); // ⌘V now pastes at the end of this chainif (Sel != c) { Sel = c; DeferRebuild(); }};DragDrop.SetAllowDrop(row, true);@@ -214,6 +216,7 @@ internal sealed partial class RackCardViewvar 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 (_ra.RackAddress is not null) { f.Items.Add(new Separator()); f.Items.Add(RcPasteItem(c)); }if (a.ChainCount() > 1){f.Items.Add(new Separator());@@ -233,7 +236,62 @@ internal sealed partial class RackCardView// ---- drops ------------------------------------------------------------------------private static bool RcIsDevice(BrowserItem it) => it.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument- or BrowserItemKind.BuiltinEffect or BrowserItemKind.PluginEffect or BrowserItemKind.BuiltinMidiEffect;+ or BrowserItemKind.BuiltinEffect or BrowserItemKind.PluginEffect or BrowserItemKind.BuiltinMidiEffect or BrowserItemKind.Preset;++ // ---- presets dropped from the Browser -----------------------------------------------+ // A factory preset, a preset file (user or Mosaic pack) or a drum kit: it brings the device+ // it is for, which lands like that device, and then the preset is applied to it in place.++ private enum RcPresetFor { None, Instrument, Effect, Midi, Plugin }+ private readonly record struct RcPreset(RcPresetFor For, int Kind, string FactoryId = "", string File = "", string KitId = "");++ private RcPreset RcResolvePreset(BrowserItem it)+ {+ if (it.Kind != BrowserItemKind.Preset) return default;+ string path = it.Path;+ if (path.StartsWith("kit:", StringComparison.Ordinal)) return new(RcPresetFor.Instrument, 4, KitId: path["kit:".Length..]);+ if (path.StartsWith("rhythmkit:", StringComparison.Ordinal)) return default; // a Nota Rhythm kit fills a Rhythm track+ if (path.StartsWith("factory:", StringComparison.Ordinal))+ {+ string id = path["factory:".Length..];+ if (_ctx.Factory is { } f)+ foreach (var fp in f.All())+ if (fp.Id == id)+ return new(fp.IsMidiEffect ? RcPresetFor.Midi : fp.IsInstrument ? RcPresetFor.Instrument : RcPresetFor.Effect, fp.BuiltinKind, FactoryId: id);+ return default;+ }+ if (App.Services?.GetService(typeof(IPresetStore)) is not IPresetStore store || store.Describe(path) is not { } d) return default;+ var to = d.Type switch+ {+ "builtin-instrument" => RcPresetFor.Instrument,+ "builtin-effect" => RcPresetFor.Effect,+ "builtin-midi-effect" => RcPresetFor.Midi,+ "plugin-instrument" or "plugin-effect" => RcPresetFor.Plugin,+ _ => RcPresetFor.None,+ };+ return new(to, d.BuiltinKind, File: path);+ }++ // Apply a resolved preset to the device it brought: the chain's instrument (device −1), or+ // the effect / MIDI effect at `device` in chain c.+ private void RcApplyPreset(RcPreset pr, int c, int device)+ {+ IAudioEngine target = pr.For switch+ {+ RcPresetFor.Instrument => pr.KitId.Length > 0 ? NestedRackEngineProxy.Create(E, c) : ChainInstrumentProxy(c),+ RcPresetFor.Effect => ChainDeviceProxy(_ra, c, device, pr.Kind),+ _ => RackChainMidiEngineProxy.Create(E, _ra, c),+ };+ string warn;+ if (pr.KitId.Length > 0)+ {+ warn = "";+ if (App.Services?.GetService(typeof(IDrumKits)) is IDrumKits kits) kits.LoadInto(target, T, pr.KitId, out warn);+ }+ else if (pr.FactoryId.Length > 0) warn = _ctx.Factory?.ApplyInPlace(target, pr.FactoryId, T, device) ?? "";+ else warn = (App.Services?.GetService(typeof(IPresetStore)) as IPresetStore)?.ApplyFileInPlace(target, pr.File, T, device) ?? "";+ if (warn.Length > 0) _ctx.Status(warn);+ }private static bool RcIsInstrument(BrowserItem it) => it.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument;@@ -241,8 +299,26 @@ internal sealed partial class RackCardViewprivate bool RcAccepts(BrowserItem it, out string why){why = "";+ if (it.Kind == BrowserItemKind.Preset)+ {+ var pr = RcResolvePreset(it);+ switch (pr.For)+ {+ case RcPresetFor.Plugin: why = "Plug-in presets can't go in a rack chain yet."; return false;+ case RcPresetFor.None: why = "This preset can't go in a rack."; return false;+ case RcPresetFor.Instrument when !_rp.TakesInstrument:+ why = _rp.Kind == RackKind.MidiEffect ? "A MIDI Effect Rack takes MIDI effects only." : "An Audio Effect Rack takes audio effects only."; return false;+ case RcPresetFor.Effect when !_rp.TakesAudioEffects: why = "A MIDI Effect Rack takes MIDI effects only."; return false;+ case RcPresetFor.Effect when pr.Kind == 5: why = "A rack can't go inside a rack."; return false;+ case RcPresetFor.Midi when !_rp.TakesMidiEffects: why = "An Audio Effect Rack takes audio effects only."; return false;+ case RcPresetFor.Midi when pr.Kind is < 0 or > 5: why = "A rack can't go inside a rack."; return false;+ }+ return true;+ }if (RcIsInstrument(it)){+ // A Drum Rack may sit in an Instrument Rack chain; an Instrument Rack can't (specs/041).+ if (_rp.TakesInstrument && it.Kind == BrowserItemKind.BuiltinInstrument && it.BuiltinKind == 3) { why = "An Instrument Rack can't go inside a rack — add its instruments as chains."; return false; }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;@@ -268,6 +344,38 @@ internal sealed partial class RackCardView{if (!RcAccepts(it, out var why)) { _ctx.Status(why); return; }var a = _ra;+ if (it.Kind == BrowserItemKind.Preset)+ {+ var pr = RcResolvePreset(it);+ E.BeginUndoGroup(); // the device and its preset are one step+ try+ {+ switch (pr.For)+ {+ case RcPresetFor.Instrument:+ // On a chain an instrument preset replaces the chain's instrument.+ if (!a.SetChainInstrument(c, pr.Kind)) { _ctx.Status($"Couldn't load {it.Name}."); return; }+ RcApplyPreset(pr, c, -1);+ break;+ case RcPresetFor.Effect:+ {+ int d = a.AddChainDevice(c, pr.Kind);+ if (d >= 0) RcApplyPreset(pr, c, d);+ break;+ }+ case RcPresetFor.Midi:+ {+ int j = a.AddChainMidi(c, pr.Kind);+ if (j >= 0) RcApplyPreset(pr, c, j);+ break;+ }+ }+ }+ finally { E.EndUndoGroup(); }+ Sel = c;+ DeferRebuild();+ return;+ }if (RcIsInstrument(it)){// On a chain an instrument replaces the chain's own; a plug-in starts a new layer.@@ -285,12 +393,33 @@ internal sealed partial class RackCardViewvar 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);+ if (it.Kind == BrowserItemKind.Preset && RcResolvePreset(it) is { For: RcPresetFor.Instrument } pr)+ {+ E.BeginUndoGroup(); // the chain and its preset are one step+ try+ {+ c = a.AddChain(pr.Kind);+ if (c >= 0 && a.ChainInstrumentKind(c) == pr.Kind) RcApplyPreset(pr, c, -1);+ else if (c >= 0) { a.RemoveChain(c); c = -1; _ctx.Status($"Couldn't load {it.Name}."); }+ }+ finally { E.EndUndoGroup(); }+ }+ else if (it.Kind == BrowserItemKind.BuiltinInstrument)+ {+ // An instrument the rack can't host would leave an empty chain: take it back.+ c = a.AddChain(it.BuiltinKind);+ if (c >= 0 && a.ChainInstrumentKind(c) != it.BuiltinKind) { a.RemoveChain(c); c = -1; _ctx.Status($"{it.Name} can't go in a rack chain."); }+ }else if (it.Kind == BrowserItemKind.PluginInstrument) c = a.AddPluginInstrumentChain(it.CatalogIndex);else{- c = a.AddChain(-1);- if (c >= 0) RcDropOnChain(c, it);+ E.BeginUndoGroup(); // the new chain and what lands on it are one step+ try+ {+ c = a.AddChain(-1);+ if (c >= 0) RcDropOnChain(c, it);+ }+ finally { E.EndUndoGroup(); }}if (c >= 0) Sel = c;DeferRebuild();@@ -331,7 +460,11 @@ internal sealed partial class RackCardView};}- var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };+ // The horizontal scrollbar floats over the bottom of the lane (16 px when it expands): keep the+ // cards above it so it never covers their Open row.+ var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Margin = new Thickness(0, 0, 0, 18) };+ _rcStrip = strip;+ RcCheckSelection();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; }@@ -373,6 +506,9 @@ internal sealed partial class RackCardViewvoid 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);+ Add("Nota Mosaic", 17);+ // A Drum Rack in a chain: racks nest one level (specs/041).+ f.Items.Add(new Separator()); Add("Nota Drum Rack", 4);f.ShowAt(anchor, showAtPointer: true);}@@ -396,7 +532,7 @@ internal sealed partial class RackCardView{if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;e.Handled = true;- if (slot == RcSlot.Midi) RcAddMidiMenu(box, c); else ShowAddDeviceMenu(_ra, c, box);+ if (slot == RcSlot.Midi) RcAddMidiMenu(box, c); else ShowAddDeviceMenu(_ra, c, box, withPaste: _ra.RackAddress is not null);};DragDrop.SetAllowDrop(box, true);DragDrop.AddDragOverHandler(box, (_, e) =>@@ -422,6 +558,7 @@ internal sealed partial class RackCardViewprivate void RcAddMidiMenu(Control anchor, int c){var f = new MenuFlyout();+ if (_ra.RackAddress is not null && E.DeviceClipboardKind() == 2) { f.Items.Add(RcPasteItem(c)); f.Items.Add(new Separator()); }foreach (var (name, kind) in RcMidiKinds){var mi = new MenuItem { Header = name };@@ -529,9 +666,18 @@ internal sealed partial class RackCardViewif (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;+ if (slot == RcSlot.Instrument) { grip.IsVisible = false; return card; }+ // Selected: the track chain's focus ring, outside the card with a small gap.+ var ring = new Border+ {+ BorderBrush = NotaPalette.Accent, BorderThickness = new Thickness(1.5), Margin = new Thickness(-2),+ CornerRadius = new CornerRadius(NotaRadius.PanelValue + 2), IsHitTestVisible = false, IsVisible = RcIsSelected(c, slot, idx),+ };+ var host = new Panel { Children = { card, ring }, Margin = new Thickness(2, 2, 2, 0) };+ RcHookCardDrag(head, host, c, slot, idx);+ RcHookCardDrag(grip, host, c, slot, idx);+ _rcCards.Add((ring, (RcCardTag)host.Tag!));+ return host;}private void RcCardMenu(Control anchor, int c, RcSlot slot, int idx, bool bypassed, Action open)@@ -556,38 +702,20 @@ internal sealed partial class RackCardViewDeferRebuild();};f.Items.Add(b);- f.Items.Add(new Separator());- f.Items.Add(MenuKit.Danger("Remove", GlyphKind.Trash, () =>+ if (_ra.RackAddress is not null) { f.Items.Add(new Separator()); RcAddDeviceMenuItems(f, c, slot, idx); }+ else{- if (slot == RcSlot.Midi) a.RemoveChainMidi(c, idx); else a.RemoveChainDevice(c, idx);- DeferRebuild();- }));+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Danger("Delete", GlyphKind.Trash, () =>+ {+ if (slot == RcSlot.Midi) a.RemoveChainMidi(c, idx); else a.RemoveChainDevice(c, idx);+ DeferRebuild();+ }, MenuKit.DeleteKey));+ }}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)diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.csnew file mode 100644index 00000000..60dbc54b--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs@@ -0,0 +1,328 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Rack card — moving, selecting, copying and pasting a chain's devices (specs/042), the way the+// track's device chain does it:+// - drag a card by its header along its section, with a drop bar at the gap, or onto another+// chain's row to move it there, mappings and all;+// - click a card to select it; Copy / Cut / Paste / Duplicate / Delete then run from its menu+// and from ⌘C / ⌘X / ⌘V / ⌘D / Delete, which the device panel routes here.+// The clipboard is the engine's one device clipboard, so a copy crosses between the track chain+// and any rack chain. The instrument card is neither dragged nor copied.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed partial class RackCardView+{+ // A lane card: which chain, section and index it shows (for the drag's gaps).+ private sealed record RcCardTag(int Chain, RcSlot Slot, int Index);++ private StackPanel? _rcStrip; // the chosen chain's lane+ private readonly List<(Border Row, int Chain)> _rcRows = new(); // the chain list rows, for drops++ // ---- selection --------------------------------------------------------------------++ private RackDeviceSel? RcSelOf(int c, RcSlot slot, int idx)+ => _ra.RackAddress is int rack && slot != RcSlot.Instrument ? new RackDeviceSel(rack, c, slot == RcSlot.Midi, idx) : null;++ private bool RcIsSelected(int c, RcSlot slot, int idx) => RcSelOf(c, slot, idx) is { } s && _ctx.RackSelection == s;++ // Index −1 is the chosen chain itself with no device selected: the keys' paste target stays+ // in the rack (⌘V lands at the end of that chain); copy, cut, duplicate and delete do nothing.+ private void RcSelect(RackDeviceSel? s)+ {+ if (s is null) { _ctx.SelectRackDevice(null, null); return; }+ if (s.Index < 0) { _ctx.SelectRackDevice(s, new RackDeviceCommands(() => { }, () => { }, () => RcPaste(s.Chain), () => { }, () => { })); return; }+ _ctx.SelectRackDevice(s, new RackDeviceCommands(() => RcCopy(s), () => RcCut(s), () => RcPaste(s.Chain, s), () => RcDuplicate(s), () => RcDelete(s)));+ }++ /// <summary>The user chose chain c of this rack: it becomes the paste target for the keys.</summary>+ private void RcSelectChain(int c)+ {+ if (_ra.RackAddress is int rack) RcSelect(new RackDeviceSel(rack, c, false, -1));+ }++ // A selection on this rack that no longer points at a device of the chosen chain falls back+ // to the chosen chain itself, so ⌘V keeps pasting into the rack.+ private void RcCheckSelection()+ {+ if (_ctx.RackSelection is not { } s || _ra.RackAddress != s.Rack) return;+ int n = s.Midi ? _ra.ChainMidiCount(s.Chain) : _ra.ChainDeviceCount(s.Chain);+ if (s.Chain != Sel || s.Index >= n) RcSelectChain(Sel);+ else RcSelect(s); // a rebuilt card hands the panel fresh commands+ }++ // ---- clipboard commands -----------------------------------------------------------++ private string RcDeviceName(RackDeviceSel s) => s.Midi ? _ra.ChainMidiName(s.Chain, s.Index) : _ra.ChainDeviceName(s.Chain, s.Index);++ private bool RcCopy(RackDeviceSel s)+ {+ bool ok = s.Midi ? E.RackDevChainMidiCopy(T, s.Rack, s.Chain, s.Index) : E.RackDevChainDeviceCopy(T, s.Rack, s.Chain, s.Index);+ if (ok) { _ctx.RackCopied(); _ctx.Status($"Copied {RcDeviceName(s)}"); }+ return ok;+ }++ private void RcCut(RackDeviceSel s)+ {+ E.BeginUndoGroup();+ try { if (RcCopy(s)) RcRemove(s); }+ finally { E.EndUndoGroup(); }+ RcSelect(null);+ DeferRebuild();+ }++ private void RcDelete(RackDeviceSel s)+ {+ RcRemove(s);+ RcSelect(null);+ DeferRebuild();+ }++ private void RcRemove(RackDeviceSel s)+ {+ if (s.Midi) _ra.RemoveChainMidi(s.Chain, s.Index); else _ra.RemoveChainDevice(s.Chain, s.Index);+ }++ private void RcDuplicate(RackDeviceSel s)+ {+ int at = s.Midi ? E.RackDevChainMidiDuplicate(T, s.Rack, s.Chain, s.Index) : E.RackDevChainDeviceDuplicate(T, s.Rack, s.Chain, s.Index);+ if (at < 0) { _ctx.Status("This device can't be duplicated"); return; }+ RcSelect(s with { Index = at });+ DeferRebuild();+ }++ /// <summary>True when the clipboard holds something chain c's sections can take.</summary>+ private bool RcCanPaste(int c)+ {+ int kind = E.DeviceClipboardKind();+ if (_ra.RackAddress is null || kind == 0) return false;+ if (kind == 2) return _rp.TakesMidiEffects && !(_rp.Kind == RackKind.Instrument && c >= RcMidiChainCount);+ return _rp.TakesAudioEffects;+ }+ private const int RcMidiChainCount = 16; // MIDI effects run in an Instrument Rack's first 16 chains++ // Paste into chain c: after `after` when it is in the clipboard's section of that chain,+ // else at the end of that section.+ private void RcPaste(int c, RackDeviceSel? after = null)+ {+ if (_ra.RackAddress is not int rack) return;+ int kind = E.DeviceClipboardKind();+ if (kind == 0) { _ctx.Status("Nothing to paste"); return; }+ bool midi = kind == 2;+ int at = after is { Index: >= 0 } s && s.Chain == c && s.Midi == midi ? s.Index + 1 : -1;+ bool keyed = !midi && E.DeviceClipboardSidechain();+ int r = midi ? E.RackDevChainMidiPaste(T, rack, c, at) : E.RackDevChainDevicePaste(T, rack, c, at);+ if (r < 0) { _ctx.Status(RcPasteRefusal(r, midi)); return; }+ var pasted = new RackDeviceSel(rack, c, midi, r);+ _ctx.Status($"Pasted {RcDeviceName(pasted)}{(keyed ? " · sidechain dropped" : "")}");+ if (Sel != c) Sel = c;+ RcSelect(pasted);+ DeferRebuild();+ }++ private string RcPasteRefusal(int code, bool midi) => code switch+ {+ -2 => _rp.Kind switch+ {+ RackKind.MidiEffect => "A MIDI Effect Rack takes MIDI effects only.",+ RackKind.AudioEffect => "An Audio Effect Rack takes audio effects only.",+ _ => midi ? "This rack's chains take no MIDI effects." : "This rack's chains take no audio effects.",+ },+ -3 => "A rack can't go inside a rack.",+ -5 => "MIDI effects run in the first 16 chains.",+ _ => "Nothing to paste here.",+ };++ // ---- undo for the card's value controls -------------------------------------------+ // A rack's faders, modes and switches write in place; these make each gesture one undo step:+ // a checkpoint forks the rack first (children and held notes carry over), and a drag's moves+ // land inside one undo group, so a zone drag that forks on every move undoes as one.++ private (Action Begin, Action End) RcEditGesture()+ {+ bool open = false;+ return (() => { if (open) return; open = true; E.BeginUndoGroup(); _ra.Checkpoint(); },+ () => { if (!open) return; open = false; E.EndUndoGroup(); });+ }++ private void RcStep(Action set)+ {+ E.BeginUndoGroup();+ try { _ra.Checkpoint(); set(); }+ finally { E.EndUndoGroup(); }+ }++ // ---- menus ----------------------------------------------------------------------++ // The card menu's move and clipboard groups (Open, on/off and the instrument items come first).+ private void RcAddDeviceMenuItems(MenuFlyout f, int c, RcSlot slot, int idx)+ {+ if (RcSelOf(c, slot, idx) is not { } s) return;+ int n = s.Midi ? _ra.ChainMidiCount(c) : _ra.ChainDeviceCount(c);+ MenuKit.AddGroups(f.Items,+ new Control[]+ {+ MenuKit.Item("Move left", GlyphKind.StepLeft, () => RcMove(s, idx - 1), null, idx > 0),+ MenuKit.Item("Move right", GlyphKind.StepRight, () => RcMove(s, idx + 1), null, idx < n - 1),+ },+ new Control[]+ {+ MenuKit.Item("Copy", GlyphKind.Copy, () => RcCopy(s), MenuKit.CopyKey),+ MenuKit.Item("Cut", GlyphKind.Cut, () => RcCut(s), MenuKit.CutKey),+ MenuKit.Item("Paste", GlyphKind.Paste, () => RcPaste(c, s), MenuKit.PasteKey, RcCanPaste(c)),+ MenuKit.Item("Duplicate", GlyphKind.Duplicate, () => RcDuplicate(s), MenuKit.DuplicateKey),+ },+ new Control[] { MenuKit.Danger("Delete", GlyphKind.Trash, () => RcDelete(s), MenuKit.DeleteKey) });+ }++ // A "Paste" item for a chain (its row menu, the lane's add menus): at the end of the section.+ private MenuItem RcPasteItem(int c) => MenuKit.Item("Paste", GlyphKind.Paste, () => RcPaste(c), MenuKit.PasteKey, RcCanPaste(c));++ private void RcMove(RackDeviceSel s, int to)+ {+ if (s.Midi) _ra.MoveChainMidi(s.Chain, s.Index, to); else _ra.MoveChainDevice(s.Chain, s.Index, to);+ RcSelect(s with { Index = to });+ DeferRebuild();+ }++ // ---- drag: along the section, or onto another chain's row ------------------------++ private RcCardTag? _rcDrag;+ private Control? _rcDragCard;+ private bool _rcDragging;+ private Point _rcDragStart;+ private int _rcDragRow = -1;+ private readonly Border _rcDropBar = new()+ {+ Width = 3, Background = NotaPalette.AccentBright, CornerRadius = NotaRadius.Clip,+ Margin = new Thickness(-2, 6, -2, 6), IsHitTestVisible = false,+ };++ private List<Control> RcSectionCards(RcCardTag t)+ => _rcStrip is null ? new() : _rcStrip.Children.OfType<Control>().Where(x => x.Tag is RcCardTag g && g.Chain == t.Chain && g.Slot == t.Slot).ToList();++ private int RcGapAt(RcCardTag t, double x)+ {+ var cards = RcSectionCards(t);+ int gap = 0;+ foreach (var card in cards) { if (x > card.Bounds.X + card.Bounds.Width * 0.5) gap++; else break; }+ return Math.Clamp(gap, 0, cards.Count);+ }++ private void RcShowDropBar(RcCardTag t, int gap)+ {+ if (_rcStrip is null) return;+ _rcStrip.Children.Remove(_rcDropBar);+ if (gap < 0) return;+ var cards = RcSectionCards(t);+ if (cards.Count == 0) return;+ int at = gap < cards.Count ? _rcStrip.Children.IndexOf(cards[gap]) : _rcStrip.Children.IndexOf(cards[^1]) + 1;+ _rcStrip.Children.Insert(Math.Clamp(at, 0, _rcStrip.Children.Count), _rcDropBar);+ }++ // The chain row under the pointer that can take the dragged device, or −1.+ private int RcRowAt(RcCardTag t, PointerEventArgs e)+ {+ foreach (var (row, chain) in _rcRows)+ {+ if (chain == t.Chain) continue;+ var p = e.GetPosition(row);+ if (p.X < 0 || p.Y < 0 || p.X > row.Bounds.Width || p.Y > row.Bounds.Height) continue;+ if (t.Slot == RcSlot.Midi && _rp.Kind == RackKind.Instrument && chain >= RcMidiChainCount) return -1;+ return chain;+ }+ return -1;+ }++ private void RcMarkRow(int chain)+ {+ if (chain == _rcDragRow) return;+ foreach (var (row, c) in _rcRows)+ {+ if (c == _rcDragRow) row.BorderBrush = c == Sel ? NotaPalette.Accent : NotaPalette.BorderDefault;+ if (c == chain) row.BorderBrush = NotaPalette.AccentBright;+ }+ _rcDragRow = chain;+ }++ /// <summary>Header press on a lane card: select it and arm a drag (the grip arms one too).</summary>+ private void RcHookCardDrag(Control handle, Control card, int c, RcSlot slot, int idx)+ {+ var tag = new RcCardTag(c, slot, idx);+ card.Tag = tag;+ handle.PointerPressed += (_, e) =>+ {+ var pt = e.GetCurrentPoint(handle).Properties;+ if (!pt.IsLeftButtonPressed || e.ClickCount > 1) return;+ RcSelect(RcSelOf(c, slot, idx));+ RcMarkSelected();+ _rcDrag = tag; _rcDragCard = card; _rcDragging = false; _rcDragRow = -1;+ _rcDragStart = e.GetPosition(_rcStrip);+ e.Pointer.Capture(handle);+ e.Handled = true;+ };+ handle.PointerMoved += (_, e) =>+ {+ if (_rcDrag is not { } t || _rcStrip is null) return;+ var p = e.GetPosition(_rcStrip);+ if (!_rcDragging && Math.Abs(p.X - _rcDragStart.X) < 5 && Math.Abs(p.Y - _rcDragStart.Y) < 5) return;+ _rcDragging = true;+ if (_rcDragCard != null) _rcDragCard.Opacity = 0.55;+ int row = RcRowAt(t, e);+ RcMarkRow(row);+ RcShowDropBar(t, row >= 0 ? -1 : RcGapAt(t, p.X));+ };+ handle.PointerReleased += (_, e) =>+ {+ if (_rcDrag is not { } t) return;+ bool dragged = _rcDragging;+ int row = dragged ? RcRowAt(t, e) : -1;+ int gap = dragged && row < 0 && _rcStrip != null ? RcGapAt(t, e.GetPosition(_rcStrip).X) : -1;+ RcEndDrag();+ e.Pointer.Capture(null);+ if (!dragged) return;+ if (row >= 0) { RcMoveToChain(t, row); return; }+ int n = RcSectionCards(t).Count;+ int to = Math.Clamp(gap > t.Index ? gap - 1 : gap, 0, Math.Max(0, n - 1));+ if (gap < 0 || to == t.Index) return;+ if (RcSelOf(t.Chain, t.Slot, t.Index) is { } s) RcMove(s, to);+ };+ handle.PointerCaptureLost += (_, _) => RcEndDrag();+ }++ private void RcEndDrag()+ {+ if (_rcDragCard != null) _rcDragCard.Opacity = 1.0;+ _rcStrip?.Children.Remove(_rcDropBar);+ RcMarkRow(-1);+ _rcDrag = null; _rcDragCard = null; _rcDragging = false;+ }++ private void RcMoveToChain(RcCardTag t, int to)+ {+ if (_ra.RackAddress is not int rack) return;+ bool midi = t.Slot == RcSlot.Midi;+ int r = midi ? E.RackDevChainMidiMoveTo(T, rack, t.Chain, t.Index, to) : E.RackDevChainDeviceMoveTo(T, rack, t.Chain, t.Index, to);+ if (r < 0) { _ctx.Status(r == -5 ? "MIDI effects run in the first 16 chains." : "The device can't go there."); return; }+ Sel = to;+ RcSelect(new RackDeviceSel(rack, to, midi, r));+ DeferRebuild();+ }++ // Show the lane's selection ring without a rebuild (a click selects, then may drag).+ private readonly List<(Border Ring, RcCardTag Tag)> _rcCards = new();++ private void RcMarkSelected()+ {+ foreach (var (ring, t) in _rcCards) ring.IsVisible = RcIsSelected(t.Chain, t.Slot, t.Index);+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.csindex 73e9f692..2b023b51 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.RightPanel.cs@@ -108,7 +108,9 @@ internal sealed partial class RackCardViewprivate 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);+ var g = RcEditGesture();+ var row = SliderRow(label, norm, set, text, out var sync, begin: g.Begin, end: g.End,+ reset: reset is null ? null : () => RcStep(reset), bipolar: bipolar, labelWidth: RcRowLabel, valueWidth: 36);_irTick.Add(sync);return row;}@@ -121,7 +123,7 @@ internal sealed partial class RackCardView{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);+ var seg = Segments(labels, Cur, i => { RcStep(() => a.SetRackMode(_rp.Modes[i].Id)); DeferRebuild(); }, out var segSync, fill: true, padX: 2, fontSize: NotaType.KnobLabel);_irTick.Add(segSync);var hint = new TextBlock{@@ -141,7 +143,7 @@ internal sealed partial class RackCardViewvar 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));+ toggles.Children.Add(Switch("Mono (last note)", () => a.RackMono(), () => RcStep(() => 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;@@ -156,19 +158,19 @@ internal sealed partial class RackCardView() => 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));+ toggles.Children.Add(Switch("Follow input level", () => a.SelectorFollows(), () => RcStep(() => { 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));+ toggles.Children.Add(Switch("Latency compensation", () => a.RackPdc(), () => RcStep(() => 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));+ toggles.Children.Add(Switch("Merge duplicate notes", () => a.RackMerge(), () => RcStep(() => 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));+ toggles.Children.Add(Switch("Pass through outside zones", () => a.RackThru(), () => RcStep(() => a.SetRackThru(!a.RackThru())), out var tSync));_irTick.Add(tSync);ToolTip.SetTip(toggles.Children[^1], "Notes no chain takes reach the instrument unchanged");break;diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.csindex 1d0fbfdd..7feabeb6 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Zones.cs@@ -57,8 +57,9 @@ internal sealed partial class RackCardViewToolTip.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;+ var barg = RcEditGesture();+ bar.Changed += (lo, _) => { barg.Begin(); a.SetSelector(lo / 127f); RcProbeUpdate(); };+ bar.Committed += () => { barg.End(); 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));@@ -85,8 +86,9 @@ internal sealed partial class RackCardView{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(); };+ var kbg = RcEditGesture();+ kb.Changed += (lo, hi) => { kbg.Begin(); a.ChainZone(cc, out _, out _, out int l, out int h); a.SetChainZone(cc, lo, hi, l, h); RcProbeUpdate(); };+ kb.Committed += () => { kbg.End(); 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);@@ -94,8 +96,9 @@ internal sealed partial class RackCardViewif (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(); };+ var vbg = RcEditGesture();+ vb.Changed += (lo, hi) => { vbg.Begin(); a.ChainZone(cc, out int k0, out int k1, out _, out _); a.SetChainZone(cc, k0, k1, lo, hi); RcProbeUpdate(); };+ vb.Committed += () => { vbg.End(); Sel = cc; DeferRebuild(); };ToolTip.SetTip(vb, "Drag the edges to set the velocity zone");Grid.SetColumn(vb, 2); grid.Children.Add(vb);}@@ -104,8 +107,9 @@ internal sealed partial class RackCardView// 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(); };+ var sbg = RcEditGesture();+ sb.Changed += (lo, hi) => { sbg.Begin(); a.SetSelectRange(cc, lo, hi); RcProbeUpdate(); };+ sb.Committed += () => { sbg.End(); 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;@@ -119,8 +123,9 @@ internal sealed partial class RackCardView{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(); };+ var sbg = RcEditGesture();+ sb.Changed += (lo, hi) => { sbg.Begin(); a.SetSelectRange(cc, lo, hi); RcProbeUpdate(); };+ sb.Committed += () => { sbg.End(); Sel = cc; DeferRebuild(); };ToolTip.SetTip(sb, "Drag the edges to set the select range");Grid.SetColumn(sb, 1); grid.Children.Add(sb);}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.csindex a302cac1..1b45a769 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.cs@@ -87,6 +87,8 @@ internal sealed partial class RackCardView_rs = RackCardState.For(T, a.Kind, rackIndex);_ownSel = true;_irTick.Clear();+ _rcRows.Clear();+ _rcCards.Clear();int n = a.ChainCount();Sel = n > 0 ? Math.Clamp(Sel, 0, n - 1) : 0;_rs.SelectedMacro = Math.Clamp(_rs.SelectedMacro, 0, 7);diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.csindex 9dac05c6..dd9ec996 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs@@ -176,8 +176,12 @@ internal sealed partial class RackCardView};g.Children.Add(DrumCap("BANK"));Grid.SetColumn(bank, 1); g.Children.Add(bank);- Grid.SetColumn(swing, 2); g.Children.Add(swing);- Grid.SetColumn(humanize, 3); g.Children.Add(humanize);+ // Kit timing shifts the whole track's notes, so a Drum Rack in a chain has none (specs/041).+ if (!Nested)+ {+ Grid.SetColumn(swing, 2); g.Children.Add(swing);+ Grid.SetColumn(humanize, 3); g.Children.Add(humanize);+ }Grid.SetColumn(fold, 4); g.Children.Add(fold);return new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 0, 0, 1), Child = g };}@@ -434,7 +438,7 @@ internal sealed partial class RackCardViewToolTip.SetTip(vol, "Pad volume · drag up or down, ⌥-click to type, double-click for 0\u2009dB");ValueEntry.Attach(vol, new ValueField("Pad volume", () => VolNorm(a.ChainGain(c)), n => VolText(NormVol(n)),n => { vol.Norm = n; a.SetChainGain(c, NormVol(n)); }, Default: VolNorm(1f)));- MidiLearn.Bind(vol, MidiTarget.RackChainGain(T, a.AutomationDeviceIndex, c), "Pad Volume");+ if (!Nested) MidiLearn.Bind(vol, MidiTarget.RackChainGain(T, a.AutomationDeviceIndex, c), "Pad Volume");Grid.SetColumn(vol, 2); g.Children.Add(vol);var pan = PanDrag(a, c);@@ -446,8 +450,8 @@ internal sealed partial class RackCardViewvar chk = MixBtn(choke > 0 ? choke.ToString() : "·", () => E.RackChainChoke(T, c) > 0, NotaPalette.Teal,() => { E.RackSetChainChoke(T, c, (E.RackChainChoke(T, c) + 1) % ChokeNames.Length); DeferRebuild(); }, choke: true);ToolTip.SetTip(mute, "Mute the pad"); ToolTip.SetTip(solo, "Solo the pad"); ToolTip.SetTip(chk, "Choke group: click for the next");- MidiLearn.Bind(mute, MidiTarget.RackChainMute(T, a.AutomationDeviceIndex, c), "Pad Mute");- MidiLearn.Bind(solo, MidiTarget.RackChainSolo(T, a.AutomationDeviceIndex, c), "Pad Solo");+ if (!Nested) MidiLearn.Bind(mute, MidiTarget.RackChainMute(T, a.AutomationDeviceIndex, c), "Pad Mute");+ if (!Nested) MidiLearn.Bind(solo, MidiTarget.RackChainSolo(T, a.AutomationDeviceIndex, c), "Pad Solo");var msc = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Children = { mute, solo, chk } };Grid.SetColumn(msc, 4); g.Children.Add(msc);return g;@@ -613,7 +617,7 @@ internal sealed partial class RackCardViewreturn r;}var volRow = Row("VOLUME", () => VolNorm(a.ChainGain(c)), v => a.SetChainGain(c, NormVol(v)), () => VolText(a.ChainGain(c)), () => a.SetChainGain(c, 1f));- MidiLearn.Bind(volRow, MidiTarget.RackChainGain(T, a.AutomationDeviceIndex, c), "Pad Volume");+ if (!Nested) MidiLearn.Bind(volRow, MidiTarget.RackChainGain(T, a.AutomationDeviceIndex, c), "Pad Volume");var panRow = Row("PAN", () => (a.ChainPan(c) + 1) / 2, v => a.SetChainPan(c, (float)(v * 2 - 1)), () => PanText(a.ChainPan(c)), () => a.SetChainPan(c, 0f), bipolar: true);var tuneRow = Row("TUNE", () => (E.RackChainTune(T, c) + 48) / 96.0, v => E.RackSetChainTune(T, c, (int)Math.Round(v * 96 - 48)),() => NotaNum.Unit(E.RackChainTune(T, c), "+0;−0;0", "st"), () => E.RackSetChainTune(T, c, 0), bipolar: true);@@ -664,7 +668,8 @@ internal sealed partial class RackCardViewmeta.Text = $"{pads.Count} pad{(pads.Count == 1 ? "" : "s")} · {groups} choke group{(groups == 1 ? "" : "s")}"+ (E.SampleRate > 0 ? " · " + NotaNum.Unit(E.SampleRate / 1000.0, "0.#", "kHz") : "");- string Timing() => $"swing {NotaNum.Pct(E.RackSwing(T))} · humanize {NotaNum.Pct(E.RackHumanize(T))}";+ // A Drum Rack in a chain has no kit timing (specs/041).+ string Timing() => Nested ? "" : $" · swing {NotaNum.Pct(E.RackSwing(T))} · humanize {NotaNum.Pct(E.RackHumanize(T))}";string PadWords(int c){string src = E.RackChainSamplerInfo(T, c, out var si) && si.SampleId != 0 && E.TryGetSampleInfo(si.SampleId, out var inf) && inf.SampleRate > 0@@ -684,13 +689,13 @@ internal sealed partial class RackCardView.Select(gr => $"choke group {gr.Key}: {string.Join(", ", gr.Select(c => PadName(a, c)))}").ToList();return $"{bank} · {inBank.Count} pad{(inBank.Count == 1 ? "" : "s")}" + (chokes.Count > 0 ? " · " + string.Join(" · ", chokes) : " · no choke groups");}- if (!IsPad(a, Sel)) return $"{bank} · no pad selected · {Timing()}";+ if (!IsPad(a, Sel)) return $"{bank} · no pad selected{Timing()}";if (_drumView == 2){int d = a.ChainDeviceCount(Sel);return $"{PadName(a, Sel)} {NoteName(a.ChainTriggerNote(Sel))} · {a.ChainInstrumentName(Sel)} → {d} effect{(d == 1 ? "" : "s")} → pad volume, pan";}- return $"{bank} · {PadWords(Sel)} · {Timing()}";+ return $"{bank} · {PadWords(Sel)}{Timing()}";}status.Text = Summary();_irTick.Add(() => status.Text = Summary());@@ -786,6 +791,8 @@ internal sealed partial class RackCardViewif (added >= 0) E.RackSetChainName(T, added, System.IO.Path.GetFileNameWithoutExtension(item.Path));break;case Nota.Presentation.BrowserItemKind.BuiltinInstrument:+ // Racks nest one level, and only in an Instrument Rack chain (specs/041).+ if (item.BuiltinKind is 3 or 4) { _ctx.Status("A rack can't go on a Drum Rack pad."); return; }if (existing >= 0) a.RemoveChain(existing);added = a.AddChain(item.BuiltinKind);if (added >= 0) a.SetChainTriggerNote(added, note);@@ -845,6 +852,7 @@ internal sealed partial class RackCardViewAdd("Nota Pentad", 14);Add("Nota Consort", 15);Add("Nota Keys", 16);+ Add("Nota Mosaic", 17);f.ShowAt(anchor, showAtPointer: true);}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex f978b686..e5f4b6d0 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -34,6 +34,9 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)private readonly DeviceCardContext _ctx = ctx;private IAudioEngine E => _ctx.Engine;+ // A Drum Rack nested in an Instrument Rack chain, shown through NestedRackEngineProxy+ // (specs/041): no kit timing and no MIDI Learn targets of its own.+ private bool Nested => E is NestedRackEngineProxy;private int T => _ctx.TrackId;// 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.@@ -179,9 +182,10 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)}// Add-device menu: built-in effects + a "Plug-ins" submenu of installed effect plug-ins.- private void ShowAddDeviceMenu(IRackAccess a, int sc, Control anchor)+ private void ShowAddDeviceMenu(IRackAccess a, int sc, Control anchor, bool withPaste = false){var f = new MenuFlyout();+ if (withPaste && E.DeviceClipboardKind() == 1) { f.Items.Add(RcPasteItem(sc)); f.Items.Add(new Separator()); }for (int k = 0; k < RackDeviceNames.Length; k++){int kk = RackDeviceKinds[k];@@ -220,6 +224,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)int ik = a.ChainInstrumentKind(sc);if (ik == -1) { try { E.RackOpenChainInstrumentEditor(T, sc); } catch { /* no-op */ } return; }if (ik == 1) { OpenChainSamplerWindow(a, anchor, sc, InstrumentPresets(a, sc, ik)); return; }+ if (ik == 4 && a is InstrumentRackAccess && !Nested) { OpenNestedDrumRackWindow(a, sc, anchor); return; }string nm = string.IsNullOrEmpty(a.ChainInstrumentName(sc)) ? "Instrument" : a.ChainInstrumentName(sc);var strategy = _irFactory.Resolve(ik, true);var proxy = ChainInstrumentProxy(sc);@@ -237,6 +242,60 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)private const double CardBodyH = DeviceCardKit.CardH - DeviceCardKit.HeaderH;+ // A Drum Rack in an Instrument Rack chain (specs/041): the Drum Rack card itself, built over+ // a NestedRackEngineProxy so every call it makes addresses the nested rack, in the device+ // window. The factory kits are the window's presets, as on a Drum Rack track.+ private void OpenNestedDrumRackWindow(IRackAccess a, int sc, Control anchor)+ {+ var proxy = NestedRackEngineProxy.Create(E, sc);+ var pp = (NestedRackEngineProxy)(object)proxy;+ // The window follows its Drum Rack by identity, not by chain index: removing or moving+ // chains in front of it shifts the index, and another chain's kit must never be driven.+ // A chain that's gone (or no longer holds this Drum Rack) leaves the window inert.+ long id = E.RackDevChainId(T, -1, sc);+ int Resolve()+ {+ if (pp.Chain >= 0 && pp.Chain < a.ChainCount() && E.RackDevChainId(T, -1, pp.Chain) == id) return pp.Chain;+ for (int c = 0; c < a.ChainCount(); c++)+ if (E.RackDevChainId(T, -1, c) == id) return pp.Chain = c;+ return pp.Chain = -1; // an address no rack has: every call from the old card goes nowhere+ }+ int sel = 0;+ var kits = App.Services?.GetService(typeof(IDrumKits)) as IDrumKits;+ DeviceWindow win = null!;+ win = new DeviceWindow("Nota Drum Rack", E.GetTrackName(T), "Drums", tickReg =>+ {+ // The chain may have moved or gone under the open window: follow it, or show nothing+ // rather than drive another rack.+ int at = Resolve();+ if (id == 0 || at < 0 || a.ChainInstrumentKind(at) != 4)+ return new DeviceWindowPage(new TextBlock { Text = "This Drum Rack is no longer in the rack.", Foreground = TextTertiary, Margin = new Thickness(12) }, 700, CardBodyH);+ tickReg(() => { if (Resolve() != at) win.Refill(); });+ var refreshers = new List<Action>();+ var ctx = new DeviceCardContext(proxy, T, tickReg, _ctx.NotifyChanged, (_, _, _, _) => { }, _ => { }, _ => { }, () => sel, v => sel = v,+ refreshers.Add, () => { foreach (var r in refreshers) r(); }, () => Avalonia.Threading.Dispatcher.UIThread.Post(() => { win.Refill(); _ctx.RequestRebuild(); }),+ _ => { }, () => { }, _ctx.Factory, _ctx.Status);+ tickReg(() => { foreach (var r in refreshers) r(); });+ var body = new RackCardView(ctx).BuildDrumRackBody(out _);+ DeviceWindowPresets? presets = null;+ if (kits is not null)+ {+ var all = kits.All().ToList();+ string cur = kits.Identify(proxy, T);+ presets = new DeviceWindowPresets(all.Select(k => k.Name).ToList(), all.FindIndex(k => k.Id == cur), i =>+ {+ kits.LoadInto(proxy, T, all[i].Id, out string warn);+ if (warn.Length > 0) _ctx.Status(warn);+ sel = 0;+ win.Refill();+ _ctx.RequestRebuild();+ });+ }+ return new DeviceWindowPage(new Border { Width = 700, Height = CardBodyH, ClipToBounds = true, Child = body }, 700, CardBodyH, presets);+ }, status: () => pp.Chain < 0 ? "Removed" : $"{ChainLocation(a, pp.Chain)} · {E.RackDevChainCount(T, RackMacroMapping.NestedRackBase - pp.Chain)} pads") { ContextTrackId = T };+ win.ShowFrom(anchor);+ }+// ---- device window: where the device lives + a live line for its status bar ----// "Drum Rack · pad C1 Kick", "Instrument Rack · chain 2 Lead", "Audio Effect Rack ·@@ -292,7 +351,9 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)var items = presets.Items;if (items.Count == 0) return null;int cur = -1;- if (_chainPresetIds.TryGetValue(presets.Key, out var curId))+ string? curId = presets.Current?.Invoke();+ if (string.IsNullOrEmpty(curId)) _chainPresetIds.TryGetValue(presets.Key, out curId);+ if (!string.IsNullOrEmpty(curId))for (int i = 0; i < items.Count; i++) if (items[i].Id == curId) { cur = i; break; }return new DeviceWindowPresets(items.Select(p => p.Name).ToList(), cur, i =>{@@ -307,7 +368,9 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)// A chain slot's preset list and how to apply one in place. Key names the slot (rack// addressing + chain + device + kind) so the header remembers the last preset applied.- private sealed record ChainPresets(string Key, IReadOnlyList<(string Id, string Name)> Items, Action<string> Apply);+ // Current, when given, names the preset the device holds now (Mosaic: by its program).+ private sealed record ChainPresets(string Key, IReadOnlyList<(string Id, string Name)> Items, Action<string> Apply,+ Func<string>? Current = null);private static readonly Dictionary<string, string> _chainPresetIds = new();private List<(string Id, string Name)> FactoryItems(int kind, bool instrument)@@ -318,18 +381,29 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)// Factory presets apply through the same proxies the bespoke editors use, so the// preset code sees the chain instrument / device as if it were the track's own.private ChainPresets InstrumentPresets(IRackAccess a, int sc, int ik)- => new($"{a.GetType().Name}:{T}:{a.AutomationDeviceIndex}:{sc}:i{ik}", FactoryItems(ik, instrument: true),+ => ik == Nota.Application.MosaicModel.Kind && _ctx.Factory is { } f ? MosaicChainPresets(a, sc, f) : new($"{a.GetType().Name}:{T}:{a.AutomationDeviceIndex}:{sc}:i{ik}", FactoryItems(ik, instrument: true),id => _ctx.Factory?.ApplyInPlace(ChainInstrumentProxy(sc), id, T, -1));private ChainPresets DevicePresets(IRackAccess a, int sc, int d, int kind)=> new($"{a.GetType().Name}:{T}:{a.AutomationDeviceIndex}:{sc}:{d}:d{kind}", FactoryItems(kind, instrument: false),id => _ctx.Factory?.ApplyInPlace(ChainDeviceProxy(a, sc, d, kind), id, T, d));- private IAudioEngine ChainInstrumentProxy(int sc)+ // A Mosaic in a chain lists what a Mosaic track does — the factory multisamples, the pack+ // presets, the program it holds and the card's Init — through the chain's proxy.+ private ChainPresets MosaicChainPresets(IRackAccess a, int sc, IFactoryPresets factory){- IAudioEngine proxy = System.Reflection.DispatchProxy.Create<IAudioEngine, RackChainEngineProxy>();- var pp = (RackChainEngineProxy)(object)proxy; pp.Inner = E; pp.Chain = sc;- return proxy;+ var proxy = ChainInstrumentProxy(sc);+ var cp = DeviceChainView.MosaicPresetsFor(factory, App.Services?.GetService(typeof(IMosaicPacks)) as IMosaicPacks, proxy, T);+ var items = new List<(string Id, string Name)>();+ if (cp.Init is not null) items.Add(("init:", "Init"));+ items.AddRange(cp.Items);+ return new($"{a.GetType().Name}:{T}:{a.AutomationDeviceIndex}:{sc}:i{Nota.Application.MosaicModel.Kind}", items, id =>+ {+ string w = id == "init:" ? cp.Init!() : cp.Apply(id);+ if (w.Length > 0) _ctx.Status(w);+ }, cp.Current);}++ private IAudioEngine ChainInstrumentProxy(int sc) => RackChainEngineProxy.Create(E, sc);private IAudioEngine ChainDeviceProxy(IRackAccess a, int sc, int d, int kind){IAudioEngine proxy = System.Reflection.DispatchProxy.Create<IAudioEngine, RackChainDeviceEngineProxy>();@@ -413,6 +487,8 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)void Add(string h, int k) { var mi = new MenuItem { Header = h }; mi.Click += (_, _) => { int c = a.AddChain(k); if (c >= 0) Sel = c; _ctx.RequestRebuild(); }; f.Items.Add(mi); }Add("Nota Volt", 6); Add("Nota Sampler", 1); 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);+ Add("Nota Mosaic", 17);+ f.Items.Add(new Separator()); Add("Nota Drum Rack", 4); // racks nest one level (specs/041)f.ShowAt(anchor, showAtPointer: true);}@@ -509,7 +585,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)// A macro rides the rack's plugin-param surface, so it's MIDI-learnable like any// plugin param — this is the in-model path for driving nested chain params over MIDI// (map a param to a macro, then learn the macro).- MidiLearn.Bind(bar, MidiTarget.PluginParam(T, di, m), "Macro " + (m + 1));+ if (!Nested) MidiLearn.Bind(bar, MidiTarget.PluginParam(T, di, m), "Macro " + (m + 1));bar.Format = x => Pct((float)x);ValueEntry.Attach(bar, "Macro " + (m + 1), val);if (di < 0) _ctx.AddInstFader(m, bar, val); // live-refresh follows the instrument-rack macros@@ -745,33 +821,50 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)}}-// 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); everything-// else delegates to the real engine.-internal class RackChainEngineProxy : System.Reflection.DispatchProxy+// A rack chain's MIDI effect seen as a track MIDI effect, so a MIDI-effect preset applies to it+// unchanged: its parameter calls (track, index, p) go to (chain, index) through the rack access.+// Any other MIDI-effect call answers a default and never reaches the track's own MIDI effect at+// that index; a chain MIDI effect has no state blob here, so a preset brings its parameters.+internal class RackChainMidiEngineProxy : System.Reflection.DispatchProxy{public Nota.Application.IAudioEngine Inner = null!;+ public IRackAccess Access = null!;public int Chain;++ public static Nota.Application.IAudioEngine Create(Nota.Application.IAudioEngine inner, IRackAccess access, int chain)+ {+ var proxy = Create<Nota.Application.IAudioEngine, RackChainMidiEngineProxy>();+ var pp = (RackChainMidiEngineProxy)(object)proxy; pp.Inner = inner; pp.Access = access; pp.Chain = chain;+ return proxy;+ }+protected override object? Invoke(System.Reflection.MethodInfo? m, object?[]? args){- switch (m?.Name)+ string name = m?.Name ?? "";+ int Idx() => (int)args![1]!;+ int P() => (int)args![2]!;+ switch (name){- case nameof(Nota.Application.IAudioEngine.PluginParamCount): return Inner.RackChainInstrumentParamCount((int)args![0]!, Chain);- case nameof(Nota.Application.IAudioEngine.PluginParamId): return Inner.RackChainInstrumentParamId((int)args![0]!, Chain, (int)args![2]!);- case nameof(Nota.Application.IAudioEngine.PluginParamGet): return Inner.RackChainInstrumentParamGet((int)args![0]!, Chain, (int)args![2]!);- case nameof(Nota.Application.IAudioEngine.PluginParamSet): Inner.RackChainInstrumentParamSet((int)args![0]!, Chain, (int)args![2]!, (float)args![3]!); return null;- case nameof(Nota.Application.IAudioEngine.InstrumentParamDefault): return Inner.RackChainInstrumentParamDefault((int)args![0]!, Chain, (int)args![1]!);- case nameof(Nota.Application.IAudioEngine.TrackInstrumentKind): return Inner.RackChainInstrumentKind((int)args![0]!, Chain);- case nameof(Nota.Application.IAudioEngine.BeginAutomationWrite):- case nameof(Nota.Application.IAudioEngine.EndAutomationWrite): return null;- // Live telemetry comes from the chain instrument, not the track's rack instrument.- case nameof(Nota.Application.IAudioEngine.InstrumentScope): return Inner.RackChainInstrumentScope((int)args![0]!, Chain, (float[])args![1]!);- case nameof(Nota.Application.IAudioEngine.InstrumentVoiceCount): return Inner.RackChainInstrumentVoiceCount((int)args![0]!, Chain);- case nameof(Nota.Application.IAudioEngine.InstrumentHeldNotes): return Inner.RackChainInstrumentHeldNotes((int)args![0]!, Chain, (int[])args![1]!);- case nameof(Nota.Application.IAudioEngine.InstrumentAction): Inner.RackChainInstrumentAction((int)args![0]!, Chain, (int)args![1]!, (int)args![2]!, (float)args![3]!); return null;- default: return m!.Invoke(Inner, args);+ case nameof(Nota.Application.IAudioEngine.MidiEffectKind): return Access.ChainMidiKind(Chain, Idx());+ case nameof(Nota.Application.IAudioEngine.MidiEffectName): return Access.ChainMidiName(Chain, Idx());+ case nameof(Nota.Application.IAudioEngine.MidiEffectParamCount): return Access.ChainMidiParamCount(Chain, Idx());+ case nameof(Nota.Application.IAudioEngine.MidiEffectParamName): return Access.ChainMidiParamName(Chain, Idx(), P());+ case nameof(Nota.Application.IAudioEngine.MidiEffectParamMin): return Access.ChainMidiParamMin(Chain, Idx(), P());+ case nameof(Nota.Application.IAudioEngine.MidiEffectParamMax): return Access.ChainMidiParamMax(Chain, Idx(), P());+ case nameof(Nota.Application.IAudioEngine.MidiEffectGetParam): return Access.ChainMidiParamGet(Chain, Idx(), P());+ // Presets land on a freshly added effect, whose values are its defaults.+ case nameof(Nota.Application.IAudioEngine.MidiEffectParamDefault): return Access.ChainMidiParamGet(Chain, Idx(), P());+ case nameof(Nota.Application.IAudioEngine.MidiEffectSetParam): Access.ChainMidiParamSet(Chain, Idx(), P(), (float)args![3]!); return null;+ }+ if (name.Contains("MidiEffect", StringComparison.Ordinal))+ {+ var rt = m!.ReturnType;+ if (rt == typeof(void)) return null;+ if (rt == typeof(byte[])) return Array.Empty<byte>();+ if (rt == typeof(string)) return "";+ return rt.IsValueType ? Activator.CreateInstance(rt) : null;}+ return m!.Invoke(Inner, args);}}diff --git a/src/managed/Nota.App/DeviceChainView.Clipboard.cs b/src/managed/Nota.App/DeviceChainView.Clipboard.csindex a0b59aa6..1254c178 100644--- a/src/managed/Nota.App/DeviceChainView.Clipboard.cs+++ b/src/managed/Nota.App/DeviceChainView.Clipboard.cs@@ -33,11 +33,33 @@ public sealed partial class DeviceChainView{if (!SelectableKind(kind)) return;Focus(); // route Ctrl+C/X/V + Delete here- if (_selChainKind == kind && _selDeviceIndex == index) return;+ bool hadRack = _rackSel != null;+ _rackSel = null; _rackCmds = null; // one selection on the panel (specs/042)+ if (_selChainKind == kind && _selDeviceIndex == index && !hadRack) return;_selChainKind = kind; _selDeviceIndex = index;Rebuild();}+ // A device in a rack chain (specs/042): the rack card selects it and hands over what the+ // keys do to it; the track chain's selection clears.+ private RackDeviceSel? _rackSel;+ private RackDeviceCommands? _rackCmds;++ private void SelectRackDevice(RackDeviceSel? sel, RackDeviceCommands? cmds)+ {+ if (sel != null) Focus();+ _rackSel = sel;+ _rackCmds = sel != null ? cmds : null;+ if (sel != null && _selDeviceIndex >= 0)+ {+ _selDeviceIndex = -1;+ foreach (var r in _selRings) r.IsVisible = false; // no rebuild: the rack card may be mid-drag+ }+ }++ // The track cards' selection rings, refilled on every rebuild.+ private readonly System.Collections.Generic.List<Border> _selRings = new();+private bool IsSelected(ChainKind kind, int index)=> HasDeviceSelection && _selChainKind == kind && _selDeviceIndex == index;@@ -52,6 +74,12 @@ public sealed partial class DeviceChainViewpublic string Preset = "", PresetId = ""; // the source card's preset label follows the paste}private DeviceClip? _clip;+ // The engine's clipboard is shared with the rack chains (specs/042): a rack copy replaces it,+ // so the preset label in _clip rides along only while the clipboard still holds the track's copy.+ private bool _clipFromTrack;+ internal void RackCopied() => _clipFromTrack = false;+ private ChainKind ClipKind => _engine.DeviceClipboardKind() switch { 1 => ChainKind.Effect, 2 => ChainKind.Midi, _ => ChainKind.Instrument };+ private bool CanPaste => _trackId > 0 && _engine.DeviceClipboardKind() != 0;private void CopySelectedDevice(){@@ -64,6 +92,7 @@ public sealed partial class DeviceChainView_ => false,};if (!ok) return;+ _clipFromTrack = true;var ex = Extra(_selChainKind, di);_clip = new DeviceClip { Kind = _selChainKind, Preset = ex.Preset, PresetId = ex.PresetId };}@@ -82,10 +111,26 @@ public sealed partial class DeviceChainViewprivate void CutSelectedDevice() { CopySelectedDevice(); DeleteSelectedDevice(); }+ // ⌘D: a copy right after the selected device, the clipboard untouched (specs/042).+ private void DuplicateSelectedDevice()+ {+ if (!HasDeviceSelection) return;+ int di = _selDeviceIndex; var k = _selChainKind;+ int end = k == ChainKind.Midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);+ int newIdx = k == ChainKind.Midi ? _engine.DuplicateMidiEffect(_trackId, di) : _engine.DuplicateDevice(_trackId, di);+ if (newIdx < 0) { StatusMessage?.Invoke("This device can't be duplicated"); return; }+ var src = Extra(k, di);+ if (newIdx < end) ExtrasMoved(k, end, newIdx);+ TrackExtras().Remove(ExtraKey(k, newIdx));+ var copy = Extra(k, newIdx); copy.Preset = src.Preset; copy.PresetId = src.PresetId;+ _selDeviceIndex = newIdx;+ Rebuild(); Changed?.Invoke();+ }+private void PasteDevice(){- if (_clip is null || _trackId <= 0) return;- var c = _clip;+ if (!CanPaste) return;+ var c = _clipFromTrack && _clip is { } own && own.Kind == ClipKind ? own : new DeviceClip { Kind = ClipKind };if (c.Kind != ChainKind.Effect && c.Kind != ChainKind.Midi) return;// Drop it right after the selected device of the same domain, else at the end.int at = _selChainKind == c.Kind && _selDeviceIndex >= 0 ? _selDeviceIndex + 1 : -1;@@ -161,9 +206,17 @@ public sealed partial class DeviceChainViewif ((e.KeyModifiers & KeyModifiers.Shift) != 0) UngroupSelectedDevice(); else GroupSelectedDevice();e.Handled = true; return;}+ // A selected rack chain device takes the clipboard keys (specs/042).+ if (_rackSel != null && _rackCmds is { } rc)+ {+ Action? run = mod ? e.Key switch { Key.C => rc.Copy, Key.X => rc.Cut, Key.V => rc.Paste, Key.D => rc.Duplicate, _ => null }+ : e.Key is Key.Delete or Key.Back ? rc.Delete : null;+ if (run != null) { run(); e.Handled = true; return; }+ }if (mod && e.Key == Key.C && HasDeviceSelection) { CopySelectedDevice(); e.Handled = true; return; }if (mod && e.Key == Key.X && HasDeviceSelection) { CutSelectedDevice(); e.Handled = true; return; }- if (mod && e.Key == Key.V && _clip != null) { PasteDevice(); e.Handled = true; return; }+ if (mod && e.Key == Key.V && CanPaste) { PasteDevice(); e.Handled = true; return; }+ if (mod && e.Key == Key.D && HasDeviceSelection) { DuplicateSelectedDevice(); e.Handled = true; return; }if (!mod && (e.Key == Key.Delete || e.Key == Key.Back) && HasDeviceSelection) { DeleteSelectedDevice(); e.Handled = true; return; }base.OnKeyDown(e);}@@ -197,7 +250,8 @@ public sealed partial class DeviceChainView{MenuKit.Item("Copy", GlyphKind.Copy, CopySelectedDevice, MenuKit.CopyKey, selectable),MenuKit.Item("Cut", GlyphKind.Cut, CutSelectedDevice, MenuKit.CutKey, selectable),- MenuKit.Item("Paste", GlyphKind.Paste, PasteDevice, MenuKit.PasteKey, _clip != null),+ MenuKit.Item("Paste", GlyphKind.Paste, PasteDevice, MenuKit.PasteKey, CanPaste),+ MenuKit.Item("Duplicate", GlyphKind.Duplicate, DuplicateSelectedDevice, MenuKit.DuplicateKey, selectable),},kind == ChainKind.Effect? new Control[]diff --git a/src/managed/Nota.App/DeviceChainView.Fold.cs b/src/managed/Nota.App/DeviceChainView.Fold.csindex 0ba14899..aac70c71 100644--- a/src/managed/Nota.App/DeviceChainView.Fold.cs+++ b/src/managed/Nota.App/DeviceChainView.Fold.cs@@ -88,6 +88,7 @@ public sealed partial class DeviceChainViewCornerRadius = new CornerRadius(NotaRadius.BodyValue + RingGap), Margin = new Thickness(-RingGap),IsHitTestVisible = false, IsVisible = IsSelected(k, di),};+ _selRings.Add(selRing);var card = new Border { Width = FoldedW, Height = CardH, Child = new Panel { Children = { strip, selRing } } };void Menu(MenuFlyout flyout)diff --git a/src/managed/Nota.App/DeviceChainView.Instruments.cs b/src/managed/Nota.App/DeviceChainView.Instruments.csindex 839b8ef4..90aa25b2 100644--- a/src/managed/Nota.App/DeviceChainView.Instruments.cs+++ b/src/managed/Nota.App/DeviceChainView.Instruments.cs@@ -7,6 +7,7 @@using System;using Avalonia.Controls;+using Nota.Application;using static Nota.App.DeviceCardKit;namespace Nota.App;@@ -56,25 +57,27 @@ public sealed partial class DeviceChainView});}+ private CardPresets MosaicPresets() => MosaicPresetsFor(_factory, _mosaic, _engine, _trackId);+// Nota Mosaic's presets: the factory multisamples, then every pack preset ("Pack / Name").// The one the instrument holds is named by its program (a pack preset keeps its name).- private CardPresets MosaicPresets()+ // `engine` may be a rack chain's proxy, so a Mosaic in a chain lists the same presets.+ internal static CardPresets MosaicPresetsFor(IFactoryPresets factory, IMosaicPacks? packs, IAudioEngine engine, int t){- int t = _trackId;var items = new System.Collections.Generic.List<(string, string)>();- foreach (var p in _factory.All())+ foreach (var p in factory.All())// The factory "Init" keeps the loaded program, so here it would read as the program's// name again: the card's own Init (every default, no program) takes its place (#165).if (p.IsInstrument && p.BuiltinKind == Nota.Application.MosaicModel.Kind && p.DisplayName != "Init") items.Add(("factory:" + p.Id, p.DisplayName));- if (_mosaic is not null)- foreach (var p in _mosaic.Presets()) items.Add((p.Path, $"{p.Folder} / {p.Name}"));+ if (packs is not null)+ foreach (var p in packs.Presets()) items.Add((p.Path, $"{p.Folder} / {p.Name}"));// A program that is no preset (an SFZ, dropped files) still names itself in the picker.- string held = Nota.Application.Mosaic.MosaicProgram.Parse(_engine.MosaicProgram(t)).Name;+ string held = Nota.Application.Mosaic.MosaicProgram.Parse(engine.MosaicProgram(t)).Name;if (held.Length > 0 && !items.Exists(i => i.Item2 == held || i.Item2.EndsWith(" / " + held, StringComparison.Ordinal)))items.Insert(0, ("program:", held));string Current(){- string name = Nota.Application.Mosaic.MosaicProgram.Parse(_engine.MosaicProgram(t)).Name;+ string name = Nota.Application.Mosaic.MosaicProgram.Parse(engine.MosaicProgram(t)).Name;if (name.Length == 0) return "";foreach (var (id, n) in items) if (n == name || n.EndsWith(" / " + name, StringComparison.Ordinal)) return id;return "";@@ -82,9 +85,9 @@ public sealed partial class DeviceChainViewreturn new CardPresets(items, Current, id =>{if (id == "program:") return "";- if (id.StartsWith("factory:", StringComparison.Ordinal)) return _factory.ApplyInPlace(_engine, id["factory:".Length..], t, -1);- return _mosaic?.ApplyInPlace(_engine, id, t) ?? "Presets are unavailable.";- }, Init: () => _factory.ResetInPlace(_engine, t, -1, false)); // every param to default, no program (#165)+ if (id.StartsWith("factory:", StringComparison.Ordinal)) return factory.ApplyInPlace(engine, id["factory:".Length..], t, -1);+ return packs?.ApplyInPlace(engine, id, t) ?? "Presets are unavailable.";+ }, Init: () => factory.ResetInPlace(engine, t, -1, false)); // every param to default, no program (#165)}// The Instrument Rack in the shared shell; the badge counts its chains.diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.csindex dab42e1b..23d21fdb 100644--- a/src/managed/Nota.App/DeviceChainView.Shell.cs+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs@@ -374,6 +374,7 @@ public sealed partial class DeviceChainViewCornerRadius = new CornerRadius(NotaRadius.BodyValue + RingGap), Margin = new Thickness(-RingGap),IsHitTestVisible = false, IsVisible = sel,};+ if (!s.Utility) _selRings.Add(selRing);var shell = new Border{Background = ShellBg, BorderBrush = BorderDef,diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.csindex ab390221..0e80eb54 100644--- a/src/managed/Nota.App/DeviceChainView.cs+++ b/src/managed/Nota.App/DeviceChainView.cs@@ -118,7 +118,7 @@ public sealed partial class DeviceChainView : UserControlHookBrowserDrop();}- public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; _selDeviceIndex = -1; Rebuild(); }+ public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; _selDeviceIndex = -1; _rackSel = null; _rackCmds = null; Rebuild(); }/// <summary>Forgets every card's remembered preset label + A/B slots (a project was/// opened / created, so track ids no longer mean the same tracks).</summary>@@ -179,6 +179,7 @@ public sealed partial class DeviceChainView : UserControlprivate void RebuildRow(){_row.Children.Clear();+ _selRings.Clear();_instrumentCard = null;_instLiveViz = null; _instFaders.Clear(); // rebuilt only when a built-in instrument card is shown_deviceLiveRefreshers.Clear(); // compressor GR meter/curve@@ -250,7 +251,10 @@ public sealed partial class DeviceChainView : UserControlc => RackPresetSaveRequested?.Invoke(c),ClearDropHints,_factory,- s => StatusMessage?.Invoke(s));+ s => StatusMessage?.Invoke(s),+ () => _rackSel,+ SelectRackDevice,+ RackCopied);// ---- instrument / sends / add ----------------------------------------diff --git a/src/managed/Nota.App/MenuKit.cs b/src/managed/Nota.App/MenuKit.csindex f8bc79ac..334b57b3 100644--- a/src/managed/Nota.App/MenuKit.cs+++ b/src/managed/Nota.App/MenuKit.cs@@ -40,8 +40,8 @@ internal static partial class MenuKitpublic static readonly KeyGesture CopyKey = Cmd(Key.C);public static readonly KeyGesture CutKey = Cmd(Key.X);public static readonly KeyGesture PasteKey = Cmd(Key.V);- public static readonly KeyGesture PasteBouncedKey = Cmd(Key.V, shift: true);public static readonly KeyGesture DuplicateKey = Cmd(Key.D);+ public static readonly KeyGesture PasteBouncedKey = Cmd(Key.V, shift: true);// Arrangement: Copy to Session · Session: Copy to Arrangement.public static readonly KeyGesture CopyToOtherViewKey = Cmd(Key.C, shift: true);public static readonly KeyGesture SplitKey = Cmd(Key.E);diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 6d0ee106..6709d5c9 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1201,7 +1201,8 @@ public sealed partial class PreferencesWindow : NotaWindow}),("Devices (after a click on a device)", new[]{- ("⌘C ⌘X ⌘V", "Copy / cut / paste the device with all its settings · paste lands after the selected device, on any track"),+ ("⌘C ⌘X ⌘V", "Copy / cut / paste the device with all its settings · paste lands after the selected device, on any track or rack chain"),+ ("⌘D", "Duplicate the selected device"),("⌘G", "Wrap the selected audio effect in an Audio Effect Rack"),("⌘⇧G", "Take the devices out of a selected one-chain rack"),("Delete", "Delete the selected device"),@@ -1213,7 +1214,8 @@ public sealed partial class PreferencesWindow : NotaWindow("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"),+ ("Drag a device's header", "Move it within its chain · onto another chain's row to move it there"),+ ("Click a device", "Select it for ⌘C ⌘X ⌘V ⌘D and Delete"),}),("Modular (after a click on the canvas)", new[]{diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex f06a4966..6c01c3d0 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -422,6 +422,9 @@ public readonly record struct RackMacroMapping(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 rack address (RackDev* deviceIndex) of the Drum Rack in chain c of a track's+ /// Instrument Rack is NestedRackBase − c (NOTA_RACK_NESTED_BASE, specs/041).</summary>+ public const int NestedRackBase = -100000;/// <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 d12ea786..35fc0c16 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -513,6 +513,7 @@ public interface IAudioEngine : IDisposablebool CopyDevice(int trackId, int deviceIndex);bool CopyMidiEffect(int trackId, int index);int DeviceClipboardKind(); // 0 empty, 1 audio effect, 2 MIDI effect+ bool DeviceClipboardSidechain(); // the copied audio effect is keyed from another trackint PasteDevice(int trackId, int atIndex); // atIndex -1 = end; new index or -1int PasteMidiEffect(int trackId, int atIndex);// A full clone right after the device / MIDI effect, one undo step; clipboard untouched.@@ -806,6 +807,43 @@ public interface IAudioEngine : IDisposableint RackDevMode(int trackId, int deviceIndex);void RackDevSetMode(int trackId, int deviceIndex, int mode);+ // ---- racks inside racks (specs/041) ---------------------------------------------+ // One level: a chain of a track's Instrument Rack may hold a Drum Rack, addressed by every+ // RackDev* call as deviceIndex RackMacroMapping.NestedRackBase − chain. These are the Rack*+ // calls the Drum Rack card makes, for any rack address.+ int RackDevAddSamplerChain(int trackId, int deviceIndex, string path, int rootNote, bool loop);+ bool RackDevSetChainSamplerSample(int trackId, int deviceIndex, int chain, string path, int rootNote);+ int RackDevAddPluginInstrumentChain(int trackId, int deviceIndex, int catalogIndex);+ string RackDevChainName(int trackId, int deviceIndex, int chain);+ void RackDevSetChainName(int trackId, int deviceIndex, int chain, string name);+ int RackDevChainChoke(int trackId, int deviceIndex, int chain);+ void RackDevSetChainChoke(int trackId, int deviceIndex, int chain, int group);+ int RackDevChainTune(int trackId, int deviceIndex, int chain);+ void RackDevSetChainTune(int trackId, int deviceIndex, int chain, int semitones);+ float RackDevChainDecay(int trackId, int deviceIndex, int chain);+ void RackDevSetChainDecay(int trackId, int deviceIndex, int chain, float v);+ float RackDevSwing(int trackId, int deviceIndex);+ void RackDevSetSwing(int trackId, int deviceIndex, float v);+ float RackDevHumanize(int trackId, int deviceIndex);+ void RackDevSetHumanize(int trackId, int deviceIndex, float v);+ bool RackDevChainSamplerInfo(int trackId, int deviceIndex, int chain, out NotaSamplerInfo info);+ bool RackDevSetChainSamplerRoot(int trackId, int deviceIndex, int chain, int rootNote);+ float RackDevChainSamplerPlayPosition(int trackId, int deviceIndex, int chain);+ string RackDevChainInstrumentParamId(int trackId, int deviceIndex, int chain, int param);+ float RackDevChainInstrumentParamDefault(int trackId, int deviceIndex, int chain, int param);+ int RackDevChainInstrumentScope(int trackId, int deviceIndex, int chain, float[] outv);+ int RackDevChainInstrumentVoiceCount(int trackId, int deviceIndex, int chain);+ int RackDevChainInstrumentHeldNotes(int trackId, int deviceIndex, int chain, int[] outNotes);+ void RackDevChainInstrumentAction(int trackId, int deviceIndex, int chain, int id, int iarg, float farg);+ void RackDevOpenChainInstrumentEditor(int trackId, int deviceIndex, int chain);+ string RackDevChainInstrumentPluginId(int trackId, int deviceIndex, int chain);+ byte[] RackDevGetChainInstrumentState(int trackId, int deviceIndex, int chain);+ /// <summary>Nota Mosaic as a chain instrument, as <see cref="MosaicSetProgram"/> & co. for a track.</summary>+ bool RackDevChainMosaicSetProgram(int trackId, int deviceIndex, int chain, string text, bool undoable = true);+ string RackDevChainMosaicProgram(int trackId, int deviceIndex, int chain);+ bool RackDevTryGetChainMosaicStatus(int trackId, int deviceIndex, int chain, out NotaMosaicStatus status);+ long RackDevChainMosaicZoneSampleId(int trackId, int deviceIndex, int chain, int zone);+// ---- 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);@@ -885,6 +923,25 @@ public interface IAudioEngine : IDisposablebool 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);+ /// <summary>Rack chain devices on the shared device clipboard (specs/042); deviceIndex addresses+ /// the rack as the other RackDev calls do (−1 Instrument/Drum Rack, ≥0 Audio Effect Rack,+ /// −1000 − mi MIDI Effect Rack, NestedRackBase − chain). Paste returns the new index or −1 nothing,+ /// −2 wrong family, −3 a rack in a rack, −5 MIDI past chain 16; each edit is one undo step.</summary>+ /// <summary>One undo step for the in-place edits that follow on a rack (a fader drag, a mode or+ /// switch change): forks the rack now, keeping its children and held notes.</summary>+ bool RackDevCheckpoint(int trackId, int deviceIndex);+ /// <summary>A chain's identity while chains move (0 = none); compare it, don't decode it.</summary>+ long RackDevChainId(int trackId, int deviceIndex, int chain);+ /// <summary>Loads a sample into a chain's Nota Grain (a Grain preset's source); one undo step.</summary>+ bool RackDevChainGrainSetSample(int trackId, int deviceIndex, int chain, string path, int rootNote = 60);+ bool RackDevChainDeviceCopy(int trackId, int deviceIndex, int chain, int index);+ bool RackDevChainMidiCopy(int trackId, int deviceIndex, int chain, int index);+ int RackDevChainDevicePaste(int trackId, int deviceIndex, int chain, int atIndex);+ int RackDevChainMidiPaste(int trackId, int deviceIndex, int chain, int atIndex);+ int RackDevChainDeviceDuplicate(int trackId, int deviceIndex, int chain, int index);+ int RackDevChainMidiDuplicate(int trackId, int deviceIndex, int chain, int index);+ int RackDevChainDeviceMoveTo(int trackId, int deviceIndex, int chain, int index, int toChain);+ int RackDevChainMidiMoveTo(int trackId, int deviceIndex, int chain, int index, int toChain);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/Engine/RackEngineProxies.cs b/src/managed/Nota.Application/Engine/RackEngineProxies.csnew file mode 100644index 00000000..06b5ea69--- /dev/null+++ b/src/managed/Nota.Application/Engine/RackEngineProxies.cs@@ -0,0 +1,129 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Engine views that let an editor written for a track's instrument drive an instrument inside+// a rack chain instead. The editors call IAudioEngine as if the instrument were the track's+// own; these DispatchProxies redirect those calls to the chain, so one editor serves both+// (the Mosaic editor on a chain, the Drum Rack card on a Drum Rack nested in a chain,+// specs/041). They live here, not in the app, so the MCP server applies presets through them.++using System.Collections.Concurrent;+using System.Reflection;++namespace Nota.Application;++/// <summary>The instrument in chain <see cref="Chain"/> of the track's Instrument Rack, seen as+/// the track's instrument: its plugin-param calls (trackId, deviceIndex −1, i) go to the chain+/// surface (trackId, chain, i); live telemetry, actions and Nota Mosaic's program come from the+/// chain instrument; automation writes are no-ops (chain params follow macros); everything else+/// reaches the real engine.</summary>+public class RackChainEngineProxy : DispatchProxy+{+ public IAudioEngine Inner = null!;+ public int Chain;++ public static IAudioEngine Create(IAudioEngine inner, int chain)+ {+ var proxy = Create<IAudioEngine, RackChainEngineProxy>();+ var pp = (RackChainEngineProxy)(object)proxy; pp.Inner = inner; pp.Chain = chain;+ return proxy;+ }++ protected override object? Invoke(MethodInfo? m, object?[]? args)+ {+ switch (m?.Name)+ {+ case nameof(IAudioEngine.PluginParamCount): return Inner.RackChainInstrumentParamCount((int)args![0]!, Chain);+ case nameof(IAudioEngine.PluginParamId): return Inner.RackChainInstrumentParamId((int)args![0]!, Chain, (int)args![2]!);+ case nameof(IAudioEngine.PluginParamGet): return Inner.RackChainInstrumentParamGet((int)args![0]!, Chain, (int)args![2]!);+ case nameof(IAudioEngine.PluginParamSet): Inner.RackChainInstrumentParamSet((int)args![0]!, Chain, (int)args![2]!, (float)args![3]!); return null;+ case nameof(IAudioEngine.InstrumentParamDefault): return Inner.RackChainInstrumentParamDefault((int)args![0]!, Chain, (int)args![1]!);+ case nameof(IAudioEngine.TrackInstrumentKind): return Inner.RackChainInstrumentKind((int)args![0]!, Chain);+ case nameof(IAudioEngine.BeginAutomationWrite):+ case nameof(IAudioEngine.EndAutomationWrite): return null;+ // Live telemetry comes from the chain instrument, not the track's rack instrument.+ case nameof(IAudioEngine.InstrumentScope): return Inner.RackChainInstrumentScope((int)args![0]!, Chain, (float[])args![1]!);+ case nameof(IAudioEngine.InstrumentVoiceCount): return Inner.RackChainInstrumentVoiceCount((int)args![0]!, Chain);+ case nameof(IAudioEngine.InstrumentHeldNotes): return Inner.RackChainInstrumentHeldNotes((int)args![0]!, Chain, (int[])args![1]!);+ case nameof(IAudioEngine.InstrumentAction): Inner.RackChainInstrumentAction((int)args![0]!, Chain, (int)args![1]!, (int)args![2]!, (float)args![3]!); return null;+ // Nota Mosaic in a chain (specs/041). Through Inner's rack address −1, which a+ // NestedRackEngineProxy under it turns into its nested Drum Rack (a Mosaic pad).+ // A factory Nota Grain preset loads its source sample into the chain's Grain.+ case nameof(IAudioEngine.SetTrackGrainSample): return Inner.RackDevChainGrainSetSample((int)args![0]!, -1, Chain, (string)args![1]!, (int)args![2]!);+ case nameof(IAudioEngine.MosaicSetProgram): return Inner.RackDevChainMosaicSetProgram((int)args![0]!, -1, Chain, (string)args![1]!, (bool)args![2]!);+ case nameof(IAudioEngine.MosaicProgram): return Inner.RackDevChainMosaicProgram((int)args![0]!, -1, Chain);+ case nameof(IAudioEngine.MosaicZoneSampleId): return Inner.RackDevChainMosaicZoneSampleId((int)args![0]!, -1, Chain, (int)args![1]!);+ case nameof(IAudioEngine.TryGetMosaicStatus):+ {+ bool ok = Inner.RackDevTryGetChainMosaicStatus((int)args![0]!, -1, Chain, out var st);+ args[1] = st;+ return ok;+ }+ default: return m!.Invoke(Inner, args);+ }+ }+}++/// <summary>The Drum Rack in chain <see cref="RackChainEngineProxy.Chain"/> of the track's+/// Instrument Rack, seen as the track's Drum Rack, so the Drum Rack card runs on it unchanged.+/// Its macros are that chain instrument's params (the base proxy); every instrument-rack call+/// <c>RackFoo(trackId, …)</c> becomes <c>RackDevFoo(trackId, nested, …)</c>, and a+/// <c>RackDevFoo(trackId, −1, …)</c> (the track's rack) the same. A Rack* call with no RackDev+/// twin is an Instrument Rack feature a Drum Rack doesn't have (mono, glide, chain MIDI+/// effects): it answers the type's default and never reaches the outer rack.</summary>+public class NestedRackEngineProxy : RackChainEngineProxy+{+ /// <summary>The nested rack's address for RackDev* calls.</summary>+ public int Nested => RackMacroMapping.NestedRackBase - Chain;++ public static new IAudioEngine Create(IAudioEngine inner, int chain)+ {+ var proxy = Create<IAudioEngine, NestedRackEngineProxy>();+ var pp = (NestedRackEngineProxy)(object)proxy; pp.Inner = inner; pp.Chain = chain;+ return proxy;+ }++ private static readonly ConcurrentDictionary<MethodInfo, MethodInfo?> Twins = new();++ // RackFoo(int trackId, rest…) → RackDevFoo(int trackId, int deviceIndex, rest…).+ private static MethodInfo? TwinOf(MethodInfo m) => Twins.GetOrAdd(m, k =>+ {+ var ps = k.GetParameters();+ var want = new[] { typeof(int), typeof(int) }.Concat(ps.Skip(1).Select(p => p.ParameterType)).ToArray();+ return typeof(IAudioEngine).GetMethod("RackDev" + k.Name[4..], want);+ });++ protected override object? Invoke(MethodInfo? m, object?[]? args)+ {+ string name = m?.Name ?? "";+ if (name.StartsWith("RackDev", StringComparison.Ordinal))+ {+ if (args is { Length: >= 2 } && args[1] is -1) args[1] = Nested;+ return m!.Invoke(Inner, args);+ }+ if (name.StartsWith("Rack", StringComparison.Ordinal) && args is { Length: >= 1 } && args[0] is int)+ {+ var twin = TwinOf(m!);+ if (twin == null) return Default(m!, args);+ var a = new object?[args.Length + 1];+ a[0] = args[0]; a[1] = Nested;+ Array.Copy(args, 1, a, 2, args.Length - 1);+ var r = twin.Invoke(Inner, a);+ for (int i = 1; i < args.Length; i++) args[i] = a[i + 1]; // out parameters+ return r;+ }+ return base.Invoke(m, args);+ }++ private static object? Default(MethodInfo m, object?[] args)+ {+ var ps = m.GetParameters();+ for (int i = 0; i < ps.Length; i++)+ if (ps[i].IsOut) args[i] = ps[i].ParameterType.GetElementType() is { IsValueType: true } et ? Activator.CreateInstance(et) : null;+ var rt = m.ReturnType;+ if (rt == typeof(void)) return null;+ if (rt == typeof(string)) return "";+ if (rt == typeof(int)) return m.Name.EndsWith("Count", StringComparison.Ordinal) ? 0 : -1;+ return rt.IsValueType ? Activator.CreateInstance(rt) : null;+ }+}diff --git a/src/managed/Nota.Application/Ports/IPresetStore.cs b/src/managed/Nota.Application/Ports/IPresetStore.csindex 5558eb11..7fea0faa 100644--- a/src/managed/Nota.Application/Ports/IPresetStore.cs+++ b/src/managed/Nota.Application/Ports/IPresetStore.cs@@ -16,6 +16,16 @@ public interface IPresetStore/// Null — nothing done — when the file isn't an instrument preset; else a warning ("" = clean).</summary>string? ApplyInstrumentInPlace(IAudioEngine engine, string path, int trackId, out bool swapped);+ /// <summary>What a preset file is for: its type ("builtin-instrument", "builtin-effect",+ /// "builtin-midi-effect", "plugin-instrument", "plugin-effect") and built-in kind (−1 for a+ /// plug-in). Null when the file can't be read.</summary>+ (string Type, int BuiltinKind)? Describe(string path);++ /// <summary>Applies a preset file to a device that already matches it, in place+ /// (<paramref name="deviceIndex"/> −1 = the instrument, else the effect or MIDI effect at that+ /// index). Returns a warning ("" = clean).</summary>+ string ApplyFileInPlace(IAudioEngine engine, string path, int trackId, int deviceIndex);+/// <summary>Captures a track's device/instrument as a preset and saves it to/// <paramref name="folder"/>. Returns false if there was nothing to capture/// (e.g. the built-in synth has no state).</summary>diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.csindex 8ebbab8b..beb09e36 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs@@ -46,6 +46,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_device_clipboard_kind")]internal static partial int DeviceClipboardKind(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_device_clipboard_sidechain")]+ internal static partial int DeviceClipboardSidechain(IntPtr engine);+[LibraryImport(Lib, EntryPoint = "nota_track_paste_device")]internal static partial int PasteDevice(IntPtr engine, int trackId, int atIndex);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.csindex 596ebb5b..f51a8ff2 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs@@ -267,4 +267,98 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_rack_humanize")]internal static partial float RackHumanize(IntPtr engine, int trackId);+ // specs/041: the Drum Rack card's nota_rack_* surface for any rack address (a nested Drum Rack too).+ [LibraryImport(Lib, EntryPoint = "nota_rackdev_add_sampler_chain", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int RackDevAddSamplerChain(IntPtr engine, int trackId, int deviceIndex, string path, int rootNote, int loop);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_chain_sampler_sample", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int RackDevSetChainSamplerSample(IntPtr engine, int trackId, int deviceIndex, int chain, string path, int rootNote);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_add_plugin_instrument_chain")]+ internal static partial int RackDevAddPluginInstrumentChain(IntPtr engine, int trackId, int deviceIndex, int catalogIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_name")]+ internal static partial IntPtr RackDevChainName(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_chain_name", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial void RackDevSetChainName(IntPtr engine, int trackId, int deviceIndex, int chain, string name);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_choke")]+ internal static partial int RackDevChainChoke(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_chain_choke")]+ internal static partial void RackDevSetChainChoke(IntPtr engine, int trackId, int deviceIndex, int chain, int group);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_tune")]+ internal static partial int RackDevChainTune(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_chain_tune")]+ internal static partial void RackDevSetChainTune(IntPtr engine, int trackId, int deviceIndex, int chain, int semitones);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_decay")]+ internal static partial float RackDevChainDecay(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_chain_decay")]+ internal static partial void RackDevSetChainDecay(IntPtr engine, int trackId, int deviceIndex, int chain, float v);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_swing")]+ internal static partial float RackDevSwing(IntPtr engine, int trackId, int deviceIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_swing")]+ internal static partial void RackDevSetSwing(IntPtr engine, int trackId, int deviceIndex, float v);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_humanize")]+ internal static partial float RackDevHumanize(IntPtr engine, int trackId, int deviceIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_humanize")]+ internal static partial void RackDevSetHumanize(IntPtr engine, int trackId, int deviceIndex, float v);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_sampler_info")]+ internal static partial int RackDevChainSamplerInfo(IntPtr engine, int trackId, int deviceIndex, int chain, out NotaSamplerInfo info);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_set_chain_sampler_root")]+ internal static partial int RackDevSetChainSamplerRoot(IntPtr engine, int trackId, int deviceIndex, int chain, int rootNote);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_sampler_play_position")]+ internal static partial float RackDevChainSamplerPlayPosition(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_param_id")]+ internal static partial IntPtr RackDevChainInstrumentParamId(IntPtr engine, int trackId, int deviceIndex, int chain, int param);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_param_default")]+ internal static partial float RackDevChainInstrumentParamDefault(IntPtr engine, int trackId, int deviceIndex, int chain, int param);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_scope")]+ internal static partial int RackDevChainInstrumentScope(IntPtr engine, int trackId, int deviceIndex, int chain, [Out] float[] outv, int maxN);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_voice_count")]+ internal static partial int RackDevChainInstrumentVoiceCount(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_held_notes")]+ internal static partial int RackDevChainInstrumentHeldNotes(IntPtr engine, int trackId, int deviceIndex, int chain, [Out] int[] outNotes, int maxN);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_action")]+ internal static partial void RackDevChainInstrumentAction(IntPtr engine, int trackId, int deviceIndex, int chain, int id, int iarg, float farg);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_open_chain_instrument_editor")]+ internal static partial void RackDevOpenChainInstrumentEditor(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_plugin_id")]+ internal static partial IntPtr RackDevChainInstrumentPluginId(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_get_state")]+ internal static partial int RackDevChainInstrumentGetState(IntPtr engine, int trackId, int deviceIndex, int chain, [Out] byte[]? outBuffer, int capacity);++ // Nota Mosaic as a chain instrument (specs/041).+ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_mosaic_set_program", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int RackDevChainMosaicSetProgram(IntPtr engine, int trackId, int deviceIndex, int chain, string text, int undoable);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_mosaic_program")]+ internal static unsafe partial int RackDevChainMosaicProgram(IntPtr engine, int trackId, int deviceIndex, int chain, byte* output, int cap);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_mosaic_status")]+ internal static partial int RackDevChainMosaicStatus(IntPtr engine, int trackId, int deviceIndex, int chain, out NotaMosaicStatus status);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_mosaic_zone_sample_id")]+ internal static partial long RackDevChainMosaicZoneSampleId(IntPtr engine, int trackId, int deviceIndex, int chain, int zone);}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.csindex eaf32b03..de0b99a9 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.RackDev.cs@@ -194,6 +194,39 @@ internal static partial class NativeMethods[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_chain_grain_set_sample", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int RackDevChainGrainSetSample(IntPtr engine, int trackId, int deviceIndex, int chain, string path, int rootNote);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_id")]+ internal static partial long RackDevChainId(IntPtr engine, int trackId, int deviceIndex, int chain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_checkpoint")]+ internal static partial int RackDevCheckpoint(IntPtr engine, int trackId, int deviceIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_device_copy")]+ internal static partial int RackDevChainDeviceCopy(IntPtr engine, int trackId, int deviceIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_midi_copy")]+ internal static partial int RackDevChainMidiCopy(IntPtr engine, int trackId, int deviceIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_device_paste")]+ internal static partial int RackDevChainDevicePaste(IntPtr engine, int trackId, int deviceIndex, int chain, int atIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_midi_paste")]+ internal static partial int RackDevChainMidiPaste(IntPtr engine, int trackId, int deviceIndex, int chain, int atIndex);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_device_duplicate")]+ internal static partial int RackDevChainDeviceDuplicate(IntPtr engine, int trackId, int deviceIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_midi_duplicate")]+ internal static partial int RackDevChainMidiDuplicate(IntPtr engine, int trackId, int deviceIndex, int chain, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_device_move_to")]+ internal static partial int RackDevChainDeviceMoveTo(IntPtr engine, int trackId, int deviceIndex, int chain, int index, int toChain);++ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_midi_move_to")]+ internal static partial int RackDevChainMidiMoveTo(IntPtr engine, int trackId, int deviceIndex, int chain, int index, int toChain);+[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 65837610..080bc491 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs@@ -81,6 +81,9 @@ public sealed partial class NotaEngine/// <summary>0 = empty, 1 = an audio effect, 2 = a MIDI effect.</summary>public int DeviceClipboardKind() { ThrowIfDisposed(); return NativeMethods.DeviceClipboardKind(_handle); }+ /// <summary>True when the clipboard holds an audio effect keyed from another track.</summary>+ public bool DeviceClipboardSidechain() { ThrowIfDisposed(); return NativeMethods.DeviceClipboardSidechain(_handle) != 0; }+/// <summary>Inserts a clone of the copied audio effect at atIndex (-1 = end), one undo step. New index or -1.</summary>public int PasteDevice(int trackId, int atIndex){ ThrowIfDisposed(); return NativeMethods.PasteDevice(_handle, trackId, atIndex); }diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.csindex d47b2159..a4b20363 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs@@ -293,4 +293,97 @@ public sealed partial class NotaEngine{ ThrowIfDisposed(); NativeMethods.RackSetHumanize(_handle, trackId, v); }public float RackHumanize(int trackId){ ThrowIfDisposed(); return NativeMethods.RackHumanize(_handle, trackId); }++ // specs/041: the Drum Rack card's Rack* surface for any rack address (a nested Drum Rack too).+ public int RackDevAddSamplerChain(int trackId, int deviceIndex, string path, int rootNote, bool loop)+ {+ ThrowIfDisposed();+ int c = NativeMethods.RackDevAddSamplerChain(_handle, trackId, deviceIndex, path, rootNote, loop ? 1 : 0);+ if (c >= 0 && RackDevChainSamplerInfo(trackId, deviceIndex, c, out var si)) RememberSampleName(si.SampleId, path);+ return c;+ }+ public bool RackDevSetChainSamplerSample(int trackId, int deviceIndex, int chain, string path, int rootNote)+ {+ ThrowIfDisposed();+ bool ok = NativeMethods.RackDevSetChainSamplerSample(_handle, trackId, deviceIndex, chain, path, rootNote) != 0;+ if (ok && RackDevChainSamplerInfo(trackId, deviceIndex, chain, out var si)) RememberSampleName(si.SampleId, path);+ return ok;+ }+ public int RackDevAddPluginInstrumentChain(int trackId, int deviceIndex, int catalogIndex)+ { ThrowIfDisposed(); return NativeMethods.RackDevAddPluginInstrumentChain(_handle, trackId, deviceIndex, catalogIndex); }+ public string RackDevChainName(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.RackDevChainName(_handle, trackId, deviceIndex, chain)) ?? ""; }+ public void RackDevSetChainName(int trackId, int deviceIndex, int chain, string name)+ { ThrowIfDisposed(); NativeMethods.RackDevSetChainName(_handle, trackId, deviceIndex, chain, name ?? ""); }+ public int RackDevChainChoke(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainChoke(_handle, trackId, deviceIndex, chain); }+ public void RackDevSetChainChoke(int trackId, int deviceIndex, int chain, int group)+ { ThrowIfDisposed(); NativeMethods.RackDevSetChainChoke(_handle, trackId, deviceIndex, chain, group); }+ public int RackDevChainTune(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainTune(_handle, trackId, deviceIndex, chain); }+ public void RackDevSetChainTune(int trackId, int deviceIndex, int chain, int semitones)+ { ThrowIfDisposed(); NativeMethods.RackDevSetChainTune(_handle, trackId, deviceIndex, chain, semitones); }+ public float RackDevChainDecay(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainDecay(_handle, trackId, deviceIndex, chain); }+ public void RackDevSetChainDecay(int trackId, int deviceIndex, int chain, float v)+ { ThrowIfDisposed(); NativeMethods.RackDevSetChainDecay(_handle, trackId, deviceIndex, chain, v); }+ public float RackDevSwing(int trackId, int deviceIndex)+ { ThrowIfDisposed(); return NativeMethods.RackDevSwing(_handle, trackId, deviceIndex); }+ public void RackDevSetSwing(int trackId, int deviceIndex, float v)+ { ThrowIfDisposed(); NativeMethods.RackDevSetSwing(_handle, trackId, deviceIndex, v); }+ public float RackDevHumanize(int trackId, int deviceIndex)+ { ThrowIfDisposed(); return NativeMethods.RackDevHumanize(_handle, trackId, deviceIndex); }+ public void RackDevSetHumanize(int trackId, int deviceIndex, float v)+ { ThrowIfDisposed(); NativeMethods.RackDevSetHumanize(_handle, trackId, deviceIndex, v); }+ public bool RackDevChainSamplerInfo(int trackId, int deviceIndex, int chain, out NotaSamplerInfo info)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainSamplerInfo(_handle, trackId, deviceIndex, chain, out info) != 0; }+ public bool RackDevSetChainSamplerRoot(int trackId, int deviceIndex, int chain, int rootNote)+ { ThrowIfDisposed(); return NativeMethods.RackDevSetChainSamplerRoot(_handle, trackId, deviceIndex, chain, rootNote) != 0; }+ public float RackDevChainSamplerPlayPosition(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainSamplerPlayPosition(_handle, trackId, deviceIndex, chain); }+ public string RackDevChainInstrumentParamId(int trackId, int deviceIndex, int chain, int param)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.RackDevChainInstrumentParamId(_handle, trackId, deviceIndex, chain, param)) ?? ""; }+ public float RackDevChainInstrumentParamDefault(int trackId, int deviceIndex, int chain, int param)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainInstrumentParamDefault(_handle, trackId, deviceIndex, chain, param); }+ public int RackDevChainInstrumentScope(int trackId, int deviceIndex, int chain, float[] outv)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainInstrumentScope(_handle, trackId, deviceIndex, chain, outv, outv.Length); }+ public int RackDevChainInstrumentVoiceCount(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainInstrumentVoiceCount(_handle, trackId, deviceIndex, chain); }+ public int RackDevChainInstrumentHeldNotes(int trackId, int deviceIndex, int chain, int[] outNotes)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainInstrumentHeldNotes(_handle, trackId, deviceIndex, chain, outNotes, outNotes.Length); }+ public void RackDevChainInstrumentAction(int trackId, int deviceIndex, int chain, int id, int iarg, float farg)+ { ThrowIfDisposed(); NativeMethods.RackDevChainInstrumentAction(_handle, trackId, deviceIndex, chain, id, iarg, farg); }+ public void RackDevOpenChainInstrumentEditor(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); NativeMethods.RackDevOpenChainInstrumentEditor(_handle, trackId, deviceIndex, chain); }+ public string RackDevChainInstrumentPluginId(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.RackDevChainInstrumentPluginId(_handle, trackId, deviceIndex, chain)) ?? ""; }+ public byte[] RackDevGetChainInstrumentState(int trackId, int deviceIndex, int chain)+ {+ ThrowIfDisposed();+ int size = NativeMethods.RackDevChainInstrumentGetState(_handle, trackId, deviceIndex, chain, null, 0);+ if (size <= 0) return System.Array.Empty<byte>();+ var buf = new byte[size];+ NativeMethods.RackDevChainInstrumentGetState(_handle, trackId, deviceIndex, chain, buf, size);+ return buf;+ }++ // Nota Mosaic as a chain instrument (specs/041), as MosaicSetProgram & co. for a track.+ public bool RackDevChainMosaicSetProgram(int trackId, int deviceIndex, int chain, string text, bool undoable = true)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMosaicSetProgram(_handle, trackId, deviceIndex, chain, text ?? "", undoable ? 1 : 0) != 0; }++ public unsafe string RackDevChainMosaicProgram(int trackId, int deviceIndex, int chain)+ {+ ThrowIfDisposed();+ int n = NativeMethods.RackDevChainMosaicProgram(_handle, trackId, deviceIndex, chain, null, 0);+ if (n <= 0) return "";+ var buf = new byte[n];+ fixed (byte* p = buf) n = System.Math.Min(n, NativeMethods.RackDevChainMosaicProgram(_handle, trackId, deviceIndex, chain, p, buf.Length));+ return System.Text.Encoding.UTF8.GetString(buf, 0, n);+ }++ public bool RackDevTryGetChainMosaicStatus(int trackId, int deviceIndex, int chain, out NotaMosaicStatus status)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMosaicStatus(_handle, trackId, deviceIndex, chain, out status) != 0; }++ public long RackDevChainMosaicZoneSampleId(int trackId, int deviceIndex, int chain, int zone)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMosaicZoneSampleId(_handle, trackId, deviceIndex, chain, zone); }}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.csindex c62ffa95..f0d47407 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.RackDev.cs@@ -196,6 +196,39 @@ public sealed partial class NotaEngine/// <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 bool RackDevChainGrainSetSample(int trackId, int deviceIndex, int chain, string path, int rootNote = 60)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainGrainSetSample(_handle, trackId, deviceIndex, chain, path, rootNote) == 0; }++ public long RackDevChainId(int trackId, int deviceIndex, int chain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainId(_handle, trackId, deviceIndex, chain); }++ public bool RackDevCheckpoint(int trackId, int deviceIndex)+ { ThrowIfDisposed(); return NativeMethods.RackDevCheckpoint(_handle, trackId, deviceIndex) != 0; }++ public bool RackDevChainDeviceCopy(int trackId, int deviceIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainDeviceCopy(_handle, trackId, deviceIndex, chain, index) != 0; }++ public bool RackDevChainMidiCopy(int trackId, int deviceIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMidiCopy(_handle, trackId, deviceIndex, chain, index) != 0; }++ public int RackDevChainDevicePaste(int trackId, int deviceIndex, int chain, int atIndex)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainDevicePaste(_handle, trackId, deviceIndex, chain, atIndex); }++ public int RackDevChainMidiPaste(int trackId, int deviceIndex, int chain, int atIndex)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMidiPaste(_handle, trackId, deviceIndex, chain, atIndex); }++ public int RackDevChainDeviceDuplicate(int trackId, int deviceIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainDeviceDuplicate(_handle, trackId, deviceIndex, chain, index); }++ public int RackDevChainMidiDuplicate(int trackId, int deviceIndex, int chain, int index)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMidiDuplicate(_handle, trackId, deviceIndex, chain, index); }++ public int RackDevChainDeviceMoveTo(int trackId, int deviceIndex, int chain, int index, int toChain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainDeviceMoveTo(_handle, trackId, deviceIndex, chain, index, toChain); }++ public int RackDevChainMidiMoveTo(int trackId, int deviceIndex, int chain, int index, int toChain)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainMidiMoveTo(_handle, trackId, deviceIndex, chain, index, toChain); }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/PresetStore.cs b/src/managed/Nota.Infrastructure/Persistence/PresetStore.csindex 01240e3f..75c1bdc9 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs@@ -42,6 +42,22 @@ public sealed class PresetStore : IPresetStorereturn PresetService.ApplyInPlace(doc, engine, trackId, -1);}+ public (string Type, int BuiltinKind)? Describe(string path)+ {+ try+ {+ var doc = PresetService.Load(path);+ return (doc.Type, doc.BuiltinKind);+ }+ catch { return null; }+ }++ public string ApplyFileInPlace(IAudioEngine engine, string path, int trackId, int deviceIndex)+ {+ try { return PresetService.ApplyInPlace(PresetService.Load(path), engine, trackId, deviceIndex); }+ catch (Exception e) { return $"Couldn't load the preset: {e.Message}"; }+ }+public bool Save(IAudioEngine engine, int trackId, int deviceIndex, string displayName, string folder){var doc = PresetService.Capture(engine, trackId, deviceIndex, displayName);diff --git a/src/managed/Nota.Mcp/Tools/EffectRackTools.cs b/src/managed/Nota.Mcp/Tools/EffectRackTools.csindex 0290a638..03c66c26 100644--- a/src/managed/Nota.Mcp/Tools/EffectRackTools.cs+++ b/src/managed/Nota.Mcp/Tools/EffectRackTools.cs@@ -53,8 +53,8 @@ public sealed class EffectRackTools(IAudioEngine engine, IEngineDispatch dispatc[McpServerTool(Name = "set_effect_rack_chain_select"), Description("Select-mode: set the chain-select position (0..1) that picks/crossfades the active chain.")]public Task SetEffectRackChainSelect(int trackId, int deviceIndex, float value) => Mutate(() => E.RackDevSetChainSelect(trackId, deviceIndex, Math.Clamp(value, 0f, 1f)));- [McpServerTool(Name = "add_effect_rack_chain"), Description("Add a parallel effect chain to the rack (instrumentKind seeds the chain's source; typically 4 = Utility). Returns the chain index.")]- public Task<int> AddEffectRackChain(int trackId, int deviceIndex, int instrumentKind = 4) => Mutate(() => E.RackDevAddChain(trackId, deviceIndex, instrumentKind));+ [McpServerTool(Name = "add_effect_rack_chain"), Description("Add an empty parallel effect chain to the rack (an effect chain holds no instrument; instrumentKind is ignored). Returns the chain index.")]+ public Task<int> AddEffectRackChain(int trackId, int deviceIndex, int instrumentKind = -1) => Mutate(() => E.RackDevAddChain(trackId, deviceIndex, instrumentKind));[McpServerTool(Name = "remove_effect_rack_chain"), Description("Remove a chain from the rack by index.")]public Task<bool> RemoveEffectRackChain(int trackId, int deviceIndex, int chain) => Mutate(() => E.RackDevRemoveChain(trackId, deviceIndex, chain));diff --git a/src/managed/Nota.Mcp/Tools/MosaicTools.cs b/src/managed/Nota.Mcp/Tools/MosaicTools.csindex ae8220b9..af6fae62 100644--- a/src/managed/Nota.Mcp/Tools/MosaicTools.cs+++ b/src/managed/Nota.Mcp/Tools/MosaicTools.cs@@ -258,16 +258,20 @@ public sealed class MosaicTools(IAudioEngine engine, IEngineDispatch dispatch, I[McpServerTool(Name = "load_mosaic_preset"), Description("Load a Nota Mosaic preset by name (a factory name, or a pack preset's name; folder narrows it) into trackId "- + "(<= 0: a new Mosaic track). Samples load in the background. Returns the track id, or -1 when no preset matches.")]- public Task<int> LoadMosaicPreset(string name, int trackId = -1, string? folder = null) => Mutate(() =>+ + "(<= 0: a new Mosaic track), or with chain >= 0 into that Instrument Rack chain's Mosaic. Samples load in the "+ + "background. Returns the track id, or -1 when no preset matches (or the chain holds no Mosaic).")]+ public Task<int> LoadMosaicPreset(string name, int trackId = -1, string? folder = null, int chain = -1) => Mutate(() =>{+ if (chain >= 0 && E.RackChainInstrumentKind(trackId, chain) != MosaicModel.Kind) return -1;var fp = factory.All().FirstOrDefault(p => p.IsInstrument && p.BuiltinKind == MosaicModel.Kind && string.Equals(p.DisplayName, name, StringComparison.OrdinalIgnoreCase));var pp = fp.Id is { Length: > 0 } ? null : packs.Presets().FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)&& (folder is null || string.Equals(p.Folder, folder, StringComparison.OrdinalIgnoreCase)));if (fp.Id is not { Length: > 0 } && pp is null) return -1;- int t = trackId > 0 && IsMosaic(trackId) ? trackId : E.AddMosaicTrack();- if (pp is null) factory.ApplyInPlace(E, fp.Id!, t, -1);- else packs.ApplyInPlace(E, pp.Path, t);+ // A chain's Mosaic takes the preset through the chain view the rack card's editor uses.+ var e = chain >= 0 ? RackChainEngineProxy.Create(E, chain) : E;+ int t = chain >= 0 ? trackId : trackId > 0 && IsMosaic(trackId) ? trackId : E.AddMosaicTrack();+ if (pp is null) factory.ApplyInPlace(e, fp.Id!, t, -1);+ else packs.ApplyInPlace(e, pp.Path, t);return t;});diff --git a/src/managed/Nota.Mcp/Tools/RackTools.cs b/src/managed/Nota.Mcp/Tools/RackTools.csindex c2ad3334..a909c618 100644--- a/src/managed/Nota.Mcp/Tools/RackTools.cs+++ b/src/managed/Nota.Mcp/Tools/RackTools.cs@@ -48,9 +48,11 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr[McpServerTool(Name = "get_rack"), Description("Snapshot of an Instrument/Drum Rack on a track: rack volume and every chain "- + "(index, instrument kind+name, MIDI trigger note, gain/pan/mute/solo, device count).")]- public Task<RackSnapshot> GetRack(int trackId) => Read(() =>+ + "(index, instrument kind+name, MIDI trigger note, gain/pan/mute/solo, device count). nestedChain >= 0 reads the "+ + "Drum Rack held by that chain of the track's Instrument Rack instead.")]+ public Task<RackSnapshot> GetRack(int trackId, [Description("-1 = the track's rack; >= 0 = the Drum Rack nested in that chain")] int nestedChain = -1) => Read(() =>{+ var E = nestedChain >= 0 ? NestedRackEngineProxy.Create(this.E, nestedChain) : this.E;int n = E.RackChainCount(trackId);var chains = new ChainInfo[n];for (int c = 0; c < n; c++)@@ -64,7 +66,7 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr// ---- chains -----------------------------------------------------------[McpServerTool(Name = "add_rack_chain"), Description("Add a parallel chain to the rack with the given built-in instrument kind. Returns the chain index.")]- public Task<int> AddRackChain(int trackId, [Description("Instrument kind id, e.g. 6=Volt, 2=Physical, 5=Aurora")] int instrumentKind)+ public Task<int> AddRackChain(int trackId, [Description("Instrument kind id, e.g. 6=Volt, 2=Physical, 5=Aurora, 17=Mosaic, 4=Drum Rack (Instrument Rack chains only; reach it with get_rack nestedChain or the effect-rack tools at deviceIndex -100000 - chain)")] 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.")]@@ -73,7 +75,7 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr[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));- [McpServerTool(Name = "set_chain_instrument"), Description("Replace a chain's instrument with another built-in kind.")]+ [McpServerTool(Name = "set_chain_instrument"), Description("Replace a chain's instrument with another built-in kind (17 = Nota Mosaic; 4 = a Drum Rack, in an Instrument Rack chain only: racks nest one level).")]public Task<bool> SetChainInstrument(int trackId, int chain, int instrumentKind)=> Mutate(() => E.RackSetChainInstrument(trackId, chain, instrumentKind));diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 12468fe7..fb9a499d 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -1722,6 +1722,40 @@ NOTA_API int32_t nota_rack_mapping_count(const NotaEngine* engine, int32_t t* 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);+/* Rack chain devices on the shared device clipboard (specs/042) — the one nota_track_copy_device /+ * nota_track_paste_device use, so a copy pastes across the track chain and every rack chain.+ * device_index addresses the rack as the other nota_rackdev_* calls do (−1 the track's Instrument+ * or Drum Rack, >= 0 an Audio Effect Rack, −1000 − mi the MIDI Effect Rack at MIDI effect index mi,+ * NOTA_RACK_NESTED_BASE − chain a nested Drum Rack). Each edit is one undo step.+ * copy: 1 = copied, 0 = no such device.+ * paste: a fresh clone at at_index (−1 = the end); the new index, or −1 nothing to paste / bad+ * address, −2 the clipboard holds the other family or the rack has no such section, −3 a rack+ * inside a rack, −5 a MIDI effect past the Instrument Rack's first 16 chains. A pasted audio+ * effect loses its sidechain key (see nota_device_clipboard_sidechain).+ * duplicate: a clone right after the device, the clipboard untouched; new index or < 0.+ * move_to: to the end of to_chain's matching section of the same rack, macro mappings and all;+ * new index, −1 bad address / the same chain, −5 as above. */+NOTA_API int32_t nota_rackdev_chain_device_copy(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);+NOTA_API int32_t nota_rackdev_chain_midi_copy(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);+NOTA_API int32_t nota_rackdev_chain_device_paste(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t at_index);+NOTA_API int32_t nota_rackdev_chain_midi_paste(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t at_index);+NOTA_API int32_t nota_rackdev_chain_device_duplicate(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);+NOTA_API int32_t nota_rackdev_chain_midi_duplicate(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index);+NOTA_API int32_t nota_rackdev_chain_device_move_to(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index, int32_t to_chain);+NOTA_API int32_t nota_rackdev_chain_midi_move_to(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t index, int32_t to_chain);+/* One undo step for the in-place edits that follow on any rack (a fader drag, a mode or switch+ * change): the rack is forked now, keeping its children and held notes. device_index as above.+ * 1 = done. */+NOTA_API int32_t nota_rackdev_checkpoint(NotaEngine* engine, int32_t track_id, int32_t device_index);+/* A chain's identity while chains are added, removed or reordered and its instrument is edited:+ * the same value until the chain's instrument is swapped for another; 0 for no chain. Compare it,+ * don't decode it. */+NOTA_API int64_t nota_rackdev_chain_id(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+/* Load an audio file into chain `chain`'s Nota Grain (kind 10) with its root note; one undo step.+ * NOTA_OK, or NOTA_ERR_INVALID_ARG when the chain holds no Grain or the file can't be decoded. */+NOTA_API NotaResult nota_rackdev_chain_grain_set_sample(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const char* path, int32_t root_note);+/* 1 when the clipboard holds an audio effect keyed from another track. */+NOTA_API int32_t nota_device_clipboard_sidechain(const NotaEngine* engine);/* 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. */@@ -1762,6 +1796,46 @@ NOTA_API float nota_rack_swing(const NotaEngine* engine, int32_t track_id)NOTA_API void nota_rack_set_humanize(NotaEngine* engine, int32_t track_id, float v);NOTA_API float nota_rack_humanize(const NotaEngine* engine, int32_t track_id);+/* ---- Racks inside racks (specs/041) -----------------------------------------------+ * One level only: a chain of a track's Instrument Rack may hold a Drum Rack (inst_kind 4),+ * addressed by every nota_rackdev_* call as device_index NOTA_RACK_NESTED_BASE − chain.+ * Nota Mosaic (inst_kind 17) may be any instrument chain's instrument. The calls below are+ * the nota_rack_* surface a Drum Rack card needs, for any rack address. */+#define NOTA_RACK_NESTED_BASE (-100000)+NOTA_API int32_t nota_rackdev_add_sampler_chain(NotaEngine* engine, int32_t track_id, int32_t device_index, const char* path, int32_t root_note, int32_t loop);+NOTA_API int32_t nota_rackdev_set_chain_sampler_sample(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const char* path, int32_t root_note);+NOTA_API int32_t nota_rackdev_add_plugin_instrument_chain(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t catalog_index);+NOTA_API const char* nota_rackdev_chain_name(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API void nota_rackdev_set_chain_name(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const char* name);+NOTA_API int32_t nota_rackdev_chain_choke(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API void nota_rackdev_set_chain_choke(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t group);+NOTA_API int32_t nota_rackdev_chain_tune(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API void nota_rackdev_set_chain_tune(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t semitones);+NOTA_API float nota_rackdev_chain_decay(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API void nota_rackdev_set_chain_decay(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, float v);+NOTA_API float nota_rackdev_swing(const NotaEngine* engine, int32_t track_id, int32_t device_index);+NOTA_API void nota_rackdev_set_swing(NotaEngine* engine, int32_t track_id, int32_t device_index, float v);+NOTA_API float nota_rackdev_humanize(const NotaEngine* engine, int32_t track_id, int32_t device_index);+NOTA_API void nota_rackdev_set_humanize(NotaEngine* engine, int32_t track_id, int32_t device_index, float v);+NOTA_API int32_t nota_rackdev_chain_sampler_info(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, NotaSamplerInfo* out);+NOTA_API int32_t nota_rackdev_set_chain_sampler_root(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t root_note);+NOTA_API float nota_rackdev_chain_sampler_play_position(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API const char* nota_rackdev_chain_instrument_param_id(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t param);+NOTA_API float nota_rackdev_chain_instrument_param_default(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t param);+NOTA_API int32_t nota_rackdev_chain_instrument_scope(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, float* out, int32_t max_n);+NOTA_API int32_t nota_rackdev_chain_instrument_voice_count(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API int32_t nota_rackdev_chain_instrument_held_notes(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t* out, int32_t max_n);+NOTA_API void nota_rackdev_chain_instrument_action(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t id, int32_t iarg, float farg);+NOTA_API void nota_rackdev_open_chain_instrument_editor(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API const char* nota_rackdev_chain_instrument_plugin_id(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);+NOTA_API int32_t nota_rackdev_chain_instrument_get_state(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, uint8_t* out, int32_t capacity);+/* Nota Mosaic in a chain, as nota_track_mosaic_*: set_program with undoable = 1 is one undo+ * step (a fresh Mosaic swaps in), 0 a live edit in place; 1 / 0 = not a Mosaic chain. */+NOTA_API int32_t nota_rackdev_chain_mosaic_set_program(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const char* text_utf8, int32_t undoable);+NOTA_API int32_t nota_rackdev_chain_mosaic_program(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, char* out, int32_t cap);+NOTA_API int32_t nota_rackdev_chain_mosaic_status(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, NotaMosaicStatus* out);+NOTA_API int64_t nota_rackdev_chain_mosaic_zone_sample_id(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t zone);+/* ---- Audio Effect Rack (a RackDevice in a track's device chain) ----------* Same rack surface as nota_rack_* but addressed by a device_index (the rack* device's position in the track chain). Its chains are effects-only, so thediff --git a/src/native/nota.engine/src/abi/nota_engine_device.cpp b/src/native/nota.engine/src/abi/nota_engine_device.cppindex db7320f5..ce7cae74 100644--- a/src/native/nota.engine/src/abi/nota_engine_device.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_device.cpp@@ -68,6 +68,7 @@ NotaResult nota_track_copy_midi_effect(NotaEngine* e, int32_t track_id, int32_treturn ENG(e)->copyMidiEffect(track_id, index) ? NOTA_OK : NOTA_ERR_INVALID_ARG;}int32_t nota_device_clipboard_kind(const NotaEngine* e) { return e ? CENG(e)->deviceClipboardKind() : 0; }+int32_t nota_device_clipboard_sidechain(const NotaEngine* e) { return (e && CENG(e)->deviceClipboardSidechain()) ? 1 : 0; }int32_t nota_track_paste_device(NotaEngine* e, int32_t track_id, int32_t at_index) {return e ? ENG(e)->pasteDevice(track_id, at_index) : -1;}diff --git a/src/native/nota.engine/src/abi/nota_engine_rack.cpp b/src/native/nota.engine/src/abi/nota_engine_rack.cppindex 86573b1f..4aa029e8 100644--- a/src/native/nota.engine/src/abi/nota_engine_rack.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_rack.cpp@@ -222,6 +222,43 @@ int32_t nota_rack_duplicate_chain(NotaEngine* e, int32_t t, int32_t chain) {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;}++NotaResult nota_rackdev_chain_grain_set_sample(NotaEngine* e, int32_t t, int32_t di, int32_t c, const char* path, int32_t root) {+ if (!e || !path) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->rackChainGrainSetSample(t, di, c, path, root) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int64_t nota_rackdev_chain_id(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ return e ? CENG(e)->rackChainId(t, di, c) : 0;+}+int32_t nota_rackdev_checkpoint(NotaEngine* e, int32_t t, int32_t di) {+ return (e && ENG(e)->rackCheckpoint(t, di)) ? 1 : 0;+}++// Rack chain devices on the shared device clipboard (specs/042).+int32_t nota_rackdev_chain_device_copy(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i) {+ return (e && ENG(e)->rackChainDeviceCopy(t, di, c, i)) ? 1 : 0;+}+int32_t nota_rackdev_chain_midi_copy(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i) {+ return (e && ENG(e)->rackChainMidiCopy(t, di, c, i)) ? 1 : 0;+}+int32_t nota_rackdev_chain_device_paste(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t at) {+ return e ? ENG(e)->rackChainDevicePaste(t, di, c, at) : -1;+}+int32_t nota_rackdev_chain_midi_paste(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t at) {+ return e ? ENG(e)->rackChainMidiPaste(t, di, c, at) : -1;+}+int32_t nota_rackdev_chain_device_duplicate(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i) {+ return e ? ENG(e)->rackChainDeviceDuplicate(t, di, c, i) : -1;+}+int32_t nota_rackdev_chain_midi_duplicate(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i) {+ return e ? ENG(e)->rackChainMidiDuplicate(t, di, c, i) : -1;+}+int32_t nota_rackdev_chain_device_move_to(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i, int32_t to) {+ return e ? ENG(e)->rackChainDeviceMoveTo(t, di, c, i, to) : -1;+}+int32_t nota_rackdev_chain_midi_move_to(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t i, int32_t to) {+ return e ? ENG(e)->rackChainMidiMoveTo(t, di, c, i, to) : -1;+}void nota_rack_set_mono(NotaEngine* e, int32_t t, int32_t on) {if (e) ENG(e)->rackSetMono(t, on != 0);}@@ -841,4 +878,112 @@ int32_t nota_midirack_set_mapping_curve(NotaEngine* e, int32_t t, int32_t mi, inreturn (e && ENG(e)->rackSetMappingCurve(t, MR(mi), index, curve)) ? 1 : 0;}++// ---- specs/041: the nota_rack_* calls a Drum Rack card needs, for any rack address+// (device_index −1, an effect rack, or NOTA_RACK_NESTED_BASE − chain: a nested Drum Rack).+int32_t nota_rackdev_add_sampler_chain(NotaEngine* e, int32_t t, int32_t di, const char* path, int32_t root, int32_t loop) {+ return (e && path) ? ENG(e)->rackAddSamplerChain(t, di, std::string(path), root, loop != 0) : -1;+}+int32_t nota_rackdev_set_chain_sampler_sample(NotaEngine* e, int32_t t, int32_t di, int32_t chain, const char* path, int32_t root) {+ return (e && path && ENG(e)->rackSetChainSamplerSample(t, di, chain, std::string(path), root)) ? 1 : 0;+}+int32_t nota_rackdev_add_plugin_instrument_chain(NotaEngine* e, int32_t t, int32_t di, int32_t catalogIndex) {+ return e ? ENG(e)->rackAddPluginInstrumentChain(t, di, catalogIndex) : -1;+}+const char* nota_rackdev_chain_name(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ static std::string s;+ s = e ? CENG(e)->rackChainName(t, di, c) : std::string{};+ return s.c_str();+}+void nota_rackdev_set_chain_name(NotaEngine* e, int32_t t, int32_t di, int32_t c, const char* name) {+ if (e) ENG(e)->rackSetChainName(t, di, c, name ? name : "");+}+int32_t nota_rackdev_chain_choke(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ return e ? CENG(e)->rackChainChoke(t, di, c) : 0;+}+void nota_rackdev_set_chain_choke(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t g) {+ if (e) ENG(e)->rackSetChainChoke(t, di, c, g);+}+int32_t nota_rackdev_chain_tune(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ return e ? CENG(e)->rackChainTune(t, di, c) : 0;+}+void nota_rackdev_set_chain_tune(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t st) {+ if (e) ENG(e)->rackSetChainTune(t, di, c, st);+}+float nota_rackdev_chain_decay(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ return e ? CENG(e)->rackChainDecay(t, di, c) : 1.0f;+}+void nota_rackdev_set_chain_decay(NotaEngine* e, int32_t t, int32_t di, int32_t c, float v) {+ if (e) ENG(e)->rackSetChainDecay(t, di, c, v);+}+float nota_rackdev_swing(const NotaEngine* e, int32_t t, int32_t di) {+ return e ? CENG(e)->rackSwing(t, di) : 0.0f;+}+void nota_rackdev_set_swing(NotaEngine* e, int32_t t, int32_t di, float v) {+ if (e) ENG(e)->rackSetSwing(t, di, v);+}+float nota_rackdev_humanize(const NotaEngine* e, int32_t t, int32_t di) {+ return e ? CENG(e)->rackHumanize(t, di) : 0.0f;+}+void nota_rackdev_set_humanize(NotaEngine* e, int32_t t, int32_t di, float v) {+ if (e) ENG(e)->rackSetHumanize(t, di, v);+}+int32_t nota_rackdev_chain_sampler_info(const NotaEngine* e, int32_t t, int32_t di, int32_t c, NotaSamplerInfo* out) {+ return e && CENG(e)->rackChainSamplerInfo(t, di, c, out) ? 1 : 0;+}+int32_t nota_rackdev_set_chain_sampler_root(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t root) {+ return e && ENG(e)->rackSetChainSamplerRoot(t, di, c, root) ? 1 : 0;+}+float nota_rackdev_chain_sampler_play_position(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ return e ? CENG(e)->rackChainSamplerPlayPosition(t, di, c) : -1.0f;+}+const char* nota_rackdev_chain_instrument_param_id(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t p) {+ static std::string s;+ s = e ? CENG(e)->rackChainInstrumentParamId(t, di, c, p) : std::string{};+ return s.c_str();+}+float nota_rackdev_chain_instrument_param_default(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t p) {+ return e ? CENG(e)->rackChainInstrumentParamDefault(t, di, c, p) : 0.0f;+}+int32_t nota_rackdev_chain_instrument_scope(const NotaEngine* e, int32_t t, int32_t di, int32_t c, float* out, int32_t n) {+ return e ? CENG(e)->rackChainInstrumentScope(t, di, c, out, n) : 0;+}+int32_t nota_rackdev_chain_instrument_voice_count(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ return e ? CENG(e)->rackChainInstrumentVoiceCount(t, di, c) : -1;+}+int32_t nota_rackdev_chain_instrument_held_notes(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t* out, int32_t n) {+ return e ? CENG(e)->rackChainInstrumentHeldNotes(t, di, c, out, n) : 0;+}+void nota_rackdev_chain_instrument_action(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t id, int32_t iarg, float farg) {+ if (e) ENG(e)->rackChainInstrumentAction(t, di, c, id, iarg, farg);+}+void nota_rackdev_open_chain_instrument_editor(NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ if (e) ENG(e)->rackOpenChainInstrumentEditor(t, di, c);+}+const char* nota_rackdev_chain_instrument_plugin_id(const NotaEngine* e, int32_t t, int32_t di, int32_t c) {+ static std::string s;+ s = e ? CENG(e)->rackChainInstrumentPluginId(t, di, c) : std::string{};+ return s.c_str();+}+int32_t nota_rackdev_chain_instrument_get_state(const NotaEngine* e, int32_t t, int32_t di, int32_t c, uint8_t* out, int32_t cap) {+ return e ? CENG(e)->rackChainInstrumentGetState(t, di, c, out, cap) : 0;+}++// ---- Nota Mosaic as a chain instrument (specs/041) ----------------------------------+int32_t nota_rackdev_chain_mosaic_set_program(NotaEngine* e, int32_t t, int32_t di, int32_t c, const char* text, int32_t undoable) {+ return e && text && ENG(e)->rackChainMosaicSetProgram(t, di, c, std::string(text), undoable != 0) ? 1 : 0;+}+int32_t nota_rackdev_chain_mosaic_program(const NotaEngine* e, int32_t t, int32_t di, int32_t c, char* out, int32_t cap) {+ if (!e) return 0;+ const std::string s = CENG(e)->rackChainMosaicProgram(t, di, c);+ if (out && cap > 0) std::memcpy(out, s.data(), std::min<size_t>(s.size(), static_cast<size_t>(cap)));+ return static_cast<int32_t>(s.size());+}+int32_t nota_rackdev_chain_mosaic_status(const NotaEngine* e, int32_t t, int32_t di, int32_t c, NotaMosaicStatus* out) {+ return e && out && CENG(e)->rackChainMosaicStatus(t, di, c, out) ? 1 : 0;+}+int64_t nota_rackdev_chain_mosaic_zone_sample_id(const NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t zone) {+ return e ? CENG(e)->rackChainMosaicZoneSampleId(t, di, c, zone) : 0;+}+} // extern "C"diff --git a/src/native/nota.engine/src/devices/racks/RackCore.cpp b/src/native/nota.engine/src/devices/racks/RackCore.cppindex 9c0cd6ce..a62f2039 100644--- a/src/native/nota.engine/src/devices/racks/RackCore.cpp+++ b/src/native/nota.engine/src/devices/racks/RackCore.cpp@@ -22,6 +22,8 @@#include "devices/instruments/Keys.h"#include "devices/instruments/GrainSynth.h"#include "devices/instruments/Sampler.h"+#include "devices/instruments/Mosaic.h"+#include "DrumRack.h"#include "devices/DeviceFactory.h"#include <cmath>@@ -210,10 +212,34 @@ bool RackCore::setChainInstrument(int32_t chain, int32_t instKind) {if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return false;inst->setSampleRate(sampleRate_);ns->chains[chain].instrument = inst;+ ++ns->chains[chain].instGen; // another instrument: windows on the old one let gocommit(ns);return true;}+bool RackCore::replaceChainInstrument(int32_t chain, std::shared_ptr<Instrument> inst, bool prepare) {+ if (!inst) return false;+ auto ns = copyState();+ if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return false;+ if (prepare) inst->setSampleRate(sampleRate_);+ ns->chains[chain].instrument = std::move(inst);+ commit(ns);+ return true;+}++void RackCore::reapplyMacros() {+ for (int32_t i = 0; i < kNumMacros; ++i) applyMacro(i, macros_[i].load(std::memory_order_relaxed));+ for (int32_t c = 0; c < chainCount(); ++c)+ if (auto* inner = dynamic_cast<RackCore*>(chainInstrument(c))) inner->reapplyMacros();+}++uint64_t RackCore::chainUid(int32_t chain) const {+ RackState* st = live();+ if (!st || chain < 0 || chain >= static_cast<int32_t>(st->chains.size())) return 0;+ const auto& c = st->chains[chain];+ return (c.uid << 16) ^ (c.instGen & 0xFFFF);+}+int32_t RackCore::chainInstrumentKind(int32_t chain) const {RackState* st = live();if (!st || chain < 0 || chain >= static_cast<int32_t>(st->chains.size())) return -2;@@ -293,6 +319,45 @@ bool RackCore::moveChainDevice(int32_t chain, int32_t from, int32_t to) {return true;}+int32_t RackCore::insertChainDeviceInstance(int32_t chain, std::shared_ptr<Device> dev, int32_t at, bool prepare) {+ if (!dev) return -1;+ auto ns = copyState();+ if (chain < 0 || chain >= static_cast<int32_t>(ns->chains.size())) return -1;+ auto& d = ns->chains[chain].devices;+ const int32_t n = static_cast<int32_t>(d.size());+ if (at < 0 || at > n) at = n;+ if (prepare) dev->setSampleRate(sampleRate_, maxBlock_);+ d.insert(d.begin() + at, std::move(dev));+ for (auto& m : ns->mappings)+ if (m.chainIndex == chain && m.deviceIndex >= at) ++m.deviceIndex;+ commit(ns);+ return at;+}++int32_t RackCore::moveChainDeviceToChain(int32_t chain, int32_t idx, int32_t toChain) {+ auto ns = copyState();+ const int32_t nc = static_cast<int32_t>(ns->chains.size());+ if (chain < 0 || chain >= nc || toChain < 0 || toChain >= nc || toChain == chain) return -1;+ auto& from = ns->chains[chain].devices;+ if (idx < 0 || idx >= static_cast<int32_t>(from.size())) return -1;+ auto x = from[idx];+ from.erase(from.begin() + idx);+ auto& to = ns->chains[toChain].devices;+ const int32_t at = static_cast<int32_t>(to.size());+ to.push_back(std::move(x));+ for (auto& m : ns->mappings) {+ if (m.chainIndex != chain || m.deviceIndex < 0) continue;+ if (m.deviceIndex == idx) {+ m.chainIndex = toChain;+ m.deviceIndex = at;+ } else if (m.deviceIndex > idx) {+ --m.deviceIndex;+ }+ }+ commit(ns);+ return at;+}+Device* RackCore::chainDeviceAt(int32_t chain, int32_t dev) const {RackState* st = live();if (!st || chain < 0 || chain >= static_cast<int32_t>(st->chains.size())) return nullptr;@@ -375,6 +440,47 @@ bool RackCore::moveChainMidiDevice(int32_t chain, int32_t from, int32_t to) {return true;}+int32_t RackCore::insertChainMidiDeviceInstance(int32_t chain, std::shared_ptr<MidiDevice> dev, int32_t at) {+ 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;+ auto& d = ns->chains[chain].midiDevices;+ const int32_t n = static_cast<int32_t>(d.size());+ if (at < 0 || at > n) at = n;+ dev->setSampleRate(sampleRate_, maxBlock_);+ d.insert(d.begin() + at, std::move(dev));+ for (auto& m : ns->mappings)+ if (m.chainIndex == chain && isMidiTarget(m.deviceIndex) && midiTargetIndex(m.deviceIndex) >= at)+ m.deviceIndex = midiTarget(midiTargetIndex(m.deviceIndex) + 1);+ commit(ns);+ return at;+}++int32_t RackCore::moveChainMidiDeviceToChain(int32_t chain, int32_t idx, int32_t toChain) {+ auto ns = copyState();+ const int32_t nc = static_cast<int32_t>(ns->chains.size());+ if (chain < 0 || chain >= nc || toChain < 0 || toChain >= nc || toChain == chain) return -1;+ auto& from = ns->chains[chain].midiDevices;+ if (idx < 0 || idx >= static_cast<int32_t>(from.size())) return -1;+ auto x = from[idx];+ from.erase(from.begin() + idx);+ auto& to = ns->chains[toChain].midiDevices;+ const int32_t at = static_cast<int32_t>(to.size());+ to.push_back(std::move(x));+ for (auto& m : ns->mappings) {+ if (m.chainIndex != chain || !isMidiTarget(m.deviceIndex)) continue;+ const int32_t j = midiTargetIndex(m.deviceIndex);+ if (j == idx) {+ m.chainIndex = toChain;+ m.deviceIndex = midiTarget(at);+ } else if (j > idx) {+ m.deviceIndex = midiTarget(j - 1);+ }+ }+ commit(ns);+ return at;+}+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;@@ -601,8 +707,16 @@ std::vector<uint8_t> RackCore::serialize() const {return b;}+// Depth of the rack blob being read on this thread: a chain of a blob read at depth > 0 is+// itself inside a nested rack, and racks nest one level (specs/041).+static thread_local int32_t tlReadDepth = 0;+void RackCore::deserialize(const uint8_t* data, int32_t size) {if (!data || size < 8) return;+ struct DepthScope {+ DepthScope() { ++tlReadDepth; }+ ~DepthScope() { --tlReadDepth; }+ } depth;Cursor cur{data, size, 0};if (getU32(cur) != kMagic) return;const uint32_t ver = getU32(cur); // v1 = no triggerNote; v2 adds it per chain@@ -667,7 +781,7 @@ void RackCore::deserialize(const uint8_t* data, int32_t size) {const uint8_t* isPtr = cur.take(isLen);if (ik == -1) // hosted plugin (via factory) or no instrument (empty id)c.instrument = instPluginId.empty() ? nullptr : pluginFactory().instrumentById(instPluginId);- else+ else if (!isRackKind(ik) || tlReadDepth == 1)c.instrument = makeInstrument(ik);if (c.instrument) {c.instrument->setSampleRate(sampleRate_);@@ -780,6 +894,8 @@ std::shared_ptr<Instrument> RackCore::makeInstrument(int32_t kind) {case 14: return std::make_shared<Pentad>();case 15: return std::make_shared<Consort>();case 16: return std::make_shared<Keys>();+ case 17: return std::make_shared<Mosaic>(); // empty: the program rides its state or the engine+ case 4: return std::make_shared<DrumRack>(); // nested Drum Rack (specs/041)default: return nullptr; // -1 = no instrument (effect rack); plugins are a follow-up}}diff --git a/src/native/nota.engine/src/devices/racks/RackCore.h b/src/native/nota.engine/src/devices/racks/RackCore.hindex 4cc76a4f..b74dcd30 100644--- a/src/native/nota.engine/src/devices/racks/RackCore.h+++ b/src/native/nota.engine/src/devices/racks/RackCore.h@@ -68,7 +68,20 @@ class RackCore {std::atomic<float> velScale{1.0f}; // 0..2};+ // A chain's identity for the UI (a window that follows its chain): every new chain takes+ // the next number, and copies of the rack state (forks for undo) keep it.+ static uint64_t nextChainUid() {+ static std::atomic<uint64_t> next{1};+ return next.fetch_add(1, std::memory_order_relaxed);+ }+struct RackChain {+ uint64_t uid = nextChainUid();+ // Bumped when the chain's instrument is swapped for another (setChainInstrument); an+ // edit of the same instrument (a nested rack's fork, a Mosaic program, a Grain sample)+ // keeps it. The chain id the UI follows is uid + this, so a window for the old+ // instrument lets go of a replacement.+ uint32_t instGen = 0;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;@@ -185,6 +198,12 @@ class RackCore {// Returns the new chain index or -1.int32_t duplicateChain(int32_t chain);bool setChainInstrument(int32_t chain, int32_t instKind);+ // Puts a ready instrument at the head of a chain, keeping the chain's devices, MIDI effects,+ // controls and mappings (a chain Mosaic's new program, a nested Drum Rack's fork). specs/041.+ // `prepare` = false for an instrument already prepared at this rate whose children are shared+ // with a playing copy (a nested rack's fork): preparing them again would reset live effects.+ bool replaceChainInstrument(int32_t chain, std::shared_ptr<Instrument> inst, bool prepare = true);+ uint64_t chainUid(int32_t chain) const; // uid and instrument generation, see RackChainint32_t chainInstrumentKind(int32_t chain) const;Instrument* chainInstrument(int32_t chain) const;int32_t chainDeviceCount(int32_t chain) const;@@ -195,6 +214,12 @@ class RackCore {int32_t addChainDeviceInstance(int32_t chain, std::shared_ptr<Device> dev, bool prepare = true);bool removeChainDevice(int32_t chain, int32_t dev);bool moveChainDevice(int32_t chain, int32_t from, int32_t to);+ // Insert a device at `at` (−1 or past the end = the end); the chain's mappings at or after+ // `at` shift up, the new device has none (specs/042). Returns its index, or −1.+ int32_t insertChainDeviceInstance(int32_t chain, std::shared_ptr<Device> dev, int32_t at, bool prepare = true);+ // Move device `idx` to the end of `toChain`'s effects; its mappings follow it (specs/042).+ // Returns its new index, or −1 (bad address, or the same chain).+ int32_t moveChainDeviceToChain(int32_t chain, int32_t idx, int32_t toChain);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).@@ -203,6 +228,8 @@ class RackCore {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);+ int32_t insertChainMidiDeviceInstance(int32_t chain, std::shared_ptr<MidiDevice> dev, int32_t at);+ int32_t moveChainMidiDeviceToChain(int32_t chain, int32_t idx, int32_t toChain);MidiDevice* chainMidiDeviceAt(int32_t chain, int32_t idx) const;ChainControls* chainControls(int32_t chain) const;@@ -378,10 +405,10 @@ class RackCore {// 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));- }+ // copy's mappings gave them (specs/040). A rack nested in a chain (a Drum Rack in an+ // Instrument Rack chain, specs/041) shares its children with its undo copies too, so it is+ // driven again as well. Message thread.+ void reapplyMacros();// ---- undoable edits ---------------------------------------------------// Take over another rack's content (#236). The engine edits a copy of the rack instead@@ -401,8 +428,11 @@ class RackCore {public:// Built-in instrument factory (public so the Engine can read a fresh one's param- // defaults for a chain instrument, e.g. double-click reset on Sampler knobs).+ // defaults for a chain instrument, e.g. double-click reset on Sampler knobs). Kind 17 is an+ // empty Nota Mosaic; kind 4 an empty Drum Rack, built only outside a rack being read+ // (racks nest one level, specs/041 — the engine decides where a Drum Rack may go).static std::shared_ptr<Instrument> makeInstrument(int32_t kind);+ static bool isRackKind(int32_t kind) { return kind == 3 || kind == 4; }protected:static std::shared_ptr<Device> makeDevice(int32_t kind) { return makeChainDevice(kind); }diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 3f8180da..dc0a3a59 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -883,8 +883,42 @@ class Engine {// 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);+ // Rack chain devices on the shared device clipboard (specs/042). Copy fills clipDevice_ /+ // clipMidi_; Paste inserts a fresh clone at `at` (−1 = the end) and returns its index or+ // −1 nothing / bad address, −2 wrong family for the section, −3 a rack inside a rack,+ // −5 a MIDI effect past the Instrument Rack's 16 MIDI chains. A pasted audio effect loses+ // its sidechain key. Duplicate inserts a clone right after; MoveTo moves a device to the end+ // of another chain of the same rack, mappings and all. Each edit is one rack fork.+ bool rackChainDeviceCopy(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index);+ bool rackChainMidiCopy(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index);+ int32_t rackChainDevicePaste(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t at);+ int32_t rackChainMidiPaste(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t at);+ int32_t rackChainDeviceDuplicate(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index);+ int32_t rackChainMidiDuplicate(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index);+ int32_t rackChainDeviceMoveTo(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index, int32_t toChain);+ int32_t rackChainMidiMoveTo(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t index, int32_t toChain);+ bool deviceClipboardSidechain() const;+ // A chain's identity for a window that must follow it while chains move: a number every new+ // chain takes and every fork of the rack keeps (nested edits too), changed when the chain's+ // instrument is swapped for another; 0 for a bad address.+ int64_t rackChainId(int32_t trackId, int32_t deviceIndex, int32_t chain) const;+ // Load a sample into a chain's Nota Grain (a factory Grain preset's source), one undo step.+ bool rackChainGrainSetSample(int32_t trackId, int32_t deviceIndex, int32_t chain, const std::string& path, int32_t rootNote);// A MIDI Effect Rack is addressed as deviceIndex kMidiRackBase − its MIDI effect index.static constexpr int32_t kMidiRackBase = -1000;+ // A Drum Rack in chain c of the track's Instrument Rack is addressed as kNestedRackBase − c+ // (racks nest one level, specs/041). Below the MIDI-rack range: test it first.+ static constexpr int32_t kNestedRackBase = -100000;+ static bool isNestedRack(int32_t deviceIndex) { return deviceIndex <= kNestedRackBase; }+ // Whether a chain of the rack at (trackId, deviceIndex) may take instrument `kind`.+ bool rackKindAllowed(int32_t trackId, int32_t deviceIndex, int32_t kind) const;+ // Nota Mosaic as a chain instrument (specs/041), mirroring mosaicSetProgram & co. for a+ // track: checkpoint = an undoable edit (a fresh Mosaic swaps into a fork of the rack).+ bool rackChainMosaicSetProgram(+ int32_t trackId, int32_t deviceIndex, int32_t chain, const std::string& text, bool checkpoint);+ std::string rackChainMosaicProgram(int32_t trackId, int32_t deviceIndex, int32_t chain) const;+ bool rackChainMosaicStatus(int32_t trackId, int32_t deviceIndex, int32_t chain, NotaMosaicStatus* out) const;+ int64_t rackChainMosaicZoneSampleId(int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t zone) const;// 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);@@ -1248,6 +1282,7 @@ class Engine {std::shared_ptr<Track> findTrackAuthoring(int32_t id) const;std::shared_ptr<Track> cloneTrack(const Track& t) const;std::shared_ptr<SampleBuffer> findSampleById(int64_t sampleId) const; // M7-6b+ static std::shared_ptr<SampleBuffer> chainSampleById(const RackCore* rack, int64_t sampleId, int depth);void publish(std::shared_ptr<Graph> g); // checkpoints (undo), then publishRawvoid publishRaw(std::shared_ptr<Graph> g); // swap live/authoring only, no undo entryvoid configureClipWarp(AudioClip& c, double spb, double devSR); // build the clip's warp cache (unless deferred)diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cppindex aaaef910..764daeb6 100644--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp@@ -785,6 +785,8 @@ bool Engine::copyMidiEffect(int32_t trackId, int32_t index) {int32_t Engine::deviceClipboardKind() const { return clipDevice_ ? 1 : clipMidi_ ? 2 : 0; }+bool Engine::deviceClipboardSidechain() const { return clipDevice_ && clipDevice_->sidechainSourceTrackId() >= 0; }+int32_t Engine::pasteDevice(int32_t trackId, int32_t atIndex) {return clipDevice_ ? insertDeviceClone(trackId, cloneDevice(*clipDevice_), atIndex) : -1;}diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cppindex 3b80eaef..be6a84e7 100644--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp@@ -4,7 +4,9 @@// 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+// effect rack at MIDI index kMidiRackBase − deviceIndex, specs/040; <= kNestedRackBase = the+// Drum Rack in chain kNestedRackBase − deviceIndex of the track's Instrument Rack, specs/041)+// 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.@@ -18,6 +20,8 @@#include "devices/racks/DrumRack.h"#include "devices/racks/MidiRack.h"#include "devices/instruments/Sampler.h"+#include "devices/instruments/Mosaic.h"+#include "devices/instruments/GrainSynth.h"#include "SnapshotHistory.h"#include <algorithm>@@ -71,7 +75,7 @@ int32_t Engine::addInstrumentRackTrack() {auto track = std::make_shared<Track>(id, TrackType::Instrument);auto rack = std::make_shared<RackInstrument>();rack->setSampleRate(transport_.sampleRate());- rack->addChain(6); // one default Nota Volt chain (specs/026)+ // No chains: the card invites an instrument dropped on it (the Volt default of specs/026 is gone).track->instrument = rack;g->tracks.push_back(track);publish(g);@@ -128,9 +132,20 @@ bool Engine::rackSetChainSamplerSample(return rackForEdit(t, di)->setChainInstrumentSample(chain, buf, rootNote, false);}+// The track's plain Instrument Rack (not a Drum Rack): the only rack whose chains take a rack.+static RackInstrument* nestingHost(const std::shared_ptr<Track>& t) {+ auto* r = t ? dynamic_cast<RackInstrument*>(t->instrument.get()) : nullptr;+ return (r && !dynamic_cast<DrumRack*>(r)) ? r : nullptr;+}+RackCore* Engine::rackCoreAt(int32_t trackId, int32_t deviceIndex) const {auto t = findTrackAuthoring(trackId);if (!t) return nullptr;+ if (isNestedRack(deviceIndex)) {+ auto* host = nestingHost(t);+ return host ? dynamic_cast<RackCore*>(dynamic_cast<RackInstrument*>(host->chainInstrument(kNestedRackBase - deviceIndex)))+ : nullptr;+ }if (deviceIndex <= kMidiRackBase) {const int32_t mi = kMidiRackBase - deviceIndex;if (mi >= static_cast<int32_t>(t->midiEffects.size()) || !t->midiEffects[mi]) return nullptr;@@ -146,9 +161,25 @@ RackCore* Engine::rackCoreAt(int32_t trackId, int32_t deviceIndex) const {// graph snapshot, so undo had nothing to go back to (#236). An edit the user can undo// forks the rack into a new object (chain children shared, so nothing restarts) and// republishes the track with it; the snapshot on the undo stack keeps the old rack as it was.+// A Drum Rack in a fork of an Instrument Rack chain: a fork of its own, put in its chain.+static std::shared_ptr<RackInstrument> forkRackInstrument(const RackInstrument& src);+RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {auto old = findTrackAuthoring(trackId);if (!old || !rackCoreAt(trackId, deviceIndex)) return nullptr;+ if (isNestedRack(deviceIndex)) {+ // Fork the outer rack (one undo step: the snapshot keeps the old outer rack, which keeps+ // the old nested one), then the nested rack inside the fork.+ const int32_t c = kNestedRackBase - deviceIndex;+ auto* outer = rackForEdit(trackId, -1);+ auto* src = outer ? dynamic_cast<RackInstrument*>(outer->chainInstrument(c)) : nullptr;+ if (!src) return nullptr;+ auto r = forkRackInstrument(*src);+ RackCore* fresh = r.get();+ // The fork shares the playing Drum Rack's pads and effects, already prepared: install it+ // without preparing them again (that would clear a reverb's tail mid-play).+ return outer->replaceChainInstrument(c, std::move(r), /*prepare=*/false) ? fresh : nullptr;+ }auto nt = cloneTrack(*old);RackCore* fresh = nullptr;if (deviceIndex <= kMidiRackBase) {@@ -168,22 +199,7 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {if (deviceIndex < 0) {auto* src = dynamic_cast<RackInstrument*>(old->instrument.get());if (!src) return nullptr;- std::shared_ptr<RackInstrument> r;- 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 on- r->setBypassed(src->bypassed());- r->folded = src->folded;- // Playback state the audio thread owns: relaxed atomics, carried over so a held pedal- // still releases its notes after the edit.- constexpr auto rl = std::memory_order_relaxed;- r->offSettled.store(src->offSettled.load(rl), rl);- r->pedalDown.store(src->pedalDown.load(rl), rl);- r->pedalHeld[0].store(src->pedalHeld[0].load(rl), rl);- r->pedalHeld[1].store(src->pedalHeld[1].load(rl), rl);- for (int i = 0; i < kCtlCount; ++i)- r->deliveredCtl[i].store(src->deliveredCtl[i].load(std::memory_order_relaxed), std::memory_order_relaxed);+ auto r = forkRackInstrument(*src);fresh = r.get();nt->instrument = std::move(r);} else {@@ -204,6 +220,32 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {return fresh;}+static std::shared_ptr<RackInstrument> forkRackInstrument(const RackInstrument& src) {+ std::shared_ptr<RackInstrument> r;+ if (dynamic_cast<const 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 on+ r->setBypassed(src.bypassed());+ r->folded = src.folded;+ // Playback state the audio thread owns: relaxed atomics, carried over so a held pedal+ // still releases its notes after the edit.+ constexpr auto rl = std::memory_order_relaxed;+ r->offSettled.store(src.offSettled.load(rl), rl);+ r->pedalDown.store(src.pedalDown.load(rl), rl);+ r->pedalHeld[0].store(src.pedalHeld[0].load(rl), rl);+ r->pedalHeld[1].store(src.pedalHeld[1].load(rl), rl);+ for (int i = 0; i < kCtlCount; ++i) r->deliveredCtl[i].store(src.deliveredCtl[i].load(rl), rl);+ return r;+}++// Racks nest one level (specs/041): an Instrument Rack chain may hold a Drum Rack; nothing+// else takes a rack, and an Instrument Rack is never a chain instrument.+bool Engine::rackKindAllowed(int32_t trackId, int32_t deviceIndex, int32_t kind) const {+ if (!RackCore::isRackKind(kind)) return true;+ return kind == 4 && deviceIndex == -1 && nestingHost(findTrackAuthoring(trackId)) != nullptr;+}+// ---- wrap a device in a rack / unwrap it (#257) ----------------------------// Whether anything outside the device points at it by its chain index: automation lanes// CV links, or an Arp's CC target. Wrapping moves the device into a rack chain, where those can't follow it.@@ -281,7 +323,7 @@ int32_t Engine::rackChainCount(int32_t t, int32_t di) const {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 (!isNestedRack(di) && 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.@@ -292,6 +334,93 @@ int32_t Engine::rackDuplicateChain(int32_t t, int32_t di, int32_t c) {return rackForEdit(t, di)->duplicateChain(c);}bool Engine::rackCheckpoint(int32_t t, int32_t di) { return rackForEdit(t, di) != nullptr; }+int64_t Engine::rackChainId(int32_t t, int32_t di, int32_t c) const {+ auto* r = rackCoreAt(t, di);+ return r ? static_cast<int64_t>(r->chainUid(c)) : 0;+}++// ---- chain devices on the device clipboard (specs/042) ----------------------------------+namespace {+// Which sections a rack's chains have: a MIDI Effect Rack only MIDI effects, an Audio Effect+// Rack and a Drum Rack only audio effects, an Instrument Rack both.+bool rackTakesAudio(const RackCore* r) { return !dynamic_cast<const MidiRack*>(r); }+bool rackTakesMidi(const RackCore* r) {+ if (dynamic_cast<const MidiRack*>(r)) return true;+ return dynamic_cast<const RackInstrument*>(r) && !dynamic_cast<const DrumRack*>(r);+}+} // namespace++bool Engine::rackChainDeviceCopy(int32_t t, int32_t di, int32_t c, int32_t i) {+ auto* r = rackCoreAt(t, di);+ Device* src = r ? r->chainDeviceAt(c, i) : nullptr;+ auto copy = src ? cloneDevice(*src) : nullptr;+ if (!copy) return false;+ clipDevice_ = std::move(copy);+ clipMidi_.reset();+ return true;+}+bool Engine::rackChainMidiCopy(int32_t t, int32_t di, int32_t c, int32_t i) {+ auto* r = rackCoreAt(t, di);+ MidiDevice* src = r ? r->chainMidiDeviceAt(c, i) : nullptr;+ auto copy = src ? cloneMidiDevice(*src) : nullptr;+ if (!copy) return false;+ clipMidi_ = std::move(copy);+ clipDevice_.reset();+ return true;+}+int32_t Engine::rackChainDevicePaste(int32_t t, int32_t di, int32_t c, int32_t at) {+ auto* r = rackCoreAt(t, di);+ if (!r || c < 0 || c >= r->chainCount()) return -1;+ if (!clipDevice_) return clipMidi_ ? -2 : -1;+ if (!rackTakesAudio(r)) return -2;+ if (dynamic_cast<const RackDevice*>(clipDevice_.get())) return -3;+ auto dev = cloneDevice(*clipDevice_);+ if (!dev) return -1;+ dev->setSidechainSourceTrackId(-1); // a chain has no sidechain input+ const int32_t idx = rackForEdit(t, di)->insertChainDeviceInstance(c, std::move(dev), at);+ recomputePdc();+ return idx;+}+int32_t Engine::rackChainMidiPaste(int32_t t, int32_t di, int32_t c, int32_t at) {+ auto* r = rackCoreAt(t, di);+ if (!r || c < 0 || c >= r->chainCount()) return -1;+ if (!clipMidi_) return clipDevice_ ? -2 : -1;+ if (!rackTakesMidi(r)) return -2;+ if (clipMidi_->midiKind() < 0 || clipMidi_->midiKind() > 5) return -3; // a MIDI Effect Rack+ if (di == -1 && c >= RackInstrument::kMaxMidiChains) return -5;+ auto dev = cloneMidiDevice(*clipMidi_);+ if (!dev) return -1;+ return rackForEdit(t, di)->insertChainMidiDeviceInstance(c, std::move(dev), at);+}+int32_t Engine::rackChainDeviceDuplicate(int32_t t, int32_t di, int32_t c, int32_t i) {+ auto* r = rackCoreAt(t, di);+ Device* src = r ? r->chainDeviceAt(c, i) : nullptr;+ auto dev = src ? cloneDevice(*src) : nullptr;+ if (!dev) return -1;+ const int32_t idx = rackForEdit(t, di)->insertChainDeviceInstance(c, std::move(dev), i + 1);+ recomputePdc();+ return idx;+}+int32_t Engine::rackChainMidiDuplicate(int32_t t, int32_t di, int32_t c, int32_t i) {+ auto* r = rackCoreAt(t, di);+ MidiDevice* src = r ? r->chainMidiDeviceAt(c, i) : nullptr;+ auto dev = src ? cloneMidiDevice(*src) : nullptr;+ if (!dev) return -1;+ return rackForEdit(t, di)->insertChainMidiDeviceInstance(c, std::move(dev), i + 1);+}+int32_t Engine::rackChainDeviceMoveTo(int32_t t, int32_t di, int32_t c, int32_t i, int32_t to) {+ auto* r = rackCoreAt(t, di);+ if (!r || !r->chainDeviceAt(c, i) || to < 0 || to >= r->chainCount() || to == c) return -1;+ const int32_t idx = rackForEdit(t, di)->moveChainDeviceToChain(c, i, to);+ recomputePdc();+ return idx;+}+int32_t Engine::rackChainMidiMoveTo(int32_t t, int32_t di, int32_t c, int32_t i, int32_t to) {+ auto* r = rackCoreAt(t, di);+ if (!r || !r->chainMidiDeviceAt(c, i) || to < 0 || to >= r->chainCount() || to == c) return -1;+ if (di == -1 && to >= RackInstrument::kMaxMidiChains) return -5;+ return rackForEdit(t, di)->moveChainMidiDeviceToChain(c, i, to);+}bool Engine::rackMono(int32_t t) const {auto* r = rackCoreAt(t, -1);return r && r->rackMono();@@ -300,7 +429,13 @@ 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;+ // Audio Effect and MIDI Effect Rack chains hold no instrument, whatever kind is asked for+ // (MCP add_effect_rack_chain long passed 4, which is now the Drum Rack).+ if (!isNestedRack(di) && (di >= 0 || di <= kMidiRackBase)) k = -1;+ if (!rackKindAllowed(t, di, k)) return -1;+ if (auto* cur = rackCoreAt(t, di);+ cur && !isNestedRack(di) && di <= kMidiRackBase && cur->chainCount() >= MidiRack::kMaxChains)+ return -1;auto* r = rackForEdit(t, di);return r ? r->addChain(k) : -1;}@@ -313,8 +448,10 @@ bool Engine::rackRemoveChain(int32_t t, int32_t di, int32_t c) {}bool Engine::rackSetChainInstrument(int32_t t, int32_t di, int32_t c, int32_t k) {auto* r = rackCoreAt(t, di);- if (!r || c < 0 || c >= r->chainCount() || !RackCore::makeInstrument(k)) return false;- return rackForEdit(t, di)->setChainInstrument(c, k);+ if (!r || c < 0 || c >= r->chainCount() || !rackKindAllowed(t, di, k) || !RackCore::makeInstrument(k)) return false;+ const bool ok = rackForEdit(t, di)->setChainInstrument(c, k);+ recomputePdc();+ return ok;}int32_t Engine::rackChainInstrumentKind(int32_t t, int32_t di, int32_t c) const {auto* r = rackCoreAt(t, di);@@ -404,6 +541,68 @@ int32_t Engine::rackChainInstrumentGetState(int32_t t, int32_t di, int32_t c, uireturn static_cast<int32_t>(v.size());}+// ---- chain Mosaic (built-in multisample instrument, specs/041) -------------+// Mirrors mosaicSetProgram & co. (Engine_Devices.cpp) for a chain instrument.+bool Engine::rackChainMosaicSetProgram(int32_t t, int32_t di, int32_t c, const std::string& text, bool checkpoint) {+ auto* r = rackCoreAt(t, di);+ auto* m = r ? dynamic_cast<Mosaic*>(r->chainInstrument(c)) : nullptr;+ if (!m) return false;+ if (!checkpoint) { // live edit: in place, voices keep going+ m->setProgram(text);+ return true;+ }+ // An undoable edit puts a fresh Mosaic (params + the samples it already holds, so a zone+ // edit is ready at once) into a fork of the rack; undo brings the old one back.+ auto fresh = std::static_pointer_cast<Mosaic>(m->clone());+ fresh->setProgram(text);+ auto* fr = rackForEdit(t, di);+ return fr && fr->replaceChainInstrument(c, std::move(fresh));+}+// ---- chain Grain sample (a factory Grain preset dropped on a rack, specs/041 review) --------+// Mirrors setTrackGrainSample: a fresh Grain with the chain's values and the sample goes into a+// fork of the rack, so undo brings the old one back.+bool Engine::rackChainGrainSetSample(int32_t t, int32_t di, int32_t c, const std::string& path, int32_t rootNote) {+ auto* r = rackCoreAt(t, di);+ auto* gr = r ? dynamic_cast<GrainSynth*>(r->chainInstrument(c)) : nullptr;+ if (!gr) return false;+ auto sample = decodeAudioFile(path);+ if (!sample || sample->empty()) return false;+ auto fresh = std::make_shared<GrainSynth>();+ fresh->setSampleRate(transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0);+ for (int i = 0; i < gr->pluginParamCount(); ++i) fresh->pluginParamSet(i, gr->pluginParamGet(i));+ fresh->setSample(sample, rootNote, false);+ auto* fr = rackForEdit(t, di);+ return fr && fr->replaceChainInstrument(c, std::move(fresh));+}++std::string Engine::rackChainMosaicProgram(int32_t t, int32_t di, int32_t c) const {+ auto* r = rackCoreAt(t, di);+ auto* m = r ? dynamic_cast<Mosaic*>(r->chainInstrument(c)) : nullptr;+ return m ? m->programText() : std::string{};+}+bool Engine::rackChainMosaicStatus(int32_t t, int32_t di, int32_t c, NotaMosaicStatus* out) const {+ auto* r = rackCoreAt(t, di);+ auto* m = r ? dynamic_cast<Mosaic*>(r->chainInstrument(c)) : nullptr;+ if (!m || !out) return false;+ const auto s = m->status();+ out->state = s.state;+ out->files_done = s.filesDone;+ out->files_total = s.filesTotal;+ out->missing = s.missing;+ out->zones = s.zones;+ out->serial = s.serial;+ out->disk_done = s.diskDone;+ out->disk_total = s.diskTotal;+ out->ram_bytes = s.ram;+ return true;+}+int64_t Engine::rackChainMosaicZoneSampleId(int32_t t, int32_t di, int32_t c, int32_t zone) const {+ auto* r = rackCoreAt(t, di);+ auto* m = r ? dynamic_cast<Mosaic*>(r->chainInstrument(c)) : nullptr;+ auto b = m ? m->zoneSample(zone) : nullptr;+ return b ? b->id : 0;+}+// ---- chain Sampler (built-in) --------------------------------------------// A chain's instrument may be a built-in Sampler; these mirror the track-level// samplerInfo/setTrackSamplerRoot/samplerPlayPosition so the rich Sampler editordiff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cppindex 570b4cbe..9e6e5a05 100644--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp@@ -45,11 +45,23 @@ std::shared_ptr<SampleBuffer> Engine::findSampleById(int64_t sampleId) const {for (int v = 0; v < RhythmMachine::kVoices; ++v)if (auto b = rh->voiceSampleBuf(v))if (b->id == sampleId) return b;- // Samplers nested in a rack's chains (Drum Rack pads / Instrument Rack chains).- if (auto* rack = dynamic_cast<RackCore*>(t->instrument.get()))- for (int32_t c = 0; c < rack->chainCount(); ++c)- if (auto* smp = dynamic_cast<Sampler*>(rack->chainInstrument(c)))- if (smp->sample() && smp->sample()->id == sampleId) return smp->sample();+ // Samplers and Mosaics in a rack's chains (Drum Rack pads / Instrument Rack chains), and+ // in the pads of a Drum Rack nested in a chain (specs/041).+ if (auto b = chainSampleById(dynamic_cast<RackCore*>(t->instrument.get()), sampleId, 0)) return b;+ }+ return nullptr;+}++std::shared_ptr<SampleBuffer> Engine::chainSampleById(const RackCore* rack, int64_t sampleId, int depth) {+ if (!rack || depth > 1) return nullptr;+ for (int32_t c = 0; c < rack->chainCount(); ++c) {+ Instrument* inst = rack->chainInstrument(c);+ if (auto* smp = dynamic_cast<Sampler*>(inst))+ if (smp->sample() && smp->sample()->id == sampleId) return smp->sample();+ if (auto* mo = dynamic_cast<Mosaic*>(inst))+ for (auto& b : mo->samples())+ if (b->id == sampleId) return b;+ if (auto b = chainSampleById(dynamic_cast<RackCore*>(inst), sampleId, depth + 1)) return b;}return nullptr;}diff --git a/tests/Nota.SmokeTest/DesignTokenCheck.cs b/tests/Nota.SmokeTest/DesignTokenCheck.csindex 7926d84a..03f68a4f 100644--- a/tests/Nota.SmokeTest/DesignTokenCheck.cs+++ b/tests/Nota.SmokeTest/DesignTokenCheck.cs@@ -360,7 +360,7 @@ internal static partial class DesignTokenCheck// two device hue tables. Each is only ever painted through NotaPalette.Ink().var hexData = new[] { "TagEditorWindow.cs", "DeviceCards/Bodies/StrataDeviceBody.cs", "DeviceCards/Instruments/RhythmInstrumentCard.cs" };// Opacity is allowed for exactly one thing: the ghost of a card being dragged.- var dragGhost = new Regex(@"\b(card|_devDragCard)\.Opacity = (0\.55|1\.0);");+ var dragGhost = new Regex(@"\b(card|_devDragCard|_rcDragCard)\.Opacity = (0\.55|1\.0);");var rules = new (string Name, Regex Re, Func<string, string, bool>? Allow)[]{diff --git a/tests/Nota.SmokeTest/DeviceCopyTests.cs b/tests/Nota.SmokeTest/DeviceCopyTests.csindex 121975df..007a5717 100644--- a/tests/Nota.SmokeTest/DeviceCopyTests.cs+++ b/tests/Nota.SmokeTest/DeviceCopyTests.cs@@ -352,6 +352,8 @@ internal static class DeviceCopyTests{using var e = new NotaEngine();int t = e.AddInstrumentRackTrack();+ e.RackAddChain(t, 6); // a Nota Volt chain first (a new rack starts empty)+ e.ClearUndoHistory();int c = e.RackAddChain(t, 0);yield return (e.RackChainCount(t) == 2 && e.Undo() && e.RackChainCount(t) == 1, "rack undo: an added Instrument Rack chain");e.RackSetChainZone(t, 0, 36, 60, 0, 127);diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 0b0c01a9..fe215b03 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -9700,8 +9700,9 @@ Console.WriteLine("-- Instrument Rack: C ABI + persistence --");using var re = new NotaEngine();int rt = re.AddInstrumentRackTrack();Check(rt > 0, "rack track created");- Check(re.RackChainCount(rt) == 1, "rack starts with one chain");- Check(re.RackChainInstrumentKind(rt, 0) == 6, "default chain hosts Nota Volt");+ Check(re.RackChainCount(rt) == 0, "a new rack starts with no chains");+ re.RackAddChain(rt, 6);+ Check(re.RackChainCount(rt) == 1 && re.RackChainInstrumentKind(rt, 0) == 6, "chain 0 hosts Nota Volt");int c2 = re.RackAddChain(rt, 2); // Nota PhysicalCheck(c2 == 1 && re.RackChainCount(rt) == 2, "second chain added");@@ -15191,4 +15192,4 @@ Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({fareturn failures == 0 ? 0 : 1;static IEnumerable<(string title, Func<IEnumerable<(bool ok, string label)>> run)> RackSections() =>- RackRedesignTests.Sections().Concat(MidiRackTests.Sections()).Concat(RackChainMidiTests.Sections());+ RackRedesignTests.Sections().Concat(MidiRackTests.Sections()).Concat(RackChainMidiTests.Sections()).Concat(RackNestingTests.Sections()).Concat(RackClipboardTests.Sections());diff --git a/tests/Nota.SmokeTest/RackClipboardTests.cs b/tests/Nota.SmokeTest/RackClipboardTests.csnew file mode 100644index 00000000..6d3eee20--- /dev/null+++ b/tests/Nota.SmokeTest/RackClipboardTests.cs@@ -0,0 +1,311 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Moving, copying and pasting devices in rack chains (specs/042). A rack chain device moves+// within its section and onto another chain of the same rack, keeping its macro mappings. It+// copies, pastes and duplicates through the engine's one device clipboard, the track chain's+// too, so a device crosses between the track chain and any rack chain with its settings.+// Every edit is one undo step, and what a section can't take is refused with a reason code.+// Runs with the other rack sections: `dotnet run --project tests/Nota.SmokeTest -- --racks`.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class RackClipboardTests+{+ private const int Eq3 = 16, Compressor = 1, Reverb = 2, Delay = 3, Arp = 0, Chord = 1, Pentad = 14;+ private const int MidiRack = 6;++ /// <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 device clipboard", Run);+ yield return ("racks: review fixes (#348)", Review);+ }++ // PR #348 review: a rack's in-place edits undo after a checkpoint, and undo puts back what a+ // nested Drum Rack's macros drive.+ private static IEnumerable<(bool, string)> Review()+ {+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentTrack();+ int mi = e.AddMidiEffect(t, MidiRack);+ e.ClearUndoHistory();+ int tr0 = e.MidiRackChainTranspose(t, mi, 0);+ e.RackDevCheckpoint(t, -1000 - mi);+ e.MidiRackSetChainTranspose(t, mi, 0, tr0 + 7);+ bool set = e.MidiRackChainTranspose(t, mi, 0) == tr0 + 7;+ e.Undo();+ yield return (set && e.MidiRackChainTranspose(t, mi, 0) == tr0, "a MIDI Effect Rack value edit after a checkpoint is one undo step");++ int it = e.AddInstrumentRackTrack();+ e.ClearUndoHistory();+ float v0 = e.RackVolume(it);+ e.RackDevCheckpoint(it, -1);+ e.RackSetVolume(it, v0 * 0.5f);+ e.Undo();+ yield return (Math.Abs(e.RackVolume(it) - v0) < 1e-5, "an Instrument Rack's volume after a checkpoint undoes");+ }++ // A nested Drum Rack: a mapping range edit, then Undo, puts the pad's decay back.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ int c = e.RackAddChain(t, 4);+ int n = RackMacroMapping.NestedRackBase - c;+ int pad = e.RackDevAddChain(t, n, 1);+ int map = e.RackDevAddMacroMapping(t, n, 0, pad, RackMacroMapping.PadControls, RackMacroMapping.PadDecay, 0.2f, 0.4f);+ e.RackDevMacroSet(t, n, 0, 1f);+ float before = e.RackDevChainDecay(t, n, pad);+ e.ClearUndoHistory();+ e.RackDevSetMappingRange(t, n, map, 0.2f, 0.9f);+ e.RackDevMacroSet(t, n, 0, 1f);+ float edited = e.RackDevChainDecay(t, n, pad);+ e.Undo();+ float after = e.RackDevChainDecay(t, n, pad);+ yield return (Math.Abs(before - 0.4f) < 1e-3 && Math.Abs(edited - 0.9f) < 1e-3 && Math.Abs(after - before) < 1e-3,+ $"undo of a nested mapping edit puts the pad back ({before:F2} → {edited:F2} → {after:F2})");+ yield return (e.RackDevChainId(t, -1, c) != 0 && e.RackDevChainId(t, -1, c) != e.RackDevChainId(t, -1, e.RackAddChain(t, 14)),+ "each chain has its own id");+ }++ // A chain keeps its id through an edit inside its nested Drum Rack (which forks it) and+ // when the chain in front of it goes.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ e.RackAddChain(t, 14);+ int c = e.RackAddChain(t, 4); // chain 1+ long id = e.RackDevChainId(t, -1, c);+ e.RackDevAddChain(t, RackMacroMapping.NestedRackBase - c, 1);+ bool keptOnEdit = e.RackDevChainId(t, -1, c) == id;+ e.RackRemoveChain(t, 0); // the Drum Rack moves up to chain 0+ int now = Enumerable.Range(0, e.RackChainCount(t)).Where(i => e.RackDevChainId(t, -1, i) == id).DefaultIfEmpty(-1).First();+ yield return (c == 1 && keptOnEdit && now == 0 && e.RackChainInstrumentKind(t, now) == 4,+ $"a chain keeps its id through nested edits and moves (edit {keptOnEdit}, now chain {now})");+ e.RackSetChainInstrument(t, now, 6); // the Drum Rack swapped for Volt+ yield return (e.RackDevChainId(t, -1, now) != id, "swapping a chain's instrument changes its id (an old window lets go)");+ }++ // An edit inside a nested Drum Rack doesn't re-prepare its playing pad effects: a reverb+ // tail rings on through it.+ using (var e = new NotaEngine())+ {+ string wav = Path.Combine(Path.GetTempPath(), "nota-rack-review-hit.wav");+ WavWriter.WriteSine(wav, 0.08, 220.0, 48000);+ int t = e.AddInstrumentRackTrack();+ int c = e.RackAddChain(t, 4);+ int n = RackMacroMapping.NestedRackBase - c;+ int pad = e.RackDevAddSamplerChain(t, n, wav, 36, false);+ e.RackDevSetChainTriggerNote(t, n, pad, 36);+ e.RackDevAddChainDevice(t, n, pad, Reverb);+ var buf = new float[512 * 2];+ double Rms() { e.RenderOffline(buf, 512, 48000); double q = 0; foreach (var x in buf) q += x * x; return Math.Sqrt(q / buf.Length); }+ e.TrackNoteOn(t, 36, 1f);+ for (int i = 0; i < 6; i++) Rms();+ e.TrackNoteOff(t, 36);+ for (int i = 0; i < 6; i++) Rms(); // the sample is over: only the tail is left+ double before = Rms();+ e.RackDevAddChain(t, n, 1); // a nested edit: the Drum Rack forks+ double after = Rms();+ yield return (before > 1e-4 && after > before * 0.3, $"a reverb tail rings on through a nested edit ({before:E1} → {after:E1})");+ }++ // A factory Grain preset applied to a chain loads its source sample into the chain's Grain.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ int c = e.RackAddChain(t, 10);+ var factory = new FactoryPresetCatalog();+ var grain = factory.All().FirstOrDefault(p => p.IsInstrument && p.BuiltinKind == 10 && p.DisplayName != "Init");+ string warn = grain.Id is null ? "no Grain preset" : factory.ApplyInPlace(RackChainEngineProxy.Create(e, c), grain.Id, t, -1);+ yield return (warn == "" && e.RackChainInstrumentKind(t, c) == 10, $"a Grain preset in a chain loads its sample ({(warn == "" ? "loaded" : warn)})");+ }+ }++ // A device's params as one comparable line.+ private static string Params(NotaEngine e, int t, int di, int c, int d)+ {+ int n = e.RackDevChainDeviceParamCount(t, di, c, d);+ return string.Join(";", Enumerable.Range(0, n).Select(p => e.RackDevChainDeviceParamGet(t, di, c, d, p).ToString("F4")));+ }++ private static string TrackParams(NotaEngine e, int t, int d)+ => string.Join(";", Enumerable.Range(0, e.DeviceParamCount(t, d)).Select(p => e.DeviceGetParam(t, d, p).ToString("F4")));++ private static string Names(NotaEngine e, int t, int di, int c)+ => string.Join(",", Enumerable.Range(0, e.RackDevChainDeviceCount(t, di, c)).Select(d => e.RackDevChainDeviceName(t, di, c, d).Replace("Nota ", "")));++ // Nudge every param of a chain device off its default so a copy is recognisable.+ private static void Tweak(NotaEngine e, int t, int di, int c, int d)+ {+ for (int p = 0; p < e.RackDevChainDeviceParamCount(t, di, c, d); p++)+ {+ float lo = e.RackDevChainDeviceParamMin(t, di, c, d, p), hi = e.RackDevChainDeviceParamMax(t, di, c, d, p);+ e.RackDevChainDeviceParamSet(t, di, c, d, p, lo + (hi - lo) * 0.37f);+ }+ }++ private static IEnumerable<(bool, string)> Run()+ {+ // ---- US1: move within a chain and to another chain, mappings follow ----+ using (var e = new NotaEngine())+ {+ int t = e.AddAudioTrack();+ int di = e.AddBuiltinDevice(t, 5);+ while (e.RackDevChainCount(t, di) > 0) e.RackDevRemoveChain(t, di, 0);+ int a = e.RackDevAddChain(t, di, -1), b = e.RackDevAddChain(t, di, -1);+ e.RackDevAddChainDevice(t, di, a, Eq3);+ int comp = e.RackDevAddChainDevice(t, di, a, Compressor);+ e.RackDevAddChainDevice(t, di, a, Reverb);+ int thr = Enumerable.Range(0, e.RackDevChainDeviceParamCount(t, di, a, comp)).First(p => e.RackDevChainDeviceParamName(t, di, a, comp, p).StartsWith("Thresh"));+ float lo = e.RackDevChainDeviceParamMin(t, di, a, comp, thr), hi = e.RackDevChainDeviceParamMax(t, di, a, comp, thr);+ e.RackDevAddMacroMapping(t, di, 0, a, comp, thr, lo, hi);+ e.ClearUndoHistory();++ e.RackDevMoveChainDevice(t, di, a, 2, 0);+ string moved = Names(e, t, di, a);+ e.Undo();+ yield return (moved == "Reverb,EQ-3,Compressor" && Names(e, t, di, a) == "EQ-3,Compressor,Reverb",+ $"a chain device moves within its chain, one undo step ({moved})");++ e.RackDevMoveChainDevice(t, di, a, 1, 2); // Compressor last+ e.RackDevMacroSet(t, di, 0, 1f);+ yield return (Math.Abs(e.RackDevChainDeviceParamGet(t, di, a, 2, thr) - hi) < 1e-3, "a macro still drives a moved device");++ string before = Params(e, t, di, a, 2);+ int to = e.RackDevChainDeviceMoveTo(t, di, a, 2, b);+ e.RackDevMacroSet(t, di, 0, 0f);+ bool there = to == 0 && Names(e, t, di, b) == "Compressor" && Names(e, t, di, a) == "EQ-3,Reverb";+ bool driven = Math.Abs(e.RackDevChainDeviceParamGet(t, di, b, 0, thr) - lo) < 1e-3;+ yield return (there && driven, $"a device moves to another chain with its mapping ({Names(e, t, di, a)} | {Names(e, t, di, b)}, driven {driven})");+ e.Undo();+ yield return (Names(e, t, di, a) == "EQ-3,Reverb,Compressor" && Names(e, t, di, b) == "",+ "moving to another chain is one undo step");+ yield return (e.RackDevChainDeviceMoveTo(t, di, a, 0, a) == -1, "a device can't move to its own chain");+ }++ // MIDI effects between Instrument Rack chains; MIDI effects stay in the first 16 chains.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ int a = e.RackAddChain(t, Pentad), b = e.RackAddChain(t, Pentad);+ e.RackChainMidiAdd(t, a, Arp);+ e.RackChainMidiAdd(t, a, Chord);+ int j = e.RackDevChainMidiMoveTo(t, -1, a, 0, b);+ yield return (j == 0 && e.RackChainMidiCount(t, a) == 1 && e.RackChainMidiKind(t, b, 0) == Arp,+ "a chain MIDI effect moves to another chain");+ while (e.RackChainCount(t) < 17) e.RackAddChain(t, Pentad);+ yield return (e.RackDevChainMidiMoveTo(t, -1, a, 0, 16) == -5, "a MIDI effect can't move past chain 16 (−5)");+ }++ // ---- US2: copy, paste, duplicate and refusals inside racks ----+ using (var e = new NotaEngine())+ {+ int t = e.AddAudioTrack();+ int di = e.AddBuiltinDevice(t, 5);+ while (e.RackDevChainCount(t, di) > 0) e.RackDevRemoveChain(t, di, 0);+ int a = e.RackDevAddChain(t, di, -1), b = e.RackDevAddChain(t, di, -1);+ int rv = e.RackDevAddChainDevice(t, di, a, Reverb);+ Tweak(e, t, di, a, rv);+ int bd = e.RackDevAddChainDevice(t, di, b, Eq3);+ e.RackDevAddMacroMapping(t, di, 1, b, bd, 0, 0f, 1f);+ e.ClearUndoHistory();++ bool copied = e.RackDevChainDeviceCopy(t, di, a, rv);+ int p1 = e.RackDevChainDevicePaste(t, di, b, -1);+ yield return (copied && p1 == 1 && Params(e, t, di, b, 1) == Params(e, t, di, a, rv) && e.DeviceClipboardKind() == 1,+ "a chain device copies into another chain with its settings");+ int maps = e.RackDevMappingCount(t, di);+ e.Undo();+ yield return (e.RackDevChainDeviceCount(t, di, b) == 1 && maps == 1, "a paste is one undo step and brings no mappings");++ int p0 = e.RackDevChainDevicePaste(t, di, b, 0);+ e.RackDevMacroSet(t, di, 1, 1f);+ bool shifted = p0 == 0 && Names(e, t, di, b) == "Reverb,EQ-3" && e.RackDevTryGetMapping(t, di, 0, out var mm) && mm.Chain == b && mm.DeviceIndex == 1;+ yield return (shifted, "pasting in front shifts the chain's mappings with their devices");++ int dup = e.RackDevChainDeviceDuplicate(t, di, b, 0);+ yield return (dup == 1 && Names(e, t, di, b) == "Reverb,Reverb,EQ-3" && Params(e, t, di, b, 1) == Params(e, t, di, b, 0) && e.DeviceClipboardKind() == 1,+ "duplicate puts a copy right after the device and leaves the clipboard");+ e.Undo();+ yield return (Names(e, t, di, b) == "Reverb,EQ-3", "duplicate is one undo step");++ // Refusals: the other family, a rack in a rack.+ int it = e.AddInstrumentTrack();+ e.AddMidiEffect(it, Arp);+ e.CopyMidiEffect(it, 0);+ yield return (e.RackDevChainDevicePaste(t, di, a, -1) == -2 && e.RackDevChainMidiPaste(t, di, a, -1) == -2,+ "a MIDI effect doesn't paste into an Audio Effect Rack (−2)");+ e.CopyDevice(t, di);+ yield return (e.RackDevChainDevicePaste(t, di, a, -1) == -3, "a rack doesn't paste into a rack chain (−3)");+ }++ // A MIDI Effect Rack: its Arp copies between its chains.+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentTrack();+ int mi = e.AddMidiEffect(t, MidiRack);+ e.MidiRackAddChain(t, mi);+ int arp = e.MidiRackChainDeviceAdd(t, mi, 0, Arp);+ e.MidiRackChainDeviceParamSet(t, mi, 0, arp, 0, e.MidiRackChainDeviceParamMax(t, mi, 0, arp, 0));+ int rack = -1000 - mi;+ e.RackDevChainMidiCopy(t, rack, 0, arp);+ int p = e.RackDevChainMidiPaste(t, rack, 1, -1);+ bool same = p == 0 && Enumerable.Range(0, e.MidiRackChainDeviceParamCount(t, mi, 0, arp))+ .All(q => Math.Abs(e.MidiRackChainDeviceParamGet(t, mi, 0, arp, q) - e.MidiRackChainDeviceParamGet(t, mi, 1, 0, q)) < 1e-5);+ yield return (same, "an Arp copies between MIDI Effect Rack chains with its settings");+ e.CopyDevice(t, -1); // nothing there: the clipboard keeps the Arp+ e.AddBuiltinDevice(t, Delay);+ e.CopyDevice(t, 0);+ yield return (e.RackDevChainDevicePaste(t, rack, 0, -1) == -2, "an audio effect doesn't paste into a MIDI Effect Rack (−2)");+ }++ // ---- US3: across the track chain and rack chains ----+ using (var e = new NotaEngine())+ {+ int t = e.AddInstrumentRackTrack();+ int c = e.RackAddChain(t, Pentad);+ int d = e.AddBuiltinDevice(t, Delay);+ for (int p = 0; p < e.DeviceParamCount(t, d); p++)+ e.DeviceSetParam(t, d, p, e.DeviceParamMin(t, d, p) + (e.DeviceParamMax(t, d, p) - e.DeviceParamMin(t, d, p)) * 0.41f);+ e.CopyDevice(t, d);+ int r = e.RackDevChainDevicePaste(t, -1, c, -1);+ yield return (r == 0 && Params(e, t, -1, c, 0) == TrackParams(e, t, d), "a track-chain effect pastes into a rack chain with its settings");++ int eq = e.RackAddChainDevice(t, c, Eq3);+ Tweak(e, t, -1, c, eq);+ e.RackDevChainDeviceCopy(t, -1, c, eq);+ int back = e.PasteDevice(t, -1);+ yield return (back == 1 && TrackParams(e, t, back) == Params(e, t, -1, c, eq), "a rack chain effect pastes onto the track chain with its settings");++ int arp = e.AddMidiEffect(t, Arp);+ e.MidiEffectSetParam(t, arp, 0, e.MidiEffectParamMax(t, arp, 0));+ e.CopyMidiEffect(t, arp);+ int rm = e.RackDevChainMidiPaste(t, -1, c, -1);+ yield return (rm == 0 && Math.Abs(e.RackChainMidiParamGet(t, c, 0, 0) - e.MidiEffectGetParam(t, arp, 0)) < 1e-5,+ "a track MIDI effect pastes into an Instrument Rack chain");++ // A keyed compressor loses its key in a chain; the source keeps it.+ int src = e.AddAudioTrack();+ int k = e.AddBuiltinDevice(t, Compressor);+ e.SetDeviceSidechainSource(t, k, src);+ e.CopyDevice(t, k);+ bool keyed = e.DeviceClipboardSidechain();+ int kc = e.RackDevChainDevicePaste(t, -1, c, -1);+ yield return (keyed && kc >= 0 && e.DeviceSidechainSource(t, k) == src, "a keyed effect pastes into a chain without its key; the source keeps it");++ // Duplicate on the track chain: one undo step each.+ e.ClearUndoHistory();+ int n = e.TrackDeviceCount(t), m = e.TrackMidiEffectCount(t);+ int dd = e.DuplicateDevice(t, d);+ int dm = e.DuplicateMidiEffect(t, arp);+ bool dupOk = dd == d + 1 && dm == arp + 1 && e.TrackDeviceCount(t) == n + 1 && e.TrackMidiEffectCount(t) == m + 1;+ e.Undo(); e.Undo();+ yield return (dupOk && e.TrackDeviceCount(t) == n && e.TrackMidiEffectCount(t) == m, "duplicate on the track chain, one undo step each");+ }+ }+}diff --git a/tests/Nota.SmokeTest/RackNestingTests.cs b/tests/Nota.SmokeTest/RackNestingTests.csnew file mode 100644index 00000000..4c1fe7e8--- /dev/null+++ b/tests/Nota.SmokeTest/RackNestingTests.cs@@ -0,0 +1,227 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Mosaic and the Drum Rack as Instrument Rack chain instruments (specs/041). A Mosaic+// chain loads a program, plays inside its chain's zone, follows a macro, keeps its program+// through the rack blob and undoes a program edit in one step. A Drum Rack nests one level:+// it goes in an Instrument Rack chain and nowhere else, is edited through its nested address+// (NOTA_RACK_NESTED_BASE − chain) and through NestedRackEngineProxy as the Drum Rack card+// sees it, plays its pads for the notes its chain lets through, undoes, and survives the+// blob and a chain copy. Sound is checked on generated sines (deterministic).+// Runs with the other rack sections: `dotnet run --project tests/Nota.SmokeTest -- --racks`.++using Nota.Application;+using Nota.Application.Mosaic;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class RackNestingTests+{+ private const int Rate = 48000, Block = 512, Sampler = 1, DrumRack = 4, InstrumentRack = 3, Mosaic = 17;+ private const int Nested = RackMacroMapping.NestedRackBase;++ /// <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: Mosaic chain", MosaicChain);+ yield return ("racks: nested Drum Rack", NestedDrumRack);+ }++ private static string Sine(string name, double hz)+ {+ string path = Path.Combine(Path.GetTempPath(), $"nota-rack-nesting-{Environment.ProcessId}-{name}.wav");+ WavWriter.WriteSine(path, 1.0, hz, Rate);+ return path;+ }++ private static double Rms(NotaEngine e, int blocks = 12)+ {+ var buf = new float[Block * 2];+ double s = 0;+ for (int b = 0; b < blocks; b++)+ {+ e.RenderOffline(buf, Block, Rate);+ foreach (float v in buf) s += v * (double)v;+ }+ return Math.Sqrt(s / (blocks * Block * 2));+ }++ // Plays a note for a moment and lets everything ring out; returns the level while it sounds.+ private static double Hit(NotaEngine e, int t, int note)+ {+ e.TrackNoteOn(t, note, 0.9f);+ double r = Rms(e);+ e.TrackNoteOff(t, note);+ Rms(e, 200);+ return r;+ }++ private static bool WaitReady(NotaEngine e, int t, int di, int c)+ {+ var sw = System.Diagnostics.Stopwatch.StartNew();+ while (sw.ElapsedMilliseconds < 5000)+ {+ if (e.RackDevTryGetChainMosaicStatus(t, di, c, out var s) && s.State == 2) { Rms(e, 1); return true; }+ Thread.Sleep(5);+ }+ return false;+ }++ private static int ParamIndex(NotaEngine e, int t, int c, string id)+ {+ int n = e.RackChainInstrumentParamCount(t, c);+ for (int i = 0; i < n; i++) if (e.RackChainInstrumentParamId(t, c, i) == id) return i;+ return -1;+ }++ private static IEnumerable<(bool, string)> MosaicChain()+ {+ string tone = Sine("c4", 261.63);+ var prog = new MosaicProgram { Name = "Rack Piano", SourceKind = "files" };+ prog.Files.Add(tone);+ prog.Zones.Add(new MosaicZone { File = 0, Root = 60, KeyLo = 0, KeyHi = 127 });+ string text = prog.Serialize();++ using var e = new NotaEngine();+ int t = e.AddInstrumentRackTrack();+ e.RackAddChain(t, 6); // a Nota Volt chain first (a new rack starts empty)+ e.RackSetChainMute(t, 0, true); // the default Volt chain stays quiet+ int c = e.RackAddChain(t, Mosaic);+ yield return (c == 1 && e.RackChainInstrumentKind(t, c) == Mosaic && e.RackChainInstrumentName(t, c) == "Nota Mosaic",+ $"an Instrument Rack chain takes Nota Mosaic (chain {c}, kind {e.RackChainInstrumentKind(t, c)})");+ yield return (e.RackSetChainInstrument(t, 0, Mosaic) && e.RackChainInstrumentKind(t, 0) == Mosaic && e.Undo()+ && e.RackChainInstrumentKind(t, 0) == 6, "a chain's instrument turns into Mosaic and back by undo");++ e.RackSetChainZone(t, c, 48, 71, 0, 127);+ yield return (e.RackDevChainMosaicSetProgram(t, -1, c, text, undoable: false) && WaitReady(e, t, -1, c),+ "the chain's Mosaic loads a program");+ yield return (e.RackDevChainMosaicProgram(t, -1, c) == text, "the chain's program reads back");+ long zid = e.RackDevChainMosaicZoneSampleId(t, -1, c, 0);+ yield return (zid > 0 && e.TryGetSampleInfo(zid, out var si) && si.Frames > 0,+ "a chain Mosaic's zone sample is found by id (the editor's waveform)");++ double inZone = Hit(e, t, 60), outZone = Hit(e, t, 84);+ yield return (inZone > 0.01 && outZone < 1e-5, $"the Mosaic chain plays inside its zone only (in {inZone:F4}, out {outZone:F6})");++ int vol = ParamIndex(e, t, c, "volume");+ e.RackAddMacroMapping(t, 2, c, -1, vol, 0f, 1f);+ e.RackMacroSet(t, 2, 0.25f);+ yield return (vol >= 0 && Math.Abs(e.RackChainInstrumentParamGet(t, c, vol) - 0.25f) < 1e-3,+ "a rack macro drives the chain Mosaic's volume");++ // The blob carries the program; a fresh rack reloads its samples from the paths.+ var blob = e.GetPluginState(t, -1);+ int t2 = e.AddInstrumentRackTrack();+ e.SetPluginState(t2, -1, blob);+ yield return (e.RackChainInstrumentKind(t2, c) == Mosaic && e.RackDevChainMosaicProgram(t2, -1, c) == text && WaitReady(e, t2, -1, c),+ "a Mosaic chain survives the rack blob (program and samples)");+ yield return (Math.Abs(e.RackChainInstrumentParamGet(t2, c, vol) - 0.25f) < 1e-3, "a Mosaic chain keeps its params through the blob");++ // An undoable program edit is one undo step.+ var p2 = MosaicProgram.Parse(text);+ p2.Name = "Rack Piano 2";+ string text2 = p2.Serialize();+ bool set = e.RackDevChainMosaicSetProgram(t, -1, c, text2, undoable: true);+ bool now = e.RackDevChainMosaicProgram(t, -1, c) == text2;+ yield return (set && now && e.Undo() && e.RackDevChainMosaicProgram(t, -1, c) == text,+ "a chain Mosaic program edit undoes in one step");+ yield return (WaitReady(e, t, -1, c) && Hit(e, t, 60) > 0.01, "the undone Mosaic still plays");++ // The editor's view of the chain: the Mosaic card's calls reach the chain.+ var proxy = RackChainEngineProxy.Create(e, c);+ yield return (proxy.TrackInstrumentKind(t) == Mosaic && proxy.MosaicProgram(t) == text+ && proxy.TryGetMosaicStatus(t, out var ps) && ps.State == 2 && proxy.MosaicZoneSampleId(t, 0) == e.RackDevChainMosaicZoneSampleId(t, -1, c, 0),+ "the chain view gives the Mosaic editor the chain's program and status");++ int d = e.AddDrumRackTrack();+ int pad = e.RackAddChain(d, Mosaic);+ yield return (pad >= 0 && e.RackChainInstrumentKind(d, pad) == Mosaic, "a Drum Rack pad takes Nota Mosaic");+ try { File.Delete(tone); } catch { }+ }++ private static IEnumerable<(bool, string)> NestedDrumRack()+ {+ string kick = Sine("kick", 110), snare = Sine("snare", 330);+ using var e = new NotaEngine();+ int t = e.AddInstrumentRackTrack();+ e.RackAddChain(t, 6); // a Nota Volt chain first (a new rack starts empty)+ e.RackSetChainMute(t, 0, true);+ int c = e.RackAddChain(t, DrumRack);+ int n = Nested - c;+ yield return (c == 1 && e.RackChainInstrumentKind(t, c) == DrumRack && e.RackDevChainCount(t, n) == 0,+ "an Instrument Rack chain takes a Drum Rack, empty");++ // One level only.+ int d = e.AddDrumRackTrack();+ yield return (e.RackAddChain(d, DrumRack) < 0 && e.RackAddChain(t, InstrumentRack) < 0 && e.RackDevAddChain(t, n, DrumRack) < 0,+ "racks nest one level: no Drum Rack on a pad, no Instrument Rack in a chain, nothing deeper");+ yield return (!e.RackSetChainInstrument(t, 0, InstrumentRack) && e.RackDevChainCount(t, Nested - 0) == 0,+ "a chain can't become an Instrument Rack, and a chain without a rack has no nested address");++ int p0 = e.RackDevAddSamplerChain(t, n, kick, 36, false);+ e.RackDevSetChainTriggerNote(t, n, p0, 36);+ int p1 = e.RackDevAddSamplerChain(t, n, snare, 38, false);+ e.RackDevSetChainTriggerNote(t, n, p1, 38);+ yield return (p0 == 0 && p1 == 1 && e.RackDevChainCount(t, n) == 2 && e.RackChainCount(t) == 2,+ "pads go into the nested Drum Rack, not the outer rack");++ e.RackSetChainZone(t, c, 36, 47, 0, 127);+ double pad = Hit(e, t, 36), empty = Hit(e, t, 40), outside = Hit(e, t, 60);+ yield return (pad > 0.01 && empty < 1e-5 && outside < 1e-5,+ $"a nested pad plays inside its chain's zone (pad {pad:F4}, empty note {empty:F6}, outside {outside:F6})");++ e.RackDevSetChainChoke(t, n, p0, 2);+ e.RackDevSetChainTune(t, n, p0, -3);+ e.RackDevSetChainDecay(t, n, p0, 0.4f);+ e.RackDevSetChainName(t, n, p0, "Kick");+ yield return (e.RackDevChainChoke(t, n, p0) == 2 && e.RackDevChainTune(t, n, p0) == -3+ && Math.Abs(e.RackDevChainDecay(t, n, p0) - 0.4f) < 1e-4 && e.RackDevChainName(t, n, p0) == "Kick",+ "nested pad shaping and names read back");++ // Undo: a nested structural edit is one step and leaves the outer rack alone.+ int p2 = e.RackDevAddChain(t, n, Sampler);+ yield return (p2 == 2 && e.Undo() && e.RackDevChainCount(t, n) == 2 && e.RackChainCount(t) == 2 && e.RackChainInstrumentKind(t, c) == DrumRack,+ "adding a nested pad undoes in one step");+ yield return (Hit(e, t, 36) > 0.01, "the nested kit still plays after the undo");++ // Outer macro → the nested rack's macro 2 (its chain instrument param 1) → pad decay.+ int nm = e.RackDevAddMacroMapping(t, n, 1, p0, RackMacroMapping.PadControls, RackMacroMapping.PadDecay, 0f, 1f);+ int om = e.RackAddMacroMapping(t, 0, c, -1, 1, 0f, 1f);+ e.RackMacroSet(t, 0, 0.3f);+ yield return (nm >= 0 && om >= 0 && Math.Abs(e.RackDevMacroGet(t, n, 1) - 0.3f) < 1e-3 && Math.Abs(e.RackDevChainDecay(t, n, p0) - 0.3f) < 1e-3,+ "an outer macro drives a nested macro, which drives a pad");++ // The blob carries the nested kit, samples included.+ var blob = e.GetPluginState(t, -1);+ int t2 = e.AddInstrumentRackTrack();+ e.SetPluginState(t2, -1, blob);+ bool shape = e.RackDevChainCount(t2, n) == 2 && e.RackDevChainTriggerNote(t2, n, 1) == 38 && e.RackDevChainChoke(t2, n, 0) == 2+ && e.RackDevChainName(t2, n, 0) == "Kick" && e.RackDevMappingCount(t2, n) == 1 && e.RackMappingCount(t2) == 1;+ bool audio = e.RackDevChainSamplerInfo(t2, n, 0, out var si) && si.SampleId > 0 && e.TryGetSampleInfo(si.SampleId, out var inf) && inf.Frames > 0;+ yield return (shape && audio, $"a nested Drum Rack survives the blob (shape {shape}, audio {audio})");++ // Copying the chain copies the kit.+ int c2 = e.RackDuplicateChain(t, c);+ yield return (c2 == c + 1 && e.RackChainInstrumentKind(t, c2) == DrumRack && e.RackDevChainCount(t, Nested - c2) == 2,+ "duplicating a Drum Rack chain copies its kit");++ // The Drum Rack card's view: its Rack* calls land on the nested rack.+ var proxy = NestedRackEngineProxy.Create(e, c);+ proxy.RackSetChainTune(t, p1, 5);+ bool redirected = proxy.RackChainCount(t) == 2 && e.RackDevChainTune(t, n, p1) == 5 && e.RackChainCount(t) == 3+ && proxy.TrackInstrumentKind(t) == DrumRack && proxy.RackChainTriggerNote(t, p1) == 38;+ bool macros = Math.Abs(proxy.PluginParamGet(t, -1, 1) - e.RackDevMacroGet(t, n, 1)) < 1e-6 && proxy.PluginParamCount(t, -1) == 8;+ bool noTwin = proxy.RackChainMidiCount(t, 0) == 0 && !proxy.RackMono(t);+ yield return (redirected && macros && noTwin,+ $"the nested view sends the Drum Rack card's calls to the nested rack (calls {redirected}, macros {macros}, no-twin defaults {noTwin})");+ proxy.RackTryGetMapping(t, 0, out var mm);+ yield return (mm.Chain == p0 && mm.DeviceIndex == RackMacroMapping.PadControls, "out parameters come back through the nested view");++ // A chain that changes its instrument leaves no nested rack behind its address.+ e.RackSetChainInstrument(t, c2, Sampler);+ yield return (e.RackDevChainCount(t, Nested - c2) == 0 && e.RackDevAddChain(t, Nested - c2, Sampler) < 0,+ "a nested address with no Drum Rack behind it does nothing");+ try { File.Delete(kick); File.Delete(snare); } catch { }+ }+}diff --git a/tests/perf/nota_perf.cpp b/tests/perf/nota_perf.cppindex 5dfc5da2..5e3067d2 100644--- a/tests/perf/nota_perf.cpp+++ b/tests/perf/nota_perf.cpp@@ -306,6 +306,13 @@ int run(const std::string& id, double seconds) {}if (id == "edit-warp-split") { // split the last piece 8 times, then undo themconstexpr int kEdits = 8;+ // Warm-up, not measured: one split + undo first, so the counted edits don't include the+ // first-call costs (lazy symbol binding, function-local statics). Those depend on the+ // library's size and layout rather than on the edit path, and they made this tiny+ // scenario move by a percent or two when unrelated code was added. The clip is back as+ // it was after the undo.+ nota_clip_split(e, gWarpTrack, 0, 1.0);+ nota_engine_undo(e);const auto t0 = std::chrono::steady_clock::now();CALLGRIND_START_INSTRUMENTATION;for (int i = 0; i < kEdits; ++i) nota_clip_split(e, gWarpTrack, i, 1.5 + i * 1.75);