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.

(fix) Copy and cut a time range; ⌘V pastes onto the track clicked last (#282)

Egor Khindikaynen974407a9919e
diff --git a/.specify/bugs/arrangement-range-clipboard/assessment.md b/.specify/bugs/arrangement-range-clipboard/assessment.md
new file mode 100644
index 00000000..56bca11a
--- /dev/null
+++ b/.specify/bugs/arrangement-range-clipboard/assessment.md
@@ -0,0 +1,158 @@
+# Bug Assessment: Arrangement clipboard ignores time ranges and the target track
+
+- **Slug**: arrangement-range-clipboard
+- **Created**: 2026-10-22
+- **Source**: pasted text (issue, reported in Russian)
+- **Verdict**: valid
+- **Severity**: medium
+
+## Report (verbatim or summarized)
+
+> When I Shift-select part of a track in the arrangement, I want to be able to copy, duplicate
+> or cut it. Cmd+Shift+V works as "paste bounced", but plain copy doesn't work.
+> Also: there's no way to copy a clip from one track to another except by dragging. E.g. I copy
+> a clip on one track with Cmd+C, put the cursor on another track, press Cmd+V — the copy
+> lands on the source track.
+
+Two problems:
+
+1. **Time range → clipboard.** A Shift+drag time-range selection has no Copy (⌘C) or Cut (⌘X).
+ ⌘D (duplicate range) and Delete already work on the range; ⌘⇧V (Paste bounced audio) works
+ because it remembers the range separately (`BounceSource`).
+2. **Keyboard paste ignores the target track.** ⌘V always pastes onto the tracks the clips
+ were copied from, wherever the user last clicked.
+
+## Symptom
+
+1. With a time range selected, ⌘C / ⌘X / Edit ▸ Copy / Cut do nothing (no status message, the
+ clipboard is unchanged). Expected: the covered slice of every selected track goes to the
+ clipboard, sliced at the range edges; Cut also removes it.
+2. ⌘C on a clip on track A, click empty space on track B (moves the playhead), ⌘V: the copy
+ lands on track A at the playhead. Expected: it lands on track B. The right-click lane menu's
+ **Paste** already does this; only the keyboard and Edit-menu paste don't.
+
+## Reproduction
+
+Range copy:
+1. Shift+drag over part of a clip on one track to make a time range.
+2. Press ⌘C. Then click elsewhere and press ⌘V.
+3. Nothing is pasted (or the clip copied earlier is pasted instead). ⌘X likewise does nothing.
+
+Cross-track paste:
+1. Click a clip on track A, press ⌘C.
+2. Click empty lane space on track B at some beat (the playhead moves there).
+3. Press ⌘V. The copy appears on track A at the playhead, not on track B.
+
+## Suspected Code Paths
+
+- `src/managed/Nota.App/MainWindow.Input.cs:272-287` — the ⌘C/X/V handler. Outside automation
+ mode it only calls `Timeline.CopySelectedClip` / `CutSelectedClip` / `PasteClipboard`; there
+ is no time-range branch. (⌘D at `MainWindow.Menu.cs:106` and Delete at `MainWindow.Input.cs:299`
+ do check `DuplicateTimeSelection` / `DeleteTimeSelection` first.)
+- `src/managed/Nota.App/MainWindow.Menu.cs:151-174` — `OnMenuCopy` / `OnMenuCut` /
+ `OnMenuPaste` (Edit menu): same gap.
+- `src/managed/Nota.App/ArrangementView.cs:1593-1601` — `SetTimeSelection` clears the clip
+ selection (the two are mutually exclusive), so `SelectionBlock()` is empty and
+ `CopySelectedClip` / `CutSelectedClip` return false: the keystroke is silently dropped.
+- `src/managed/Nota.App/ArrangementView.cs:1290-1299` — `PasteClipboard()` (keyboard path)
+ calls `_engine.PasteClipBlock(playhead, -1)`; `-1` = "paste onto the source tracks". Its doc
+ comment states this as the intent. `PasteClipboardAt(trackId, beat)` (used by the lane menu)
+ already remaps onto a destination track.
+- `src/managed/Nota.App/ArrangementView.cs:1608-1611` + `ArrangementView.LaneControl.cs:587` —
+ `FocusTrackId`: the track the user last clicked (clip, header or empty lane space). Paste
+ bounced (`MainWindow.PasteBounced.cs:38`) already targets it; plain paste doesn't.
+- `src/native/nota.engine/src/engine/Engine_Tracks.cpp:2740` (`copyClipBlock`), `:2749`
+ (`cutClipBlock`), `:1773` (`duplicateRange`) — the engine has a block clipboard of whole
+ clips, and range slicing (`midiSlice` / `audioSlice`) used by `duplicateRange`, but no
+ operation that captures a *range* into the block clipboard.
+
+## Root Cause Hypothesis
+
+Not a regression; the feature was never built. The time-range selection (Phase 2) received
+Delete, Duplicate, Split, Consolidate, Duplicate Time, Insert Silence and Paste Bounced, but
+not Copy/Cut. The keyboard paste was designed to restore clips onto their source tracks at
+the playhead, so the lane menu's track-aware paste never reached ⌘V. Confidence: high. Both
+problems follow directly from the code above.
+
+## Proposed Remediation
+
+**Preferred**:
+
+*Engine (C++ + C ABI).* Add `Engine::copyRange(trackIds, start, end)` and
+`Engine::cutRange(...)`. `copyRange` builds `BlockClip`s from `midiSlice` / `audioSlice` of
+every clip that overlaps `[start,end)` on each listed track. Each `relStart` is measured from
+`start`, not from the first clip, so leading space in the range is kept. Each slice's
+clip-relative automation goes in the same way `captureBlock` does it. It then sets
+`clipboardBlock_` and `clipboardBlockLen_ = end - start`. `cutRange` = `copyRange` +
+`deleteClipsInRange` (plus the range's automation) as one undo step. Expose
+`nota_clips_range_copy` / `nota_clips_range_cut` and wrap them in `IAudioEngine` /
+`NotaEngine.Tracks.cs`.
+
+*App.*
+- `ArrangementView`: add `CopyTimeSelection()` / `CutTimeSelection()` (use
+ `TimeSelectionTrackIds()`, call `ClipTransfer.TookFromArrangement()`, and on cut refresh and
+ clear the range).
+- Put them ahead of the clip path in `MainWindow.Input.cs` (⌘C/⌘X) and in `OnMenuCopy` /
+ `OnMenuCut`, mirroring how ⌘D and Delete already put the range first.
+- Add Copy / Cut entries for the range to the lane context menu's `inRange` block
+ (`ArrangementView.LaneControl.cs:1121`) and to the clip menu when right-clicking inside the
+ range.
+- Keyboard paste: `PasteClipboard()` uses `FocusTrackId` when it refers to a live track
+ (`PasteClipBlock(playhead, FocusTrackId)`), falling back to `-1`. Because copying a clip
+ also sets `FocusTrackId` to its track, "copy → ⌘V" without clicking elsewhere still pastes
+ onto the source track. A multi-track block remaps by the top-track delta, the same as the
+ lane menu today. Do the same for `PasteSessionSlot(…, -1)` so a slot copied in the Session
+ view also lands on the focused track.
+
+**Alternatives**:
+- *Managed only:* `SplitClipsInRange` first, then select the covered clips and `CopyClipBlock`.
+ No engine change, but **Copy then modifies the project** (it splits clips and adds an undo
+ step), and the block length/offset is measured from the first clip, not the range start.
+ Rejected.
+- *Paste onto the selected track (`SelectedTrackId`) instead of `FocusTrackId`.* A click on
+ empty lane space clears the selection, so the user's "put the cursor on another track"
+ gesture would be lost. `FocusTrackId` exists for exactly this and is already used by Paste
+ bounced.
+
+**Files likely to change**:
+- `src/native/nota.engine/src/engine/Engine.h`, `Engine_Tracks.cpp`
+- `src/native/nota.engine/include/nota/nota_engine.h`, `src/abi/nota_engine_track.cpp`
+- `src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs`, `NotaEngine.Tracks.cs`
+- `src/managed/Nota.Application/Engine/IAudioEngine.cs` (+ any test fakes implementing it)
+- `src/managed/Nota.App/ArrangementView.cs`, `ArrangementView.LaneControl.cs`
+- `src/managed/Nota.App/MainWindow.Input.cs`, `MainWindow.Menu.cs`
+- Shortcuts pane (`nota-shortcuts`), `CHANGELOG.md`, `FEATURES.md`, docs (`nota-docs`)
+- `tests/Nota.SmokeTest/…` (new checks)
+
+**Tests to add or update** (smoke test, engine level + the `ArrangementView` methods):
+- Range copy of part of a MIDI clip → paste elsewhere: notes match the slice and start at the
+ same offset from the range start; the source is unchanged; undo count unchanged by the copy.
+- Range copy of part of an audio clip → pasted clip has the sliced source offset/length.
+- Range cut: covered content removed and on the clipboard, in one undo step; undo restores it.
+- Multi-track range copy → paste with destination = second track: block shifts down by one;
+ type-mismatched rows are skipped.
+- Keyboard paste after focusing another track (`FocusTrackId` = B) lands on B; with focus
+ still on the source it lands on the source (no behaviour change for the common case).
+
+## Risks & Considerations
+
+- **Behaviour change for ⌘V.** Users who copy, click on another track's empty space just to
+ move the playhead, and expect a same-track paste will now get the cross-track paste. This
+ matches the issue and other DAWs (Ableton pastes onto the selected track), but needs a
+ CHANGELOG "Changed" entry.
+- **Range paste and overlap.** `placeBlock` avoids overlap by shifting the whole block right.
+ For a range paste, overwriting the target span (as `duplicateRange` does) may match user
+ expectations better; decide in the fix (`placeBlock(..., overwrite)` already exists).
+- **Automation.** Whether a range copy carries track automation for the span should match
+ `duplicateRange` / Duplicate Time. Device/plugin automation is dropped on cross-track
+ remaps, as today.
+- Warped audio slices need `configureClipWarp` on paste. `placeBlock` already does this.
+- Paste bounced (⌘⇧V) keeps working: it reads `BounceSource`, not the block clipboard.
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: should a pasted range overwrite what it lands on (like ⌘D on a range)
+ or shift right to avoid overlap (like clip paste)? Recommendation: overwrite, for parity
+ with ⌘D.]
+- [NEEDS CLARIFICATION: is "duplicate" in the report already covered by ⌘D on a range (it
+ works today), or is something else expected?]
diff --git a/.specify/bugs/arrangement-range-clipboard/fix.md b/.specify/bugs/arrangement-range-clipboard/fix.md
new file mode 100644
index 00000000..273f9a06
--- /dev/null
+++ b/.specify/bugs/arrangement-range-clipboard/fix.md
@@ -0,0 +1,49 @@
+# Bug Fix: Arrangement clipboard ignores time ranges and the target track
+
+- **Slug**: arrangement-range-clipboard
+- **Fixed**: 2026-10-22
+- **Assessment**: ./assessment.md
+- **Issue**: nota-daw/nota#281
+- **Status**: applied
+
+## Summary
+
+The engine can now copy a time range into the block clipboard. `copyRange` slices every
+covered clip at the range edges with `midiSlice` / `audioSlice`, positions each slice from
+the range start and carries its automation. `cutRange` adds the range delete in one undo
+step. A range block pastes in overwrite mode, like ⌘D on a range. A cross-track paste anchors
+on the range's top row, even when that row has no clips. In the app, ⌘C / ⌘X and Edit ▸ Copy
+/ Cut act on a time range first. The range's right-click menus have Copy / Cut / Duplicate.
+⌘V pastes at the playhead onto `FocusTrackId`, the track clicked last. A clip or range copy
+moves that focus to the block's top track, so copy → ⌘V still lands on the source.
+
+Open questions from the assessment, resolved with the recommended defaults:
+- A pasted range overwrites what it lands on, matching ⌘D on a range.
+- Duplicate was already available through ⌘D on a range. The range menus now list it too.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/native/nota.engine/src/engine/Engine.h` | modified | `copyRange` / `cutRange`, `clipboardBlockOverwrite_`, `clipboardBlockAnchor_`, `remapBlock(…, anchorTrackId)` |
+| `src/native/nota.engine/src/engine/Engine_Tracks.cpp` | modified | range copy/cut; paste uses overwrite + anchor for range blocks; clip copy resets both |
+| `src/native/nota.engine/src/engine/Engine_Session.cpp` | modified | block → session paste honours the anchor |
+| `src/native/nota.engine/include/nota/nota_engine.h`, `src/abi/nota_engine_track.cpp` | modified | `nota_clips_copy_range` / `nota_clips_cut_range` |
+| `src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs`, `NotaEngine.Tracks.cs`, `src/managed/Nota.Application/Engine/IAudioEngine.cs` | modified | `CopyRange` / `CutRange` |
+| `src/managed/Nota.App/ArrangementView.cs` | modified | `CopyTimeSelection` / `CutTimeSelection`; `PasteClipboard` targets `FocusTrackId`; copy/cut focus the block's top track |
+| `src/managed/Nota.App/ArrangementView.LaneControl.cs` | modified | lane + clip menus: Copy / Cut / Duplicate act on the range when right-clicked inside it |
+| `src/managed/Nota.App/MainWindow.Input.cs`, `MainWindow.Menu.cs` | modified | ⌘C / ⌘X and Edit menu: range first |
+| `src/managed/Nota.App/PreferencesWindow.cs` | modified | Shortcuts row for ⌘C ⌘X ⌘V |
+| `tests/Nota.SmokeTest/RangeClipboardTests.cs`, `Program.cs` | added test | 21 checks; full run + `--range-clipboard` |
+| `CHANGELOG.md`, `FEATURES.md` | modified | [Unreleased] → Fixed; Arrangement View entry |
+
+## Verification
+
+- `--range-clipboard` smoke: 21/21 pass. Covered: MIDI and audio slices, the leading gap,
+ overwrite on paste, the clip-block paste still shifting, cut + undo, the empty-top-row
+ anchor and an empty range.
+- Headless harness (`/tmp/rangeharness`): the real MainWindow driven with Meta+C/X/V key
+ presses. Checked: a clip pastes onto the focused track B; copy → ⌘V with no click pastes
+ on the source; range ⌘C leaves the project unchanged and ⌘V puts the slice on B; range ⌘X
+ cuts.
+- `scripts/build.sh`: see the test record.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00bd0eb6..2ea0273a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -141,6 +141,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
- **⌘1–⌘5 change a grid you can see** (nota-daw/nota#114): after a click in the audio clip
editor while its view follows no grid (ADSR, or an unwarped clip), the grid shortcuts act
on the arrangement instead of silently changing the clip editor's.
+- **Copy, cut and paste a time range; paste onto another track** (nota-daw/nota#281): with
+ a time range selected (⇧-drag), ⌘C / ⌘X copy or cut the covered part of every selected
+ track, cut at the range edges, and the range's right-click menu has **Copy**, **Cut** and
+ **Duplicate**. A pasted range keeps its distance from the range start and replaces what it
+ lands on. ⌘V now pastes onto the track you clicked last, so copy a clip, click another
+ track and ⌘V to put the copy there. Without that click it lands on its own track, as before.
- **Context menus are never cut off at the sides**: a menu whose longest item had no shortcut
(the track menu of a live-frozen track, with *Flatten (remove source)*) could open a little
too narrow, clipping every row on both sides. Every menu and submenu now opens at its full
diff --git a/FEATURES.md b/FEATURES.md
index 1cd17811..cc46960d 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -111,6 +111,9 @@ track count and closes with Escape.
recording into the arrangement (audio and MIDI); split at the cursor or across a
selection (Cmd/Ctrl+E cuts every track in the selection); clip scrubbing on the ruler.
⌘A selects every clip; moving several selected clips is one undo step.
+ A selected time range (⇧-drag) copies, cuts, duplicates and deletes with ⌘C / ⌘X / ⌘D /
+ Delete — just the covered part of each track, cut at the range edges; ⌘V pastes clips or a
+ range at the playhead onto the track clicked last (a range replaces what it lands on).
**Duplicate time** (⌘⇧D) copies a selected time range right after itself and **Insert
silence** (⌘⇧I) opens a gap of its length, across the whole song — clips and automation
after it move right, clips crossing it are cut (Edit menu and the range's right-click menu).
diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.cs
index e33d3f8a..bf3e349f 100644
--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs
+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs
@@ -1098,8 +1098,9 @@ public sealed partial class ArrangementView
}
// Right-click on empty lane space: paste the clipboard clip (or the bounced range) here,
- // insert a MIDI clip on an instrument track, and consolidate the time selection when the
- // click lands inside it. Always opens, so the menu never silently fails to appear.
+ // insert a MIDI clip on an instrument track, and — when the click lands inside the time
+ // selection — copy / cut / duplicate / consolidate it. Always opens, so the menu never
+ // silently fails to appear.
private void ShowLaneMenu(Point pos, double beat)
{
int ti = _o.RowAtY(pos.Y);
@@ -1109,10 +1110,14 @@ public sealed partial class ArrangementView
bool inRange = _o.TimeSelectionCovers(trackId, beat);
double at = _o.Snap(beat);
var flyout = new MenuFlyout();
- var paste = new MenuItem { Header = "Paste", IsEnabled = _o.HasClipClipboard, Icon = MenuKit.Icon(GlyphKind.Paste), InputGesture = MenuKit.PasteKey };
- paste.Click += (_, _) => _o.PasteClipboardAt(trackId, at);
- flyout.Items.Add(paste);
- if (PasteBouncedItem(trackId, at) is { } bounced) flyout.Items.Add(bounced);
+ var clipboard = MenuKit.ClipboardGroup(
+ inRange ? () => _o.CopyTimeSelection() : null,
+ inRange ? () => _o.CutTimeSelection() : null,
+ () => _o.PasteClipboardAt(trackId, at),
+ inRange ? () => _o.DuplicateTimeSelection() : null,
+ _o.HasClipClipboard).ToList();
+ if (PasteBouncedItem(trackId, at) is { } bounced) clipboard.Insert(inRange ? 3 : 1, bounced); // right after Paste
+ foreach (var mi in clipboard) flyout.Items.Add(mi);
if (track.IsInstrument)
{
var insert = new MenuItem { Header = "Insert MIDI clip", Icon = MenuKit.Icon(GlyphKind.Plus) };
@@ -1231,11 +1236,12 @@ public sealed partial class ArrangementView
session.Add(toScene);
}
+ // Inside the time selection, Copy / Cut / Duplicate act on the range (like ⌘C / ⌘X / ⌘D).
var clipboard = MenuKit.ClipboardGroup(
- () => { EnsureSelected(); _o.CopySelectedClip(); },
- () => { EnsureSelected(); _o.CutSelectedClip(); },
+ inRange ? () => _o.CopyTimeSelection() : () => { EnsureSelected(); _o.CopySelectedClip(); },
+ inRange ? () => _o.CutTimeSelection() : () => { EnsureSelected(); _o.CutSelectedClip(); },
() => _o.PasteClipboardAt(trackId, at),
- () => { EnsureSelected(); _o.DuplicateSelectedClip(); },
+ inRange ? () => _o.DuplicateTimeSelection() : () => { EnsureSelected(); _o.DuplicateSelectedClip(); },
_o.HasClipClipboard).Cast<Control>().ToList();
if (PasteBouncedItem(trackId, at) is { } bounced) clipboard.Insert(3, bounced);
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index 6044b2a6..12d27f62 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -1252,6 +1252,7 @@ public sealed partial class ArrangementView : UserControl
var sel = SelectionBlock();
if (sel.Length == 0 || !_engine.CopyClipBlock(sel)) return false;
ClipTransfer.TookFromArrangement();
+ FocusTopTrackOf(sel);
return true;
}
@@ -1263,6 +1264,7 @@ public sealed partial class ArrangementView : UserControl
var sel = SelectionBlock();
if (sel.Length == 0 || !_engine.CutClipBlock(sel)) return false;
ClipTransfer.TookFromArrangement();
+ FocusTopTrackOf(sel);
Select(-1, -1);
Refresh();
return true;
@@ -1281,19 +1283,42 @@ public sealed partial class ArrangementView : UserControl
return true;
}
- /// <summary>Keyboard paste: the block lands on its source tracks at the playhead (a slot
- /// copied in the Session view: on its own track).</summary>
+ /// <summary>Keyboard paste at the playhead, onto the track the user last clicked
+ /// (<see cref="FocusTrackId"/>) — a multi-track block shifts so its top track lands there.
+ /// With no focused clip track the block lands on its source tracks (a slot copied in the
+ /// Session view: on its own track).</summary>
public bool PasteClipboard()
{
if (_engine is null) return false;
- if (ClipTransfer.FromSession) return PasteSessionSlot(Math.Max(0.0, _playheadBeats), -1);
+ double at = Math.Max(0.0, _playheadBeats);
+ int dest = PasteTargetTrackId();
+ if (ClipTransfer.FromSession) return PasteSessionSlot(at, dest);
if (_engine.ClipboardBlockCount() == 0) return false;
- if (_engine.PasteClipBlock(Math.Max(0.0, _playheadBeats), -1) <= 0) return false;
+ if (_engine.PasteClipBlock(at, dest) <= 0)
+ {
+ if (dest <= 0) return false;
+ StatusMessage?.Invoke("Paste a MIDI clip onto a MIDI track, audio onto audio.");
+ return true;
+ }
Refresh();
ReselectPlaced();
return true;
}
+ // After a copy/cut the keyboard paste targets the block's own top track until the user
+ // clicks another one (a marquee selection doesn't move the focus by itself).
+ private void FocusTopTrackOf((int trackId, int clipIndex)[] sel)
+ {
+ int top = -1, topRow = int.MaxValue;
+ foreach (var (track, _) in sel)
+ if (RowOfTrack(track) is var r and >= 0 && r < topRow) { topRow = r; top = track; }
+ if (top > 0) FocusTrackId = top;
+ }
+
+ // The keyboard paste's target: the focused track when it can hold clips, else -1 (source tracks).
+ private int PasteTargetTrackId()
+ => _tracks.Find(t => t.Id == FocusTrackId) is { IsReturn: false, IsGroup: false } ? FocusTrackId : -1;
+
// The session clipboard's slot onto the timeline (destTrackId -1 = its own track); a cut
// slot moves, emptying its slot in the same undo step.
private bool PasteSessionSlot(double atBeat, int destTrackId)
@@ -1711,6 +1736,33 @@ public sealed partial class ArrangementView : UserControl
return true;
}
+ /// <summary>⌘C over a time selection: the covered slice of every selected track goes to the
+ /// block clipboard (cut at the range edges, nothing in the project changes). The range's top
+ /// track becomes the paste target, so ⌘V without clicking elsewhere pastes it back there.
+ /// False when there's no range or it covers no clip.</summary>
+ public bool CopyTimeSelection()
+ {
+ if (_engine is null || !HasTimeSelection) return false;
+ var ids = TimeSelectionTrackIds();
+ if (ids.Length == 0 || !_engine.CopyRange(ids, _timeSelStart, _timeSelEnd)) return false;
+ ClipTransfer.TookFromArrangement();
+ FocusTrackId = ids[0];
+ return true;
+ }
+
+ /// <summary>⌘X over a time selection: <see cref="CopyTimeSelection"/>, then the slice is
+ /// removed (one undo step). The range stays selected. False when nothing was cut.</summary>
+ public bool CutTimeSelection()
+ {
+ if (_engine is null || !HasTimeSelection) return false;
+ var ids = TimeSelectionTrackIds();
+ if (ids.Length == 0 || !_engine.CutRange(ids, _timeSelStart, _timeSelEnd)) return false;
+ ClipTransfer.TookFromArrangement();
+ FocusTrackId = ids[0];
+ Refresh();
+ return true;
+ }
+
/// <summary>Duplicate the time selection right after its end and move the selection onto
/// the copy, so repeated presses chain (req 4.1-range).</summary>
public bool DuplicateTimeSelection()
diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.cs
index 8f7637da..17a28cbe 100644
--- a/src/managed/Nota.App/MainWindow.Input.cs
+++ b/src/managed/Nota.App/MainWindow.Input.cs
@@ -281,6 +281,10 @@ public partial class MainWindow
if (e.Key == Key.X && Timeline.CutAutoSelection()) { _vm.StatusText = "Cut automation"; e.Handled = true; return; }
if (e.Key == Key.V && Timeline.PasteAuto()) { _vm.StatusText = "Pasted automation"; e.Handled = true; return; }
}
+ // A time range (Shift+drag) copies / cuts the covered slice; it and a clip selection
+ // are exclusive, so these return false whenever clips are selected instead.
+ if (e.Key == Key.C && Timeline.CopyTimeSelection()) { _vm.StatusText = "Copied range"; e.Handled = true; return; }
+ if (e.Key == Key.X && Timeline.CutTimeSelection()) { _session?.Refresh(); _vm.StatusText = "Cut range"; e.Handled = true; return; }
if (e.Key == Key.C && Timeline.CopySelectedClip()) { _vm.StatusText = "Copied clip(s)"; e.Handled = true; return; }
if (e.Key == Key.X && Timeline.CutSelectedClip()) { _session?.Refresh(); _vm.StatusText = "Cut clip(s)"; e.Handled = true; return; }
if (e.Key == Key.V && Timeline.PasteClipboard()) { _session?.Refresh(); _vm.StatusText = "Pasted clip(s)"; e.Handled = true; return; }
diff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.cs
index 42b84c25..230497b5 100644
--- a/src/managed/Nota.App/MainWindow.Menu.cs
+++ b/src/managed/Nota.App/MainWindow.Menu.cs
@@ -154,6 +154,7 @@ public partial class MainWindow
if (SessionFocused && _session!.CopySelection()) return;
if (_trackHeadersFocused && Timeline.CopySelectedTracks()) { _vm.StatusText = "Copied track(s)"; return; }
if (ActiveRoll() is { } roll && roll.CopySelection()) { _vm.StatusText = "Copied notes"; return; }
+ if (Timeline.CopyTimeSelection()) { _vm.StatusText = "Copied range"; return; }
if (Timeline.CopySelectedClip()) _vm.StatusText = "Copied clip";
}
private void OnMenuCut(object? sender, EventArgs e)
@@ -162,6 +163,7 @@ public partial class MainWindow
if (SessionFocused && _session!.CutSelection()) return;
if (_trackHeadersFocused && Timeline.CutSelectedTracks()) { _vm.StatusText = "Cut track(s)"; return; }
if (ActiveRoll() is { } roll && roll.CutSelection()) { _vm.StatusText = "Cut notes"; return; }
+ if (Timeline.CutTimeSelection()) { _session?.Refresh(); _vm.StatusText = "Cut range"; return; }
if (Timeline.CutSelectedClip()) { _session?.Refresh(); _vm.StatusText = "Cut clip"; }
}
private void OnMenuPaste(object? sender, EventArgs e)
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index b5f1f7be..0342540c 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -1166,7 +1166,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("Tab", "Cycle Devices / Pattern / Clip in the detail panel"),
("Esc", "Cancel the current gesture / clear the selection · close the patch-bay overlay"),
("⌘G ⌘⇧G", "Group / ungroup selected tracks"),
- ("⌘C ⌘X ⌘V", "Copy / cut / paste clip (or automation range) · a clip copied in Session pastes here"),
+ ("⌘C ⌘X ⌘V", "Copy / cut / paste clips, a time range or an automation range · pastes onto the track clicked last"),
("⌘⇧C", "Copy the selected clips to Session · the first scene row where they fit"),
("⌘⇧V", "Paste the last range as audio rendered through its devices"),
("⌘D", "Duplicate the selected clip(s) / range"),
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 619e1f93..3c35dff7 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -287,6 +287,13 @@ public interface IAudioEngine : IDisposable
double DuplicateClipBlock((int trackId, int clipIndex)[] sel);
/// <summary>Number of clips in the block clipboard (0 = empty).</summary>
int ClipboardBlockCount();
+ /// <summary>Copies the [start,end) slice of the given tracks' clips (with automation) to the
+ /// block clipboard, positioned relative to <paramref name="start"/>. The project is untouched;
+ /// a range block pastes overwriting what it lands on. False when the range covers no clip.</summary>
+ bool CopyRange(int[] trackIds, double start, double end);
+ /// <summary><see cref="CopyRange"/>, then carves the range out like <see cref="DeleteClipsInRange"/>
+ /// (one undo step). False when the range covers no clip.</summary>
+ bool CutRange(int[] trackIds, double start, double end);
/// <summary>Copies arrangement clips into session slots: each track's clips, in time order, fill
/// consecutive slots from startScene (-1 = the first scene row where every slot needed is empty;
/// missing rows are appended). One undo step. Returns the first scene row filled, or -1.</summary>
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 5c237ca7..a8aece8d 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -228,6 +228,12 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_clips_block_count")]
internal static partial int ClipsBlockCount(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_clips_copy_range")]
+ internal static partial NotaResult ClipsCopyRange(IntPtr engine, [In] int[] trackIds, int n, double start, double end);
+
+ [LibraryImport(Lib, EntryPoint = "nota_clips_cut_range")]
+ internal static partial NotaResult ClipsCutRange(IntPtr engine, [In] int[] trackIds, int n, double start, double end);
+
[LibraryImport(Lib, EntryPoint = "nota_clips_delete_range")]
internal static partial NotaResult ClipsDeleteRange(IntPtr engine, [In] int[] trackIds, int n, double start, double end);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index cb07c814..3ece3bcc 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -396,6 +396,15 @@ public sealed partial class NotaEngine
public int ClipboardBlockCount()
{ ThrowIfDisposed(); return NativeMethods.ClipsBlockCount(_handle); }
+ /// <summary>Copies the [start,end) slice of the given tracks' clips to the block clipboard
+ /// (relative to <paramref name="start"/>, with automation). False when no clip is covered.</summary>
+ public bool CopyRange(int[] trackIds, double start, double end)
+ { ThrowIfDisposed(); return NativeMethods.ClipsCopyRange(_handle, trackIds, trackIds.Length, start, end) == NativeMethods.NotaResult.Ok; }
+
+ /// <summary>Copies the range slice, then carves it out (one undo step). False when no clip is covered.</summary>
+ public bool CutRange(int[] trackIds, double start, double end)
+ { ThrowIfDisposed(); return NativeMethods.ClipsCutRange(_handle, trackIds, trackIds.Length, start, end) == NativeMethods.NotaResult.Ok; }
+
/// <summary>Copies arrangement clips into session slots: each track's clips, in time order,
/// fill consecutive slots from <paramref name="startScene"/> (-1 = the first scene row where
/// every slot needed is empty; missing rows are appended). One undo step. Returns the first
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 67301008..2316ffb7 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1284,6 +1284,13 @@ NOTA_API NotaResult nota_clips_block_cut(NotaEngine* engine, const int32_t* trac
NOTA_API int32_t nota_clips_block_paste(NotaEngine* engine, double at_beat, int32_t source_track_id); /* dest -1 = source tracks; -> clips pasted */
NOTA_API double nota_clips_block_duplicate(NotaEngine* engine, const int32_t* track_ids, const int32_t* clip_indices, int32_t count);
NOTA_API int32_t nota_clips_block_count(NotaEngine* engine);
+/* Range copy/cut (arrangement time-selection): the slice of each listed track's clips inside
+ * [start,end) becomes the block clipboard, positioned relative to `start`, with automation.
+ * copy_range leaves the project untouched; cut_range also carves the range out (one undo
+ * step, like delete_range). A range block pastes overwriting what it lands on. Error when
+ * the range covers no clip. */
+NOTA_API NotaResult nota_clips_copy_range(NotaEngine* engine, const int32_t* track_ids, int32_t n, double start, double end);
+NOTA_API NotaResult nota_clips_cut_range(NotaEngine* engine, const int32_t* track_ids, int32_t n, double start, double end);
NOTA_API int32_t nota_clips_last_placed(NotaEngine* engine, int32_t* out_track_ids, int32_t* out_clip_indices, int32_t cap);
/* Arrangement clips -> session slots. Each track's clips, in time order, fill consecutive
* slots from start_scene; start_scene -1 = the first scene row where every slot needed is
diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cpp
index f364b74f..fd9fe23e 100644
--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp
@@ -559,6 +559,18 @@ double nota_clips_block_duplicate(NotaEngine* e, const int32_t* track_ids, const
int32_t nota_clips_block_count(NotaEngine* e) {
return e ? CENG(e)->clipboardBlockCount() : 0;
}
+NotaResult nota_clips_copy_range(NotaEngine* e, const int32_t* track_ids, int32_t n, double start, double end) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ std::vector<int32_t> ids;
+ if (track_ids && n > 0) ids.assign(track_ids, track_ids + n);
+ return ENG(e)->copyRange(ids, start, end) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
+NotaResult nota_clips_cut_range(NotaEngine* e, const int32_t* track_ids, int32_t n, double start, double end) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ std::vector<int32_t> ids;
+ if (track_ids && n > 0) ids.assign(track_ids, track_ids + n);
+ return ENG(e)->cutRange(ids, start, end) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
int32_t nota_clips_to_session(
NotaEngine* e, const int32_t* track_ids, const int32_t* clip_indices, int32_t n, int32_t start_scene) {
return e ? ENG(e)->arrangementClipsToSession(makeSel(track_ids, clip_indices, n), start_scene) : -1;
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index fa2ebabd..64cc5d33 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -546,6 +546,13 @@ class Engine {
bool cutClipBlock(const std::vector<std::pair<int32_t, int32_t>>& sel);
int32_t pasteClipBlock(double atBeat, int32_t sourceTrackId); // -> clips pasted
double duplicateClipBlock(const std::vector<std::pair<int32_t, int32_t>>& sel); // -> block length (>0), or -1
+ // Range copy/cut (arrangement time-selection ⌘C / ⌘X): the slice of every listed track's
+ // clips inside [start,end) becomes the block clipboard, beats relative to `start` (so a
+ // leading gap is kept), each slice with its automation. Copy leaves the project alone;
+ // cut then carves the range out like deleteClipsInRange (one undo step). A range block
+ // pastes in overwrite mode — it replaces what it lands on, like a range duplicate.
+ bool copyRange(const std::vector<int32_t>& trackIds, double start, double end);
+ bool cutRange(const std::vector<int32_t>& trackIds, double start, double end);
int32_t clipboardBlockCount() const { return static_cast<int32_t>(clipboardBlock_.size()); }
const std::vector<std::pair<int32_t, int32_t>>& lastPlaced() const { return lastPlaced_; }
@@ -1263,6 +1270,8 @@ class Engine {
};
std::vector<BlockClip> clipboardBlock_;
double clipboardBlockLen_ = 0.0;
+ bool clipboardBlockOverwrite_ = false; // a range copy: paste replaces what it lands on
+ int32_t clipboardBlockAnchor_ = -1; // a range copy: its top row (remap anchor), else -1
// Clips created by the last block paste/duplicate — (trackId, clipIndex) — so the UI
// can re-select exactly what it produced.
std::vector<std::pair<int32_t, int32_t>> lastPlaced_;
@@ -1293,8 +1302,10 @@ class Engine {
std::vector<BlockClip> captureBlock(const std::vector<std::pair<int32_t, int32_t>>& sel, double& blockLen) const;
void placeBlock(const std::vector<BlockClip>& items, double placedStart, bool overwrite = false);
// Remap a block by the track-index delta from its top track to destTrackId, dropping
- // clips that fall off the track list or onto a track of the other kind.
- std::vector<BlockClip> remapBlock(const std::vector<BlockClip>& items, int32_t destTrackId) const;
+ // clips that fall off the track list or onto a track of the other kind. anchorTrackId >= 0
+ // pins the "top track" instead (a range block: the range's top row, even when empty).
+ std::vector<BlockClip> remapBlock(const std::vector<BlockClip>& items, int32_t destTrackId,
+ int32_t anchorTrackId = -1) const;
int32_t landBlockInSession(const std::vector<BlockClip>& items, int32_t startScene);
// A fresh slot looping one arrangement clip (see Engine_Session.cpp).
SessionSlot slotFromMidiClip(const MidiClip& m) const;
diff --git a/src/native/nota.engine/src/engine/Engine_Session.cpp b/src/native/nota.engine/src/engine/Engine_Session.cpp
index 7e402f50..b6b007ab 100644
--- a/src/native/nota.engine/src/engine/Engine_Session.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Session.cpp
@@ -762,7 +762,7 @@ int32_t Engine::arrangementClipsToSession(const std::vector<std::pair<int32_t, i
int32_t Engine::pasteClipBlockToSession(int32_t destTrackId, int32_t startScene) {
if (clipboardBlock_.empty() || !authoring_) return -1;
return landBlockInSession(
- destTrackId >= 0 ? remapBlock(clipboardBlock_, destTrackId) : clipboardBlock_, startScene);
+ destTrackId >= 0 ? remapBlock(clipboardBlock_, destTrackId, clipboardBlockAnchor_) : clipboardBlock_, startScene);
}
int32_t Engine::sessionSlotsToArrangement(
diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
index 6b612d60..8ce470fd 100644
--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp
@@ -2743,6 +2743,63 @@ bool Engine::copyClipBlock(const std::vector<std::pair<int32_t, int32_t>>& sel)
if (items.empty()) return false;
clipboardBlock_ = std::move(items);
clipboardBlockLen_ = len;
+ clipboardBlockOverwrite_ = false;
+ clipboardBlockAnchor_ = -1;
+ return true;
+}
+
+bool Engine::copyRange(const std::vector<int32_t>& trackIds, double start, double end) {
+ if (end <= start + 1e-9 || trackIds.empty() || !authoring_) return false;
+ const double spb = transport_.samplesPerBeat(), devSR = transport_.sampleRate();
+ constexpr double eps = 1e-6;
+ auto listed = [&](int32_t id) { return std::find(trackIds.begin(), trackIds.end(), id) != trackIds.end(); };
+ std::vector<BlockClip> items;
+ int32_t anchor = -1; // the range's top row
+ for (const auto& t : authoring_->tracks) {
+ if (t->type() == TrackType::Return || !listed(t->id())) continue;
+ if (anchor < 0) anchor = t->id();
+ auto add = [&](BlockClip b, double s) {
+ b.trackId = t->id();
+ b.relStart = s - start;
+ b.autom = captureClipAutomation(*t, s, s + b.len);
+ items.push_back(std::move(b));
+ };
+ if (t->type() == TrackType::Instrument) {
+ for (const auto& c : t->midiClips) {
+ const double cs = c.startBeat, ce = cs + c.lengthBeats;
+ if (ce <= start + eps || cs >= end - eps) continue;
+ BlockClip b;
+ b.kind = 1;
+ b.midi = midiSlice(c, start, end);
+ b.len = b.midi.lengthBeats;
+ const double s = b.midi.startBeat;
+ add(std::move(b), s);
+ }
+ } else if (t->type() == TrackType::Audio) {
+ for (const auto& c : t->clips) {
+ const double cs = c.startBeat, ce = cs + audioDisplayLenBeats(c, spb, devSR);
+ if (ce <= start + eps || cs >= end - eps) continue;
+ BlockClip b;
+ b.kind = 0;
+ b.audio = audioSlice(c, start, end, spb, devSR);
+ b.audio.warpCache = nullptr; // the paste rebuilds the cache
+ b.len = audioDisplayLenBeats(b.audio, spb, devSR);
+ const double s = b.audio.startBeat;
+ add(std::move(b), s);
+ }
+ }
+ }
+ if (items.empty()) return false;
+ clipboardBlock_ = std::move(items);
+ clipboardBlockLen_ = end - start;
+ clipboardBlockOverwrite_ = true;
+ clipboardBlockAnchor_ = anchor;
+ return true;
+}
+
+bool Engine::cutRange(const std::vector<int32_t>& trackIds, double start, double end) {
+ if (!copyRange(trackIds, start, end)) return false;
+ deleteClipsInRange(trackIds, start, end);
return true;
}
@@ -2790,9 +2847,9 @@ bool Engine::cutClipBlock(const std::vector<std::pair<int32_t, int32_t>>& sel) {
int32_t Engine::pasteClipBlock(double atBeat, int32_t sourceTrackId) {
if (clipboardBlock_.empty() || !authoring_) return 0;
// sourceTrackId >= 0 remaps the whole block onto that track (see remapBlock).
- std::vector<BlockClip> items = sourceTrackId >= 0 ? remapBlock(clipboardBlock_, sourceTrackId) : clipboardBlock_;
+ std::vector<BlockClip> items = sourceTrackId >= 0 ? remapBlock(clipboardBlock_, sourceTrackId, clipboardBlockAnchor_) : clipboardBlock_;
if (items.empty()) return 0;
- placeBlock(items, atBeat);
+ placeBlock(items, atBeat, clipboardBlockOverwrite_);
return static_cast<int32_t>(lastPlaced_.size());
}
@@ -2800,7 +2857,8 @@ int32_t Engine::pasteClipBlock(double atBeat, int32_t sourceTrackId) {
// clip lands on that track; a multi-track block shifts together). Clips that fall off the
// track list or hit a type-mismatched track are skipped; a remapped clip's device/plugin
// automation is dropped (indices are positional).
-std::vector<Engine::BlockClip> Engine::remapBlock(const std::vector<BlockClip>& items, int32_t destTrackId) const {
+std::vector<Engine::BlockClip> Engine::remapBlock(const std::vector<BlockClip>& items, int32_t destTrackId,
+ int32_t anchorTrackId) const {
auto idxOf = [&](int32_t tid) -> int {
for (size_t i = 0; i < authoring_->tracks.size(); ++i)
if (authoring_->tracks[i]->id() == tid) return static_cast<int>(i);
@@ -2812,6 +2870,7 @@ std::vector<Engine::BlockClip> Engine::remapBlock(const std::vector<BlockClip>&
int ix = idxOf(b.trackId);
if (ix >= 0) topIdx = std::min(topIdx, ix);
}
+ if (anchorTrackId >= 0 && idxOf(anchorTrackId) >= 0) topIdx = idxOf(anchorTrackId);
if (destIdx < 0 || topIdx == std::numeric_limits<int>::max()) return {};
const int delta = destIdx - topIdx;
std::vector<BlockClip> remapped;
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 13c6f8b5..f928e262 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -345,6 +345,14 @@ if (args.Length >= 1 && args[0] == "--returns")
Console.WriteLine(failures == 0 ? "RETURNS PASSED" : $"RETURNS FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Arrangement range copy / cut alone: `--range-clipboard`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--range-clipboard")
+{
+ Console.WriteLine("-- range clipboard --");
+ foreach (var (ok, label) in RangeClipboardTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "RANGE CLIPBOARD PASSED" : $"RANGE CLIPBOARD FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Stereo Map measurements alone: `--stereomap`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--stereomap")
{
@@ -15036,6 +15044,9 @@ foreach (var (ok, label) in ProjectTemplateTests.Run()) Check(ok, label);
Console.WriteLine("-- return delete --");
foreach (var (ok, label) in ReturnDeleteTests.Run()) Check(ok, label);
+Console.WriteLine("-- range clipboard --");
+foreach (var (ok, label) in RangeClipboardTests.Run()) Check(ok, label);
+
Console.WriteLine("-- pan law --");
foreach (var (ok, label) in PanLawTests.Run()) Check(ok, label);
diff --git a/tests/Nota.SmokeTest/RangeClipboardTests.cs b/tests/Nota.SmokeTest/RangeClipboardTests.cs
new file mode 100644
index 00000000..ccd4d112
--- /dev/null
+++ b/tests/Nota.SmokeTest/RangeClipboardTests.cs
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Range copy / cut (.specify/bugs/arrangement-range-clipboard, issue #281): a time range's
+// slice of every selected track goes to the block clipboard, cut at the range edges and
+// positioned from the range start; copy leaves the project alone, cut is one undo step; a
+// range block pastes overwriting what it lands on, and a cross-track paste shifts it so the
+// range's top row (even an empty one) lands on the target. Also runnable alone:
+// `dotnet run --project tests/Nota.SmokeTest -- --range-clipboard`.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class RangeClipboardTests
+{
+ private const double Eps = 1e-6;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ // MIDI: copy [2,6) out of a [0,8) clip with notes at 1, 3 and 5.
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int a = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(a, 0.0, 8.0);
+ e.SetClipNotes(a, c, new[] { new NotaNote(60, 1.0, 0.5, 0.8f), new NotaNote(62, 3.0, 0.5, 0.8f), new NotaNote(64, 5.0, 0.5, 0.8f) });
+
+ yield return (e.CopyRange(new[] { a }, 2.0, 6.0), "range: copy [2,6) of a MIDI clip");
+ yield return (e.ClipboardBlockCount() == 1, $"range: the block clipboard holds the slice ({e.ClipboardBlockCount()})");
+ yield return (e.TryGetClipInfo(a, 0, out var src) && Near(src.StartBeat, 0) && Near(src.LengthBeats, 8)
+ && !e.TryGetClipInfo(a, 1, out _) && e.GetClipNotes(a, 0).Length == 3,
+ "range: copy leaves the source clip whole");
+
+ yield return (e.PasteClipBlock(16.0, -1) == 1, "range: paste at beat 16 on the source track");
+ int pasted = LastIndexOn(e, a);
+ yield return (e.TryGetClipInfo(a, pasted, out var p) && Near(p.StartBeat, 16) && Near(p.LengthBeats, 4),
+ $"range: the pasted slice is [16,20) (start {p.StartBeat}, len {p.LengthBeats})");
+ var notes = e.GetClipNotes(a, pasted).OrderBy(n => n.StartBeat).ToArray();
+ yield return (notes.Length == 2 && notes[0].Pitch == 62 && notes[1].Pitch == 64
+ && Near(notes[1].StartBeat - notes[0].StartBeat, 2.0),
+ $"range: the slice keeps only the notes inside the range ({notes.Length})");
+ }
+
+ // A clip starting inside the range keeps its offset from the range start.
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack();
+ e.AddMidiClip(a, 4.0, 4.0);
+ e.CopyRange(new[] { a }, 2.0, 6.0);
+ e.PasteClipBlock(16.0, -1);
+ int pasted = LastIndexOn(e, a);
+ yield return (e.TryGetClipInfo(a, pasted, out var p) && Near(p.StartBeat, 18) && Near(p.LengthBeats, 2),
+ $"range: a leading gap is kept — the slice lands at 18 (got {p.StartBeat}, len {p.LengthBeats})");
+ }
+
+ // A range paste overwrites what it lands on instead of shifting past it.
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack();
+ int b = e.AddInstrumentTrack();
+ e.AddMidiClip(a, 0.0, 4.0);
+ e.AddMidiClip(b, 0.0, 8.0);
+ e.CopyRange(new[] { a }, 0.0, 4.0);
+ yield return (e.PasteClipBlock(2.0, b) == 1, "range: paste onto track b at beat 2");
+ var spans = Spans(e, b);
+ yield return (spans.Any(s => Near(s.start, 2) && Near(s.len, 4)) && spans.Any(s => Near(s.start, 0) && Near(s.len, 2))
+ && spans.Any(s => Near(s.start, 6) && Near(s.len, 2)) && spans.Count == 3,
+ $"range: the paste carves [2,6) out of b's clip instead of shifting ({string.Join(" ", spans)})");
+ }
+
+ // Clip copy after a range copy pastes the old way again (shifts past a taken spot).
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(a, 0.0, 4.0);
+ e.CopyRange(new[] { a }, 0.0, 2.0);
+ e.CopyClipBlock(new[] { (a, c) });
+ e.PasteClipBlock(2.0, -1);
+ int pasted = LastIndexOn(e, a);
+ yield return (e.TryGetClipInfo(a, pasted, out var p) && Near(p.StartBeat, 4),
+ $"range: a clip block still shifts past the source (lands at {p.StartBeat})");
+ }
+
+ // Cut: carves the range out in one undo step, and the slice pastes back.
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack();
+ e.AddMidiClip(a, 0.0, 8.0);
+ yield return (e.CutRange(new[] { a }, 2.0, 6.0), "range: cut [2,6)");
+ var spans = Spans(e, a);
+ yield return (spans.Count == 2 && spans.Any(s => Near(s.start, 0) && Near(s.len, 2)) && spans.Any(s => Near(s.start, 6) && Near(s.len, 2)),
+ $"range: cut leaves [0,2) and [6,8) ({string.Join(" ", spans)})");
+ yield return (e.Undo() && Spans(e, a).Count == 1, "range: one undo restores the whole clip");
+ yield return (e.PasteClipBlock(20.0, -1) == 1 && Spans(e, a).Any(s => Near(s.start, 20) && Near(s.len, 4)),
+ "range: the cut slice pastes at beat 20");
+ }
+
+ // Cross-track paste anchors on the range's top row, even when that row is empty.
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack(), b = e.AddInstrumentTrack();
+ int c = e.AddInstrumentTrack(), d = e.AddInstrumentTrack();
+ e.AddMidiClip(b, 0.0, 4.0);
+ e.CopyRange(new[] { a, b }, 0.0, 4.0);
+ yield return (e.PasteClipBlock(8.0, c) == 1, "range: paste a two-row range onto track c");
+ yield return (Spans(e, d).Any(s => Near(s.start, 8)) && Spans(e, c).Count == 0,
+ "range: the row-b slice lands on d — the empty top row maps to c");
+ }
+
+ // Audio: the slice keeps its place in the sample.
+ {
+ string wav = Path.Combine(Path.GetTempPath(), $"nota-range-clip-{Guid.NewGuid():N}.wav");
+ WavWriter.WriteSine(wav, 4.0, 440, 48000);
+ try
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120); // 4 s = 8 beats
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ yield return (e.CopyRange(new[] { t }, 2.0, 6.0), "range: copy [2,6) of an audio clip");
+ yield return (e.PasteClipBlock(16.0, -1) == 1, "range: paste the audio slice at 16");
+ int pasted = LastIndexOn(e, t);
+ yield return (e.TryGetClipInfo(t, pasted, out var p) && Near(p.StartBeat, 16) && Math.Abs(p.LengthBeats - 4) < 1e-3,
+ $"range: the audio slice is [16,20) (start {p.StartBeat}, len {p.LengthBeats})");
+ yield return (e.TryGetAudioClipInfo(t, pasted, out var ai) && ai.SourceOffsetFrames > 0,
+ $"range: the audio slice starts 1 s into the sample (offset {ai.SourceOffsetFrames} frames)");
+ }
+ finally { File.Delete(wav); }
+ }
+
+ // Nothing covered → nothing copied, the old clipboard survives.
+ {
+ using var e = new NotaEngine();
+ int a = e.AddInstrumentTrack();
+ int c = e.AddMidiClip(a, 0.0, 2.0);
+ e.CopyClipBlock(new[] { (a, c) });
+ yield return (!e.CopyRange(new[] { a }, 4.0, 8.0) && e.ClipboardBlockCount() == 1,
+ "range: an empty range copies nothing and keeps the clipboard");
+ }
+ }
+
+ private static bool Near(double a, double b) => Math.Abs(a - b) < Eps;
+
+ private static List<(double start, double len)> Spans(NotaEngine e, int track)
+ {
+ var list = new List<(double, double)>();
+ for (int i = 0; e.TryGetClipInfo(track, i, out var ci); i++) list.Add((ci.StartBeat, ci.LengthBeats));
+ return list;
+ }
+
+ private static int LastIndexOn(NotaEngine e, int track)
+ {
+ var placed = e.LastPlacedClips();
+ foreach (var (t, c) in placed) if (t == track) return c;
+ return -1;
+ }
+}