Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) Edit several MIDI clips at once

Egor Khindikaynen82babfe160bb
diff --git a/.gitignore b/.gitignore
index ce3cf315..3e6e04fe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,3 +31,5 @@ dist/
# Nota Remote phone page: Vite output of src/web/remote, rebuilt by the Nota.Remote build
src/managed/Nota.Remote/wwwroot/
+
+.netcoredbg_hist
diff --git a/.netcoredbg_hist b/.netcoredbg_hist
new file mode 100644
index 00000000..f5bdd214
--- /dev/null
+++ b/.netcoredbg_hist
@@ -0,0 +1 @@
+run
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c02da32d..2e51893b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Edit several MIDI clips at once** (nota-daw/nota#48): select two or more MIDI clips — on
+ one track or several — and double-click one of them (or right-click → **Edit selected
+ clips together**). The Clip editor shows all their notes on the arrangement's bars: fix a
+ bass line split over several clips in one go, or write a melody while you see the chords
+ of another clip. Select, move, transpose, quantize, delete or run a clip tool across
+ clips; one undo reverts the whole edit. A note dragged across the seam into the next open
+ clip of its track moves into that clip. A strip under the ruler shows the open clips:
+ click one to make it the active clip (its name, start, length and envelopes in the
+ editor), or lock it as a dimmed reference that cannot be changed by accident. New notes go
+ into the active clip.
- **Nota Vocoder** (nota-daw/nota#113): a new audio effect with two inputs. The track it
sits on is the voice; drop it on a vocal and you hear a robot voice straight away, from an
internal **Saw** (at a chosen **Pitch**). Switch the carrier to **Noise** for a whisper, or
diff --git a/FEATURES.md b/FEATURES.md
index 47c8be9b..db1586d1 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -262,6 +262,15 @@ track count and closes with Escape.
- A MIDI clip trimmed in the arrangement mutes note tails at its boundary.
- Live edits (moving a note, changing its length) reach the engine immediately, and a
whole drag is a single undo step.
+ - **Several clips at once**: double-click one of two or more selected MIDI clips (one
+ track or several), or right-click → **Edit selected clips together** (also in the
+ command palette), to open them together on the arrangement's bars. Selecting, moving,
+ transposing, quantizing, deleting and clip tools work across clips, one undo for the
+ whole edit; a note moved past the seam into the next open clip of its track moves into
+ that clip. A **clip strip** under the ruler shows the open clips: click one to make it
+ the active clip (header, inspector and envelopes follow it; new notes go into it), or
+ click its lock to keep it as a dimmed, read-only reference. The set stays as opened
+ while the arrangement selection changes.
- **Clip tools (generate and transform)**: a **Tools** rail beside the piano roll with
fifteen tools that write or rewrite notes. Six **generators** — *Rhythm* (a pattern that
leans on the strong beats), *Seed* (learns the clip's own intervals and rhythm, then
@@ -273,7 +282,9 @@ track count and closes with Escape.
before deciding — and **Apply** keeps it as a single undo step. Backing out leaves no
trace in the history.
- A selection scopes the tool to those notes; with nothing selected it works the whole
- clip. Output can **replace** what it was given or be **added** on top.
+ clip. Output can **replace** what it was given or be **added** on top. With several
+ clips open, the tool runs on each clip that has selected notes (or the active clip),
+ and what it writes stays in that clip.
- Everything is **seeded**, so a result is repeatable and "New seed" re-rolls it.
- Tools that think in pitch follow the roll's **Set Scale** key, so what they write
stays in key.
diff --git a/specs/029-multi-clip-editing/checklists/requirements.md b/specs/029-multi-clip-editing/checklists/requirements.md
new file mode 100644
index 00000000..f99b2f6a
--- /dev/null
+++ b/specs/029-multi-clip-editing/checklists/requirements.md
@@ -0,0 +1,38 @@
+# Specification Quality Checklist: Multi-Clip Editing in the Clip Editor
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-20
+**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 section names code areas by design (project template); the user-facing
+ sections stay implementation-free.
+- No clarification markers: open design choices (reference mode is an explicit per-clip
+ toggle, notes never move between clips, new notes go to the active clip) were taken as
+ informed defaults and are good candidates for `/speckit-clarify`.
diff --git a/specs/029-multi-clip-editing/contracts/piano-roll-api.md b/specs/029-multi-clip-editing/contracts/piano-roll-api.md
new file mode 100644
index 00000000..e172f17b
--- /dev/null
+++ b/specs/029-multi-clip-editing/contracts/piano-roll-api.md
@@ -0,0 +1,60 @@
+# Contract: PianoRollView ↔ host (MainWindow) and panels
+
+In-process C# contract (no C ABI change). Existing members keep their meaning for a
+one-clip set.
+
+## New / changed on `PianoRollView`
+
+```csharp
+// Load a set (replaces SetNotes for arrangement clips). notes[i] are clip-local per clip.
+void SetClips(ClipSet set, IReadOnlyList<ClipNotes> notes);
+ClipSet? Clips { get; }
+OpenClip? ActiveClip { get; }
+event Action? ActiveClipChanged; // header, inspector, envelope overlay rebind
+void SetActiveClip(int slot);
+void SetReference(int slot, bool on); // refused for the active slot
+
+// Commit paths. When CommitClips is set it is used instead of Commit; only clips whose
+// notes changed since the last commit are passed (except the drag seed: all editable).
+Action<IReadOnlyList<ClipNotes>>? CommitClips { get; set; }
+Action<IReadOnlyList<ClipNotes>>? CommitClipsLive { get; set; }
+
+// Clip tools (R6)
+IReadOnlyList<ClipNotes> SourceClipNotes { get; } // ignoring a preview in flight
+IReadOnlyList<(int Slot, int Index)> SelectionByClip { get; } // clip-local indices
+void ShowPreview(IReadOnlyList<ClipNotes> perClip);
+
+// Coordinates
+double Origin { get; } // arrangement beat of editor beat 0
+// SetPlayhead and Seek take/give editor beats; host converts with Origin.
+```
+
+Unchanged: `Commit`, `CommitLive`, `SetNotes(notes, length)` stay for the Session-slot
+editor (one clip, no `ClipSet` commit wiring).
+
+## Host obligations (`MainWindow.Detail.cs`)
+
+- `CommitClips`: `BeginUndoGroup`; for each entry `TryGetClipInfo(...).IsMidi` else drop
+ the clip from the set; `SetClipNotes`; `EndUndoGroup` (in `finally`); `Timeline.Refresh()`.
+- `CommitClipsLive`: same validation, `SetClipNotesLive` per entry, no group.
+- Before replacing the set or saving/exporting: `SettlePlacement()` (as today).
+- `OnTrackSelected` / `OnDetailClip`: no reset or re-point while `Clips.IsMulti`.
+
+## `ArrangementView`
+
+```csharp
+// The selected MIDI clips, in time order; used by double-click and "Edit selected clips".
+IReadOnlyList<(int TrackId, int ClipIndex)> SelectedMidiClips();
+event Action<int, int>? MidiClipActivated; // unchanged; host checks membership
+```
+
+## `NoteOverwrite` (Nota.Application/Editing)
+
+```csharp
+static void Settle(IReadOnlyList<NotaNote> notes, IReadOnlyList<int> placed,
+ List<NotaNote> outNotes, List<int> outPlaced,
+ IReadOnlyList<int>? owners = null, List<int>? outOwners = null);
+static NoteFate Fate(int i, IReadOnlyList<NotaNote> notes, IReadOnlyList<int> placed,
+ IReadOnlyList<int>? owners = null);
+```
+`owners == null` ⇒ identical to today.
diff --git a/specs/029-multi-clip-editing/contracts/ui.md b/specs/029-multi-clip-editing/contracts/ui.md
new file mode 100644
index 00000000..f642a5c8
--- /dev/null
+++ b/specs/029-multi-clip-editing/contracts/ui.md
@@ -0,0 +1,38 @@
+# Contract: user-facing behaviour
+
+## Opening
+
+| Action | Result |
+|--------|--------|
+| Double-click a MIDI clip that is in a selection of ≥2 MIDI clips | All selected MIDI clips open; clicked clip active |
+| Double-click a clip outside the selection / single selection | Single-clip editor (unchanged) |
+| Command palette / arrangement clip context menu: **Edit selected clips** | All selected MIDI clips open; first in time active. Disabled with <2 MIDI clips selected |
+| Change arrangement selection while a multi-clip editor is open | Editor unchanged |
+
+No new keyboard shortcut is bound by default (the command is available to the shortcut
+builder). If one is added, run `nota-shortcuts`.
+
+## Clip strip (multi-clip editor only)
+
+Row between the ruler and the note grid, on the roll's beat axis.
+
+| Gesture | Result |
+|---------|--------|
+| Click a clip bar | That clip becomes active |
+| Click the lock on a non-active bar | Toggle reference (dimmed, read-only) |
+| Lock on the active bar | Not shown (active is always editable) |
+
+Mouse gestures are listed in Preferences → Shortcuts (nota-shortcuts).
+
+## Header
+
+`<active clip name> · +N clips` with the active clip's track colour cell.
+
+## Visual states (DESIGN.md, via nota-design)
+
+| Notes of | Look |
+|----------|------|
+| Active clip | full track colour (as today) |
+| Other editable clip | track colour, subdued |
+| Reference clip | dimmed further, no hover / no edge cursors |
+| Outside every open clip | existing outside-clip wash |
diff --git a/specs/029-multi-clip-editing/data-model.md b/specs/029-multi-clip-editing/data-model.md
new file mode 100644
index 00000000..6c18bb91
--- /dev/null
+++ b/specs/029-multi-clip-editing/data-model.md
@@ -0,0 +1,69 @@
+# Data Model: Multi-Clip Editing
+
+Managed-only, in-memory editor state. Nothing new is persisted in the project file; the
+engine's per-clip note lists stay the source of truth.
+
+## OpenClip
+
+One MIDI clip shown in a Clip editor. `Nota.Application/Editing/ClipSet.cs`.
+
+| Field | Type | Notes |
+|-------|------|-------|
+| TrackId | int | arrangement track |
+| ClipIndex | int | clip index on that track (as used by `SetClipNotes`) |
+| StartBeat | double | arrangement start; refreshed on geometry change (R8) |
+| LengthBeats | double | > 0 |
+| IsReference | bool | read-only lock (FR-009); never true for the active clip |
+
+Identity: `(TrackId, ClipIndex)`; unique within a set.
+
+## ClipSet
+
+The open clip set of one editor (FR-001, FR-001a).
+
+| Member | Meaning |
+|--------|---------|
+| Clips | `IReadOnlyList<OpenClip>`, ordered by StartBeat then TrackId; the index is the **slot** stored per note |
+| Active | slot of the active clip |
+| Origin | min StartBeat — editor beat 0 |
+| SpanBeats | max(Start + Length) − Origin |
+| IsMulti | Clips.Count > 1 (strip shown, selection-follow disabled) |
+| ToEditor(slot, localBeat) / ToLocal(slot, editorBeat) | coordinate conversion |
+| Reach(slot) | contiguous run of open, editable clips on the slot's track around it (R4) |
+| OwnerAfterMove(slot, editorStart) | FR-006 owner rule (R4) |
+| Split(notes, owners) → `ClipNotes[]` | per-clip lists in clip-local beats |
+| Merge(`ClipNotes[]`) → (notes, owners) | inverse of Split |
+
+Validation:
+- At least one clip; Active is a valid slot and not a reference.
+- Setting a clip to reference is refused for Active; making a reference clip Active
+ clears its reference flag first (it becomes editable).
+- Removing a clip (dead after an arrangement edit) remaps slots; Active moves to the next
+ clip; an empty set closes the editor.
+
+## ClipNotes
+
+Commit payload: `(int TrackId, int ClipIndex, IReadOnlyList<NotaNote> Notes)` in
+clip-local beats.
+
+## Roll note ownership
+
+`PianoRollView._notes[i]` (editor beats) ↔ `_owner[i]` (slot). Invariant: equal lengths
+after every mutation. Notes of reference clips are present (drawn) but never selectable.
+
+## Clipboard note
+
+Spec 007's clipboard entry plus `SourceTrackId`, `SourceClipIndex`, `SourceClipStart`
+(R11).
+
+## State transitions
+
+```text
+open (double-click in multi-selection / "Edit selected clips")
+ └─► Active = clicked clip (or first in time)
+click strip bar / click a note of clip X → Active = X (settles pending placement)
+click lock on non-active X → X.IsReference toggled (settles placement)
+arrangement geometry change on X → X.Start/Length updated, notes reloaded
+X deleted / no longer MIDI → X removed from set
+re-open → set replaced (old placement settled first)
+```
diff --git a/specs/029-multi-clip-editing/plan.md b/specs/029-multi-clip-editing/plan.md
new file mode 100644
index 00000000..7cdfa962
--- /dev/null
+++ b/specs/029-multi-clip-editing/plan.md
@@ -0,0 +1,132 @@
+# Implementation Plan: Multi-Clip Editing in the Clip Editor
+
+**Branch**: `feat/multi-clip-editing` | **Date**: 2026-10-20 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `specs/029-multi-clip-editing/spec.md`
+
+## Summary
+
+Open several selected arrangement MIDI clips together in the Clip editor (GitHub
+nota-daw/nota#48). The piano roll keeps one flat note list, now in *editor beats* (offset
+from the earliest open clip) with a parallel per-note owner; a pure `ClipSet` model in
+`Nota.Application/Editing` owns coordinates, the owner/"reach" rules for moving notes
+across seams, and per-clip split/merge. A one-clip set is today's editor (parity by
+construction). Cross-clip edits are committed per clip inside the engine's existing undo
+group, so one Undo restores every clip — no engine or C ABI change. A clip strip under the
+ruler switches the active clip and toggles reference (read-only) clips. See
+[research.md](research.md).
+
+## Nota: Read Before Planning
+
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill (clip strip,
+ subdued / reference note looks, header).
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+- Engine untouched; [`ARCHITECTURE.md`](../../ARCHITECTURE.md) AR rules hold trivially.
+
+## Technical Context
+
+**Language/Version**: C# / .NET 10 (managed app only)
+
+**Primary Dependencies**: Avalonia (existing). No new dependency.
+
+**Storage**: N/A — the open clip set and reference flags are editor-session state; notes
+persist through the existing per-clip engine lists.
+
+**Audio-Thread Impact**: None. Notes reach the engine through the existing
+`SetClipNotes` / `SetClipNotesLive` calls; grouping uses the existing
+`nota_engine_undo_group_begin/end` on the message thread.
+
+**Testing**: `tests/Nota.SmokeTest` — new `MultiClipTests.cs` (`--multiclip`) for pure
+logic + one grouped-undo engine check; existing `--notes` must stay green; headless
+Avalonia render for the strip and note looks.
+
+**Target Platform**: macOS, Linux, Windows (desktop app).
+
+**Project Type**: Desktop app (Avalonia) over a native engine.
+
+**Performance Goals**: SC-003 — 8 clips / 2,000 notes drag as smoothly as one clip with
+2,000 notes: owner lookups O(1); live drag pushes only clips whose notes changed.
+
+**Constraints**: Single-clip and Session-slot editors behave exactly as today (FR-002).
+
+**Scale/Scope**: ~1 new Application file, ~1 new App control, changes in
+`PianoRollView*.cs`, `ClipEditorView.cs`, `ClipPropsView.cs`, `MidiToolsView.cs`,
+`MainWindow.Detail.cs`, `MainWindow.Commands.cs`, `ArrangementView*.cs`,
+`NoteOverwrite.cs`.
+
+## Constitution Check
+
+| Principle | Status |
+|-----------|--------|
+| I. Real-time audio safety | Pass — no audio-thread code touched |
+| II. Boundary discipline | Pass — no ABI change; existing undo-group call reused |
+| III. Licensing hygiene | Pass — new files get SPDX headers; no dependency |
+| IV. Verification gate | Pass — smoke test extended (`MultiClipTests`, grouped undo); `scripts/build.sh` before PR |
+| V. One logical change per PR | Pass — one feature; docs in the same PR as per repo practice |
+| VI. Docs in sync | Planned — CHANGELOG `[Unreleased]`, `nota-features`, `nota-docs`, `nota-shortcuts` (strip gestures, palette command) |
+| VII. Spec-first | Pass — spec + clarifications done |
+| VIII. Rules not weakened | Pass |
+
+Post-design re-check: unchanged — Phase 1 introduced no engine, ABI or dependency change.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/029-multi-clip-editing/
+├── plan.md
+├── research.md
+├── data-model.md
+├── quickstart.md
+├── contracts/
+│ ├── piano-roll-api.md
+│ └── ui.md
+├── checklists/requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code
+
+```text
+src/managed/
+├── Nota.Application/Editing/
+│ ├── ClipSet.cs # NEW: OpenClip, ClipSet, ClipNotes — coords, reach, owner rule, split/merge
+│ └── NoteOverwrite.cs # owner-aware Settle/Fate overloads (null owners = today)
+└── Nota.App/
+ ├── PianoRollView.cs # _owner list, SetClips, active/reference, per-clip commit, paste routing, bounds
+ ├── PianoRollView.ClipStrip.cs # NEW: the clip strip control
+ ├── PianoRollView.Expression.cs # notes by owner (velocity lane colours, reference skipped)
+ ├── ClipEditorView.cs # header "+N clips", ActiveClipChanged → EnvOverlay rebind
+ ├── ClipPropsView.cs # start/length/loop of the active clip
+ ├── MidiToolsView.cs # per-clip tool runs (R6)
+ ├── MainWindow.Detail.cs # BuildClipEditor(set), CommitClips + undo group, reload/geometry/selection-follow
+ ├── MainWindow.Commands.cs # "Edit selected clips" command
+ ├── MainWindow.axaml.cs # playhead via Origin
+ └── ArrangementView*.cs # SelectedMidiClips(), context-menu item
+
+tests/Nota.SmokeTest/
+├── MultiClipTests.cs # NEW (--multiclip)
+└── Program.cs # register the suite
+```
+
+**Structure Decision**: Managed-only change. Pure, testable rules go to
+`Nota.Application/Editing` next to `NoteOverwrite`/`SnapGrid`; view and host changes stay
+in `Nota.App` where the piano roll lives today.
+
+## Delivery order (feeds /speckit-tasks)
+
+1. `ClipSet` + owner-aware `NoteOverwrite` + `MultiClipTests` (pure, test-first).
+2. Roll internals: `_owner`, editor beats, `SetClips`, per-clip commit; single-clip parity
+ (`--notes` green). Host `BuildClipEditor(set)` + `CommitClips` with undo group. → Story 1 + core of Story 2.
+3. Cross-clip editing details: draw target, move reach/owner, paste routing, select-all /
+ marquee across clips, playhead/seek. → Story 2.
+4. Clip strip, active switching, reference lock, note looks. → Story 3 (+ FR-008).
+5. Inspector / envelopes / header / clip tools per clip / velocity lane. → Story 4.
+6. Host robustness: selection-follow off in multi, geometry/reload/dead-clip handling.
+7. Docs: CHANGELOG, FEATURES (`nota-features`), user docs (`nota-docs`), Shortcuts
+ (`nota-shortcuts`); `scripts/build.sh`; `/speckit-converge`.
+
+## Complexity Tracking
+
+None — no constitution violations.
diff --git a/specs/029-multi-clip-editing/quickstart.md b/specs/029-multi-clip-editing/quickstart.md
new file mode 100644
index 00000000..b309a038
--- /dev/null
+++ b/specs/029-multi-clip-editing/quickstart.md
@@ -0,0 +1,43 @@
+# Quickstart: validating multi-clip editing
+
+## Automated
+
+```bash
+dotnet run --project tests/Nota.SmokeTest -- --multiclip
+```
+
+Expect all `multiclip:` checks green: owner reassignment across a seam, a gap and a
+reference clip as walls, Split/Merge round-trip, per-clip overwrite, paste routing, and
+one grouped undo restoring two clips.
+
+```bash
+dotnet run --project tests/Nota.SmokeTest -- --notes
+```
+
+Spec 007 checks must stay green unchanged (single-clip parity, R3).
+
+```bash
+scripts/build.sh
+```
+
+The PR gate (native + managed build and the full smoke test).
+
+## Manual / headless scenarios
+
+Setup: one MIDI track with clips A (bars 1–4) and B (bars 5–8) holding a bass line, and a
+second track with a chord clip C (bars 1–8). Use `NOTA_DATA_DIR` to isolate data.
+
+1. Select A, B, C; double-click B → three clips open, strip shows three bars, B active,
+ ruler reads arrangement bars 1–8. (Story 1)
+2. Click one clip only in the arrangement → editor unchanged. (FR-001a)
+3. Rubber-band notes over A and B, press ↑ → both clips change; ⌘Z once → both restored.
+ (Story 2, FR-011)
+4. Drag a note of A so it starts in bar 5 → it lands in B; ⌘Z → back in A. (FR-006)
+5. Lock C in the strip; Select All → no chord notes selected; chords still play. (Story 3)
+6. Click a note of C after unlocking → C active; inspector shows C's start/length;
+ Envelopes tab edits C. (Story 4)
+7. Clip tools → Arpeggiate with notes selected in A and B → each clip gets its own
+ result; Apply → one undo step. (R6)
+8. Delete clip B in the arrangement → B drops out of the editor; A stays active-able.
+ (FR-013)
+9. Open a single clip → no strip, behaviour as before. (FR-002)
diff --git a/specs/029-multi-clip-editing/research.md b/specs/029-multi-clip-editing/research.md
new file mode 100644
index 00000000..afc7074d
--- /dev/null
+++ b/specs/029-multi-clip-editing/research.md
@@ -0,0 +1,129 @@
+# Research: Multi-Clip Editing in the Clip Editor
+
+Phase 0 of [plan.md](plan.md). Each entry: decision, rationale, alternatives.
+
+## R1 — One undo step across several clips (FR-011)
+
+**Decision**: Wrap every multi-clip commit in the engine's existing undo group
+(`nota_engine_undo_group_begin/end`, managed `IAudioEngine.BeginUndoGroup/EndUndoGroup`)
+and push each affected clip with the existing `SetClipNotes`. Live drag frames keep using
+`SetClipNotesLive` (no checkpoint), unchanged.
+
+**Rationale**: The group API exists and is already used by the MCP tools for multi-edit
+operations, so no C ABI or engine change is needed (constitution II, IV untouched). The
+single-clip drag already seeds its undo entry by committing the pre-drag notes once and
+then streaming live; the multi-clip version seeds all editable open clips inside one group.
+
+**Alternatives**: a new `set_clips_notes` batch call in the C ABI — rejected, duplicates
+what groups already provide and would need smoke coverage for no gain; managed-side
+undo stack — rejected, the engine owns undo for notes.
+
+## R2 — Where the "which clip owns this note" lives
+
+**Decision**: `PianoRollView` keeps its flat `_notes` list (now in *editor beats*: offset
+from the earliest open clip's start) plus a parallel `_owner` list of clip slots. A small
+set of private helpers (`AddNote`, `RemoveNoteAt`, `ReplaceAll`) keeps the two in sync;
+the ~13 structural mutations in `PianoRollView.cs` are routed through them. Owner rules,
+coordinate conversion, bounds and per-clip split/merge live in a pure class
+`Nota.Application/Editing/ClipSet.cs` so they are unit-testable in the smoke test.
+
+**Rationale**: `NotaNote` is blittable and mirrors the native struct, so no owner field
+can be added to it. Reworking every `_notes[i].X` read (≈100 sites) into a wrapper type is a
+large, risky diff; a parallel list touches only the mutation sites.
+
+**Alternatives**: one `PianoRollView` per clip stacked as layers — rejected, selection,
+marquee, drag and keyboard edits must span clips; wrapper struct `RollNote` — rejected
+for diff size (could be a later refactor).
+
+## R3 — Single-clip parity (FR-002, SC-004)
+
+**Decision**: The single-clip editor is a `ClipSet` of one clip whose origin is that
+clip's start, so editor beats equal clip-local beats and every existing code path runs
+unchanged. The clip strip is hidden for one clip. The session-slot editor keeps the plain
+`Commit` callback (no `ClipSet` commit wiring).
+
+**Rationale**: One code path; parity is provable by the existing note-editing tests
+running unchanged.
+
+## R4 — Move bounds and moving between clips (FR-006)
+
+**Decision**: For a group move, each note's allowed start range is its **reach**: the run
+of open, editable clips on its track that are contiguous with its current clip (next
+start ≤ previous end + ε). The shared delta is clamped so every note's start stays in its
+reach (shape kept, as today). After the move each moved note's owner is recomputed:
+keep the current clip if it contains the start, else the active clip if it is in the reach
+and contains the start, else the later-starting clip containing it. Tail overhang past the
+containing clip's end follows today's single-clip limits (start ≤ end − min length).
+Resize-left/right never change the owner.
+
+**Rationale**: Matches clarification 2; reach makes a gap or a reference clip a wall, which
+is exactly "stops at the edge as today".
+
+## R5 — Overwrite rule per clip (FR-010)
+
+**Decision**: Add owner-aware overloads of `NoteOverwrite.Settle` / `Fate` (an optional
+`IReadOnlyList<int>? owners`); same-pitch overlap only counts when owners match. With
+`owners == null` behaviour is byte-identical to today.
+
+## R6 — Clip tools and whole-clip commands (FR-005, Story 4)
+
+**Decision**: `MidiToolsView` runs `MidiToolRunner.Apply` **once per clip** in clip-local
+beats (`MidiToolContext.LengthBeats` = that clip's length): on clips that have selected
+notes, or — with no selection — on the active clip only. Results are merged back with
+their owner through a new `ShowPreview(IReadOnlyList<ClipNotes>)` overload. Quantize,
+Transpose, Remove-out-of-scale apply to all editable clips.
+
+**Rationale**: Generators add notes whose owner could not otherwise be known; per-clip runs
+also keep each clip's own length as the tool's boundary.
+
+## R7 — Arrangement selection vs. fixed clip set (FR-001a)
+
+**Finding**: Today `OnTrackSelected` resets the editor on a track switch and
+`OnDetailClip` re-points the Clip tab at the newly selected clip.
+
+**Decision**: When the open set has more than one clip, both skip the reset/re-point; the
+set only changes through `OpenClipEditor` (double-click / "Edit selected clips"). With one
+clip, today's follow-the-selection behaviour stays (FR-002).
+
+## R8 — Following arrangement changes (FR-013)
+
+**Decision**: Every host hook that touches the single editor today is generalised to the
+set: `OnClipGeometryChanged` updates the matching `OpenClip` (start/length) and reloads;
+`ReloadEditorNotes` (undo/redo, recording) reloads all clips; each commit validates every
+clip with `TryGetClipInfo(...).IsMidi` and drops dead clips from the set (active falls to
+the next clip; empty set → `InvalidateClipEditor`). Index shifts after a lower-index
+delete are handled exactly as the single editor handles them today (known limitation,
+not widened).
+
+## R9 — Envelopes, inspector, header, playhead, seek, record preview
+
+**Decision**: These follow the active clip. `ClipEditorView` listens to a new
+`PianoRollView.ActiveClipChanged` and rebinds the `EnvOverlay` (track/clip/length and an
+editor-beat offset), `ClipPropsView` start/length/loop and the header name
+("Name · +N clips"). Playhead and seek convert with the set origin
+(editor beat = arrangement beat − origin). The record-take preview is shown when the take
+clip is in the set, with `clipStart = origin`.
+
+## R10 — Clip strip UI (FR-008, FR-009)
+
+**Decision**: A new `ClipStrip` control (row between `RulerLane` and the note grid, ~18px,
+only when the set has ≥2 clips) draws one bar per clip on the roll's beat axis, stacked in
+rows when clips of different tracks overlap; track colour fill, clip name, chosen marker
+on the active bar (accent per DESIGN.md: accent reserved for what is chosen), lock glyph
+on non-active bars. Click bar → active; click lock → toggle reference. Visuals via the
+`nota-design` skill.
+
+## R11 — Clipboard routing (FR-012)
+
+**Decision**: Clipboard entries carry their source `(trackId, clipIndex)` and the source
+clip's arrangement start. Paste: if the source clip is open, the copy goes to that clip at
+its original position; otherwise to the active clip at its clip-relative beat (spec 007
+rule). Single-clip behaviour unchanged.
+
+## R12 — Testing
+
+**Decision**: Pure logic (`ClipSet`, owner-aware `NoteOverwrite`, paste routing) gets
+`tests/Nota.SmokeTest/MultiClipTests.cs` (runnable alone: `--multiclip`), plus one
+engine-driven check that a grouped `SetClipNotes` on two clips is undone by one
+`Undo`. UI is verified with the headless Avalonia recipe (memory: nota-ui-verify) and a
+manual pass from [quickstart.md](quickstart.md).
diff --git a/specs/029-multi-clip-editing/spec.md b/specs/029-multi-clip-editing/spec.md
new file mode 100644
index 00000000..ffd11a3b
--- /dev/null
+++ b/specs/029-multi-clip-editing/spec.md
@@ -0,0 +1,329 @@
+# Feature Specification: Multi-Clip Editing in the Clip Editor
+
+**Feature Branch**: `feat/multi-clip-editing`
+
+**Created**: 2026-10-20
+
+**Status**: Draft
+
+**Input**: User description: "Clip editor: edit several clips at once (GitHub issue nota-daw/nota#48). Users want to edit notes across several MIDI clips at once — e.g. fix a bass line split into several clips, or write a melody against the chords in another clip. Select several MIDI clips (on one track or several) and open them together in the clip editor: all their notes are shown and editable on the shared timeline, with the active clip in full colour and the others either editable or dimmed for reference (as in Ableton Live 11+ multi-clip editing or Bitwig). Today the clip editor shows exactly one clip. Related: #49 (track mode)."
+
+## 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
+
+The engine is expected to be untouched: each clip's notes are still committed through the
+existing per-clip note path. Whether several per-clip commits can form one undo step is a
+plan-phase question (FR-011).
+
+**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).
+
+**Current state (for reference)**:
+
+- The arrangement already supports selecting several clips (click, Shift/Cmd-click,
+ rubber band). Double-clicking a MIDI clip opens the Clip editor for **that one clip**,
+ whatever else is selected.
+- The piano roll works in the clip's own beats (0 … clip length): the ruler, grid, notes,
+ velocity lane, expression lanes, clipboard, overwrite rule (spec 007), length/velocity
+ keys and the clip-tools panel all act on one note list. The inspector shows that clip's
+ start, length and loop.
+- Session-view slots open the same editor for one slot.
+
+## Clarifications
+
+### Session 2026-10-20
+
+- Q: How do open clips other than the active one behave by default? → A: All open clips
+ are editable; the active one is full colour, the others subdued; any non-active clip can
+ be switched to reference (dimmed, read-only).
+- Q: What happens when a note is dragged past its clip's edge into another open clip of
+ the same track? → A: A note whose start lands inside another open, editable clip of the
+ same track moves into that clip (one undo step); with no clip there it stops at the
+ edge as today. Notes never move between tracks.
+- Q: How does a set of clips get into the editor, and does it follow later arrangement
+ selection changes? → A: Fixed at opening (double-click on a selected clip, or "Edit
+ selected clips"); later selection changes leave the editor as it is until it is opened
+ again.
+- Q: Where does the user see the open clips and switch the active clip or reference
+ mode? → A: A clip strip above the note grid (under the ruler): one bar per clip in its
+ track colour over its time span; click makes it active, a lock icon toggles reference.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Open several clips together and see them on one timeline (Priority: P1)
+
+A user selects three consecutive bass clips on one track and opens them in the Clip
+editor. The piano roll shows all their notes laid out on the arrangement's timeline, each
+clip's span marked, so the bass line reads as one continuous part. One clip is the
+active clip (the one the user double-clicked) and is drawn in full colour.
+
+**Why this priority**: Seeing the clips together is the foundation of every other story
+and already answers the "write against the chords" use case visually.
+
+**Independent Test**: Select two MIDI clips at different positions, double-click one;
+the editor shows both clips' notes at their arrangement positions, the ruler shows
+arrangement bars, and the double-clicked clip is the active one.
+
+**Acceptance Scenarios**:
+
+1. **Given** clips A (bars 1–4) and B (bars 5–8) on one track are selected, **When** the
+ user double-clicks B, **Then** the editor shows A's and B's notes on a shared
+ timeline covering bars 1–8, B is the active clip, and the view scrolls to B.
+2. **Given** clips on two different tracks are selected, **When** the editor opens,
+ **Then** each clip's notes are drawn in its own track's colour and the clip spans are
+ visible behind the grid.
+3. **Given** several clips are selected, including audio clips, **When** the user
+ double-clicks a selected MIDI clip, **Then** only the MIDI clips open; audio clips are
+ ignored.
+4. **Given** one clip is selected, or the user double-clicks a clip that is not part of
+ the selection, **When** the editor opens, **Then** it behaves exactly as today
+ (single clip) — no change for users who never select several clips.
+5. **Given** a multi-clip editor is open, **When** the user selects other clips in the
+ arrangement with a single click, **Then** the editor keeps its clips; it changes only
+ when the user opens clips again.
+6. **Given** a multi-clip editor is open, **When** the editor header is read, **Then** it
+ names the active clip and shows how many clips are open (e.g. "Bass 2 · +2 clips").
+
+---
+
+### User Story 2 - Edit notes across all open clips (Priority: P1)
+
+The user fixes a bass line split over several clips without switching clips: they select
+notes in different clips with one rubber band, transpose, nudge, quantize or delete them
+together, and draw new notes wherever a clip is.
+
+**Why this priority**: The core request — editing, not just viewing, across clips.
+
+**Independent Test**: Open two clips together, rubber-band notes spanning both, press ↑;
+every selected note in both clips moves up a semitone, and one Undo reverts all of them.
+
+**Acceptance Scenarios**:
+
+1. **Given** two open clips, **When** the user rubber-bands across both, **Then** notes
+ from both clips are selected, and Select All selects the notes of every editable clip.
+2. **Given** a selection spanning two clips, **When** the user moves, resizes, transposes,
+ nudges, changes velocity, quantizes or deletes it, **Then** each note is changed in its
+ own clip, and a single Undo reverts the whole edit in every clip.
+3. **Given** the user draws a note inside clip B's span, **Then** the note is added to
+ clip B and B becomes the active clip; drawing where no open clip of the active
+ track lies does nothing.
+4. **Given** clips A (bars 1–4) and B (bars 5–8) on one track, **When** a note of A is
+ dragged so that it starts in bar 5, **Then** it moves into clip B (keeping its
+ arrangement position), and one Undo puts it back in A.
+4a. **Given** a note of clip A is dragged past A's end where no open clip of that track
+ lies (a gap, or the next clip is not open or is a reference), **Then** it stays in A
+ and stops at A's edge as today.
+4b. **Given** clips on two tracks, **When** a note is dragged vertically or over the other
+ track's clip span, **Then** it never moves to the other track's clip.
+5. **Given** two open clips on the same track overlap in time, **When** a note is drawn in
+ the overlapping area, **Then** it goes to the active clip.
+6. **Given** clicking a note of a non-active clip, **Then** that clip becomes the active
+ clip (full colour, inspector and header follow) and the note is selected.
+7. **Given** notes were copied in a multi-clip editor, **When** pasted, **Then** each copy
+ lands on top of its original in the original's clip (spec 007 paste rule); notes
+ copied from a clip that is not open land in the active clip at their clip-relative
+ beats.
+8. **Given** a placed note overlaps a same-pitch note **of the same clip**, **Then** the
+ spec 007 overwrite rule applies; notes of other clips are never cut or removed by it.
+
+---
+
+### User Story 3 - Keep some clips as read-only reference (Priority: P2)
+
+Writing a melody against the chords, the user wants the chord clip visible but not
+accidentally edited. They mark a clip as reference: its notes are drawn dimmed, cannot be
+selected or changed, and are skipped by Select All and rubber band.
+
+**Why this priority**: The issue asks for "editable or dimmed for reference"; editing all
+clips (Story 2) delivers value on its own, the reference mode refines it.
+
+**Independent Test**: Open a melody clip and a chord clip, mark the chord clip as
+reference, rubber-band over everything; only melody notes are selected, and chord notes
+are drawn dimmed.
+
+**Acceptance Scenarios**:
+
+1. **Given** a multi-clip editor, **When** the user clicks the lock on a clip's bar in
+ the clip strip, **Then** the clip becomes a reference:
+ its notes are drawn dimmed and ignore clicks, rubber band, Select All and every edit.
+2. **Given** the active clip, **When** the user tries to mark it as reference, **Then**
+ it is not allowed (the active clip is always editable); marking another clip active
+ first is required.
+3. **Given** a reference clip, **When** the user toggles it back, **Then** its notes are
+ editable again.
+4. **Given** reference clips, **Then** they still play back normally — reference is only
+ an editing lock, not a mute.
+
+---
+
+### User Story 4 - Inspector, envelopes and tools in multi-clip mode (Priority: P3)
+
+The panels around the roll keep working: the inspector shows the active clip's start,
+length and loop; the Envelopes tab edits the active clip's envelope; clip-tools and the
+Selection read-out act on the selected notes wherever they are; the velocity and
+expression lanes show the notes of all editable clips.
+
+**Why this priority**: Needed for a complete, unsurprising editor, but each panel already
+works on one clip; extending them is polish over Stories 1–2.
+
+**Independent Test**: With two clips open, switch the active clip by clicking a note and
+check that the inspector's Start/Length change to that clip; change velocities in the
+velocity lane for notes of both clips.
+
+**Acceptance Scenarios**:
+
+1. **Given** the active clip changes, **Then** the inspector (Start, Length, Loop) and the
+ Envelopes tab switch to that clip.
+2. **Given** selected notes in two clips, **When** a clip-tool (e.g. quantize, humanize)
+ is applied, **Then** it acts on the selected notes in both clips as one undo step.
+3. **Given** the velocity lane, **Then** it shows a bar for every note of every editable
+ clip, in its track colour, and editing a bar changes that note in its own clip.
+4. **Given** the Scale overlay, **Then** it applies to the editor as a whole (one key and
+ mode), as today.
+
+### Edge Cases
+
+- An open clip is deleted, moved, resized or undone away while the editor is open: that
+ clip drops out of the editor (or follows its new position); if the active clip goes,
+ the next open clip becomes active; if none remain, the editor closes as today.
+- An open clip is moved in the arrangement: its notes follow it on the shared timeline.
+- Two open clips of one track overlap in time and a moved note starts in the overlap: it
+ stays in its current clip if that clip contains the start, otherwise it goes to the
+ active clip, otherwise to the clip that starts later.
+- A selection whose notes would move into several different clips is allowed; each note
+ lands in the clip containing its new start, and notes that would land in a gap stop the
+ whole selection at the edge, keeping its shape (as moves stop at the clip edge today).
+- Clips far apart (e.g. bar 1 and bar 200): the timeline covers the full span; zoom-to-fit
+ fits all open clips; gaps between clips are drawn as outside-clip area.
+- Clips on several tracks with the same pitches at the same time: notes overlap visually;
+ the active clip's notes are drawn on top.
+- Note audition plays into the track of the note being placed or clicked.
+- The ruler seeks in arrangement beats (no clip-local conversion needed).
+- Deactivated clips open like any other; their notes are drawn as deactivated clips are
+ today.
+- Session-view slots cannot be combined with arrangement clips; multi-clip applies to
+ the arrangement only.
+- Recording into a track while its clip is open in a multi-clip editor behaves like the
+ single-clip editor does today.
+- The placement settle rule (spec 007) still applies: switching the active clip, closing
+ the editor or saving settles the pending placement in every clip it touches.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Double-clicking a MIDI clip that is part of a selection of two or more MIDI
+ clips MUST open all selected MIDI clips together in the Clip editor, with the
+ double-clicked clip active. A menu/command "Edit selected clips" MUST do the same, with
+ the first selected clip in time active.
+- **FR-001a**: The open clip set MUST be fixed when the editor opens. Changing the
+ arrangement selection afterwards MUST NOT add, remove or re-activate clips in the
+ editor; only opening the editor again (FR-001) replaces the set.
+- **FR-002**: Opening a single clip, or a clip outside the selection, MUST behave exactly
+ as the current single-clip editor.
+- **FR-003**: In a multi-clip editor the roll's horizontal axis MUST be arrangement time:
+ ruler, grid, bar numbers and seek use arrangement beats; each open clip's span MUST be
+ drawn, the area outside all spans drawn as outside-clip.
+- **FR-004**: The active clip's notes MUST be drawn in full colour; other editable clips'
+ notes MUST be drawn in their track colour but visibly subdued; reference clips' notes
+ MUST be drawn dimmed further. The active clip MUST be distinguishable in the header.
+- **FR-005**: Selection, rubber band, Select All, move, resize, transpose, nudge,
+ length/velocity keys, delete, duplicate, quantize and the clip-tools MUST act on
+ selected notes across all editable clips; each changed note stays in its own clip.
+- **FR-006**: A note belongs to the clip that contains its start. When a move puts a
+ note's start inside another open, editable clip of the same track, the note MUST move
+ into that clip, keeping its arrangement position; this is part of the same undo step as
+ the move. Where no such clip lies, the move MUST stop at the note's clip edge as today.
+ Note ends follow the same limits as in the single-clip editor, measured against the
+ clip that contains the note; resizing never moves a note between clips; notes never
+ move between tracks. While a moved selection is still unsettled
+ (spec 007), the move into another clip MAY be shown live but the overwrite rule in the
+ destination clip applies only on settle.
+- **FR-007**: New notes (draw, paste of foreign notes) MUST go to the active clip, or —
+ when drawn inside the span of another open clip of the active clip's track — to that
+ clip, which then becomes active. Drawing outside every open clip of that track MUST do
+ nothing.
+- **FR-008**: A multi-clip editor MUST show a clip strip between the ruler and the note
+ grid: one bar per open clip, in its track colour, spanning the clip's time range and
+ labelled with the clip name; the active clip's bar is marked as chosen. Clicking a bar
+ MUST make that clip active; clicking or selecting a single note of a non-active clip
+ MUST do the same. The header, inspector and Envelopes tab MUST follow the active clip.
+ Overlapping clips of different tracks stack in the strip. The strip is not shown in
+ the single-clip editor.
+- **FR-009**: The user MUST be able to mark any non-active open clip as reference
+ (read-only) and back with a lock icon on its bar in the clip strip; reference clips' notes cannot be selected or edited and are
+ excluded from Select All and rubber band. Reference state lasts for the editor session
+ and is not saved in the project.
+- **FR-010**: The overwrite rule (spec 007) MUST only apply between notes of the same
+ clip.
+- **FR-011**: Any single edit that changes notes in several clips MUST be one undo step,
+ and one Undo MUST restore every affected clip.
+- **FR-012**: Copy/paste MUST keep each copied note's clip: copies paste on top of their
+ originals in the original clip when that clip is open; notes from a clip that is not
+ open paste into the active clip at their clip-relative beats.
+- **FR-013**: The editor MUST follow arrangement changes to its open clips (move, resize,
+ delete, undo) without pushing edits to clips that no longer exist.
+- **FR-014**: CHANGELOG, FEATURES.md, the user docs and (for any new shortcut or gesture)
+ the Shortcuts pane MUST describe multi-clip editing.
+
+### Key Entities
+
+- **Open clip set**: the MIDI clips shown in one Clip editor — each with its track,
+ arrangement start, length, track colour and an editable/reference flag; exactly one is
+ active.
+- **Active clip**: the clip that receives new notes and drives the header, inspector and
+ envelopes.
+- **Note (in multi-clip mode)**: as today (pitch, start, length, velocity, expression),
+ plus the clip it belongs to (the open clip containing its start); its on-screen
+ position is clip start + note start.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: A bass line split over 4 clips can be transposed by a semitone in one
+ selection + one key press, versus opening each clip separately (4× today).
+- **SC-002**: One Undo after any cross-clip edit leaves every affected clip identical to
+ its state before the edit, in 100% of cases.
+- **SC-003**: Editing with 8 clips and 2,000 notes open stays as responsive as the
+ single-clip editor with the same number of notes (drags follow the pointer without
+ visible lag).
+- **SC-004**: Users who never select more than one clip see no change in behaviour.
+- **SC-005**: No edit in a multi-clip editor ever changes a reference clip or a clip that
+ is not open.
+
+## Assumptions
+
+- Only arrangement MIDI clips take part; audio clips and Session slots are out of scope.
+- Track mode (#49 — editing all clips of a track without selecting them) is a separate
+ feature; this spec's open clip set is designed so #49 can reuse it.
+- Notes move between clips only by dragging across a seam between open clips of one
+ track; merging or splitting clips stays an arrangement edit.
+- The Scale overlay, snap grid, zoom and audition settings remain editor-wide.
+- Clip loop is fixed ("clips always loop" in the inspector); the roll shows each clip's
+ own notes over its span, not looped repetitions.
+- Reference state is per editor session and not persisted.
+- The engine already supports per-clip note commits; grouping several commits into one
+ undo step is resolved in the plan (managed-side grouping preferred, engine change only
+ if unavoidable).
+
+## 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: none expected — note edits go through the existing per-clip commit path
+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); a grouped-undo call, if needed, is added there
+- [x] Smoke-test impact assessed: none unless the plan adds an engine undo-group call, which would then be covered by the smoke test
+- [x] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned, plus FEATURES.md and user docs (nota-features / nota-docs); Shortcuts pane via nota-shortcuts if a binding is added
+- [x] UI change → follows `DESIGN.md` (Studio design language): track colours carry the work, the orange accent only for the active/chosen clip
diff --git a/specs/029-multi-clip-editing/tasks.md b/specs/029-multi-clip-editing/tasks.md
new file mode 100644
index 00000000..45fa8819
--- /dev/null
+++ b/specs/029-multi-clip-editing/tasks.md
@@ -0,0 +1,220 @@
+---
+
+description: "Tasks for 029 multi-clip editing"
+---
+
+# Tasks: Multi-Clip Editing in the Clip Editor
+
+**Input**: Design documents from `specs/029-multi-clip-editing/`
+
+**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),
+[data-model.md](data-model.md), [contracts/](contracts/), [quickstart.md](quickstart.md)
+
+**Tests**: Included — the constitution's verification gate (IV) and plan.md call for
+`tests/Nota.SmokeTest/MultiClipTests.cs` (`--multiclip`) for the pure rules plus one
+engine-driven grouped-undo check; `--notes` (spec 007) must stay green unchanged.
+
+**Organization**: Grouped by user story. Paths are real Nota paths (the UI lives in
+`src/managed/Nota.App/`).
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
+- **[Story]**: US1 … US4 from spec.md
+
+---
+
+## Phase 1: Setup
+
+**Purpose**: Test harness entry point for the new suite.
+
+- [X] T001 Create `tests/Nota.SmokeTest/MultiClipTests.cs` (SPDX header, `internal static class MultiClipTests` with `public static IEnumerable<(bool Ok, string Label)> Run()` returning no checks yet) and register it in `tests/Nota.SmokeTest/Program.cs` both as a standalone `--multiclip` mode (mirror the `--notes` block near line 284) and in the full run (next to `NoteEditingTests.Run()` near line 14939)
+
+---
+
+## Phase 2: Foundational (Blocking Prerequisites)
+
+**Purpose**: The pure `ClipSet` model, owner-aware overwrite, and the roll's owner
+plumbing with single-clip parity. Every story builds on these.
+
+**⚠️ CRITICAL**: No user story work can begin until this phase is complete.
+
+### Tests (write first, see them fail)
+
+- [X] T002 [P] Add `ClipSet` checks to `tests/Nota.SmokeTest/MultiClipTests.cs`: Origin = min StartBeat, SpanBeats = max(Start+Length) − Origin; ToEditor/ToLocal round-trip; clips ordered by StartBeat then TrackId; Split→Merge round-trip preserves every note and owner; a one-clip set has Origin = clip start so editor beats equal clip-local beats; validation per data-model.md ("At least one clip; Active is a valid slot and not a reference"; "Setting a clip to reference is refused for Active"; "making a reference clip Active clears its reference flag first"); removing a clip remaps slots and moves Active to the next clip
+- [X] T003 [P] Add owner-aware overwrite checks to `tests/Nota.SmokeTest/MultiClipTests.cs`: two same-pitch overlapping notes with different owners are both kept by `NoteOverwrite.Settle(..., owners)`; same owners behave exactly as spec 007; `Fate(..., owners)` agrees with `Settle`; `owners == null` gives results identical to the existing overloads
+
+### Implementation
+
+- [X] T004 [P] Create `src/managed/Nota.Application/Editing/ClipSet.cs` (SPDX header, namespace `Nota.Application.Editing`): `OpenClip` (TrackId, ClipIndex, StartBeat, LengthBeats, IsReference), `ClipNotes(int TrackId, int ClipIndex, IReadOnlyList<NotaNote> Notes)`, and `ClipSet` with `Clips`, `Active`, `Origin`, `SpanBeats`, `IsMulti`, `ToEditor`, `ToLocal`, `Split(notes, owners)`, `Merge(perClip)`, `SetActive`, `SetReference`, `Remove(trackId, clipIndex)`, `UpdateGeometry(trackId, clipIndex, start, length)` per [data-model.md](data-model.md); make T002 pass
+- [X] T005 [P] Add optional `IReadOnlyList<int>? owners` (and `List<int>? outOwners` for Settle) parameters to `Settle` and `Fate` in `src/managed/Nota.Application/Editing/NoteOverwrite.cs`; same-pitch overlap counts only when owners match; `owners == null` must stay byte-identical to today; make T003 pass
+- [X] T006 Add the parallel owner list to `src/managed/Nota.App/PianoRollView.cs`: field `List<int> _owner`, private helpers `AddNote(NotaNote, int owner)`, `RemoveNoteAt(int)`, `ReplaceAll(IEnumerable<NotaNote>, IEnumerable<int>)`, and route every structural `_notes` mutation through them (SetNotes, DuplicateSelection, DeleteSelection, RemoveOutOfScaleNotes, ShowPreview, CancelPreview, PasteClipboard, SettlePlacement, `_previewBackup` save/restore, NoteGrid double-click add/remove near line 1585); add a debug assert that `_notes.Count == _owner.Count` after each helper
+- [X] T007 Add `SetClips(ClipSet set, IReadOnlyList<ClipNotes> notes)`, `Clips`, `ActiveClip`, `Origin` to `src/managed/Nota.App/PianoRollView.cs` per [contracts/piano-roll-api.md](contracts/piano-roll-api.md): merge notes into editor beats with owners, `_lengthBeats = set.SpanBeats`, view-state key = active clip; make existing `SetNotes(notes, length)` build a one-clip set internally so single-clip and Session-slot callers are unchanged (R3)
+- [X] T008 Add `CommitClips` / `CommitClipsLive` (`Action<IReadOnlyList<ClipNotes>>`) to `src/managed/Nota.App/PianoRollView.cs`; `CommitNotes` and `PushLive` split via `ClipSet.Split` and call them when set (only clips whose notes changed since the last commit; the drag-seed commit passes every editable clip), falling back to `Commit`/`CommitLive` otherwise; keep a per-clip last-committed snapshot for the change check
+- [X] T009 Pass `_owner` to `NoteOverwrite.Settle`/`Fate` everywhere the roll calls them (SettlePlacement, DuplicateSelection, the overwrite marks in NoteGrid render) in `src/managed/Nota.App/PianoRollView.cs`, carrying owners through to the settled list
+- [X] T010 Run `dotnet run --project tests/Nota.SmokeTest -- --notes` and `-- --multiclip`; both green (single-clip parity checkpoint)
+
+**Checkpoint**: Roll can hold notes of several clips with owners; one-clip behaviour unchanged.
+
+---
+
+## Phase 3: User Story 1 - Open several clips together (Priority: P1) 🎯 MVP
+
+**Goal**: Double-click a clip within a multi-selection opens all selected MIDI clips on one
+arrangement-time axis, clicked clip active, notes in track colours.
+
+**Independent Test**: Select two MIDI clips at different positions, double-click one; both
+clips' notes appear at their arrangement positions, the ruler shows arrangement bars, the
+double-clicked clip is active; with one clip selected nothing changed.
+
+### Tests
+
+- [X] T011 [P] [US1] Add an engine-driven check to `tests/Nota.SmokeTest/MultiClipTests.cs`: create two MIDI clips, `BeginUndoGroup`, `SetClipNotes` on both, `EndUndoGroup`, one `Undo` restores both clips' previous notes (FR-011 basis; follow the engine setup used in `tests/Nota.SmokeTest/HistoryTests.cs`)
+
+### Implementation
+
+- [X] T012 [P] [US1] Add `IReadOnlyList<(int TrackId, int ClipIndex)> SelectedMidiClips()` to `src/managed/Nota.App/ArrangementView.cs` (from `_sel`, MIDI only, ordered by StartBeat then track order)
+- [X] T013 [US1] Generalise `BuildClipEditor` in `src/managed/Nota.App/MainWindow.Detail.cs` to take a list of `(trackId, clipIndex)` plus the active one: build `ClipSet` from `Engine.TryGetClipInfo`, load each clip's notes, `roll.SetClips`, store the set (replace `_editorTrackId/_editorClipIndex` usages with the active clip where a single id is still needed); wire `CommitClips` (validate each clip `TryGetClipInfo(...).IsMidi` else drop it from the set; `Engine.BeginUndoGroup()`; `SetClipNotes` per entry; `EndUndoGroup()` in `finally`; `Timeline.Refresh()`) and `CommitClipsLive` (`SetClipNotesLive`, `Timeline.Refresh(rebuildHeaders: false)`)
+- [X] T014 [US1] In `OpenClipEditor` (`src/managed/Nota.App/MainWindow.Detail.cs`) open every `Timeline.SelectedMidiClips()` when the double-clicked clip is among them and there are ≥2, active = double-clicked; otherwise one clip as today (FR-001, FR-002); audio clips in the selection are ignored
+- [X] T015 [US1] Draw notes of all clips in `src/managed/Nota.App/PianoRollView.cs` NoteGrid render with their own track brush (host passes per-clip brushes via `ClipSet`/a `Func<int, ISolidColorBrush>`), active clip full colour, other clips subdued (opacity per `nota-design`), active clip's notes drawn last (on top); replace `DrawOutsideClip` with a wash over every editor-beat range not covered by any open clip
+- [X] T016 [US1] Ruler/playhead/seek in arrangement time: `RulerLane` bar numbers offset by `Origin` (`src/managed/Nota.App/PianoRollView.cs`), `Seek` callback gets `Origin + editorBeat` and the playhead in `src/managed/Nota.App/MainWindow.axaml.cs` (near line 306) uses `beats − Origin`; on open, scroll so the active clip is in view
+- [X] T017 [US1] Header in `src/managed/Nota.App/ClipEditorView.cs`: active clip name and track colour cell, plus "· +N clips" when the set is multi (Story 1 scenario 6)
+- [X] T018 [US1] Fixed set (FR-001a): in `OnTrackSelected` and `OnDetailClip` (`src/managed/Nota.App/MainWindow.Detail.cs`) skip `ResetClipEditor` / re-pointing while the open set is multi; single-clip behaviour unchanged
+- [X] T019 [US1] Add the "Edit selected clips" command: `B("roll.editSelected", …)` in `src/managed/Nota.App/MainWindow.Commands.cs` (enabled only with ≥2 selected MIDI clips; active = first in time) and an item in the arrangement clip context menu in `src/managed/Nota.App/ArrangementView.LaneControl.cs` (near line 1158)
+
+**Checkpoint**: Multi-clip view works; edits already land in the right clips through the owner plumbing.
+
+---
+
+## Phase 4: User Story 2 - Edit notes across all open clips (Priority: P1)
+
+**Goal**: Selection and every edit span clips; draw goes to the right clip; notes cross seams
+into neighbouring open clips; paste routes copies to their source clip; one Undo per edit.
+
+**Independent Test**: Open two clips, rubber-band across both, press ↑ → both change, one
+⌘Z restores both; drag a note of A to start in B → it moves to B.
+
+### Tests
+
+- [X] T020 [P] [US2] Add reach/owner checks to `tests/Nota.SmokeTest/MultiClipTests.cs`: A(0–16)+B(16–32) same track → note moved to start 17 gets owner B; gap between A(0–16) and B(20–36) → move clamped at A's edge (start ≤ 16 − min length); B reference → wall; clip on another track never becomes owner; overlapping same-track clips → keep current if it contains the start, else active, else later-starting; resize never changes owner
+- [X] T021 [P] [US2] Add paste-routing checks to `tests/Nota.SmokeTest/MultiClipTests.cs` (FR-012): copies from an open clip land on their originals in that clip; copies from a clip not in the set land in the active clip at their clip-relative beats
+
+### Implementation
+
+- [X] T022 [US2] Add `Reach(slot)` and `OwnerAfterMove(slot, editorStart)` to `src/managed/Nota.Application/Editing/ClipSet.cs` per research R4 (contiguous = next start ≤ previous end + 1e-9; only open, non-reference clips of the same track); make T020 pass
+- [X] T023 [US2] Use reach in moves in `src/managed/Nota.App/PianoRollView.cs`: `MoveSelection` and NoteGrid `DragUpdate` Mode.Move clamp the shared delta so every moved note's start stays in its reach (shape kept; replaces the `_lengthBeats` cap), then set `_owner[i] = OwnerAfterMove(...)`; ResizeSelection / resize drags clamp against the owner clip's end and never change owner
+- [X] T024 [US2] Draw target (FR-007) in NoteGrid double-click (`src/managed/Nota.App/PianoRollView.cs`, near line 1588): owner = the active clip if it contains the beat, else another open editable clip of the active clip's track containing it (which then becomes active), else do nothing; `NewNoteLen` caps at the owner clip's end
+- [X] T025 [US2] Selection across clips in `src/managed/Nota.App/PianoRollView.cs`: marquee, Select All (`SelectPitch` and the select-all path), hit-test and keyboard edits skip notes whose owner is a reference clip; clicking or selecting a single note of a non-active clip calls `SetActiveClip` (settles a pending placement first)
+- [X] T026 [US2] Clipboard with source (R11) in `src/managed/Nota.App/PianoRollView.cs`: `s_clipboard` entries keep source `(TrackId, ClipIndex)` and the source clip's arrangement start; `PasteClipboard` routes per T021 and trims/skips against the target clip's span; `DuplicateSelection` keeps each copy in its original's clip (cap at that clip's end); make T021 pass
+- [X] T027 [US2] Whole-clip commands across editable clips in `src/managed/Nota.App/PianoRollView.cs`: `Quantize`, `TransposeBy`, `RemoveOutOfScaleNotes` skip reference-clip notes; quantize snaps on the editor grid, which with several clips open is the arrangement's bar grid (ClipSet puts editor beat 0 on a bar line), so every clip lands on the same grid
+- [X] T028 [US2] Audition plays on the note's own track: replace the single `AuditionOn/AuditionOff` target with a track resolved from `_owner` of the placed/clicked note (`src/managed/Nota.App/PianoRollView.cs` + wiring in `src/managed/Nota.App/MainWindow.Detail.cs`)
+
+**Checkpoint**: Stories 1+2 deliver the core request (the bass-line fix).
+
+---
+
+## Phase 5: User Story 3 - Reference clips (Priority: P2)
+
+**Goal**: Clip strip under the ruler; click a bar to make it active; lock toggles reference
+(dimmed, read-only, still plays).
+
+**Independent Test**: Open a melody clip and a chord clip, lock the chord clip, rubber-band
+everything → only melody notes selected; chord notes dimmed; playback unchanged.
+
+- [X] T029 [US3] Design the strip and note looks with the `nota-design` skill (bar height ~18px, track-colour fill, clip name, chosen marker on the active bar, lock glyph, subdued and reference note opacities, stacking rows when clips of different tracks overlap); record the chosen tokens in a comment header of the new file
+- [X] T030 [US3] Create `src/managed/Nota.App/PianoRollView.ClipStrip.cs` (SPDX header): `ClipStrip : Control` on the roll's beat axis (BeatToX), visible only when `Clips.IsMulti`, hosted between `RulerLane` and the note grid in the `PianoRollView` layout; click bar → `SetActiveClip`; click lock (non-active bars only) → `SetReference`; repaint with `Invalidate()`
+- [X] T031 [US3] `SetActiveClip(int)` / `SetReference(int, bool)` + `ActiveClipChanged` in `src/managed/Nota.App/PianoRollView.cs`: settle pending placement first, refuse reference for the active slot, drop reference notes from the selection, redraw reference notes dimmed with no hover/edge cursors
+- [X] T032 [US3] Velocity lane in `src/managed/Nota.App/PianoRollView.cs` (`VelocityLane`): bars in each note's track colour, reference-clip notes not drawn and not grabbable
+
+**Checkpoint**: Composing against a locked chord clip works.
+
+---
+
+## Phase 6: User Story 4 - Inspector, envelopes and tools (Priority: P3)
+
+**Goal**: Panels follow the active clip; clip tools act per clip.
+
+**Independent Test**: With two clips open, click a note of the other clip → inspector Start/
+Length and Envelopes switch to it; Arpeggiate on notes in both clips → each clip gets its
+own result, Apply is one undo step.
+
+- [X] T033 [P] [US4] `src/managed/Nota.App/ClipPropsView.cs`: Start/Length/Loop read the active clip (subscribe to `ActiveClipChanged`); Start edits move the active clip as today
+- [X] T034 [P] [US4] `src/managed/Nota.App/ClipEditorView.cs`: on `ActiveClipChanged` rebind `EnvOverlay` to the active clip's track/clip/length and draw it offset by that clip's editor start; refresh the header (T017)
+- [X] T035 [US4] Per-clip tool runs (R6): add `SourceClipNotes`, `SelectionByClip` and `ShowPreview(IReadOnlyList<ClipNotes>)` to `src/managed/Nota.App/PianoRollView.cs`; in `src/managed/Nota.App/MidiToolsView.cs` `Resync`/`Preview` run `MidiToolRunner.Apply` once per clip that has selected notes (no selection → active clip only) with `MidiToolContext.LengthBeats` = that clip's length, merge results with owners; `ApplyPreview` commits all through `CommitClips` (one undo group); the scope text reads "N selected" / "clip · N"
+- [X] T036 [US4] Expression lanes in `src/managed/Nota.App/PianoRollView.Expression.cs` work on selected notes whatever their clip (editor-beat positions); reference notes excluded
+
+**Checkpoint**: All stories functional.
+
+---
+
+## Phase 7: Host robustness (cross-cutting, FR-013)
+
+- [X] T037 `OnClipGeometryChanged` in `src/managed/Nota.App/MainWindow.Detail.cs`: if the clip is in the open set, `ClipSet.UpdateGeometry` and reload the set (`SetClips`); `ReloadEditorNotes` reloads every clip of the set (undo/redo, recording); record-take preview shown when the take clip is in the set, with `clipStart = Origin`
+- [X] T038 Dead clips in `src/managed/Nota.App/MainWindow.Detail.cs`: on commit/reload, clips failing `TryGetClipInfo(...).IsMidi` are removed from the set (Active → next); empty set → `InvalidateClipEditor()`; `BuildClipEditor` and save/export keep calling `SettlePlacement()` before replacing the set
+
+---
+
+## Phase 8: Polish & Cross-Cutting Concerns
+
+- [X] T039 Performance check (SC-003): 8 clips / 2,000 notes in a headless or manual session; drag stays smooth; live pushes only changed clips (T008)
+- [X] T040 Headless Avalonia render of a three-clip editor (strip, subdued and reference notes, header) per the nota-ui-verify recipe; compare against the `nota-design` intent
+- [X] T041 Run the manual scenarios in [quickstart.md](quickstart.md)
+
+### Nota closing tasks *(PR gates)*
+
+- [X] T042 Run `scripts/build.sh` until native + managed + smoke test are green
+- [X] T043 AGPL-3.0-only SPDX two-line header on `ClipSet.cs`, `PianoRollView.ClipStrip.cs`, `MultiClipTests.cs`
+- [X] T044 New dependency: N/A (none)
+- [X] T045 `CHANGELOG.md` `[Unreleased]` → Added: edit several MIDI clips at once in the Clip editor (#48)
+- [X] T046 FEATURES.md via `nota-features`; clip-editor docs page (EN + RU) via `nota-docs`; Preferences → Shortcuts (clip-strip clicks, "Edit selected clips") via `nota-shortcuts`
+- [X] T047 Engine behaviour change: N/A (engine untouched; grouped undo covered by T011)
+
+---
+
+## Dependencies & Execution Order
+
+### Phase Dependencies
+
+- Setup (T001) → Foundational (T002–T010) → user stories.
+- US1 (Phase 3) depends on Foundational only.
+- US2 (Phase 4) depends on US1 (it needs a multi-clip editor to open: T013/T014).
+- US3 (Phase 5) depends on US1; independent of US2 except T025's reference skip, which reads the flag T031 sets (either order works; the skip is a no-op without the strip).
+- US4 (Phase 6) depends on US1; T035 uses `CommitClips` (T008/T013).
+- Host robustness (Phase 7) after US1; Polish last.
+
+### Within phases
+
+- Tests before their implementation (T002/T003 → T004/T005; T020 → T022; T021 → T026).
+- `PianoRollView.cs` tasks are sequential (same file).
+
+## Parallel Opportunities
+
+- Phase 2: T002 ∥ T003 (tests, same file — write together) ; T004 ∥ T005 (different files).
+- Phase 3: T011 ∥ T012 ∥ T017 (test file, ArrangementView, ClipEditorView).
+- Phase 6: T033 ∥ T034 (ClipPropsView, ClipEditorView).
+- Docs (T045, T046) in parallel once behaviour is final.
+
+```text
+# Phase 2 parallel start
+T004 ClipSet.cs ∥ T005 NoteOverwrite.cs
+# Phase 3 parallel start
+T011 grouped-undo test ∥ T012 SelectedMidiClips() ∥ T017 header
+```
+
+## Implementation Strategy
+
+- **MVP**: Phases 1–3 (US1) + Phase 4 (US2) — the issue's core: see and edit a split bass
+ line together. US1 alone is a viewable increment but not shippable without US2.
+- **Increment 2**: US3 (reference lock + strip).
+- **Increment 3**: US4 (panels, tools), Phase 7 robustness, polish and gates.
+- After all tasks: `/speckit-converge` must report Converged before the PR.
+
+## Nota Compliance Re-check
+
+- [x] SPDX headers planned for every new file (T043)
+- [x] No new dependency (T044)
+- [x] No audio-thread code touched
+- [x] No C ABI change; existing undo group reused
+- [x] Smoke test extended (T001–T003, T011, T020, T021)
+- [x] CHANGELOG / FEATURES / docs / shortcuts planned (T045, T046)
+- [x] UI follows DESIGN.md via `nota-design` (T029, T040)
diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.cs
index 19ff5530..41214d78 100644
--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs
+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs
@@ -281,6 +281,7 @@ public sealed partial class ArrangementView
// the select→Devices path), so the Clip tab targets this clip.
_o.SelTrackId = hh.track.Id;
_o.SelClipIndex = hh.clip.ClipIndex;
+ _o.RestoreNarrowed(hh.track.Id, hh.clip.ClipIndex);
_o.OnClipDoubleClicked(hh.track.Id, hh.clip.ClipIndex, hh.clip.IsMidi);
return;
}
@@ -554,7 +555,12 @@ public sealed partial class ArrangementView
_pending = false;
e.Pointer.Capture(null);
if (!_pendingWasSelected || _o.SelectionCount > 1)
+ {
+ // The first click of a double-click narrows too; keep what it narrowed so the
+ // double-click can open the whole selection together (specs/029).
+ _o.RememberNarrowed(_pendingTrackId, _pendingClipIndex, _pendingWasSelected);
_o.Select(_pendingTrackId, _pendingClipIndex);
+ }
// Also drop the playhead where the user clicked (same as clicking empty lane) —
// but not during playback: scrubbing off the grid is disruptive, use the ruler.
if (_o._engine is not { IsPlaying: true })
@@ -1225,6 +1231,14 @@ public sealed partial class ArrangementView
flyout.Items.Add(new Separator());
flyout.Items.Add(loop);
+ // Several MIDI clips selected: open them together in the Clip editor (specs/029).
+ if (clip.IsMidi && inGroup && _o.SelectedMidiClips().Count >= 2)
+ {
+ var together = new MenuItem { Header = "Edit selected clips together", Icon = MenuKit.Icon(GlyphKind.Edit) };
+ together.Click += (_, _) => _o.EditSelectedClipsRequested?.Invoke();
+ flyout.Items.Add(together);
+ }
+
// Audio clip → stems (AI model) and → MIDI: Convert / Slice to New MIDI Track.
if (!clip.IsMidi)
{
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index d5d9a1db..28724d5b 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -228,6 +228,8 @@ public sealed partial class ArrangementView : UserControl
/// <summary>Raised when a MIDI clip is double-clicked (trackId, clipIndex).</summary>
public event Action<int, int>? MidiClipActivated;
+ /// <summary>"Edit selected clips together" from a clip's context menu (specs/029).</summary>
+ public event Action? EditSelectedClipsRequested;
/// <summary>Raised when an audio clip is double-clicked (trackId, clipIndex).</summary>
public event Action<int, int>? AudioClipActivated;
/// <summary>Raised when a track becomes selected (clip or header click).</summary>
@@ -1124,6 +1126,35 @@ public sealed partial class ArrangementView : UserControl
// vertically (don't handle, so the event bubbles up to it).
}
+ // The multi-selection a click just narrowed down to one clip, kept for the double-click
+ // that click may be the first half of (specs/029).
+ private (int Track, int Clip, (int, int)[] Before)? _narrowed;
+
+ internal void RememberNarrowed(int trackId, int clipIndex, bool wasSelected)
+ => _narrowed = wasSelected && _sel.Count > 1 ? (trackId, clipIndex, _sel.ToArray()) : null;
+
+ /// <summary>A double-click on the clip a click just narrowed the selection to: put the
+ /// selection back, so the clips open together.</summary>
+ internal void RestoreNarrowed(int trackId, int clipIndex)
+ {
+ if (_narrowed is { } n && n.Track == trackId && n.Clip == clipIndex && _sel.Count == 1 && _sel.Contains((trackId, clipIndex)))
+ {
+ SetSelection(n.Before);
+ SelTrackId = trackId; SelClipIndex = clipIndex;
+ }
+ _narrowed = null;
+ }
+
+ /// <summary>The selected MIDI clips, ordered by start then track order (specs/029).</summary>
+ public IReadOnlyList<(int TrackId, int ClipIndex)> SelectedMidiClips()
+ {
+ var list = new List<(int, int, double, int)>();
+ for (int r = 0; r < _tracks.Count; r++)
+ foreach (var c in _tracks[r].Clips)
+ if (c.IsMidi && _sel.Contains((_tracks[r].Id, c.ClipIndex))) list.Add((_tracks[r].Id, c.ClipIndex, c.StartBeat, r));
+ return list.OrderBy(x => x.Item3).ThenBy(x => x.Item4).Select(x => (x.Item1, x.Item2)).ToList();
+ }
+
internal void OnClipDoubleClicked(int trackId, int clipIndex, bool isMidi)
{
if (isMidi) MidiClipActivated?.Invoke(trackId, clipIndex);
diff --git a/src/managed/Nota.App/ClipEditorKit.cs b/src/managed/Nota.App/ClipEditorKit.cs
index c662309c..52f6d844 100644
--- a/src/managed/Nota.App/ClipEditorKit.cs
+++ b/src/managed/Nota.App/ClipEditorKit.cs
@@ -26,6 +26,12 @@ internal static class ClipEditorKit
/// <summary>The 38px header: clip cell | modes | (flex) | right-hand controls.</summary>
public static Border Header(IBrush trackColor, string name, string kind, Control modes, Control? afterModes, Control? right)
+ => Header(trackColor, name, kind, modes, afterModes, right, out _, out _);
+
+ /// <summary>As above, handing back the name and the colour bar so a header can follow the
+ /// clip it names (the multi-clip editor's active clip).</summary>
+ public static Border Header(IBrush trackColor, string name, string kind, Control modes, Control? afterModes, Control? right,
+ out TextBlock nameOut, out Border colorBar)
{
var cell = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 9 };
var nameText = new TextBlock
@@ -39,6 +45,7 @@ internal static class ClipEditorKit
Foreground = NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Center,
};
cell.Children.Add(nameText);
+ nameOut = nameText;
Grid.SetColumn(badge, 1); cell.Children.Add(badge);
var cellHost = new Border
{
@@ -47,7 +54,7 @@ internal static class ClipEditorKit
{
Children =
{
- new Border { Width = 3, HorizontalAlignment = HorizontalAlignment.Left, Background = trackColor },
+ (colorBar = new Border { Width = 3, HorizontalAlignment = HorizontalAlignment.Left, Background = trackColor }),
new Border { Padding = new Thickness(14, 0), Child = cell },
},
},
diff --git a/src/managed/Nota.App/ClipEditorView.cs b/src/managed/Nota.App/ClipEditorView.cs
index 853073e3..a0f5bb3b 100644
--- a/src/managed/Nota.App/ClipEditorView.cs
+++ b/src/managed/Nota.App/ClipEditorView.cs
@@ -6,7 +6,8 @@
// scale", and the Tools toggle — over the 232px inspector (ClipPropsView), the piano roll (PianoRollView) and
// the 272px clip-tools panel (MidiToolsView). Envelopes is a mode of the same canvas: the
// notes dim under a wash and the clip envelope (Velocity / Volume) is drawn over them in
-// brass, on the roll's own beat axis so zoom and scroll carry over.
+// brass, on the roll's own beat axis so zoom and scroll carry over. With several clips open
+// (specs/029) the header, inspector and envelopes follow the roll's active clip.
using System;
using Avalonia;
@@ -24,7 +25,10 @@ public sealed class ClipEditorView : UserControl
{
public PianoRollView Roll { get; }
- private readonly EnvOverlay? _envOverlay;
+ private EnvOverlay? _envOverlay;
+ private readonly IAudioEngine? _engine;
+ private readonly TextBlock _nameText;
+ private readonly Border _colorBar;
private readonly ClipPropsView _props;
private readonly MidiToolsView _tools;
private readonly ToggleButton _toolsToggle;
@@ -35,11 +39,11 @@ public sealed class ClipEditorView : UserControl
IAudioEngine? engine = null, int trackId = -1, int clipIndex = -1, double lengthBeats = 4)
{
Roll = roll;
+ _engine = engine;
if (engine is not null && trackId > 0 && clipIndex >= 0)
{
_envOverlay = new EnvOverlay(roll, engine, trackId, clipIndex, lengthBeats);
- var named = engine.GetClipName(trackId, clipIndex);
- if (!string.IsNullOrWhiteSpace(named)) clipName = named;
+ clipName = ClipName(trackId, clipIndex, clipName);
}
// Inspector | roll | clip-tools panel. The tools panel is a toggle rather than a
@@ -63,9 +67,37 @@ public sealed class ClipEditorView : UserControl
Orientation = Orientation.Horizontal, Spacing = 12,
Children = { AuditionControl(), FitControl(roll), SnapControl(roll), HeaderDivider(), ScaleControls(), HeaderDivider(), _toolsToggle },
};
- var header = Header(roll.TrackBrush, clipName, "MIDI", tabs, null, right);
+ var header = Header(roll.TrackBrush, HeaderName(clipName), "MIDI", tabs, null, right, out _nameText, out _colorBar);
DockPanel.SetDock(header, Dock.Top);
Content = new DockPanel { Background = NotaPalette.Gutter, Children = { header, grid } };
+ roll.ActiveClipChanged += OnActiveClipChanged;
+ if (roll.Clips.IsMulti) OnActiveClipChanged(); // envelopes on the active clip's place on the axis
+ }
+
+ private string ClipName(int trackId, int clipIndex, string fallback)
+ {
+ var named = _engine?.GetClipName(trackId, clipIndex);
+ return string.IsNullOrWhiteSpace(named) ? fallback : named;
+ }
+
+ // "Bass 2 · +2 clips" while several clips are open.
+ private string HeaderName(string name)
+ => Roll.Clips.IsMulti ? $"{name} · +{Roll.Clips.Count - 1} {(Roll.Clips.Count == 2 ? "clip" : "clips")}" : name;
+
+ // Another clip became active: name, colour, start and the envelope target follow it.
+ private void OnActiveClipChanged()
+ {
+ if (_engine is null) return;
+ var a = Roll.ActiveClip;
+ if (a.TrackId <= 0) return;
+ _nameText.Text = HeaderName(ClipName(a.TrackId, a.ClipIndex, $"Track {a.TrackId} clip"));
+ _colorBar.Background = Roll.TrackBrush;
+ _props.SetStart(a.StartBeat);
+ _envOverlay = new EnvOverlay(Roll, _engine, a.TrackId, a.ClipIndex, a.LengthBeats)
+ {
+ Offset = Roll.Clips.EditorStart(Roll.Clips.Active),
+ };
+ if (_envMode) Roll.SetOverlay(_envOverlay);
}
// Note audition (#46): the speaker chip. One app-wide setting, so every open editor's
@@ -226,6 +258,9 @@ public sealed class ClipEditorView : UserControl
public void SetLength(double lengthBeats) => _canvas.SetLength(lengthBeats);
+ /// <summary>Editor beat where this clip starts (several clips open; 0 for one).</summary>
+ public double Offset { get => _canvas.Offset; init => _canvas.Offset = value; }
+
private void Load()
{
var pts = _engine.GetMidiClipEnvelope(_trackId, _clipIndex, _target);
@@ -289,8 +324,10 @@ public sealed class ClipEditorView : UserControl
InvalidateVisual();
}
- private double BeatToX(double beat, double w) => _roll.BeatToX(beat);
- private double XToBeat(double x, double w) => Math.Clamp(_roll.XToBeat(x), 0, _clipBeats);
+ /// <summary>Editor beat of the clip's beat 0 (specs/029).</summary>
+ public double Offset { get; set; }
+ private double BeatToX(double beat, double w) => _roll.BeatToX(beat + Offset);
+ private double XToBeat(double x, double w) => Math.Clamp(_roll.XToBeat(x) - Offset, 0, _clipBeats);
private static double ValToY(double v, double h) { double pad = 6; return pad + (1 - Math.Clamp(v, 0, 1)) * (h - 2 * pad); }
private static double YToVal(double y, double h) { double pad = 6; return Math.Clamp((h - pad - y) / Math.Max(1, h - 2 * pad), 0, 1); }
private static double Shape(double t, float curve) => curve == 0f ? t : Math.Pow(t, Math.Pow(2.0, -curve * 4.0));
diff --git a/src/managed/Nota.App/ClipPropsView.cs b/src/managed/Nota.App/ClipPropsView.cs
index 29541dfb..49535175 100644
--- a/src/managed/Nota.App/ClipPropsView.cs
+++ b/src/managed/Nota.App/ClipPropsView.cs
@@ -105,7 +105,7 @@ public sealed class ClipPropsView : UserControl
private void OnRollChanged()
{
- double len = _roll.LengthBeats;
+ double len = _roll.ActiveLengthBeats; // the active clip's own length, several clips open or one
_lengthText.Text = Duration(len);
_loopText.Text = string.Format(NotaNum.Culture, "{0:0.##} {1}", len, Math.Abs(len - 1) < 1e-9 ? "beat" : "beats");
PaintSelection();
diff --git a/src/managed/Nota.App/Controls/Glyph.cs b/src/managed/Nota.App/Controls/Glyph.cs
index e6d707af..c1eb2900 100644
--- a/src/managed/Nota.App/Controls/Glyph.cs
+++ b/src/managed/Nota.App/Controls/Glyph.cs
@@ -36,6 +36,7 @@ internal enum GlyphKind
Palette, Note, Input, Arrow, Grid, Select, Save, List, Compare, Flatten,
// Path kinds (16-unit grid, see Paths)
Arrangement, Session, Modular, Keyboard, Sliders, Downloads, Star, StarFilled, Bookmark, Doc, Midi, Map, History, Sidebar, Options, Search, CaretRight, CaretDown, Levels, Gamepad, Phone, Plug, Library, Appearance, Shortcuts, MidiPort, Action, Track, Device, Preset, Patch, Loop, Speaker, SpeakerMute, SpeakerLow, SpeakerHigh, Metronome, Follow, Snap, Automation, Apple, Windows, Linux, ChainLink,
+ Lock, LockOpen, // a reference (read-only) clip in the multi-clip editor, and the unlocked toggle
}
internal sealed class Glyph : Control
@@ -508,6 +509,9 @@ internal sealed class Glyph : Control
// The Linux penguin (even-odd, so the belly is a hole).
[GlyphKind.Linux] = (null, "F1 M8 1.333 C9.333 1.333 10.133 2.4 10.133 3.867 C10.133 4.933 9.667 5.467 10 6.267 C11.067 7.733 12.667 9.6 12.267 11.867 L13.2 14 H2.8 L3.733 11.867 C3.333 9.6 4.933 7.733 6 6.267 C6.333 5.467 5.867 4.933 5.867 3.867 C5.867 2.4 6.667 1.333 8 1.333 ZM8 6.8 C6.733 6.8 5.867 8.667 5.867 10.533 C5.867 12.2 6.8 13.2 8 13.2 C9.2 13.2 10.133 12.2 10.133 10.533 C10.133 8.667 9.267 6.8 8 6.8 Z"),
// Two interlocked chain links (a live-freeze link).
+ // A padlock, shut and open: a clip locked as reference in the multi-clip editor (specs/029).
+ [GlyphKind.Lock] = ("M3.333 7.333 h9.333 v6.667 h-9.333 z M5.333 7.333 v-2 a2.667 2.667 0 0 1 5.333 0 v2", null),
+ [GlyphKind.LockOpen] = ("M3.333 7.333 h9.333 v6.667 h-9.333 z M5.333 7.333 v-2 a2.667 2.667 0 0 1 5.2 -0.8", null),
[GlyphKind.ChainLink] = ("M2.711 5.619 L6.266 9.175 A2.057 2.057 0 0 0 9.175 6.266 L5.619 2.711 A2.057 2.057 0 0 0 2.711 5.619 ZM6.825 9.734 L10.381 13.289 A2.057 2.057 0 0 0 13.289 10.381 L9.734 6.825 A2.057 2.057 0 0 0 6.825 9.734 Z", null),
};
diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.cs
index d1c92adf..d727edf2 100644
--- a/src/managed/Nota.App/MainWindow.Commands.cs
+++ b/src/managed/Nota.App/MainWindow.Commands.cs
@@ -128,6 +128,8 @@ public partial class MainWindow
B("roll.octaveUp", () => _editorRoll?.TransposeBy(12), Roll);
B("roll.octaveDown", () => _editorRoll?.TransposeBy(-12), Roll);
B("roll.fitNotes", () => _editorRoll?.FitToNotes(), Roll);
+ B("roll.editSelected", () => EditSelectedClips(),
+ _ => Need(Timeline.SelectedMidiClips().Count >= 2, "Select two or more MIDI clips"));
B("roll.removeOutOfScale", () => _editorRoll?.RemoveOutOfScaleNotes(),
c => Need(c.HasOpenMidiClip && _editorRoll?.HasOutOfScaleNotes == true, "No notes outside the scale"));
diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.cs
index 5e21686c..9d129737 100644
--- a/src/managed/Nota.App/MainWindow.Detail.cs
+++ b/src/managed/Nota.App/MainWindow.Detail.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
+using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -14,7 +15,9 @@ using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Microsoft.Extensions.DependencyInjection;
+using Avalonia.Threading;
using Nota.Application;
+using Nota.Application.Editing;
using Nota.Presentation;
namespace Nota.App;
@@ -140,7 +143,8 @@ public partial class MainWindow
// Switching to a different track abandons the previously edited clip. Reset the clip
// editor to empty so a stale editor from the old track doesn't linger — most visible
// in the popped-out Devices/Clip window, whose top pane isn't touched by ShowDevices.
- if (_editorTrackId != trackId && _audioEditorTrackId != trackId)
+ // A multi-clip editor keeps its clips until it is opened again (specs/029 FR-001a).
+ if (_editorTrackId != trackId && _audioEditorTrackId != trackId && !MultiClipEditorOpen)
ResetClipEditor();
// Selecting a clip in the arrangement also selects its track — including the select
@@ -354,12 +358,31 @@ public partial class MainWindow
ShowDetail(1 + 32 + 2 * DeviceChainView.ChainInset + DeviceCardKit.CardH, honorPersist: false);
}
+ // Double-click on a MIDI clip: that clip — or, when it is one of two or more selected MIDI
+ // clips, all of them together with it active (specs/029-multi-clip-editing).
private void OpenClipEditor(int trackId, int clipIndex)
{
- BuildClipEditor(trackId, clipIndex);
+ var sel = Timeline.SelectedMidiClips();
+ if (sel.Count >= 2 && sel.Contains((trackId, clipIndex))) BuildClipEditor(sel, trackId, clipIndex);
+ else BuildClipEditor(trackId, clipIndex);
ShowClipPanel();
}
+ /// <summary>"Edit selected clips": every selected MIDI clip in one editor, the first in time
+ /// active. False with fewer than two selected.</summary>
+ internal bool EditSelectedClips()
+ {
+ var sel = Timeline.SelectedMidiClips();
+ if (sel.Count < 2) return false;
+ BuildClipEditor(sel, sel[0].TrackId, sel[0].ClipIndex);
+ ShowClipPanel();
+ return true;
+ }
+
+ /// <summary>A Clip editor with several clips open — its set stays put while the
+ /// arrangement selection changes (specs/029 FR-001a).</summary>
+ private bool MultiClipEditorOpen => _editorRoll is { Clips.IsMulti: true } && _clipEditor is not null && _editorTrackId > 0;
+
// --- audio clip editor (M-audio-editor) --------------------------------
private void OpenAudioClipEditor(int trackId, int clipIndex)
{
@@ -404,66 +427,123 @@ public partial class MainWindow
// Build the piano-roll editor for a specific arrangement clip (no panel switch).
private void BuildClipEditor(int trackId, int clipIndex)
+ => BuildClipEditor(new[] { (trackId, clipIndex) }, trackId, clipIndex);
+
+ // Build the piano-roll editor for a set of arrangement MIDI clips, (activeTrack, activeClip)
+ // active (no panel switch). One clip is the classic single-clip editor.
+ private void BuildClipEditor(IReadOnlyList<(int TrackId, int ClipIndex)> clips, int activeTrack, int activeClip)
{
if (_vm is null) return;
- // The editor being replaced lets its pending placement go into its own clip first (it
+ var open = new List<OpenClip>();
+ foreach (var (t, c) in clips)
+ if (Engine.TryGetClipInfo(t, c, out var info) && info.IsMidi)
+ open.Add(new OpenClip(t, c, info.StartBeat, info.LengthBeats > 0 ? info.LengthBeats : 4));
+ if (open.Count == 0) return;
+ // The editor being replaced lets its pending placement go into its own clips first (it
// may never have had focus to lose, e.g. after a menu paste).
_editorRoll?.SettlePlacement();
- var roll = new PianoRollView
+ var set = new ClipSet(open, activeTrack, activeClip, Timeline.BeatsPerBar);
+ PianoRollView roll = null!;
+ roll = new PianoRollView
{
BeatsPerBar = Timeline.BeatsPerBar, // bar lines and bar steps match the arrangement
- Commit = notes =>
+ // Each clip whose notes changed, as one undo step. The roll can outlive a clip: the
+ // track/clip may have been removed, shifted by a lower-index delete, undone, or
+ // replaced by a project load while this editor stayed on screen. Pushing a stale
+ // (trackId, clipIndex) throws InvalidArg — verify each is still a live MIDI clip
+ // first, drop the dead ones, and drop the editor when none is left.
+ CommitClips = changed =>
{
- // The roll can outlive its clip: the target track/clip may have been
- // removed, shifted by a lower-index delete, undone, or replaced by a
- // project load while this editor stayed on screen. Pushing a stale
- // (trackId, clipIndex) throws InvalidArg — verify it's still a live
- // MIDI clip first, otherwise drop the dead editor.
- if (!Engine.TryGetClipInfo(trackId, clipIndex, out var live) || !live.IsMidi)
+ var live = LiveClips(roll, changed);
+ if (live is null) return;
+ Engine.BeginUndoGroup();
+ try
{
- InvalidateClipEditor();
- return;
+ foreach (var cn in live) Engine.SetClipNotes(cn.TrackId, cn.ClipIndex, cn.Notes.ToArray());
}
- var arr = new NotaNote[notes.Count];
- for (int i = 0; i < notes.Count; i++) arr[i] = notes[i];
- Engine.SetClipNotes(trackId, clipIndex, arr);
+ finally { Engine.EndUndoGroup(); }
Timeline.Refresh();
},
// Live drag stream: push every frame with no undo checkpoint so playback follows the
- // note instantly (the grid seeds one undo entry at the gesture start).
- CommitLive = notes =>
+ // note instantly (the roll seeds one undo step at the gesture start).
+ CommitClipsLive = changed =>
{
- if (!Engine.TryGetClipInfo(trackId, clipIndex, out var live) || !live.IsMidi) { InvalidateClipEditor(); return; }
- var arr = new NotaNote[notes.Count];
- for (int i = 0; i < notes.Count; i++) arr[i] = notes[i];
- Engine.SetClipNotesLive(trackId, clipIndex, arr);
+ var live = LiveClips(roll, changed);
+ if (live is null) return;
+ foreach (var cn in live) Engine.SetClipNotesLive(cn.TrackId, cn.ClipIndex, cn.Notes.ToArray());
Timeline.Refresh(rebuildHeaders: false);
},
// Light up the key being played (computer keyboard S–K / MIDI), regardless of routing.
PollHeldNotes = buf => Engine.LiveHeldNotes(buf),
ExpressionOf = id => Engine.GetNoteExpression(id),
CreateExpression = pts => Engine.CreateNoteExpression(pts),
- AuditionOn = (pitch, vel) => AuditionNoteOn(trackId, pitch, vel),
- AuditionOff = pitch => Engine.TrackNoteOff(trackId, pitch),
- // The ruler moves the transport (#50): clip-local beat → arrangement beat.
+ // A note sounds on its own clip's track; the keys column on the active clip's.
+ AuditionOn = (pitch, vel) => AuditionNoteOn(roll.AuditionTrackId > 0 ? roll.AuditionTrackId : _editorTrackId, pitch, vel),
+ AuditionOff = pitch => Engine.TrackNoteOff(roll.AuditionTrackId > 0 ? roll.AuditionTrackId : _editorTrackId, pitch),
+ ClipNameOf = (t, c) => Engine.GetClipName(t, c) is { Length: > 0 } n ? n : $"Track {t} clip",
+ // The ruler moves the transport (#50): editor beat → arrangement beat.
Seek = local =>
{
- if (!Engine.TryGetClipInfo(trackId, clipIndex, out var live) || !live.IsMidi) return;
- double beat = Math.Max(0, live.StartBeat + local);
+ double beat = Math.Max(0, roll.Origin + local);
Engine.Seek(beat);
Timeline.SetPlayhead(beat);
},
};
- double length = Engine.TryGetClipInfo(trackId, clipIndex, out var ci) && ci.LengthBeats > 0 ? ci.LengthBeats : 4;
- double start = ci.StartBeat;
- roll.SetTrackColor(TrackBrush(trackId));
- roll.SetClipIdentity(trackId, clipIndex);
- roll.SetNotes(Engine.GetClipNotes(trackId, clipIndex), length);
+ roll.SetTrackColor(TrackBrush(set.ActiveClip.TrackId));
+ if (!set.IsMulti) roll.SetClipIdentity(set.ActiveClip.TrackId, set.ActiveClip.ClipIndex);
+ roll.SetClips(set, ClipNotesOf(set), TrackBrush);
- _editorTrackId = trackId;
- _editorClipIndex = clipIndex;
+ _editorTrackId = set.ActiveClip.TrackId;
+ _editorClipIndex = set.ActiveClip.ClipIndex;
_editorRoll = roll;
- _clipEditor = new ClipEditorView(roll, $"Track {trackId} clip", start, Engine, trackId, clipIndex, length);
+ _clipEditor = new ClipEditorView(roll, $"Track {_editorTrackId} clip", set.ActiveClip.StartBeat, Engine,
+ _editorTrackId, _editorClipIndex, set.ActiveClip.LengthBeats);
+ // The active clip drives the detail chip, the playhead's live check and the envelopes.
+ roll.ActiveClipChanged += () =>
+ {
+ if (!ReferenceEquals(_editorRoll, roll)) return;
+ _editorTrackId = roll.ActiveClip.TrackId;
+ _editorClipIndex = roll.ActiveClip.ClipIndex;
+ SetDetailChip(_editorTrackId);
+ };
+ }
+
+ // Every open clip's notes, as the engine holds them.
+ private List<ClipNotes> ClipNotesOf(ClipSet set)
+ => set.Clips.Select(c => new ClipNotes(c.TrackId, c.ClipIndex, Engine.GetClipNotes(c.TrackId, c.ClipIndex))).ToList();
+
+ // The entries whose clip is still a live MIDI clip; dead clips leave the editor (reloaded
+ // without them), and null — after dropping the editor — when none of its clips is left.
+ private List<ClipNotes>? LiveClips(PianoRollView roll, IReadOnlyList<ClipNotes> changed)
+ {
+ var live = new List<ClipNotes>(changed.Count);
+ bool lost = false;
+ foreach (var cn in changed)
+ {
+ if (Engine.TryGetClipInfo(cn.TrackId, cn.ClipIndex, out var info) && info.IsMidi) live.Add(cn);
+ else lost = true;
+ }
+ if (lost && !PruneDeadClips(roll)) return null;
+ return live;
+ }
+
+ // Removes clips that no longer exist from the open set. False (and the editor dropped)
+ // when none is left.
+ private bool PruneDeadClips(PianoRollView roll)
+ {
+ var set = roll.Clips;
+ bool removed = false;
+ foreach (var c in set.Clips.ToList())
+ if (!Engine.TryGetClipInfo(c.TrackId, c.ClipIndex, out var info) || !info.IsMidi)
+ { set.Remove(c.TrackId, c.ClipIndex); removed = true; }
+ if (set.IsEmpty)
+ {
+ if (ReferenceEquals(roll, _editorRoll)) InvalidateClipEditor();
+ return false;
+ }
+ if (removed && ReferenceEquals(roll, _editorRoll))
+ Dispatcher.UIThread.Post(() => { if (ReferenceEquals(roll, _editorRoll)) roll.SetClips(set, ClipNotesOf(set), TrackBrush); });
+ return true;
}
// Drop a clip editor whose target no longer exists (removed/undone/reloaded) and
@@ -505,14 +585,19 @@ public partial class MainWindow
if (_patternView is not null && _patternTrackId == trackId && _patternClipIndex == clipIndex && _patternScene < 0)
_patternView.Reload();
- if (_editorRoll is not null && _editorTrackId == trackId && _editorClipIndex == clipIndex)
+ if (_editorRoll is { } roll && _editorTrackId > 0 && roll.Clips.IndexOf(trackId, clipIndex) >= 0)
{
- double len = ci.LengthBeats > 0 ? ci.LengthBeats : _editorRoll.LengthBeats;
- // SetNotes resets the roll's selection, so only re-seed it when the span really moved;
- // a pure move leaves the notes (clip-local) untouched.
- if (Math.Abs(len - _editorRoll.LengthBeats) > 1e-9)
- _editorRoll.SetNotes(Engine.GetClipNotes(trackId, clipIndex), len);
- _clipEditor?.SetClipBounds(ci.StartBeat, len);
+ double len = ci.LengthBeats > 0 ? ci.LengthBeats : 4;
+ var set = roll.Clips;
+ var before = set.Clips[set.IndexOf(trackId, clipIndex)];
+ set.UpdateGeometry(trackId, clipIndex, ci.StartBeat, len);
+ // A reload resets the roll's selection, so only re-seed it when the clips really
+ // moved on the editor's axis; a lone clip's pure move leaves its notes untouched.
+ bool lengthChanged = Math.Abs(len - before.LengthBeats) > 1e-9;
+ bool axisMoved = set.IsMulti && Math.Abs(ci.StartBeat - before.StartBeat) > 1e-9;
+ if (lengthChanged || axisMoved) roll.SetClips(set, ClipNotesOf(set), TrackBrush);
+ if (set.ActiveClip.TrackId == trackId && set.ActiveClip.ClipIndex == clipIndex)
+ _clipEditor?.SetClipBounds(ci.StartBeat, len);
}
else if (_audioEditor is not null && _audioEditorTrackId == trackId && _audioEditorClipIndex == clipIndex)
{
@@ -533,13 +618,19 @@ public partial class MainWindow
slotLen > 0 ? slotLen : _editorRoll.LengthBeats);
return;
}
- bool hasInfo = Engine.TryGetClipInfo(_editorTrackId, _editorClipIndex, out var ci);
- double len = hasInfo && ci.LengthBeats > 0 ? ci.LengthBeats : _editorRoll.LengthBeats;
- _editorRoll.SetNotes(Engine.GetClipNotes(_editorTrackId, _editorClipIndex), len);
+ // Every open clip, as the engine now holds it (undo/redo, recording); clips that are
+ // gone leave the set, and their lengths/starts are re-read.
+ var roll = _editorRoll;
+ if (!PruneDeadClips(roll)) return;
+ var set = roll.Clips;
+ foreach (var c in set.Clips.ToList())
+ if (Engine.TryGetClipInfo(c.TrackId, c.ClipIndex, out var info))
+ set.UpdateGeometry(c.TrackId, c.ClipIndex, info.StartBeat, info.LengthBeats > 0 ? info.LengthBeats : c.LengthBeats);
+ roll.SetClips(set, ClipNotesOf(set), TrackBrush);
// The roll shows the recording take: draw its held notes too (#56).
bool take = _recordPreview is { Active: true, SessionScene: < 0 } rp
- && rp.TrackId == _editorTrackId && rp.TakeClipIndex == _editorClipIndex;
- _editorRoll.SetRecordTake(take ? _recordPreview : null, hasInfo ? ci.StartBeat : 0);
+ && set.IndexOf(rp.TrackId, rp.TakeClipIndex) >= 0;
+ roll.SetRecordTake(take ? _recordPreview : null, roll.Origin);
}
// Tab (when the detail panel was last used) flips between Devices and Clip.
@@ -588,7 +679,7 @@ public partial class MainWindow
}
if (isMidi)
{
- if (_clipEditor is null || _editorTrackId != tid || _editorClipIndex != ci)
+ if (_clipEditor is null || (!MultiClipEditorOpen && (_editorTrackId != tid || _editorClipIndex != ci)))
BuildClipEditor(tid, ci);
ShowClipPanel();
}
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 99d84f71..ab1ad618 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -201,6 +201,7 @@ public partial class MainWindow : Window
Timeline.FreezeTracksMenuItems = BuildTracksFreezeMenu; // multi-track menu: Freeze / Unfreeze all
Timeline.RefreshStarting = PruneFreezeLinks; // drop links to deleted / undone tracks
Timeline.MidiClipActivated += OpenClipEditor;
+ Timeline.EditSelectedClipsRequested += () => EditSelectedClips();
Timeline.AudioClipActivated += OpenAudioClipEditor;
Timeline.ItemDropped += OnArrangementDrop; // browser drag & drop (M7-5)
Timeline.SampleToInstrument += (item, t) => { DropBrowserItem(item, t); Timeline.Select(t, -1); }; // audio clip → Grain / Drum Rack / Sampler… (that track becomes the selection)
@@ -307,8 +308,9 @@ public partial class MainWindow : Window
{
if (_editorTrackId > 0)
{
+ // Editor beats count from the open clips' origin (the clip's start for one).
if (Engine.TryGetClipInfo(_editorTrackId, _editorClipIndex, out var pci) && pci.IsMidi)
- _editorRoll.SetPlayhead(beats - pci.StartBeat, true);
+ _editorRoll.SetPlayhead(beats - _editorRoll.Origin, true);
}
else if (_sessionSlotTrack > 0 && _sessionSlotScene >= 0)
_editorRoll.SetPlayhead(SessionSlotPlayhead(_sessionSlotTrack, _sessionSlotScene), true);
diff --git a/src/managed/Nota.App/MidiToolsView.cs b/src/managed/Nota.App/MidiToolsView.cs
index 0f2ab858..a87911cf 100644
--- a/src/managed/Nota.App/MidiToolsView.cs
+++ b/src/managed/Nota.App/MidiToolsView.cs
@@ -19,6 +19,7 @@ using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Nota.Application;
+using Nota.Application.Editing;
using Nota.Application.Midi;
using static Nota.App.ClipEditorKit;
@@ -46,8 +47,12 @@ public sealed class MidiToolsView : UserControl
private int _seed = 1;
// The clip as it stood before the preview, plus the selection the tool is scoped to.
- private List<NotaNote> _source = new();
- private HashSet<int> _scope = new();
+ // The working set: each clip the tool runs on — its notes (clip-local beats), the selected
+ // ones among them, and its length. One clip normally; with several clips open (specs/029)
+ // every clip that has selected notes, or the active clip when none is selected, each run
+ // on its own so what a tool adds stays in that clip.
+ private List<(ClipNotes Clip, HashSet<int> Scope, double Length)> _work = new();
+ private int SourceCount => _work.Sum(w => w.Clip.Notes.Count);
private bool _suppressResync;
public MidiToolsView(PianoRollView roll)
@@ -157,16 +162,22 @@ public sealed class MidiToolsView : UserControl
/// <summary>Re-reads the clip and the selection as the working set for the next run.</summary>
private void Resync()
{
- _source = new List<NotaNote>(_roll.SourceNotes);
- _scope = new HashSet<int>(_roll.SelectionIndices.Where(i => i >= 0 && i < _source.Count));
- _scopeText.Text = _scope.Count > 0
- ? $"{_scope.Count} selected"
- : $"clip · {_source.Count}";
+ var (clips, selected) = _roll.SourceByClip();
+ var set = _roll.Clips;
+ _work = new();
+ for (int k = 0; k < clips.Count; k++)
+ if (selected[k].Count > 0) _work.Add((clips[k], selected[k], set.Clips[k].LengthBeats));
+ if (_work.Count == 0 && set.Active < clips.Count)
+ _work.Add((clips[set.Active], new HashSet<int>(), set.ActiveClip.LengthBeats));
+ int scoped = _work.Sum(w => w.Scope.Count);
+ _scopeText.Text = scoped > 0
+ ? $"{scoped} selected"
+ : $"clip · {SourceCount}";
}
- private MidiToolContext Context() => new()
+ private MidiToolContext Context(double lengthBeats) => new()
{
- LengthBeats = _roll.LengthBeats,
+ LengthBeats = lengthBeats,
Grid = _roll.Grids.Quantize.Beats(_roll.BeatsPerBar), // like Quantize: never the zoom's step
ScaleOn = _roll.ScaleOn,
ScaleRoot = _roll.ScaleRoot,
@@ -186,11 +197,12 @@ public sealed class MidiToolsView : UserControl
// A tool must not build on notes still stacked under a pending placement: let it go
// first (its Changed re-reads the working set through OnRollChanged).
if (!_roll.Previewing) _roll.SettlePlacement();
- var result = MidiToolRunner.Apply(_tool, _source, _scope, SettingsFor(_tool), Context(), _blend);
+ var results = _work.Select(w => new ClipNotes(w.Clip.TrackId, w.Clip.ClipIndex,
+ MidiToolRunner.Apply(_tool, w.Clip.Notes, w.Scope, SettingsFor(_tool), Context(w.Length), _blend))).ToList();
_suppressResync = true;
- _roll.ShowPreview(result);
+ _roll.ShowPreview(results);
_suppressResync = false;
- PaintResult(result.Count);
+ PaintResult(results.Sum(r => r.Notes.Count));
}
private void Apply()
@@ -203,7 +215,7 @@ public sealed class MidiToolsView : UserControl
// Deliberately no re-preview: the applied result is the new source, so running the
// tool again here would show it applied twice before the user asked for anything.
// The next knob move (or Reroll) arms a fresh preview from the new source.
- _resultText.Text = $"{_source.Count} notes · applied";
+ _resultText.Text = $"{SourceCount} notes · applied";
_resultText.Foreground = NotaPalette.TextMuted;
PaintApply();
}
@@ -232,10 +244,10 @@ public sealed class MidiToolsView : UserControl
_resultText.Text = _tool is null ? "Pick a tool" : "—";
else
{
- int delta = count - _source.Count;
+ int delta = count - SourceCount;
_resultText.Text = _blend == MidiToolBlend.Add
? $"{delta:+0;−0;\u00b10} notes"
- : $"{count} notes, was {_source.Count}";
+ : $"{count} notes, was {SourceCount}";
}
_resultText.Foreground = NotaPalette.TextMuted;
PaintApply();
diff --git a/src/managed/Nota.App/PianoRollView.ClipStrip.cs b/src/managed/Nota.App/PianoRollView.ClipStrip.cs
new file mode 100644
index 00000000..c94d3243
--- /dev/null
+++ b/src/managed/Nota.App/PianoRollView.ClipStrip.cs
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The clip strip of the multi-clip editor (specs/029-multi-clip-editing): a row under the
+// ruler, on the roll's own beat axis, with one bar per open clip over its span. Clips of
+// different tracks that overlap stack in rows. The active clip is the chosen one: a solid
+// track-colour bar with derived ink and an accent outline. The others are panel-toned with a
+// track-colour stripe; a reference (locked) clip's name steps down an ink and its lock is
+// shut. A click makes a clip active; the lock on a non-active bar toggles reference. Shown
+// only while two or more clips are open.
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+public sealed partial class PianoRollView
+{
+ private sealed class ClipStrip : Control
+ {
+ public const double RowH = 18;
+ private const double BarInset = 2, LockW = 16, Stripe = 3;
+ private readonly PianoRollView _o;
+ private readonly List<int> _rowOf = new(); // per slot: its row
+ private int _rows = 1;
+
+ public ClipStrip(PianoRollView o)
+ {
+ _o = o;
+ Cursor = new Cursor(StandardCursorType.Hand);
+ ToolTip.SetTip(this, "Click a clip to edit it · the lock keeps a clip for reference");
+ }
+
+ /// <summary>Re-stacks the bars (clips added, removed, moved) and sizes the strip.</summary>
+ public void Relayout()
+ {
+ var set = _o._set;
+ IsVisible = set.IsMulti;
+ _rowOf.Clear();
+ var rowEnds = new List<double>();
+ for (int k = 0; k < set.Count; k++)
+ {
+ double s = set.EditorStart(k), e = set.EditorEnd(k);
+ int r = rowEnds.FindIndex(end => end <= s + 1e-9);
+ if (r < 0) { r = rowEnds.Count; rowEnds.Add(e); } else rowEnds[r] = e;
+ _rowOf.Add(r);
+ }
+ _rows = Math.Max(1, rowEnds.Count);
+ Height = _rows * RowH;
+ InvalidateVisual();
+ }
+
+ private Rect BarRect(int slot)
+ {
+ var set = _o._set;
+ double x0 = _o.BeatToX(set.EditorStart(slot)), x1 = _o.BeatToX(set.EditorEnd(slot));
+ int row = slot < _rowOf.Count ? _rowOf[slot] : 0;
+ return new Rect(x0 + 1, row * RowH + BarInset, Math.Max(2, x1 - x0 - 2), RowH - 2 * BarInset);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0) return;
+ ctx.FillRectangle(KeysBg, new Rect(0, 0, w, h));
+ ctx.DrawLine(new Pen(Divider, 1), new Point(0, h - 0.5), new Point(w, h - 0.5));
+ var set = _o._set;
+ if (!set.IsMulti) return;
+ for (int k = 0; k < set.Count; k++)
+ {
+ var r = BarRect(k);
+ if (r.Right < 0 || r.X > w) continue;
+ bool active = k == set.Active, locked = !set.IsEditable(k);
+ var track = (k < _o._slotBrushes.Count ? _o._slotBrushes[k] : _o._trackBrush) as SolidColorBrush ?? NotaPalette.TextSecondary;
+ using (ctx.PushClip(r))
+ {
+ if (active)
+ {
+ ctx.FillRectangle(track, r, (float)NotaRadius.ClipValue);
+ ctx.DrawRectangle(null, new Pen(NotaPalette.Accent, 1), r.Deflate(0.5), NotaRadius.ClipValue, NotaRadius.ClipValue);
+ }
+ else
+ {
+ ctx.FillRectangle(NotaPalette.SurfaceRaised, r, (float)NotaRadius.ClipValue);
+ ctx.FillRectangle(track, new Rect(r.X, r.Y, Stripe, r.Height));
+ }
+ IBrush ink = active ? NotaPalette.InkOn(track) : locked ? NotaPalette.TextTertiary : NotaPalette.TextSecondary;
+ var clip = set.Clips[k];
+ string name = _o.ClipNameOf?.Invoke(clip.TrackId, clip.ClipIndex) ?? $"Track {clip.TrackId}";
+ var ft = new FormattedText(name, NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.SansMedium, 9, ink);
+ double textX = r.X + (active ? 6 : Stripe + 5);
+ double room = r.Width - (textX - r.X) - (active ? 6 : LockW + 2);
+ if (room > 12)
+ {
+ ft.MaxTextWidth = room;
+ ft.Trimming = TextTrimming.CharacterEllipsis;
+ ft.MaxLineCount = 1;
+ ctx.DrawText(ft, new Point(textX, r.Y + (r.Height - ft.Height) / 2));
+ }
+ if (!active && r.Width >= LockW + Stripe + 4)
+ Glyph.Draw(ctx, locked ? GlyphKind.Lock : GlyphKind.LockOpen,
+ new Rect(r.Right - LockW + 2, r.Y + (r.Height - 11) / 2, 11, 11),
+ locked ? NotaPalette.TextSecondary : NotaPalette.TextTertiary);
+ }
+ }
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ var p = e.GetPosition(this);
+ var set = _o._set;
+ // Topmost row first is irrelevant: bars in one row never overlap.
+ for (int k = 0; k < set.Count; k++)
+ {
+ var r = BarRect(k);
+ if (!r.Contains(p)) continue;
+ if (k != set.Active && p.X >= r.Right - LockW) _o.SetReference(k, set.IsEditable(k));
+ else _o.SetActiveClip(k);
+ e.Handled = true;
+ return;
+ }
+ }
+
+ protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
+ {
+ _o.RouteWheel(e, e.GetPosition(this).X);
+ base.OnPointerWheelChanged(e);
+ }
+ }
+}
diff --git a/src/managed/Nota.App/PianoRollView.Expression.cs b/src/managed/Nota.App/PianoRollView.Expression.cs
index 09e803db..e1874d3c 100644
--- a/src/managed/Nota.App/PianoRollView.Expression.cs
+++ b/src/managed/Nota.App/PianoRollView.Expression.cs
@@ -263,7 +263,7 @@ public sealed partial class PianoRollView
for (int i = 0; i < notes.Count; i++)
{
bool sel = _o._selection.Contains(i);
- if (sel != selPass || _o.IsGhost(i)) continue;
+ if (sel != selPass || _o.IsGhost(i) || _o.IsLocked(i)) continue;
var n = notes[i];
double x0 = _o.BeatToX(n.StartBeat), x1 = _o.BeatToX(n.StartBeat + n.LengthBeats);
if (x1 < 0 || x0 > w) continue;
@@ -287,7 +287,7 @@ public sealed partial class PianoRollView
g.LineTo(new Point(x1, ValueToY(c[^1].Value)));
g.EndFigure(false);
}
- IPen pen = sel ? CurvePen : TrackPen(n);
+ IPen pen = sel ? CurvePen : TrackPen(i);
using (ctx.PushClip(new Rect(x0, 0, Math.Max(1, x1 - x0), h))) ctx.DrawGeometry(null, pen, line);
if (!sel) continue;
for (int k = 0; k < c.Count; k++)
@@ -308,9 +308,9 @@ public sealed partial class PianoRollView
_o.DrawOutsideClip(ctx, w, h);
}
- private IPen TrackPen(NotaNote n)
+ private IPen TrackPen(int i)
{
- var c = _o._trackColor;
+ var c = _o.ColorOf(i);
return new Pen(new SolidColorBrush(Color.FromArgb(0x99, c.R, c.G, c.B)), 1.25);
}
@@ -347,7 +347,7 @@ public sealed partial class PianoRollView
_o.SettlePlacement(); // the selection changes below, and this lane never takes focus
int pick = -1;
for (int i = 0; i < _o._notes.Count; i++)
- if (Spans(i, beat) && (pick < 0 || _o._notes[i].Pitch > _o._notes[pick].Pitch)) pick = i;
+ if (!_o.IsLocked(i) && Spans(i, beat) && (pick < 0 || _o._notes[i].Pitch > _o._notes[pick].Pitch)) pick = i;
if (pick < 0) return sel;
if (!shift) _o._selection.Clear();
_o._selection.Add(pick);
diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.cs
index 4cfb12f4..5414ec0a 100644
--- a/src/managed/Nota.App/PianoRollView.cs
+++ b/src/managed/Nota.App/PianoRollView.cs
@@ -65,12 +65,14 @@ public sealed partial class PianoRollView : UserControl
private int _auditionPitch = -1;
/// <summary>Sound <paramref name="pitch"/> until <see cref="StopAudition"/>. The note grid
/// asks only while audition is on; the keys column always plays (force).</summary>
- internal void Audition(int pitch, float velocity, bool force = false)
+ internal void Audition(int pitch, float velocity, bool force = false, int slot = -1)
{
- if (AuditionOn is null || (!force && !AuditionEnabled) || pitch == _auditionPitch) return;
+ int track = TrackOfSlot(slot >= 0 ? slot : _set.Active);
+ if (AuditionOn is null || (!force && !AuditionEnabled) || (pitch == _auditionPitch && track == _auditionTrack)) return;
StopAudition();
if (pitch < MinPitch || pitch > MaxPitch) return;
_auditionPitch = pitch;
+ _auditionTrack = track;
AuditionOn(pitch, Math.Clamp(velocity, 0.05f, 1f));
_keys.InvalidateVisual();
}
@@ -80,6 +82,7 @@ public sealed partial class PianoRollView : UserControl
int p = _auditionPitch;
_auditionPitch = -1;
AuditionOff?.Invoke(p);
+ _auditionTrack = -1;
_keys.InvalidateVisual();
}
@@ -90,7 +93,7 @@ public sealed partial class PianoRollView : UserControl
SettlePlacement(); // a pending placement lands first: it can cut or remove notes
if (!add) _selection.Clear();
for (int i = 0; i < _notes.Count; i++)
- if (_notes[i].Pitch == pitch) _selection.Add(i);
+ if (_notes[i].Pitch == pitch && !IsLocked(i)) _selection.Add(i);
Invalidate();
Changed?.Invoke();
}
@@ -148,8 +151,14 @@ public sealed partial class PianoRollView : UserControl
private double _rowH = DefaultRowH;
internal double RowH => _rowH;
+ // The notes on screen, in editor beats (specs/029): beats from the open clip set's origin —
+ // the clip's own beats when one clip is open. _owner[i] is note i's clip (its ClipSet slot);
+ // the two lists change together, only through AddNote / RemoveNoteAt / ReplaceAll.
private readonly List<NotaNote> _notes = new();
- private double _lengthBeats = 4;
+ private readonly List<int> _owner = new();
+ private ClipSet _set = ClipSet.Single(-1, -1, 0, 4);
+ private readonly List<ISolidColorBrush> _slotBrushes = new();
+ private double _lengthBeats = 4; // the set's span: the scrollable range
private readonly HashSet<int> _selection = new(); // indices into _notes
private ISolidColorBrush _trackBrush = NotaPalette.TrackBrushes[3]; // read .Color at draw time: it follows the theme
private Color _trackColor => _trackBrush.Color;
@@ -195,10 +204,10 @@ public sealed partial class PianoRollView : UserControl
// Live playback cursor in clip-local beats; < 0 = hidden. Set by the host each tick.
private double _playheadBeat = -1;
- // Note clipboard, shared across clips (copy here, paste into another clip). Stored
- // normalized so the earliest note starts at beat 0; s_clipAnchor is its origin.
- private static readonly List<NotaNote> s_clipboard = new();
- private static double s_clipAnchor;
+ // Note clipboard, shared across clips (copy here, paste into another clip): each note at
+ // its beat in the clip it was copied from, with that clip (specs/029 pastes it back there).
+ private readonly record struct ClipboardNote(NotaNote Note, int TrackId, int ClipIndex);
+ private static readonly List<ClipboardNote> s_clipboard = new();
// The last note touched — clicked, moved, resized or its velocity drawn — in any clip (#44):
// a new note takes its length and velocity. Before any is touched, a new note is one grid
@@ -211,13 +220,28 @@ public sealed partial class PianoRollView : UserControl
s_lastLen = _notes[i].LengthBeats;
s_lastVel = _notes[i].Velocity;
}
- private double NewNoteLen(double start)
+ private double NewNoteLen(double start, int slot)
{
double len = double.IsNaN(s_lastLen) ? MinNoteLen : Math.Max(MinNoteLen, s_lastLen);
- return Math.Max(MinNoteLen, Math.Min(len, _lengthBeats - start));
+ return Math.Max(MinNoteLen, Math.Min(len, _set.EditorEnd(slot) - start));
+ }
+
+ /// <summary>The clip a note drawn at <paramref name="beat"/> goes into (specs/029 FR-007):
+ /// the active clip when it holds the beat, else another open, editable clip of the active
+ /// clip's track that does; −1 when none does (nothing is drawn).</summary>
+ private int DrawTarget(double beat)
+ {
+ if (_set.Contains(_set.Active, beat)) return _set.Active;
+ int track = _set.ActiveClip.TrackId;
+ for (int k = 0; k < _set.Count; k++)
+ if (k != _set.Active && _set.Clips[k].TrackId == track && _set.IsEditable(k) && _set.Contains(k, beat)) return k;
+ return -1;
}
private readonly RulerLane _ruler;
+ private readonly ClipStrip _strip;
+ /// <summary>A clip's name for the clip strip (null → "Track N"). Set by the host.</summary>
+ public Func<int, int, string?>? ClipNameOf { get; set; }
private readonly KeysColumn _keys;
private readonly NoteGrid _gridControl;
private readonly VelocityLane _vel;
@@ -245,6 +269,14 @@ public sealed partial class PianoRollView : UserControl
// The fit happens mid-render: tell the snap chip after it, not during.
Dispatcher.UIThread.Post(NotifyGrid);
}
+ // A newly opened multi-clip set too long to fit: start at the active clip.
+ if (_pendingScrollTo is { } to && _pixelsPerBeat > 0 && viewportW > 0)
+ {
+ _pendingScrollTo = null;
+ double vpBeats = viewportW / _pixelsPerBeat;
+ _scrollBeats = Math.Clamp(to, 0, Math.Max(0, _lengthBeats - vpBeats));
+ Dispatcher.UIThread.Post(SyncScroll);
+ }
}
private double MaxScrollBeats
@@ -300,6 +332,9 @@ public sealed partial class PianoRollView : UserControl
// Past the clip's end (seen once you zoom out): a dark wash and an Ink 2 end line, so the
// clip's edge reads at a glance.
private static readonly IBrush OutsideClip = NotaPalette.Wash(NotaPalette.SurfaceAbyss, 0xC8);
+ // Several clips open (specs/029): the active clip's notes at full strength, the other
+ // clips' quieter, and reference (locked) clips' quieter still — present, but out of the way.
+ private const double OtherClipAlpha = 0.6, ReferenceClipAlpha = 0.28;
private static readonly IPen ClipEndPen = new Pen(NotaPalette.TextStrong, 1);
// Scale overlay: out-of-scale rows/keys get a translucent dark wash (they read
// dimmed / semi-transparent), in-scale rows a faint accent, the root a stronger one.
@@ -342,6 +377,7 @@ public sealed partial class PianoRollView : UserControl
// Clip the horizontally-scrolling lanes to their own column so notes / beat marks
// scrolled past the left edge don't bleed over the fixed keyboard + label gutter.
_ruler = new RulerLane(this) { ClipToBounds = true };
+ _strip = new ClipStrip(this) { ClipToBounds = true, IsVisible = false, Height = ClipStrip.RowH };
_keys = new KeysColumn(this) { Height = RangeH };
_gridControl = new NoteGrid(this) { Height = RangeH, ClipToBounds = true };
_vel = new VelocityLane(this) { ClipToBounds = true };
@@ -369,6 +405,13 @@ public sealed partial class PianoRollView : UserControl
Avalonia.Controls.Grid.SetColumn(_ruler, 1);
rulerRow.Children.Add(_ruler);
+ // The clip strip (several clips open): corner + strip, under the ruler.
+ var stripRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*") };
+ stripRow.Children.Add(new Border { Background = KeysBg, BorderBrush = Divider, BorderThickness = new Thickness(0, 0, 1, 1) });
+ Avalonia.Controls.Grid.SetColumn(_strip, 1);
+ stripRow.Children.Add(_strip);
+ stripRow.Bind(IsVisibleProperty, _strip.GetObservable(IsVisibleProperty));
+
var velRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*"), Height = VelH };
_laneRow = velRow;
// The lane's gutter picks what it edits: velocity, or a recorded-MPE dimension.
@@ -386,17 +429,19 @@ public sealed partial class PianoRollView : UserControl
Avalonia.Controls.Grid.SetColumn(_hScroll, 1);
scrollRow.Children.Add(_hScroll);
- var root = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,Auto") };
+ var root = new Grid { RowDefinitions = new RowDefinitions("Auto,Auto,*,Auto,Auto") };
root.Children.Add(rulerRow);
- Avalonia.Controls.Grid.SetRow(_bodyScroll, 1);
+ Avalonia.Controls.Grid.SetRow(stripRow, 1);
+ root.Children.Add(stripRow);
+ Avalonia.Controls.Grid.SetRow(_bodyScroll, 2);
root.Children.Add(_bodyScroll);
// Overlay slot over the note grid (the clip editor's Envelopes mode draws there).
- Avalonia.Controls.Grid.SetRow(_overlayHost, 1);
+ Avalonia.Controls.Grid.SetRow(_overlayHost, 2);
_overlayHost.Margin = new Thickness(KeysW, 0, 0, 0);
root.Children.Add(_overlayHost);
- Avalonia.Controls.Grid.SetRow(velRow, 2);
+ Avalonia.Controls.Grid.SetRow(velRow, 3);
root.Children.Add(velRow);
- Avalonia.Controls.Grid.SetRow(scrollRow, 3);
+ Avalonia.Controls.Grid.SetRow(scrollRow, 4);
root.Children.Add(scrollRow);
Content = root;
@@ -543,14 +588,121 @@ public sealed partial class PianoRollView : UserControl
public void SetTrackColor(ISolidColorBrush b) { _trackBrush = b; Invalidate(); }
public ISolidColorBrush TrackBrush => _trackBrush;
+ // ---- the open clip set (specs/029-multi-clip-editing) ------------------------
+ /// <summary>The clips this roll edits; a set of one for the single-clip editor.</summary>
+ public ClipSet Clips => _set;
+ public OpenClip ActiveClip => _set.ActiveClip;
+ /// <summary>Raised when another clip becomes active (strip click, a note of it clicked or
+ /// drawn into) or a clip is locked / unlocked; the header, inspector and envelopes follow.</summary>
+ public event Action? ActiveClipChanged;
+ /// <summary>Arrangement beat of editor beat 0 — the host converts playhead and seek with it.</summary>
+ public double Origin => _set.Origin;
+ /// <summary>Length of the active clip (the inspector's LENGTH / LOOP).</summary>
+ public double ActiveLengthBeats => _set.ActiveClip.LengthBeats;
+
+ /// <summary>Track colour of note i's clip; the active colour for a one-clip set.</summary>
+ private Color ColorOf(int i)
+ {
+ int s = i >= 0 && i < _owner.Count ? _owner[i] : 0;
+ return s < _slotBrushes.Count && _set.IsMulti ? _slotBrushes[s].Color : _trackColor;
+ }
+ internal Color SlotColor(int slot) => slot < _slotBrushes.Count && _set.IsMulti ? _slotBrushes[slot].Color : _trackColor;
+ /// <summary>Whether note i belongs to a reference (read-only) clip.</summary>
+ internal bool IsLocked(int i) => i >= 0 && i < _owner.Count && !_set.IsEditable(_owner[i]);
+ /// <summary>How strongly note i reads: its own clip is full strength when active (or the
+ /// only clip), quieter otherwise, and a reference clip quieter still.</summary>
+ internal double ClipEmphasis(int i)
+ {
+ if (!_set.IsMulti || i < 0 || i >= _owner.Count || _owner[i] == _set.Active) return 1;
+ return _set.IsEditable(_owner[i]) ? OtherClipAlpha : ReferenceClipAlpha;
+ }
+
+ private void AddNote(NotaNote n, int owner) { _notes.Add(n); _owner.Add(owner); }
+ private void RemoveNoteAt(int i) { _notes.RemoveAt(i); _owner.RemoveAt(i); }
+ private void ReplaceAll(IEnumerable<NotaNote> notes, IEnumerable<int> owners)
+ {
+ var n = notes.ToList(); var o = owners.ToList(); // either may alias the lists being replaced
+ _notes.Clear(); _notes.AddRange(n);
+ _owner.Clear(); _owner.AddRange(o);
+ System.Diagnostics.Debug.Assert(_notes.Count == _owner.Count);
+ }
+ private void RemoveWhere(Func<int, bool> drop)
+ {
+ for (int i = _notes.Count - 1; i >= 0; i--) if (drop(i)) RemoveNoteAt(i);
+ }
+
+ /// <summary>Loads one clip's notes (clip-local beats); the Session slot editor and anything
+ /// that edits a single clip without a <see cref="ClipSet"/>.</summary>
public void SetNotes(IEnumerable<NotaNote> notes, double lengthBeats)
+ {
+ var list = notes.ToList();
+ _set = ClipSet.Single(-1, -1, 0, Math.Max(1, lengthBeats));
+ _slotBrushes.Clear();
+ Load(list, Enumerable.Repeat(0, list.Count), Math.Max(1, lengthBeats));
+ }
+
+ /// <summary>Loads a set of clips (specs/029): <paramref name="perClip"/> holds each clip's
+ /// notes in its own beats; <paramref name="brushOf"/> gives a track's colour. A set of one is
+ /// exactly the single-clip editor.</summary>
+ public void SetClips(ClipSet set, IReadOnlyList<ClipNotes> perClip, Func<int, ISolidColorBrush> brushOf)
+ {
+ bool rescroll = !ReferenceEquals(set, _set) && set.IsMulti;
+ _set = set;
+ _slotBrushes.Clear();
+ foreach (var c in set.Clips) _slotBrushes.Add(brushOf(c.TrackId));
+ _trackBrush = _slotBrushes[set.Active];
+ var notes = new List<NotaNote>(); var owners = new List<int>();
+ set.Merge(perClip, notes, owners);
+ // Multi-clip view state is not remembered per clip: fit the span, then show the active clip.
+ if (set.IsMulti) _clipKey = (int.MinValue, int.MinValue);
+ Load(notes, owners, Math.Max(1, set.SpanBeats));
+ if (rescroll) _pendingScrollTo = set.EditorStart(set.Active);
+ ActiveClipChanged?.Invoke();
+ }
+
+ private double? _pendingScrollTo; // editor beat to bring into view once the zoom is fitted
+
+ /// <summary>Makes clip <paramref name="slot"/> the active one (a locked clip is unlocked).
+ /// A pending placement lands first.</summary>
+ public void SetActiveClip(int slot)
+ {
+ if (slot == _set.Active && _set.IsEditable(slot)) return;
+ SettlePlacement();
+ if (!_set.SetActive(slot)) return;
+ _trackBrush = slot < _slotBrushes.Count ? _slotBrushes[slot] : _trackBrush;
+ Invalidate();
+ ActiveClipChanged?.Invoke();
+ Changed?.Invoke();
+ }
+
+ /// <summary>Locks (<paramref name="on"/>) or unlocks clip <paramref name="slot"/> as a
+ /// read-only reference. Refused for the active clip. Its notes leave the selection.</summary>
+ public bool SetReference(int slot, bool on)
+ {
+ SettlePlacement();
+ if (!_set.SetReference(slot, on)) return false;
+ if (on) _selection.RemoveWhere(i => i < _owner.Count && _owner[i] == slot);
+ Invalidate();
+ ActiveClipChanged?.Invoke();
+ Changed?.Invoke();
+ return true;
+ }
+
+ /// <summary>The track a note being heard plays on (its own clip's track); −1 for the host's
+ /// own track. Read by the host's <see cref="AuditionOn"/> / <see cref="AuditionOff"/>.</summary>
+ public int AuditionTrackId => _auditionTrack;
+ private int _auditionTrack = -1;
+ private int TrackOfSlot(int slot) => slot >= 0 && slot < _set.Count ? _set.Clips[slot].TrackId : -1;
+
+ private void Load(IEnumerable<NotaNote> notes, IEnumerable<int> owners, double lengthBeats)
{
_previewBackup = null;
_placementPending = false; // a reload (undo, recording, another clip) is the truth now
- _notes.Clear();
- _notes.AddRange(notes);
- _lengthBeats = Math.Max(1, lengthBeats);
+ ReplaceAll(notes, owners);
+ _lengthBeats = lengthBeats;
_selection.Clear();
+ _strip.Relayout();
+ RememberCommitted();
_saveAfterApply = false; // a zoom queued on the previous clip must not save onto this one
// Restore this clip's saved scroll/zoom if we've edited it before; otherwise fit the
@@ -615,7 +767,8 @@ public sealed partial class PianoRollView : UserControl
public bool GridFocused => _gridControl.IsFocused;
/// <summary>Duplicates the selected notes, shifted right by the selection span, and
- /// selects the copies. Returns false if nothing was selected. Undoable (one Commit).</summary>
+ /// selects the copies. Returns false if nothing was selected. Undoable (one Commit).
+ /// Each copy stays in its original's clip, never past that clip's end.</summary>
public bool DuplicateSelection()
{
SettlePlacement();
@@ -624,19 +777,26 @@ public sealed partial class PianoRollView : UserControl
double minStart = double.MaxValue, maxEnd = double.MinValue;
foreach (int i in sel) { var n = _notes[i]; minStart = Math.Min(minStart, n.StartBeat); maxEnd = Math.Max(maxEnd, n.StartBeat + n.LengthBeats); }
double shift = Math.Max(SnapStep, maxEnd - minStart);
- double cap = Math.Max(0, _lengthBeats - SnapStep);
var copies = new List<NotaNote>(sel.Count);
- foreach (int i in sel) { var n = _notes[i]; n.StartBeat = Math.Min(n.StartBeat + shift, cap); copies.Add(n); }
+ var copyOwners = new List<int>(sel.Count);
+ foreach (int i in sel)
+ {
+ var n = _notes[i];
+ double cap = Math.Max(_set.EditorStart(_owner[i]), _set.EditorEnd(_owner[i]) - SnapStep);
+ n.StartBeat = Math.Min(n.StartBeat + shift, cap);
+ copies.Add(n);
+ copyOwners.Add(_owner[i]);
+ }
// Like a duplicated clip in the arrangement, the copies overwrite what they land on
// straight away, with the same rule a settled placement uses (NoteOverwrite).
int baseIdx = _notes.Count;
- _notes.AddRange(copies);
+ for (int k = 0; k < copies.Count; k++) AddNote(copies[k], copyOwners[k]);
var placed = Enumerable.Range(baseIdx, copies.Count).ToList();
var settled = new List<NotaNote>(_notes.Count);
var placedOut = new List<int>(copies.Count);
- NoteOverwrite.Settle(_notes, placed, settled, placedOut);
- _notes.Clear();
- _notes.AddRange(settled);
+ var ownersOut = new List<int>(_notes.Count);
+ NoteOverwrite.Settle(_notes, placed, settled, placedOut, _owner, ownersOut);
+ ReplaceAll(settled, ownersOut);
_selection.Clear();
_selection.UnionWith(placedOut);
Invalidate();
@@ -651,7 +811,7 @@ public sealed partial class PianoRollView : UserControl
if (_selection.Count == 0) return false;
_placementPending = false; // the placed notes are what goes
foreach (int i in _selection.OrderByDescending(x => x))
- if (i >= 0 && i < _notes.Count) _notes.RemoveAt(i);
+ if (i >= 0 && i < _notes.Count) RemoveNoteAt(i);
_selection.Clear();
Invalidate();
CommitNotes();
@@ -659,16 +819,24 @@ public sealed partial class PianoRollView : UserControl
return true;
}
- /// <summary>True when the scale overlay is on and some note falls outside it.</summary>
- public bool HasOutOfScaleNotes => _scaleOn && _notes.Exists(n => !InScale(n.Pitch));
+ /// <summary>True when the scale overlay is on and some editable note falls outside it.</summary>
+ public bool HasOutOfScaleNotes
+ {
+ get
+ {
+ if (!_scaleOn) return false;
+ for (int i = 0; i < _notes.Count; i++) if (!IsLocked(i) && !InScale(_notes[i].Pitch)) return true;
+ return false;
+ }
+ }
- /// <summary>Removes every note outside the scale overlay. No-op with the scale off.
+ /// <summary>Removes every editable note outside the scale overlay. No-op with the scale off.
/// Undoable (one Commit).</summary>
public bool RemoveOutOfScaleNotes()
{
if (!HasOutOfScaleNotes) return false;
SettlePlacement();
- _notes.RemoveAll(n => !InScale(n.Pitch));
+ RemoveWhere(i => !IsLocked(i) && !InScale(_notes[i].Pitch));
_selection.Clear();
Invalidate();
CommitNotes();
@@ -679,8 +847,9 @@ public sealed partial class PianoRollView : UserControl
// --- clip-tool preview -------------------------------------------------------
// A tool's result is shown in the roll and streamed to the engine with no undo
// checkpoint, exactly like a note drag, so the knobs are audible while they move.
- // The clip's own notes are held here until the preview is applied or dropped.
+ // The clips' own notes are held here until the preview is applied or dropped.
private List<NotaNote>? _previewBackup;
+ private List<int>? _previewOwners;
public bool Previewing => _previewBackup is not null;
@@ -697,24 +866,62 @@ public sealed partial class PianoRollView : UserControl
/// while no preview is running, which is when a tool captures its working set.</summary>
public IReadOnlyCollection<int> SelectionIndices => _selection;
+ /// <summary>Every open clip's notes (clip-local beats) ignoring a preview in flight, and
+ /// each clip's selected notes as indices into its own list — a tool's per-clip working set
+ /// (specs/029: a tool runs once per clip, so what it adds stays in that clip).</summary>
+ public (List<ClipNotes> Clips, List<HashSet<int>> Selected) SourceByClip()
+ {
+ var notes = _previewBackup ?? _notes;
+ var owners = _previewOwners ?? _owner;
+ var clips = _set.Split(notes, owners);
+ var selected = new List<HashSet<int>>(clips.Count);
+ var local = new int[clips.Count];
+ for (int k = 0; k < clips.Count; k++) selected.Add(new HashSet<int>());
+ for (int i = 0; i < notes.Count; i++)
+ {
+ int o = owners[i];
+ if (o < 0 || o >= clips.Count) continue;
+ if (_previewBackup is null && _selection.Contains(i)) selected[o].Add(local[o]);
+ local[o]++;
+ }
+ return (clips, selected);
+ }
+
/// <summary>Puts a tool's result on screen and in the engine without touching undo.</summary>
public void ShowPreview(IReadOnlyList<NotaNote> notes)
+ => ShowPreview(new[] { new ClipNotes(_set.ActiveClip.TrackId, _set.ActiveClip.ClipIndex, notes) });
+
+ /// <summary>As <see cref="ShowPreview(IReadOnlyList{NotaNote})"/> for several clips: each
+ /// entry replaces its clip's notes (clip-local beats); clips without an entry keep theirs.</summary>
+ public void ShowPreview(IReadOnlyList<ClipNotes> perClip)
{
// The tool computed its result from the notes as they stand, so a pending placement
// is part of what it replaces; settling now would only reshuffle stale indices.
_placementPending = false;
_previewBackup ??= new List<NotaNote>(_notes);
- _notes.Clear();
- _notes.AddRange(notes);
+ _previewOwners ??= new List<int>(_owner);
+ var merged = _set.Split(_previewBackup, _previewOwners);
+ foreach (var cn in perClip)
+ {
+ int slot = _set.IndexOf(cn.TrackId, cn.ClipIndex);
+ if (_set.Count == 1) slot = 0; // a one-clip set: whatever its ids, the result is its
+ if (slot >= 0) merged[slot] = new ClipNotes(merged[slot].TrackId, merged[slot].ClipIndex, cn.Notes);
+ }
+ var notes = new List<NotaNote>(); var owners = new List<int>();
+ _set.Merge(merged, notes, owners);
+ ReplaceAll(notes, owners);
// What the tool added (not in the clip before) draws as a brass outline over the notes.
- var before = new HashSet<(int, long, long, int)>(_previewBackup.Select(NoteKey));
+ var before = new HashSet<(int, int, long, long, int)>(Enumerable.Range(0, _previewBackup.Count)
+ .Select(i => Keyed(_previewBackup[i], _previewOwners[i])));
_ghosts.Clear();
- for (int i = 0; i < _notes.Count; i++) if (!before.Contains(NoteKey(_notes[i]))) _ghosts.Add(i);
+ for (int i = 0; i < _notes.Count; i++) if (!before.Contains(Keyed(_notes[i], _owner[i]))) _ghosts.Add(i);
_selection.Clear();
EnsureNotesVisible();
Invalidate();
- CommitLive?.Invoke(_notes);
+ PushLive(_notes, _owner);
Changed?.Invoke();
+
+ static (int, int, long, long, int) Keyed(NotaNote n, int o) { var k = NoteKey(n); return (o, k.Item1, k.Item2, k.Item3, k.Item4); }
}
/// <summary>Centres the pitch range when not one note is on screen — which is what a
@@ -741,12 +948,12 @@ public sealed partial class PianoRollView : UserControl
public void CancelPreview()
{
if (_previewBackup is null) return;
- _notes.Clear();
- _notes.AddRange(_previewBackup);
+ ReplaceAll(_previewBackup, _previewOwners!);
_previewBackup = null;
+ _previewOwners = null;
_selection.Clear();
Invalidate();
- CommitLive?.Invoke(_notes);
+ PushLive(_notes, _owner);
Changed?.Invoke();
}
@@ -756,35 +963,103 @@ public sealed partial class PianoRollView : UserControl
if (_previewBackup is null) return;
_placementPending = false;
var original = _previewBackup;
+ var originalOwners = _previewOwners!;
_selection.Clear();
Invalidate();
// A commit checkpoints whatever the engine currently holds — and the live stream
// has already put the preview there, so committing straight away would make undo
// land on the preview. Rewind the engine to the clip's own notes first (no undo
// step of its own), then commit, so the one entry points at the original.
- CommitLive?.Invoke(original);
+ PushLive(original, originalOwners);
CommitNotes();
Changed?.Invoke();
}
+ // ---- pushing notes to the engine -------------------------------------------------
+ /// <summary>Several-clip commit (specs/029): the clips whose notes changed, each in its own
+ /// beats. The host makes one undo step of the whole list. When set, it replaces
+ /// <see cref="Commit"/>.</summary>
+ public Action<IReadOnlyList<ClipNotes>>? CommitClips { get; set; }
+ /// <summary>Live, no-undo variant of <see cref="CommitClips"/> (drags, tool previews).</summary>
+ public Action<IReadOnlyList<ClipNotes>>? CommitClipsLive { get; set; }
+
+ private bool HasLivePath => CommitClipsLive is not null || CommitLive is not null;
+
+ // What each clip holds in the engine as far as this roll knows: what it loaded or last pushed.
+ private NotaNote[][] _pushed = Array.Empty<NotaNote[]>();
+
+ private void RememberCommitted()
+ => _pushed = _set.Split(_notes, _owner).Select(c => c.Notes.ToArray()).ToArray();
+
+ private static bool SameNotes(IReadOnlyList<NotaNote> a, NotaNote[] b)
+ {
+ if (a.Count != b.Length) return false;
+ for (int i = 0; i < b.Length; i++)
+ {
+ var x = a[i]; var y = b[i];
+ if (x.Pitch != y.Pitch || x.StartBeat != y.StartBeat || x.LengthBeats != y.LengthBeats
+ || x.Velocity != y.Velocity || x.ExprId != y.ExprId) return false;
+ }
+ return true;
+ }
+
+ // The clips whose notes differ from what was last pushed — or, for the undo seed of a
+ // drag, every editable clip (a drag may carry notes into any of them).
+ private List<ClipNotes> DirtyClips(IReadOnlyList<NotaNote> notes, IReadOnlyList<int> owners, bool all)
+ {
+ var split = _set.Split(notes, owners);
+ if (_pushed.Length != split.Count) _pushed = new NotaNote[split.Count][];
+ var dirty = new List<ClipNotes>();
+ for (int k = 0; k < split.Count; k++)
+ {
+ bool changed = _pushed[k] is null || !SameNotes(split[k].Notes, _pushed[k]);
+ if (!changed && !(all && _set.IsEditable(k))) continue;
+ _pushed[k] = split[k].Notes.ToArray();
+ dirty.Add(split[k]);
+ }
+ return dirty;
+ }
+
/// <summary>Pushes a note set as one undoable edit. Any clip-tool preview in flight is
/// superseded — the notes on screen become the clip's own and the tools rail re-reads
/// them on the next <see cref="Changed"/>. Without this, quantizing (or drawing a note)
/// while a generator previewed would leave the rail holding a baseline it could later
- /// revert the clip to.</summary>
- private void CommitNotes(IReadOnlyList<NotaNote>? notes = null)
+ /// revert the clip to. <paramref name="seed"/>: the pre-drag state that seeds a drag's
+ /// undo step — every editable clip goes.</summary>
+ private void CommitNotes(IReadOnlyList<NotaNote>? notes = null, IReadOnlyList<int>? owners = null, bool seed = false)
{
_previewBackup = null;
- Commit?.Invoke(notes ?? _notes);
+ _previewOwners = null;
+ notes ??= _notes;
+ owners ??= _owner;
+ if (CommitClips is not null)
+ {
+ var dirty = DirtyClips(notes, owners, seed);
+ if (dirty.Count > 0) CommitClips(dirty);
+ }
+ else Commit?.Invoke(notes);
}
- /// <summary>Moves note starts toward the Quantize step (its own value, never the zoom's).</summary>
+ /// <summary>Streams notes to the engine with no undo checkpoint.</summary>
+ private void PushLive(IReadOnlyList<NotaNote> notes, IReadOnlyList<int> owners)
+ {
+ if (CommitClipsLive is not null)
+ {
+ var dirty = DirtyClips(notes, owners, false);
+ if (dirty.Count > 0) CommitClipsLive(dirty);
+ }
+ else CommitLive?.Invoke(notes);
+ }
+
+ /// <summary>Moves note starts toward the Quantize step (its own value, never the zoom's).
+ /// Notes of reference clips stay put.</summary>
public void Quantize(double strength)
{
SettlePlacement();
double qStep = Grids.Quantize.Beats(_beatsPerBar);
for (int i = 0; i < _notes.Count; i++)
{
+ if (IsLocked(i)) continue;
var n = _notes[i];
double q = SnapGrid.SnapBeat(n.StartBeat, qStep, _beatsPerBar);
n.StartBeat += (q - n.StartBeat) * Math.Clamp(strength, 0, 1);
@@ -800,6 +1075,7 @@ public sealed partial class PianoRollView : UserControl
SettlePlacement();
for (int i = 0; i < _notes.Count; i++)
{
+ if (IsLocked(i)) continue;
var n = _notes[i];
n.Pitch = Math.Clamp(n.Pitch + semis, 0, 127);
_notes[i] = n;
@@ -809,8 +1085,8 @@ public sealed partial class PianoRollView : UserControl
Changed?.Invoke();
}
- /// <summary>Live playback cursor in clip-local beats; playing=false or an out-of-range
- /// beat hides it. Cheap: repaints only the grid + ruler, not the whole roll.</summary>
+ /// <summary>Live playback cursor in editor beats (clip-local for one clip); playing=false
+ /// or an out-of-range beat hides it. Cheap: repaints only the grid + ruler, not the whole roll.</summary>
public void SetPlayhead(double clipLocalBeat, bool playing)
{
double b = (playing && clipLocalBeat >= 0 && clipLocalBeat <= _lengthBeats) ? clipLocalBeat : -1;
@@ -821,15 +1097,20 @@ public sealed partial class PianoRollView : UserControl
_ruler.InvalidateVisual();
}
- /// <summary>Copies the selected notes to the shared clipboard (normalized to beat 0).</summary>
+ /// <summary>Copies the selected notes to the shared clipboard, each with the clip it came
+ /// from and its beat in that clip (specs/029).</summary>
public bool CopySelection()
{
- var sel = _selection.Where(i => i >= 0 && i < _notes.Count).Select(i => _notes[i]).ToList();
+ var sel = _selection.Where(i => i >= 0 && i < _notes.Count).OrderBy(i => i).ToList();
if (sel.Count == 0) return false;
- double min = sel.Min(n => n.StartBeat);
s_clipboard.Clear();
- s_clipAnchor = min;
- foreach (var n in sel) { var c = n; c.StartBeat -= min; s_clipboard.Add(c); }
+ foreach (int i in sel)
+ {
+ var c = _notes[i];
+ var clip = _set.Clips[_owner[i]];
+ c.StartBeat = _set.ToLocal(_owner[i], c.StartBeat);
+ s_clipboard.Add(new ClipboardNote(c, clip.TrackId, clip.ClipIndex));
+ }
return true;
}
@@ -838,21 +1119,24 @@ public sealed partial class PianoRollView : UserControl
/// <summary>Pastes the clipboard on top of the copied notes' original position (whatever
/// the transport is doing) and selects the copies, ready to be moved off with the arrows or
- /// the mouse. The copies overwrite nothing until they are let go (SettlePlacement). Undoable.</summary>
+ /// the mouse: back into the clip they came from when it is open, else into the active clip
+ /// at the same clip-relative beats. The copies overwrite nothing until they are let go
+ /// (SettlePlacement). Undoable.</summary>
public bool PasteClipboard()
{
if (s_clipboard.Count == 0) return false;
SettlePlacement();
- double anchor = s_clipAnchor;
int baseIdx = _notes.Count;
foreach (var c in s_clipboard)
{
- var n = c;
- n.StartBeat = anchor + c.StartBeat;
- if (n.StartBeat >= _lengthBeats) continue; // past the clip end → skip
- if (n.StartBeat + n.LengthBeats > _lengthBeats) // trim a note that overruns
- n.LengthBeats = Math.Max(MinNoteLen, _lengthBeats - n.StartBeat);
- _notes.Add(n);
+ var n = c.Note;
+ var (slot, at) = _set.PasteTarget(c.TrackId, c.ClipIndex, c.Note.StartBeat);
+ double end = _set.EditorEnd(slot);
+ n.StartBeat = at;
+ if (n.StartBeat >= end - 1e-9) continue; // past the clip end → skip
+ if (n.StartBeat + n.LengthBeats > end) // trim a note that overruns
+ n.LengthBeats = Math.Max(MinNoteLen, end - n.StartBeat);
+ AddNote(n, slot);
}
if (_notes.Count == baseIdx) return false;
_selection.Clear();
@@ -862,31 +1146,47 @@ public sealed partial class PianoRollView : UserControl
return true;
}
+ /// <summary>The allowed shift of the selected notes, in beats, so that every note still
+ /// starts within its reach (its clip, joined with neighbouring open clips of its track) and
+ /// — for a nudge — still ends within it; the selection moves as a block.</summary>
+ private (double Lo, double Hi) ShiftRange(IEnumerable<int> sel, Func<int, (double start, double len, int owner)> at, bool endsInside)
+ {
+ double lo = double.MinValue, hi = double.MaxValue;
+ foreach (int i in sel)
+ {
+ var (start, len, owner) = at(i);
+ var (rs, re) = _set.Reach(owner);
+ lo = Math.Max(lo, rs - start);
+ hi = Math.Min(hi, endsInside ? re - (start + len) : Math.Max(0, re - MinNoteLen - start));
+ }
+ return (Math.Min(lo, 0), Math.Max(hi, 0));
+ }
+
/// <summary>Nudges the selection by dPitch semitones and/or dBeat beats, clamped to the
- /// pitch range and clip bounds (moves as a block, stopping at the edge). Undoable.
+ /// pitch range and clip bounds (moves as a block, stopping at the edge). A note whose start
+ /// crosses into a neighbouring open clip of its track moves into that clip. Undoable.
/// Scrolls vertically to keep pitch-moved notes in view.</summary>
public bool MoveSelection(int dPitch, double dBeat)
{
var sel = _selection.Where(i => i >= 0 && i < _notes.Count).ToList();
if (sel.Count == 0) return false;
- double minStart = double.MaxValue, maxEnd = double.MinValue;
int minP = 128, maxP = -1;
foreach (int i in sel)
{
- var n = _notes[i];
- minStart = Math.Min(minStart, n.StartBeat);
- maxEnd = Math.Max(maxEnd, n.StartBeat + n.LengthBeats);
- minP = Math.Min(minP, n.Pitch);
- maxP = Math.Max(maxP, n.Pitch);
- }
- double db = dBeat;
- if (minStart + db < 0) db = -minStart;
- if (maxEnd + db > _lengthBeats) db = _lengthBeats - maxEnd;
+ minP = Math.Min(minP, _notes[i].Pitch);
+ maxP = Math.Max(maxP, _notes[i].Pitch);
+ }
+ var (lo, hi) = ShiftRange(sel, i => (_notes[i].StartBeat, _notes[i].LengthBeats, _owner[i]), endsInside: true);
+ double db = Math.Clamp(dBeat, lo, hi);
int dp = dPitch;
if (minP + dp < MinPitch) dp = MinPitch - minP;
if (maxP + dp > MaxPitch) dp = MaxPitch - maxP;
if (Math.Abs(db) < 1e-9 && dp == 0) return false;
- foreach (int i in sel) { var n = _notes[i]; n.StartBeat += db; n.Pitch += dp; _notes[i] = n; }
+ foreach (int i in sel)
+ {
+ var n = _notes[i]; n.StartBeat += db; n.Pitch += dp; _notes[i] = n;
+ _owner[i] = _set.OwnerAfterMove(_owner[i], n.StartBeat);
+ }
_placementPending = true;
Invalidate(); CommitNotes(); Changed?.Invoke();
if (dp != 0) EnsurePitchVisible(dp > 0 ? maxP + dp : minP + dp);
@@ -894,12 +1194,12 @@ public sealed partial class PianoRollView : UserControl
}
/// <summary>Lengthens (dir +1) or shortens (dir −1) every selected note by one grid step,
- /// keeping starts; never below the minimum length or past the clip end. Undoable.</summary>
+ /// keeping starts; never below the minimum length or past its clip's end. Undoable.</summary>
public bool ResizeSelection(int dir)
{
if (_selection.Count == 0) return false;
double step = SnapGridState.SnapOn ? SnapStep : MinNoteLen;
- if (!NoteOverwrite.ResizeBy(_notes, _selection, dir * step, MinNoteLen, _lengthBeats)) return false;
+ if (!NoteOverwrite.ResizeBy(_notes, _selection, dir * step, MinNoteLen, i => _set.EditorEnd(_owner[i]))) return false;
_placementPending = true;
Invalidate(); CommitNotes(); Changed?.Invoke();
return true;
@@ -928,7 +1228,8 @@ public sealed partial class PianoRollView : UserControl
// ---- pending placement (specs/007-midi-note-editing) -------------------------
// Notes moved, stretched, drawn or pasted overwrite same-pitch notes they land on, but
// only once the selection is let go: until then the notes underneath stay whole and are
- // drawn marked, so a pasted copy can be walked off its original with the arrows.
+ // drawn marked, so a pasted copy can be walked off its original with the arrows. Only
+ // notes of the same clip overwrite each other (specs/029).
private bool _placementPending;
// The selection as a list for the per-frame overwrite marks (Fate is allocation-free over a
@@ -945,9 +1246,9 @@ public sealed partial class PianoRollView : UserControl
}
/// <summary>Applies a pending placement: the selected notes overwrite the same-pitch notes
- /// they cover (NoteOverwrite). Its own undo step. Called whenever the selection is let go —
- /// selection change, focus loss, whole-clip edits, and by the host before save/export.
- /// Returns true when notes were cut or removed (indices may have shifted).</summary>
+ /// of their own clip they cover (NoteOverwrite). Its own undo step. Called whenever the
+ /// selection is let go — selection change, focus loss, whole-clip edits, and by the host
+ /// before save/export. Returns true when notes were cut or removed (indices may have shifted).</summary>
public bool SettlePlacement()
{
if (!_placementPending) return false;
@@ -956,13 +1257,13 @@ public sealed partial class PianoRollView : UserControl
var placed = _selection.Where(i => i >= 0 && i < _notes.Count).ToList();
var settled = new List<NotaNote>(_notes.Count);
var placedOut = new List<int>(placed.Count);
- NoteOverwrite.Settle(_notes, placed, settled, placedOut);
+ var ownersOut = new List<int>(_notes.Count);
+ NoteOverwrite.Settle(_notes, placed, settled, placedOut, _owner, ownersOut);
bool changed = settled.Count != _notes.Count;
for (int i = 0; !changed && i < settled.Count; i++)
changed = settled[i].LengthBeats != _notes[i].LengthBeats;
if (!changed) return false;
- _notes.Clear();
- _notes.AddRange(settled);
+ ReplaceAll(settled, ownersOut);
_selection.Clear();
_selection.UnionWith(placedOut);
Invalidate(); CommitNotes(); Changed?.Invoke();
@@ -989,9 +1290,14 @@ public sealed partial class PianoRollView : UserControl
_overlayHost.IsVisible = overlay is not null;
}
- /// <summary>The selected notes, in clip order.</summary>
+ /// <summary>The selected notes, in list order, each at its beat in its own clip.</summary>
public IReadOnlyList<NotaNote> SelectedNotes()
- => _selection.Where(i => i >= 0 && i < _notes.Count).OrderBy(i => i).Select(i => _notes[i]).ToList();
+ => _selection.Where(i => i >= 0 && i < _notes.Count).OrderBy(i => i).Select(i =>
+ {
+ var n = _notes[i];
+ n.StartBeat = _set.ToLocal(_owner[i], n.StartBeat);
+ return n;
+ }).ToList();
/// <summary>The ⌘/Ctrl-wheel zoom and Shift/horizontal-wheel scroll of the note grid, for an
/// overlay that sits on top of it.</summary>
@@ -1008,20 +1314,47 @@ public sealed partial class PianoRollView : UserControl
e.Handled = true;
}
- /// <summary>Darkens everything right of the clip's end and marks the edge with a line.</summary>
+ /// <summary>Darkens everything outside the open clips and marks each covered stretch's
+ /// edges with a line; with one clip, everything right of its end.</summary>
private void DrawOutsideClip(DrawingContext ctx, double w, double h)
{
- double x = BeatToX(_lengthBeats);
- if (x >= w) return;
- x = Math.Max(0, x);
- ctx.FillRectangle(OutsideClip, new Rect(x, 0, w - x, h));
- ctx.DrawLine(ClipEndPen, new Point(x + 0.5, 0), new Point(x + 0.5, h));
+ double from = 0; // editor beat where the current uncovered stretch starts
+ foreach (var (s, e) in CoveredSpans())
+ {
+ Wash(from, s, edgeAtEnd: true);
+ from = e;
+ }
+ Wash(from, double.PositiveInfinity, edgeAtEnd: false);
+
+ void Wash(double b0, double b1, bool edgeAtEnd)
+ {
+ double x0 = Math.Max(0, BeatToX(b0)), x1 = double.IsPositiveInfinity(b1) ? w : Math.Min(w, BeatToX(b1));
+ if (x1 > x0) ctx.FillRectangle(OutsideClip, new Rect(x0, 0, x1 - x0, h));
+ // The edge line where a clip ends (b0) and, between clips, where the next begins.
+ double xe = BeatToX(b0);
+ if (b0 > 0 && xe >= 0 && xe < w) ctx.DrawLine(ClipEndPen, new Point(xe + 0.5, 0), new Point(xe + 0.5, h));
+ double xs = BeatToX(b1);
+ if (edgeAtEnd && b1 > b0 && xs >= 0 && xs < w) ctx.DrawLine(ClipEndPen, new Point(xs + 0.5, 0), new Point(xs + 0.5, h));
+ }
+ }
+
+ // The editor-beat stretches covered by at least one open clip, merged, in order.
+ private List<(double Start, double End)> CoveredSpans()
+ {
+ var spans = new List<(double, double)>();
+ foreach (var (s, e) in Enumerable.Range(0, _set.Count).Select(k => (_set.EditorStart(k), _set.EditorEnd(k))).OrderBy(t => t.Item1))
+ {
+ if (spans.Count > 0 && s <= spans[^1].Item2 + 1e-9) spans[^1] = (spans[^1].Item1, Math.Max(spans[^1].Item2, e));
+ else spans.Add((s, e));
+ }
+ return spans;
}
private void Invalidate()
{
_overlayHost.Child?.InvalidateVisual();
_ruler.InvalidateVisual();
+ _strip.InvalidateVisual();
_keys.InvalidateVisual();
_gridControl.InvalidateVisual();
_vel.InvalidateVisual();
@@ -1080,7 +1413,7 @@ public sealed partial class PianoRollView : UserControl
// Ruler label at beat b: "bar.beat", plus a 1/16 index when mid-beat (e.g. 3.2.3).
internal string GridLabel(double b)
{
- int bar = (int)Math.Floor(b / _beatsPerBar) + 1;
+ int bar = (int)Math.Floor(b / _beatsPerBar) + 1 + RulerBarOffset;
double inBar = b - Math.Floor(b / _beatsPerBar) * _beatsPerBar;
int beat = (int)Math.Floor(inBar) + 1;
double frac = inBar - Math.Floor(inBar);
@@ -1088,6 +1421,10 @@ public sealed partial class PianoRollView : UserControl
return $"{bar}.{beat}.{(int)Math.Round(frac * 4) + 1}";
}
+ // Ruler bar numbers: the clip's own bars for one clip, the arrangement's when several are
+ // open (their origin sits on a bar line, see ClipSet).
+ private int RulerBarOffset => _set.IsMulti ? (int)Math.Round(_set.Origin / Math.Max(1, _beatsPerBar)) : 0;
+
// ---- ruler -----------------------------------------------------------
private sealed class RulerLane : Control
{
@@ -1145,9 +1482,12 @@ public sealed partial class PianoRollView : UserControl
_o.EnsurePpb(w);
double ppb = _o.PixelsPerBeat;
double viewEnd = Math.Min(_o._lengthBeats, _o.ScrollBeats + w / Math.Max(1e-6, ppb));
- double loopEnd = Math.Min(w, _o.BeatToX(_o._lengthBeats));
- double loopStart = Math.Max(0, _o.BeatToX(0));
- if (loopEnd > loopStart) ctx.FillRectangle(LoopStrip, new Rect(loopStart, 0, loopEnd - loopStart, 3));
+ foreach (var (cs, ce) in _o.CoveredSpans())
+ {
+ double loopEnd = Math.Min(w, _o.BeatToX(ce));
+ double loopStart = Math.Max(0, _o.BeatToX(cs));
+ if (loopEnd > loopStart) ctx.FillRectangle(LoopStrip, new Rect(loopStart, 0, loopEnd - loopStart, 3));
+ }
// Label every beat while there is room for "12.4", else bars only.
double step = ppb >= 30 ? 1 : _o._beatsPerBar;
double startB = Math.Max(0, Math.Floor(_o.ScrollBeats / step) * step);
@@ -1160,7 +1500,7 @@ public sealed partial class PianoRollView : UserControl
bool bar = Math.Abs(b / bpb - Math.Round(b / bpb)) < 1e-6;
ctx.DrawLine(bar ? BarPen : BeatPen, new Point(x + 0.5, 0), new Point(x + 0.5, h));
if (b >= _o._lengthBeats - 1e-9) continue;
- int barNo = (int)Math.Floor(b / bpb) + 1, beatNo = (int)Math.Round(b - Math.Floor(b / bpb) * bpb) + 1;
+ int barNo = (int)Math.Floor(b / bpb) + 1 + _o.RulerBarOffset, beatNo = (int)Math.Round(b - Math.Floor(b / bpb) * bpb) + 1;
string label = bar ? barNo.ToString(NotaNum.Culture) : $"{barNo}.{beatNo}";
var ft = new FormattedText(label, NotaNum.Culture, FlowDirection.LeftToRight, Mono, 9, bar ? RulerBarText : LabelText);
ctx.DrawText(ft, new Point(x + 4, h - 5 - ft.Height));
@@ -1324,7 +1664,7 @@ public sealed partial class PianoRollView : UserControl
private bool _dragMoved;
// Move/resize: each selected note's state at grab time + the primary grabbed.
- private readonly Dictionary<int, (double start, int pitch, double len)> _orig = new();
+ private readonly Dictionary<int, (double start, int pitch, double len, int owner)> _orig = new();
private int _primary = -1;
private double _grabBeat; // pointer-beat minus primary start, at grab (Move)
private double _edgeGrab; // pointer beat minus the grabbed edge at press (Resize / ResizeLeft)
@@ -1347,6 +1687,7 @@ public sealed partial class PianoRollView : UserControl
// Live drag (feature): the pre-drag note list (to seed one undo entry) + whether the
// live stream has started this gesture.
private readonly List<NotaNote> _preDrag = new();
+ private readonly List<int> _preDragOwners = new();
private bool _liveStarted;
// Vertical auto-scroll while a drag runs past the viewport edges.
@@ -1354,7 +1695,7 @@ public sealed partial class PianoRollView : UserControl
private double _autoVelY;
private Point _lastGrid;
- private readonly List<Rect> _doomed = new(); // per-frame scratch for the overwrite marks
+ private readonly List<(Rect, Color)> _doomed = new(); // per-frame scratch for the overwrite marks
public NoteGrid(PianoRollView o)
{
@@ -1407,10 +1748,14 @@ public sealed partial class PianoRollView : UserControl
double ppb = Ppb;
_o.DrawGridLines(ctx, w, h);
var notes = _o._notes;
+ // Other clips' notes first, so the active clip's draw on top where they overlap.
+ bool multi = _o._set.IsMulti;
+ for (int pass = multi ? 0 : 1; pass < 2; pass++)
for (int i = 0; i < notes.Count; i++)
{
var n = notes[i];
if (n.Pitch < MinPitch || n.Pitch > MaxPitch) continue;
+ if (multi && (_o._owner[i] == _o._set.Active) != (pass == 1)) continue;
double x = BeatToX(n.StartBeat), y = PitchToY(n.Pitch);
double nw = Math.Max(3, n.LengthBeats * ppb);
bool sel = _o._selection.Contains(i);
@@ -1423,14 +1768,15 @@ public sealed partial class PianoRollView : UserControl
if (sel) ctx.DrawRectangle(NoteSel, NoteSelEdge, r.Deflate(0.5), 2, 2);
else
{
- // Track colour, quieter the softer the note.
- var c = _o._trackColor;
- double a = 0.45 + 0.55 * Math.Clamp(n.Velocity, 0, 1);
+ // Track colour, quieter the softer the note — and, with several clips open,
+ // quieter for clips other than the active one.
+ var c = _o.ColorOf(i);
+ double a = (0.45 + 0.55 * Math.Clamp(n.Velocity, 0, 1)) * _o.ClipEmphasis(i);
if (!_o.InScale(n.Pitch)) a *= 0.4; // out-of-scale notes read faint
// A pending placement covers part of this note: the part settling will cut
// (or all of it, when it goes) reads faint behind a dashed track-colour edge.
var fate = _o._placementPending && _o._selection.Count > 0
- ? NoteOverwrite.Fate(i, notes, _o.PlacedForRender()) : default;
+ ? NoteOverwrite.Fate(i, notes, _o.PlacedForRender(), _o._owner) : default;
double appear = _o._recPreview?.Progress(n.Pitch, _o._recClipStart + n.StartBeat) ?? 1;
if (fate.Kind == NoteFateKind.Kept && appear < 1)
ctx.FillRectangle(RecordPreview.AppearBrush(c, appear), r, 2);
@@ -1443,12 +1789,12 @@ public sealed partial class PianoRollView : UserControl
ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a), c.R, c.G, c.B)), r.WithWidth(keepW), 2);
var doomed = new Rect(r.X + keepW, r.Y, Math.Max(1, r.Width - keepW), r.Height);
ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a * 0.25), c.R, c.G, c.B)), doomed, 2);
- _doomed.Add(doomed); // its dashed edge goes on top of the notes covering it
+ _doomed.Add((doomed, c)); // its dashed edge goes on top of the notes covering it
}
}
if (n.ExprId > 0 || _o._expr.Editing(i)) DrawExpression(ctx, i, n, r, sel, ppb);
// Resize-edge affordance: a bright bar on the edge a drag would trim.
- bool edgeHi = ((_drag == Mode.Resize || _drag == Mode.ResizeLeft) && sel) || (_drag == Mode.None && _hoverNote == i);
+ bool edgeHi = ((_drag == Mode.Resize || _drag == Mode.ResizeLeft) && sel) || (_drag == Mode.None && _hoverNote == i && !_o.IsLocked(i));
if (edgeHi)
{
bool left = _drag == Mode.ResizeLeft || (_drag == Mode.None && _hoverLeft);
@@ -1459,8 +1805,8 @@ public sealed partial class PianoRollView : UserControl
// so a note hidden under a pasted copy still shows that it is there and will go.
if (_doomed.Count > 0)
{
- var pen = new Pen(new SolidColorBrush(_o._trackColor), 1, DashStyle.Dash);
- foreach (var d in _doomed) ctx.DrawRectangle(null, pen, d.Deflate(0.5), 2, 2);
+ foreach (var (d, dc) in _doomed)
+ ctx.DrawRectangle(null, new Pen(new SolidColorBrush(dc), 1, DashStyle.Dash), d.Deflate(0.5), 2, 2);
_doomed.Clear();
}
// Keys held into the recording take (#56): from the key-down to the capture clock,
@@ -1553,17 +1899,25 @@ public sealed partial class PianoRollView : UserControl
{
edge = 0;
var notes = _o._notes;
+ // The active clip's notes are on top, so they win a click where clips overlap.
+ int best = -1, bestEdge = 0;
for (int i = notes.Count - 1; i >= 0; i--)
{
var n = notes[i];
- if (n.Pitch < MinPitch || n.Pitch > MaxPitch) continue;
+ if (n.Pitch < MinPitch || n.Pitch > MaxPitch || _o.IsLocked(i)) continue;
double x = BeatToX(n.StartBeat), y = PitchToY(n.Pitch), nw = Math.Max(3, n.LengthBeats * Ppb);
if (!new Rect(x, y, nw, RowH).Contains(p)) continue;
+ if (_o._owner[i] != _o._set.Active)
+ {
+ if (best < 0) { best = i; double z = Math.Min(EdgePx, nw / 3); bestEdge = p.X >= x + nw - z ? 1 : p.X <= x + z ? -1 : 0; }
+ continue;
+ }
double zone = Math.Min(EdgePx, nw / 3);
edge = p.X >= x + nw - zone ? 1 : p.X <= x + zone ? -1 : 0;
return i;
}
- return -1;
+ edge = bestEdge;
+ return best;
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
@@ -1582,15 +1936,18 @@ public sealed partial class PianoRollView : UserControl
// Double-click: add a note on empty space, delete one under the cursor.
if (e.ClickCount == 2)
{
- if (hit >= 0) { _o._notes.RemoveAt(hit); _o._selection.Clear(); }
+ if (hit >= 0) { _o.RemoveNoteAt(hit); _o._selection.Clear(); }
else
{
double at = Math.Max(0, Snap(XToBeat(p.X)));
- var nt = new NotaNote(YToPitch(p.Y), at, _o.NewNoteLen(at), s_lastVel);
- _o._notes.Add(nt);
+ int slot = _o.DrawTarget(at);
+ if (slot < 0) { e.Handled = true; return; } // no open clip of the active track here
+ if (slot != _o._set.Active) _o.SetActiveClip(slot);
+ var nt = new NotaNote(YToPitch(p.Y), at, _o.NewNoteLen(at, slot), s_lastVel);
+ _o.AddNote(nt, slot);
_o._selection.Clear(); _o._selection.Add(_o._notes.Count - 1);
_o._placementPending = true; // a drawn note overwrites what it lands on
- _o.Audition(nt.Pitch, nt.Velocity); // heard until the button comes up
+ _o.Audition(nt.Pitch, nt.Velocity, slot: slot); // heard until the button comes up
e.Pointer.Capture(this);
}
_o.Invalidate(); _o.CommitNotes(); _o.Changed?.Invoke();
@@ -1608,15 +1965,19 @@ public sealed partial class PianoRollView : UserControl
return;
}
if (!_o._selection.Contains(hit)) { _o._selection.Clear(); _o._selection.Add(hit); }
+ // A note of another clip makes that clip active (header, inspector, envelopes).
+ if (_o._selection.Count == 1 && _o._owner[hit] != _o._set.Active) _o.SetActiveClip(_o._owner[hit]);
e.Pointer.Capture(this);
- _o.Audition(_o._notes[hit].Pitch, _o._notes[hit].Velocity);
+ _o.Audition(_o._notes[hit].Pitch, _o._notes[hit].Velocity, slot: _o._owner[hit]);
_primary = hit;
_o.Remember(hit);
_dragMoved = false;
_orig.Clear();
foreach (int i in _o._selection)
- if (i >= 0 && i < _o._notes.Count) { var nn = _o._notes[i]; _orig[i] = (nn.StartBeat, nn.Pitch, nn.LengthBeats); }
- _preDrag.Clear(); _preDrag.AddRange(_o._notes); _liveStarted = false;
+ if (i >= 0 && i < _o._notes.Count) { var nn = _o._notes[i]; _orig[i] = (nn.StartBeat, nn.Pitch, nn.LengthBeats, _o._owner[i]); }
+ _preDrag.Clear(); _preDrag.AddRange(_o._notes);
+ _preDragOwners.Clear(); _preDragOwners.AddRange(_o._owner);
+ _liveStarted = false;
if (edge != 0)
{
_drag = edge > 0 ? Mode.Resize : Mode.ResizeLeft;
@@ -1659,11 +2020,12 @@ public sealed partial class PianoRollView : UserControl
var pr = _orig[_primary];
double dBeat = targetStart - pr.start;
int dPitch = YToPitch(p.Y) - pr.pitch;
- // Clamp the shared delta so the whole group stays in-bounds (keeps shape).
- double minStart = double.MaxValue; int minP = int.MaxValue, maxP = int.MinValue;
- foreach (var v in _orig.Values) { minStart = Math.Min(minStart, v.start); minP = Math.Min(minP, v.pitch); maxP = Math.Max(maxP, v.pitch); }
- double cap = Math.Max(0, _o._lengthBeats - _o.MinNoteLen);
- dBeat = Math.Clamp(dBeat, -minStart, Math.Max(0, cap - MaxStart()));
+ // Clamp the shared delta so the whole group stays in-bounds (keeps shape): every
+ // start within its reach — its clip and the open clips of its track it touches.
+ int minP = int.MaxValue, maxP = int.MinValue;
+ foreach (var v in _orig.Values) { minP = Math.Min(minP, v.pitch); maxP = Math.Max(maxP, v.pitch); }
+ var (lo, hi) = _o.ShiftRange(_orig.Keys, i => (_orig[i].start, _orig[i].len, _orig[i].owner), endsInside: false);
+ dBeat = Math.Clamp(dBeat, lo, hi);
dPitch = Math.Clamp(dPitch, MinPitch - minP, MaxPitch - maxP);
foreach (var kv in _orig)
{
@@ -1671,11 +2033,12 @@ public sealed partial class PianoRollView : UserControl
n.StartBeat = kv.Value.start + dBeat;
n.Pitch = kv.Value.pitch + dPitch;
_o._notes[kv.Key] = n;
+ _o._owner[kv.Key] = _o._set.OwnerAfterMove(kv.Value.owner, n.StartBeat);
}
_dragMoved = true;
PushLive();
// A drag to a new pitch re-triggers the grabbed note there (#46).
- _o.Audition(_o._notes[_primary].Pitch, _o._notes[_primary].Velocity);
+ _o.Audition(_o._notes[_primary].Pitch, _o._notes[_primary].Velocity, slot: _o._owner[_primary]);
}
else if (_drag == Mode.Resize)
{
@@ -1699,7 +2062,10 @@ public sealed partial class PianoRollView : UserControl
var pr = _orig[_primary];
double dStart = Snap(XToBeat(p.X) - _edgeGrab) - pr.start;
foreach (var v in _orig.Values)
- dStart = Math.Clamp(dStart, -v.start, Math.Max(-v.start, v.len - _o.MinNoteLen));
+ {
+ double floor = _o._set.EditorStart(v.owner) - v.start;
+ dStart = Math.Clamp(dStart, floor, Math.Max(floor, v.len - _o.MinNoteLen));
+ }
foreach (var kv in _orig)
{
var n = _o._notes[kv.Key];
@@ -1724,13 +2090,11 @@ public sealed partial class PianoRollView : UserControl
// the normal Commit; every subsequent frame uses the no-undo live path.
private void PushLive()
{
- if (_o.CommitLive is null) return; // no live path wired (e.g. session) → commit on release
- if (!_liveStarted) { _liveStarted = true; _o.CommitNotes(_preDrag); }
- _o.CommitLive(_o._notes);
+ if (!_o.HasLivePath) return; // no live path wired → commit on release
+ if (!_liveStarted) { _liveStarted = true; _o.CommitNotes(_preDrag, _preDragOwners, seed: true); }
+ _o.PushLive(_o._notes, _o._owner);
}
- private double MaxStart() { double m = double.MinValue; foreach (var v in _orig.Values) m = Math.Max(m, v.start); return m; }
-
private void RecomputeMarquee()
{
var r = RectOf(_marqueeA, _marqueeB);
@@ -1740,7 +2104,7 @@ public sealed partial class PianoRollView : UserControl
{
var n = _o._notes[i];
double x = BeatToX(n.StartBeat), y = PitchToY(n.Pitch), nw = Math.Max(3, n.LengthBeats * Ppb);
- if (r.Intersects(new Rect(x, y, nw, RowH))) _o._selection.Add(i);
+ if (!_o.IsLocked(i) && r.Intersects(new Rect(x, y, nw, RowH))) _o._selection.Add(i);
}
}
@@ -1783,7 +2147,7 @@ public sealed partial class PianoRollView : UserControl
_o._placementPending = true; // overwrites once the selection is let go
// Live path: undo was seeded on the first move; push the final state (no undo).
// No live path (session): fall back to a single committing push.
- if (_o.CommitLive is not null && _liveStarted) _o.CommitLive(_o._notes);
+ if (_o.HasLivePath && _liveStarted) _o.PushLive(_o._notes, _o._owner);
else _o.CommitNotes();
}
_liveStarted = false;
@@ -1899,7 +2263,7 @@ public sealed partial class PianoRollView : UserControl
{
_o.SettlePlacement();
_o._selection.Clear();
- for (int i = 0; i < _o._notes.Count; i++) _o._selection.Add(i);
+ for (int i = 0; i < _o._notes.Count; i++) if (!_o.IsLocked(i)) _o._selection.Add(i);
_o.Invalidate(); _o.Changed?.Invoke(); e.Handled = true; return;
}
if (meta && e.Key == Key.D) // cross-platform fallback (macOS uses the native menu)
@@ -1938,6 +2302,7 @@ public sealed partial class PianoRollView : UserControl
var notes = _o._notes;
for (int i = 0; i < notes.Count; i++)
{
+ if (_o.IsLocked(i)) continue; // a reference clip's velocities are not on offer
var n = notes[i];
double x = _o.BeatToX(n.StartBeat) + 3;
double bh = Math.Clamp(n.Velocity, 0, 1) * (h - 8);
@@ -1948,8 +2313,8 @@ public sealed partial class PianoRollView : UserControl
else if (sel) b = NoteSel;
else
{
- var c = hov ? Brighten(_o._trackColor) : _o._trackColor;
- double a = 0.45 + 0.55 * Math.Clamp(n.Velocity, 0, 1);
+ var c = hov ? Brighten(_o.ColorOf(i)) : _o.ColorOf(i);
+ double a = (0.45 + 0.55 * Math.Clamp(n.Velocity, 0, 1)) * _o.ClipEmphasis(i);
b = new SolidColorBrush(Color.FromArgb((byte)(255 * a), c.R, c.G, c.B));
}
ctx.FillRectangle(b, new Rect(x, h - bh, 2, bh));
@@ -1972,6 +2337,7 @@ public sealed partial class PianoRollView : UserControl
int best = -1; double bx = 14, by = double.MaxValue;
for (int i = 0; i < _o._notes.Count; i++)
{
+ if (_o.IsLocked(i)) continue;
double dx = Math.Abs(_o.BeatToX(_o._notes[i].StartBeat) + 4 - p.X);
if (dx > 14) continue;
double dy = Math.Abs(CapY(i) - p.Y);
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 906f50ac..68ce2fdf 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -1209,6 +1209,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("Drag velocity stem", "Set velocity · selected notes move together · ⇧ adds a note"),
("Drag in the Bend / Pres / Slide lane", "Draw the selected note's MPE curve · ⌥ draws a straight line · drag a point to move it"),
("Double-click in an MPE lane", "Add a point · on a point, delete it · right-click to clear the curve"),
+ ("Click a clip in the clip strip", "Make it the active clip (several clips open) · its lock keeps it as a read-only reference"),
("⌘⌥ + wheel", "Zoom rows (vertical zoom)"),
("Click a key", "Play it on the track's instrument · ⇧-drag glides through the keys · ⌘-click selects every note of that pitch"),
("Drag on the keys", "Zoom rows · down taller, up shorter"),
@@ -1242,7 +1243,7 @@ public sealed partial class PreferencesWindow : NotaWindow
}),
("Mouse", new[]
{
- ("Double-click clip", "Open in the clip editor"),
+ ("Double-click clip", "Open in the clip editor · on one of several selected MIDI clips, open them all together"),
("Double-click a browser instrument", "Swap it onto the selected instrument track · clips and effects stay · no track selected starts one"),
("⌥ + double-click a browser instrument", "Always start a new track with it"),
("Right-click the metronome", "Count-in before Play / Record: off · 1 · 2 · 4 bars"),
diff --git a/src/managed/Nota.Application/Editing/ClipSet.cs b/src/managed/Nota.Application/Editing/ClipSet.cs
new file mode 100644
index 00000000..586dd4b6
--- /dev/null
+++ b/src/managed/Nota.Application/Editing/ClipSet.cs
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The clips one Clip editor shows (specs/029-multi-clip-editing). The piano roll keeps a single
+// note list in *editor beats* — beats from the earliest open clip's start — with each note's
+// owner clip (its slot here) alongside. This class owns the rules that must agree everywhere:
+// coordinates, which clips a moved note can reach, which clip it belongs to after a move,
+// and splitting the roll's list back into each clip's own notes. A single-clip editor is a
+// set of one, so editor beats equal clip-local beats there. Pure and UI-free: the smoke test
+// drives it directly.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Nota.Application.Editing;
+
+/// <summary>One MIDI clip open in a Clip editor. Start and length are arrangement beats.</summary>
+public sealed record OpenClip(int TrackId, int ClipIndex, double StartBeat, double LengthBeats, bool IsReference = false)
+{
+ public double EndBeat => StartBeat + LengthBeats;
+}
+
+/// <summary>One clip's notes in its own (clip-local) beats — what the engine stores.</summary>
+public readonly record struct ClipNotes(int TrackId, int ClipIndex, IReadOnlyList<NotaNote> Notes);
+
+public sealed class ClipSet
+{
+ private const double Eps = 1e-9;
+ private readonly List<OpenClip> _clips;
+
+ private readonly double _barBeats;
+
+ /// <summary>A set of the given clips (at least one), ordered by start then track; the clip
+ /// (activeTrack, activeClip) is active, or the first in time when it is not among them.
+ /// With <paramref name="barBeats"/> &gt; 0 a multi-clip set puts editor beat 0 on the bar
+ /// line at or before the earliest clip, so the editor's grid is the arrangement's; a single
+ /// clip always starts at editor beat 0.</summary>
+ public ClipSet(IEnumerable<OpenClip> clips, int activeTrack, int activeClip, double barBeats = 0)
+ {
+ _barBeats = barBeats;
+ _clips = clips.Select(c => c with { IsReference = false })
+ .GroupBy(c => (c.TrackId, c.ClipIndex)).Select(g => g.First())
+ .OrderBy(c => c.StartBeat).ThenBy(c => c.TrackId).ToList();
+ if (_clips.Count == 0) throw new ArgumentException("A clip set needs at least one clip.", nameof(clips));
+ Active = Math.Max(0, IndexOf(activeTrack, activeClip));
+ Measure();
+ }
+
+ public static ClipSet Single(int trackId, int clipIndex, double startBeat, double lengthBeats)
+ => new(new[] { new OpenClip(trackId, clipIndex, startBeat, lengthBeats) }, trackId, clipIndex);
+
+ public IReadOnlyList<OpenClip> Clips => _clips;
+ public int Count => _clips.Count;
+ public bool IsEmpty => _clips.Count == 0;
+ public bool IsMulti => _clips.Count > 1;
+ /// <summary>Slot of the active clip: it receives new notes and drives header, inspector and envelopes.</summary>
+ public int Active { get; private set; }
+ public OpenClip ActiveClip => _clips[Active];
+
+ /// <summary>Arrangement beat of editor beat 0 (cached: the roll reads it per note per frame).</summary>
+ public double Origin { get; private set; }
+ public double SpanBeats { get; private set; }
+
+ private void Measure()
+ {
+ if (_clips.Count == 0) { Origin = 0; SpanBeats = 0; return; }
+ Origin = _clips.Min(c => c.StartBeat);
+ if (_clips.Count > 1 && _barBeats > 0) Origin = Math.Floor(Origin / _barBeats + 1e-9) * _barBeats;
+ SpanBeats = _clips.Max(c => c.EndBeat) - Origin;
+ }
+
+ public int IndexOf(int trackId, int clipIndex) => _clips.FindIndex(c => c.TrackId == trackId && c.ClipIndex == clipIndex);
+ public bool IsEditable(int slot) => slot >= 0 && slot < _clips.Count && !_clips[slot].IsReference;
+
+ public double EditorStart(int slot) => _clips[slot].StartBeat - Origin;
+ public double EditorEnd(int slot) => _clips[slot].EndBeat - Origin;
+ public double ToEditor(int slot, double localBeat) => localBeat + EditorStart(slot);
+ public double ToLocal(int slot, double editorBeat) => editorBeat - EditorStart(slot);
+
+ /// <summary>Whether editor beat <paramref name="b"/> lies inside the clip (start inclusive, end exclusive).</summary>
+ public bool Contains(int slot, double b) => b >= EditorStart(slot) - Eps && b < EditorEnd(slot) - Eps;
+
+ /// <summary>Makes <paramref name="slot"/> active; a reference clip becomes editable first.
+ /// Returns whether anything changed.</summary>
+ public bool SetActive(int slot)
+ {
+ if (slot < 0 || slot >= _clips.Count) return false;
+ bool changed = slot != Active || _clips[slot].IsReference;
+ if (_clips[slot].IsReference) _clips[slot] = _clips[slot] with { IsReference = false };
+ Active = slot;
+ return changed;
+ }
+
+ /// <summary>Locks or unlocks a clip as read-only reference. Refused for the active clip.</summary>
+ public bool SetReference(int slot, bool on)
+ {
+ if (slot < 0 || slot >= _clips.Count || slot == Active || _clips[slot].IsReference == on) return false;
+ _clips[slot] = _clips[slot] with { IsReference = on };
+ return true;
+ }
+
+ /// <summary>Drops a clip that no longer exists. Returns its old slot (or −1); notes owned by
+ /// later slots must shift down by one. The active clip falls to the next one.</summary>
+ public int Remove(int trackId, int clipIndex)
+ {
+ int slot = IndexOf(trackId, clipIndex);
+ if (slot < 0) return -1;
+ _clips.RemoveAt(slot);
+ Measure();
+ if (_clips.Count == 0) { Active = 0; return slot; }
+ if (Active > slot) Active--;
+ else if (Active == slot) Active = Math.Min(slot, _clips.Count - 1);
+ if (_clips[Active].IsReference) _clips[Active] = _clips[Active] with { IsReference = false };
+ return slot;
+ }
+
+ /// <summary>A clip moved or was trimmed in the arrangement. Slots stay put.</summary>
+ public bool UpdateGeometry(int trackId, int clipIndex, double startBeat, double lengthBeats)
+ {
+ int slot = IndexOf(trackId, clipIndex);
+ if (slot < 0) return false;
+ var c = _clips[slot];
+ if (Math.Abs(c.StartBeat - startBeat) < Eps && Math.Abs(c.LengthBeats - lengthBeats) < Eps) return false;
+ _clips[slot] = c with { StartBeat = startBeat, LengthBeats = lengthBeats };
+ Measure();
+ return true;
+ }
+
+ /// <summary>The editor-beat range a note of <paramref name="slot"/> can start in when moved:
+ /// its own clip joined with every open, editable clip of the same track that touches or
+ /// overlaps it, transitively. A gap, a reference clip or a clip not open is a wall.</summary>
+ public (double Start, double End) Reach(int slot)
+ {
+ double lo = EditorStart(slot), hi = EditorEnd(slot);
+ int track = _clips[slot].TrackId;
+ bool grew = true;
+ while (grew)
+ {
+ grew = false;
+ for (int k = 0; k < _clips.Count; k++)
+ {
+ if (k == slot || _clips[k].TrackId != track || _clips[k].IsReference) continue;
+ double s = EditorStart(k), e = EditorEnd(k);
+ if (s > hi + Eps || e < lo - Eps) continue;
+ if (s < lo - Eps) { lo = s; grew = true; }
+ if (e > hi + Eps) { hi = e; grew = true; }
+ }
+ }
+ return (lo, hi);
+ }
+
+ /// <summary>The clip a note of <paramref name="slot"/> belongs to once its start is at
+ /// <paramref name="editorStart"/>: its own clip while that holds the start; otherwise an open,
+ /// editable clip of the same track holding it — the active clip first, else the one that
+ /// starts later; otherwise unchanged.</summary>
+ public int OwnerAfterMove(int slot, double editorStart)
+ {
+ if (Contains(slot, editorStart)) return slot;
+ int track = _clips[slot].TrackId, best = -1;
+ for (int k = 0; k < _clips.Count; k++)
+ {
+ if (k == slot || _clips[k].TrackId != track || _clips[k].IsReference || !Contains(k, editorStart)) continue;
+ if (k == Active) return k;
+ if (best < 0 || _clips[k].StartBeat > _clips[best].StartBeat) best = k;
+ }
+ return best >= 0 ? best : slot;
+ }
+
+ /// <summary>Where a pasted note goes (specs/029 FR-012): back into the clip it was copied
+ /// from when that clip is open, else into the active clip — at its clip-relative beat
+ /// <paramref name="localStart"/> either way. Returns the slot and the editor-beat start.</summary>
+ public (int Slot, double EditorStart) PasteTarget(int sourceTrack, int sourceClip, double localStart)
+ {
+ int slot = IndexOf(sourceTrack, sourceClip);
+ if (slot < 0 || _clips[slot].IsReference) slot = Active;
+ return (slot, ToEditor(slot, localStart));
+ }
+
+ /// <summary>Each clip's notes in clip-local beats, in list order. Every clip gets an entry.</summary>
+ public List<ClipNotes> Split(IReadOnlyList<NotaNote> notes, IReadOnlyList<int> owners)
+ {
+ var lists = new List<NotaNote>[_clips.Count];
+ for (int k = 0; k < lists.Length; k++) lists[k] = new List<NotaNote>();
+ for (int i = 0; i < notes.Count; i++)
+ {
+ int o = owners[i];
+ if (o < 0 || o >= _clips.Count) continue;
+ var n = notes[i];
+ n.StartBeat = ToLocal(o, n.StartBeat);
+ lists[o].Add(n);
+ }
+ var result = new List<ClipNotes>(_clips.Count);
+ for (int k = 0; k < _clips.Count; k++) result.Add(new ClipNotes(_clips[k].TrackId, _clips[k].ClipIndex, lists[k]));
+ return result;
+ }
+
+ /// <summary>Inverse of <see cref="Split"/>: every clip's notes in editor beats, clip by
+ /// clip, with their owners. Entries for clips not in the set are ignored.</summary>
+ public void Merge(IEnumerable<ClipNotes> perClip, List<NotaNote> notesOut, List<int> ownersOut)
+ {
+ notesOut.Clear();
+ ownersOut.Clear();
+ foreach (var cn in perClip)
+ {
+ int slot = IndexOf(cn.TrackId, cn.ClipIndex);
+ if (slot < 0) continue;
+ foreach (var src in cn.Notes)
+ {
+ var n = src;
+ n.StartBeat = ToEditor(slot, n.StartBeat);
+ notesOut.Add(n);
+ ownersOut.Add(slot);
+ }
+ }
+ }
+}
diff --git a/src/managed/Nota.Application/Editing/NoteOverwrite.cs b/src/managed/Nota.Application/Editing/NoteOverwrite.cs
index ca015b08..0c30d96e 100644
--- a/src/managed/Nota.Application/Editing/NoteOverwrite.cs
+++ b/src/managed/Nota.Application/Editing/NoteOverwrite.cs
@@ -4,7 +4,8 @@
// Piano-roll note edits that must agree everywhere (specs/007-midi-note-editing): the
// "placed notes win" overwrite rule shared by Duplicate and by settling a moved, stretched,
// drawn or pasted selection, plus the keyboard length and velocity steps. Pure and UI-free:
-// the smoke test drives it directly.
+// the smoke test drives it directly. With several clips open in one editor (specs/029) each
+// note has an owner clip, and notes only ever overwrite notes of their own clip.
using System;
using System.Collections.Generic;
@@ -24,15 +25,18 @@ public static class NoteOverwrite
/// its start lies under a same-pitch placed note, cut where the earliest placed note it runs
/// into starts, else kept. Placed notes themselves are always kept. Allocation-free when
/// <paramref name="placed"/> is a list or an array (the piano roll calls it per frame).</summary>
- public static NoteFate Fate(int index, IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed)
+ public static NoteFate Fate(int index, IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed,
+ IReadOnlyList<int>? owners = null)
{
var m = notes[index];
+ int own = owners is null ? 0 : owners[index];
double cut = double.MaxValue;
if (placed is IReadOnlyList<int> list)
{
for (int k = 0; k < list.Count; k++)
{
if (list[k] == index) return new(NoteFateKind.Kept, 0);
+ if (!SameOwner(owners, list[k], own)) continue;
if (Against(m, notes, list[k], ref cut)) return new(NoteFateKind.Removed, 0);
}
}
@@ -41,12 +45,16 @@ public static class NoteOverwrite
foreach (int i in placed)
{
if (i == index) return new(NoteFateKind.Kept, 0);
+ if (!SameOwner(owners, i, own)) continue;
if (Against(m, notes, i, ref cut)) return new(NoteFateKind.Removed, 0);
}
}
return cut < double.MaxValue ? new(NoteFateKind.Cut, cut - m.StartBeat) : new(NoteFateKind.Kept, 0);
}
+ private static bool SameOwner(IReadOnlyList<int>? owners, int i, int own)
+ => owners is null || (i >= 0 && i < owners.Count && owners[i] == own);
+
// True when placed note i removes m; otherwise tightens `cut` if m runs into it.
private static bool Against(in NotaNote m, IReadOnlyList<NotaNote> notes, int i, ref double cut)
{
@@ -61,11 +69,15 @@ public static class NoteOverwrite
/// <summary>Applies the rule: placed notes unchanged, every other note kept, cut or removed
/// (see <see cref="Fate"/>). Survivors keep their order; <paramref name="placedOut"/> gets
- /// the new indices of the placed notes, in the order of <paramref name="placed"/>.</summary>
- public static void Settle(IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed, List<NotaNote> output, List<int> placedOut)
+ /// the new indices of the placed notes, in the order of <paramref name="placed"/>. With
+ /// <paramref name="owners"/>, only notes of the same owner affect each other, and
+ /// <paramref name="ownersOut"/> receives the survivors' owners.</summary>
+ public static void Settle(IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed, List<NotaNote> output, List<int> placedOut,
+ IReadOnlyList<int>? owners = null, List<int>? ownersOut = null)
{
output.Clear();
placedOut.Clear();
+ ownersOut?.Clear();
var isPlaced = new bool[notes.Count];
foreach (int i in placed) if (i >= 0 && i < notes.Count) isPlaced[i] = true;
var newIndex = new int[notes.Count];
@@ -75,12 +87,13 @@ public static class NoteOverwrite
var m = notes[i];
if (!isPlaced[i])
{
- var f = Fate(i, notes, placed);
+ var f = Fate(i, notes, placed, owners);
if (f.Kind == NoteFateKind.Removed) continue;
if (f.Kind == NoteFateKind.Cut) m.LengthBeats = f.CutLength;
}
newIndex[i] = output.Count;
output.Add(m);
+ ownersOut?.Add(owners is null ? 0 : owners[i]);
}
foreach (int i in placed) if (i >= 0 && i < notes.Count) placedOut.Add(newIndex[i]);
}
@@ -89,13 +102,17 @@ public static class NoteOverwrite
/// <paramref name="delta"/> beats, keeping their starts: never below <paramref name="minLen"/>,
/// never past <paramref name="clipLength"/>. Returns whether any note changed.</summary>
public static bool ResizeBy(List<NotaNote> notes, IEnumerable<int> indices, double delta, double minLen, double clipLength)
+ => ResizeBy(notes, indices, delta, minLen, _ => clipLength);
+
+ /// <summary>As above, with each note's own limit — the end of the clip that holds it (specs/029).</summary>
+ public static bool ResizeBy(List<NotaNote> notes, IEnumerable<int> indices, double delta, double minLen, Func<int, double> endOf)
{
bool changed = false;
foreach (int i in indices)
{
if (i < 0 || i >= notes.Count) continue;
var n = notes[i];
- double max = Math.Max(minLen, clipLength - n.StartBeat);
+ double max = Math.Max(minLen, endOf(i) - n.StartBeat);
double len = n.LengthBeats + delta;
// Clamp toward the limits, but never pull a note that is already past one further.
if (delta > 0) len = Math.Min(len, Math.Max(n.LengthBeats, max));
diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.cs
index 53d6f2f6..ce502e17 100644
--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs
+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs
@@ -97,6 +97,7 @@ public static class CommandCatalog
C("roll.octaveDown", "Transpose notes down an octave", "Piano roll", "", "pitch shift"),
C("roll.removeOutOfScale", "Remove out-of-scale notes", "Piano roll", "", "key fix"),
C("roll.fitNotes", "Fit to notes", "Piano roll", Shortcut.Shift('F'), "zoom vertical rows height"),
+ C("roll.editSelected", "Edit selected clips together", "Piano roll", "", "multi clip several open piano roll", view: "Arrangement"),
// ---- Grid (the arrangement or the piano roll — whichever was used last) -----------
C("grid.narrower", "Narrow grid", "Grid", Shortcut.Cmd('1'), "finer smaller snap"),
diff --git a/tests/Nota.SmokeTest/MultiClipTests.cs b/tests/Nota.SmokeTest/MultiClipTests.cs
new file mode 100644
index 00000000..4faf9c2f
--- /dev/null
+++ b/tests/Nota.SmokeTest/MultiClipTests.cs
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Several clips in one Clip editor (specs/029-multi-clip-editing): the ClipSet rules (editor
+// beats, reach and owner of moved notes, split/merge, paste routing), the overwrite rule kept
+// within a clip, and one undo step for an edit spanning clips.
+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --multiclip`.
+
+using Nota.Application;
+using Nota.Application.Editing;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class MultiClipTests
+{
+ private static bool Near(double a, double b) => Math.Abs(a - b) < 1e-9;
+ private static NotaNote N(int pitch, double start, double end, float vel = 0.8f) => new(pitch, start, end - start, vel);
+
+ public static IEnumerable<(bool Ok, string Label)> Run()
+ {
+ foreach (var r in Model()) yield return r;
+ foreach (var r in Overwrite()) yield return r;
+ foreach (var r in Moves()) yield return r;
+ foreach (var r in Paste()) yield return r;
+ foreach (var r in GroupedUndo()) yield return r;
+ }
+
+ // Track 1: A (bars 1–4 = beats 0–16), B (16–32). Track 2: C (8–40).
+ private static ClipSet ABC(int activeTrack = 1, int activeClip = 1) => new(new[]
+ {
+ new OpenClip(1, 1, 16, 16),
+ new OpenClip(2, 0, 8, 32),
+ new OpenClip(1, 0, 0, 16),
+ }, activeTrack, activeClip);
+
+ private static IEnumerable<(bool, string)> Model()
+ {
+ var s = ABC();
+ yield return (s.Clips.Select(c => (c.TrackId, c.ClipIndex)).SequenceEqual(new[] { (1, 0), (2, 0), (1, 1) }),
+ "multiclip: clips are ordered by start, then track");
+ yield return (Near(s.Origin, 0) && Near(s.SpanBeats, 40) && s.IsMulti, "multiclip: origin is the earliest start, span reaches the latest end");
+ yield return (s.ActiveClip is { TrackId: 1, ClipIndex: 1 }, "multiclip: the requested clip is active");
+ yield return (Near(s.ToEditor(2, 3), 19) && Near(s.ToLocal(2, 19), 3), "multiclip: editor and clip-local beats convert both ways");
+
+ var bars = new ClipSet(new[] { new OpenClip(1, 0, 6, 4), new OpenClip(1, 1, 10, 4) }, 1, 0, barBeats: 4);
+ yield return (Near(bars.Origin, 4) && Near(bars.SpanBeats, 10) && Near(bars.EditorStart(0), 2),
+ "multiclip: with several clips editor beat 0 sits on the bar line before the first");
+
+ var one = ClipSet.Single(4, 2, 24, 8);
+ yield return (Near(one.Origin, 24) && Near(one.ToEditor(0, 5), 5) && !one.IsMulti,
+ "multiclip: a one-clip set's editor beats are its clip-local beats");
+
+ var notes = new List<NotaNote> { N(60, 1, 2), N(64, 9, 10), N(62, 17, 18), N(60, 3, 4) };
+ var owners = new List<int> { 0, 1, 2, 0 };
+ var split = s.Split(notes, owners);
+ yield return (split.Count == 3 && split[0].Notes.Count == 2 && split[1].Notes.Count == 1 && Near(split[1].Notes[0].StartBeat, 1)
+ && Near(split[2].Notes[0].StartBeat, 1), "multiclip: Split gives each clip its notes in clip-local beats");
+ var back = new List<NotaNote>(); var backOwners = new List<int>();
+ s.Merge(split, back, backOwners);
+ bool round = back.Count == notes.Count;
+ for (int k = 0; round && k < notes.Count; k++)
+ {
+ int j = back.FindIndex(n => n.Pitch == notes[k].Pitch && Near(n.StartBeat, notes[k].StartBeat));
+ round = j >= 0 && backOwners[j] == owners[k];
+ }
+ yield return (round, "multiclip: Merge undoes Split (every note and owner)");
+
+ yield return (!s.SetReference(s.Active, true), "multiclip: the active clip cannot be a reference");
+ yield return (s.SetReference(1, true) && !s.IsEditable(1), "multiclip: another clip can be locked as reference");
+ yield return (s.SetActive(1) && s.IsEditable(1) && s.Active == 1, "multiclip: making a reference clip active unlocks it");
+
+ var r = ABC(1, 0); // A active (slot 0)
+ int removed = r.Remove(1, 0);
+ yield return (removed == 0 && r.Count == 2 && r.ActiveClip is { TrackId: 2, ClipIndex: 0 } && Near(r.Origin, 8),
+ "multiclip: removing the active clip passes active to the next clip and re-measures");
+ yield return (r.UpdateGeometry(1, 1, 20, 16) && Near(r.SpanBeats, 32) && r.Clips[1].StartBeat == 20,
+ "multiclip: a moved clip keeps its slot and the span follows");
+ }
+
+ private static IEnumerable<(bool, string)> Overwrite()
+ {
+ // Two C4s overlapping: note 1 placed over note 0.
+ var notes = new[] { N(60, 0, 2), N(60, 1, 2) };
+ var outN = new List<NotaNote>(); var outP = new List<int>(); var outO = new List<int>();
+ NoteOverwrite.Settle(notes, new[] { 1 }, outN, outP, new[] { 0, 1 }, outO);
+ yield return (outN.Count == 2 && Near(outN[0].LengthBeats, 2) && outO.SequenceEqual(new[] { 0, 1 }),
+ "multiclip: a placed note never cuts a note of another clip");
+ NoteOverwrite.Settle(notes, new[] { 1 }, outN, outP, new[] { 3, 3 }, outO);
+ yield return (outN.Count == 2 && Near(outN[0].LengthBeats, 1) && outO.SequenceEqual(new[] { 3, 3 }),
+ "multiclip: within one clip the spec 007 rule still cuts");
+ var plain = new List<NotaNote>(); var plainP = new List<int>();
+ NoteOverwrite.Settle(notes, new[] { 1 }, plain, plainP);
+ yield return (plain.Count == outN.Count && Near(plain[0].LengthBeats, outN[0].LengthBeats),
+ "multiclip: without owners Settle is unchanged");
+ yield return (NoteOverwrite.Fate(0, notes, new[] { 1 }, new[] { 0, 1 }).Kind == NoteFateKind.Kept
+ && NoteOverwrite.Fate(0, notes, new[] { 1 }).Kind == NoteFateKind.Cut,
+ "multiclip: the overwrite mark agrees with Settle");
+ }
+
+ private static IEnumerable<(bool, string)> Moves()
+ {
+ var s = ABC(); // slots: 0 = A (1/0, 0–16), 1 = C (2/0, 8–40), 2 = B (1/1, 16–32)
+ var (lo, hi) = s.Reach(0);
+ yield return (Near(lo, 0) && Near(hi, 32), "multiclip: a note of A can reach B across the seam");
+ yield return (s.OwnerAfterMove(0, 17) == 2, "multiclip: a note moved to start in B belongs to B");
+ yield return (s.OwnerAfterMove(0, 15) == 0, "multiclip: a note still starting in A stays in A");
+ yield return (s.OwnerAfterMove(0, 30) == 2 && s.OwnerAfterMove(2, 9) == 0,
+ "multiclip: notes never move to another track's clip");
+
+ var gap = new ClipSet(new[] { new OpenClip(1, 0, 0, 16), new OpenClip(1, 1, 20, 16) }, 1, 0);
+ var g = gap.Reach(0);
+ yield return (Near(g.Start, 0) && Near(g.End, 16), "multiclip: a gap between clips is a wall");
+
+ var locked = ABC(1, 0); // A active, so B can be locked
+ bool lockedB = locked.SetReference(2, true);
+ var l = locked.Reach(0);
+ yield return (lockedB && Near(l.End, 16) && locked.OwnerAfterMove(0, 17) == 0, "multiclip: a reference clip is a wall");
+
+ // Overlapping clips of one track: X (0–16), Y (8–24), Z (12–28); Y active.
+ var ov = new ClipSet(new[] { new OpenClip(1, 0, 0, 16), new OpenClip(1, 1, 8, 16), new OpenClip(1, 2, 12, 16) }, 1, 1);
+ yield return (ov.OwnerAfterMove(0, 13) == 0, "multiclip: overlap — a note stays in its clip while it holds the start");
+ yield return (ov.OwnerAfterMove(2, 9) == 1, "multiclip: overlap — otherwise the active clip takes it");
+ var ov2 = new ClipSet(ov.Clips, 1, 0); // X active
+ yield return (ov2.OwnerAfterMove(0, 20) == 2, "multiclip: overlap — otherwise the later-starting clip");
+ }
+
+ private static IEnumerable<(bool, string)> Paste()
+ {
+ var s = ABC(); // B (slot 2) active
+ var (slot, at) = s.PasteTarget(1, 0, 3);
+ yield return (slot == 0 && Near(at, 3), "multiclip: copies from an open clip paste back into it");
+ (slot, at) = s.PasteTarget(9, 9, 3);
+ yield return (slot == 2 && Near(at, 19), "multiclip: copies from a clip not open paste into the active clip");
+ s.SetReference(0, true);
+ (slot, _) = s.PasteTarget(1, 0, 3);
+ yield return (slot == 2, "multiclip: copies never paste into a reference clip");
+ }
+
+ // FR-011's basis: the host commits each clip inside one undo group.
+ private static IEnumerable<(bool, string)> GroupedUndo()
+ {
+ using var e = new NotaEngine();
+ int t1 = e.AddInstrumentTrack();
+ int t2 = e.AddInstrumentTrack();
+ int a = e.AddMidiClip(t1, 0.0, 4.0);
+ int b = e.AddMidiClip(t2, 4.0, 4.0);
+ e.SetClipNotes(t1, a, new[] { N(60, 0, 1) });
+ e.SetClipNotes(t2, b, new[] { N(48, 0, 1) });
+ e.BeginUndoGroup();
+ try
+ {
+ e.SetClipNotes(t1, a, new[] { N(61, 0, 1) });
+ e.SetClipNotes(t2, b, new[] { N(49, 0, 1) });
+ }
+ finally { e.EndUndoGroup(); }
+ bool edited = e.GetClipNotes(t1, a)[0].Pitch == 61 && e.GetClipNotes(t2, b)[0].Pitch == 49;
+ e.Undo();
+ var na = e.GetClipNotes(t1, a); var nb = e.GetClipNotes(t2, b);
+ yield return (edited && na.Length == 1 && na[0].Pitch == 60 && nb.Length == 1 && nb[0].Pitch == 48,
+ "multiclip: one undo restores every clip of a grouped edit");
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 7c319215..657ea72c 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -288,6 +288,14 @@ if (args.Length >= 1 && args[0] == "--notes")
Console.WriteLine(failures == 0 ? "NOTES PASSED" : $"NOTES FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Several clips in one Clip editor alone: `--multiclip`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--multiclip")
+{
+ Console.WriteLine("-- multi-clip editing --");
+ foreach (var (ok, label) in MultiClipTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "MULTICLIP PASSED" : $"MULTICLIP FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Default project template alone: `--template`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--template")
{
@@ -14938,6 +14946,9 @@ foreach (var (ok, label) in SnapGridTests.Run()) Check(ok, label);
Console.WriteLine("-- note editing --");
foreach (var (ok, label) in NoteEditingTests.Run()) Check(ok, label);
+Console.WriteLine("-- multi-clip editing --");
+foreach (var (ok, label) in MultiClipTests.Run()) Check(ok, label);
+
Console.WriteLine("-- default project template --");
foreach (var (ok, label) in ProjectTemplateTests.Run()) Check(ok, label);