Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Arrangement: arrow-key clip moves, Shift-click track ranges, drop below the last track for a new track (#324)
Chris Laupama065d54c26728
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 941e8faf..485df780 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Move clips with the keyboard** (nota-daw/nota#302): in the Arrangement, ← / → nudge the+ selected clips by the grid step and ⌥← / ⌥→ by a 64th note, stopping at the song start;+ ⌥↑ / ⌥↓ move them to the next track up or down that takes them, at the same beats. Each+ press is one undo step.+- **Drop clips below the last track to make a new one** (nota-daw/nota#301): dragging clips+ into the empty space under the tracks shows a **New track** ring per source track; on release+ each source track gets a new track with the same instrument, devices and mix, and the clips+ move there. One undo takes back both.+- **Shift-click track headers to select a range** (nota-daw/nota#249): Shift-click selects every+ track from the last clicked one; ⌘-click (Ctrl on Windows / Linux) adds or removes one track.- **File → Exit** (nota-daw/nota#316): Windows and Linux can quit from the menu or withCtrl+Q, the same way as the window's close button, so unsaved changes still ask first. OnmacOS Quit Nota (⌘Q) stays in the app menu.diff --git a/specs/039-arrangement-keyboard-moves/plan.md b/specs/039-arrangement-keyboard-moves/plan.mdnew file mode 100644index 00000000..4d6108f0--- /dev/null+++ b/specs/039-arrangement-keyboard-moves/plan.md@@ -0,0 +1,86 @@+# Implementation Plan: Arrangement keyboard moves++**Branch**: `feat/arrangement-keyboard-moves` | **Date**: 2026-10-26 | **Spec**: [spec.md](spec.md)++## Summary++Three Arrangement gestures (#302, #249, #301): arrow keys move the clip selection (←/→ by+the grid step or a 64th, ⌥↑/⌥↓ to the next track that takes every clip), Shift-click on a+track header selects a range, and dropping clips below the last track moves them onto new+tracks like their sources. Every move goes through the existing atomic `MoveClipBlock`, so+each gesture is one undo step. The only engine addition is `addTrackLike`.++## Technical Context++- **Engine**: `Engine::addTrackLike(trackId)` (`Engine_Tracks.cpp`), exposed as+ `nota_engine_add_track_like` (pure C ABI, AR-7). It clones the source with+ `deepCloneTrack(src, newId, withContent = false)`: instrument, MIDI effects and devices+ get their own DSP state; clips, Session slots and automation are not copied. Group+ membership, arm, name and colour are reset. The new track is published in a new graph+ snapshot (AR-5) right after the last non-return track. A track added after the returns+ exist sits after them in the graph, so "in front of the first return" is not enough.+ Returns -1 for the master, a return, a group or an unknown id.+- **Pure rules**: `Nota.Application/Editing/ArrangementMoves.cs`, UI-free and driven by+ the smoke test:+ - `NudgeDelta`: the block's shift, clamped at the song start.+ - `RowShift`: the nearest row offset where every clip lands on a track that takes it.+ - `Range`: Shift-click header ids.+ - `Reindex` / `Invert` / `SameStarts`: where clips are after a block move, and after its+ undo or redo.+- **App**:+ - `ArrangementView.KeyMoves.cs`: nudge, track moves, and `MoveBlock`, which wraps+ `MoveClipBlock` and returns a `ClipBlockMove`.+ - `ArrangementView.NewTrackDrop.cs`: inside one undo group, one `AddTrackLike` per+ source track, then a single `MoveBlock`. If any step fails, the group is undone.+ - `LaneControl`: draws the drop ring below the last track.+ - `MainWindow.Input.cs`: the arrows reach the Arrangement only when nothing else owns+ them: not the piano roll grid, the docked detail panel or the floating detail window,+ and not with ⌘/Ctrl or Shift held.+- **Open editors**: clips are addressed by index, and a move can re-index a track. A+ landing that carves away a clip shifts the clips after it, and a cross-track move+ appends. `MainWindow.OnClipsMoved` re-targets the piano roll, the audio editor and the+ step grid. It also keeps the recent moves, so an undo or redo of exactly that move+ takes the editors back or forward. The move is recognised when the touched tracks'+ clip starts match the starts from before or after it.++**Audio-Thread Impact**: None. All work happens on the UI thread, through the existing+snapshot publish (AR-5). `addTrackLike` and `MoveClipBlock` allocate and publish off the+audio thread; the audio thread only picks up the new snapshot. No new locks, allocations+or I/O on the audio thread (AR-6).++**Testing**: The smoke test section `ArrangementMovesTests` (`--moves`) covers:++- the pure rules;+- `addTrackLike` placement, contents and refusals;+- one-step undo of a drop onto new tracks;+- clip re-indexing after a carving move, and after its undo and redo.++The app was also checked by hand on Linux (Xvfb) and on macOS (Mac mini).++## Constitution Check++| Principle | Status | Note |+|---|---|---|+| I. Real-Time Audio Safety | Pass | No audio-thread code; edits publish snapshots. |+| II. Boundary Discipline | Pass | One new C ABI call; the app uses only the interop layer. |+| III. Licensing Hygiene | Pass | New files carry the AGPL-3.0-only SPDX header; no new dependency. |+| IV. Verification Gate | Pass | Full smoke test with `CI=true`; new `--moves` section. |+| V. One Logical Change per PR | Pass | Three related Arrangement editing gestures, one spec. |+| VI. Documentation Stays in Sync | Pass | CHANGELOG, Settings → Shortcuts, nota-docs EN + RU. |+| VII. Spec-First | Pass | spec.md, plan.md, tasks.md. |+| VIII. Safety Rules Never Weakened | Pass | Nothing weakened. |++## Project Structure++```text+src/native/nota.engine/src/engine/Engine_Tracks.cpp # addTrackLike, deepCloneTrack(withContent)+src/native/nota.engine/include/nota/nota_engine.h # nota_engine_add_track_like (ABI: src/abi/nota_engine_track.cpp)+src/managed/Nota.Infrastructure/Interop/ # AddTrackLike+src/managed/Nota.Application/Editing/ArrangementMoves.cs+src/managed/Nota.App/ArrangementView.KeyMoves.cs+src/managed/Nota.App/ArrangementView.NewTrackDrop.cs+src/managed/Nota.App/ArrangementView.LaneControl.cs # drop ring, drag commit via MoveBlock+src/managed/Nota.App/MainWindow.Input.cs # arrow routing+src/managed/Nota.App/MainWindow.Detail.cs # editors follow moves, undo / redo+tests/Nota.SmokeTest/ArrangementMovesTests.cs+```diff --git a/specs/039-arrangement-keyboard-moves/spec.md b/specs/039-arrangement-keyboard-moves/spec.mdnew file mode 100644index 00000000..8e33bee2--- /dev/null+++ b/specs/039-arrangement-keyboard-moves/spec.md@@ -0,0 +1,67 @@+# Feature Specification: Keyboard clip moves, header range select, drop below the last track++**Feature Branch**: `feat/arrangement-keyboard-moves`++**Created**: 2026-10-26++**Status**: Implemented++**Input**: Issues nota-daw/nota#302 (move clips with the arrow keys), #249 (Shift / ⌘-click+track headers to select several tracks) and #301 (dragging a clip below the last track+should create a new track for it).++## Nota Context++**Feature area**: Engine (one new ABI call) and the managed app (Arrangement view).++What exists today:++- Clips move only by mouse. `MoveClipBlock` moves a set of clips atomically (one undo+ step) and `LastPlacedClips` reports where they landed.+- Track headers select one track per click; ⌘A selects all. The multi-track set+ (`_selTracks`) already drives group, duplicate, copy and delete.+- A clip dragged below the last lane has no target and snaps back.+- `DuplicateTrack` deep-copies a track (mixer, instrument, devices, clips, automation).++## User Scenarios++1. **Nudge (P1).** With clips selected in the Arrangement, ← / → move them by the current+ grid step; ⌥← / ⌥→ by a 64th note. The block moves as one and stops at the song start.+ Each press is one undo step.+2. **Move to another track (P1).** ⌥↑ / ⌥↓ move the selected clips to the nearest tracks+ above / below that take every clip (audio on audio tracks, MIDI on instrument tracks),+ at the same beats. When none does, the status bar says so and nothing moves.+3. **Range select headers (P2).** A Shift-click on a track header selects every track from+ the last plainly- or ⌘-clicked track to it; ⌘-click (Ctrl on Windows / Linux) adds or+ removes one track.+4. **Drop below the last track (P1).** Dragging clips into the empty space under the last+ track shows one "New track" drop ring per source track, with the clips previewed in it.+ Releasing creates, for each source track, a new track like it: same kind, instrument,+ devices and mix, but no clips, automation or session clips, not in a group, placed after+ the last regular track (before the returns). The clips move there at their dropped+ beats. One undo takes back both the move and the new tracks.++## Decisions (the open points in #301)++- The new track copies the source track's instrument and devices, so a MIDI clip sounds+ the same after the move.+- A multi-clip selection gets one new track per source track, in source order, so the+ layout of the selection is kept.++## Requirements++- **FR-1** ←/→ and ⌥←/⌥→ act only when the Arrangement has focus (not the detail panel+ or the piano roll) and no ⌘ / Shift is held.+- **FR-2** ⌥↑/⌥↓ never put a clip on a group, a return or a track of the other kind.+- **FR-3** `nota_engine_add_track_like(engine, trackId)` returns the new id, or -1 for+ the master, a return, a group or an unknown id. It checkpoints undo like any track add.+- **FR-4** If any step of a drop below the last track fails, the new tracks are taken+ back and the clips stay where they were.+- **FR-5** Esc during the drag removes the ghost rows and changes nothing.++## Success Criteria++- Smoke test `--moves` covers the nudge clamp, the row-shift rule, the header range and+ `AddTrackLike` (placement, instrument and devices, no clips or automation, top-level,+ one-step undo with the move, refused for return / group / unknown).+- Checked in the real app on Linux and macOS with before/after screenshots.diff --git a/specs/039-arrangement-keyboard-moves/tasks.md b/specs/039-arrangement-keyboard-moves/tasks.mdnew file mode 100644index 00000000..9ee137cf--- /dev/null+++ b/specs/039-arrangement-keyboard-moves/tasks.md@@ -0,0 +1,14 @@+# Tasks: 039 Arrangement keyboard moves++- [x] T1 Engine: `Engine::addTrackLike` + ABI `nota_engine_add_track_like` + header doc+- [x] T2 Interop: `NativeMethods.AddTrackLike`, `NotaEngine.AddTrackLike`+- [x] T3 `Nota.Application/Editing/ArrangementMoves.cs`: NudgeDelta, RowShift, Range+- [x] T4 `ArrangementView.KeyMoves.cs`: NudgeSelectedClips, MoveSelectedClipsToTrack+- [x] T5 `MainWindow.Input.cs`: arrow keys route to the Arrangement+- [x] T6 Track headers: Shift-click range, ⌘-click toggle, anchor+- [x] T7 LaneControl: ghost rows below the last track; `MoveClipsToNewTracks` on release+- [x] T8 Smoke test `ArrangementMovesTests` (`--moves`) and the full run+- [x] T9 Settings → Shortcuts rows, CHANGELOG+- [x] T10 Real-app check on Linux and macOS, screenshots on `pr-assets`+- [x] T11 nota-docs EN + RU (nota-docs#31)+- [x] T12 Review fixes: open editors follow clips re-indexed by a move and by its undo / redo; arrows stay in the floating detail window; `addTrackLike` skips copying contentdiff --git a/src/managed/Nota.App/ArrangementView.Groups.cs b/src/managed/Nota.App/ArrangementView.Groups.csindex 0b8d0bfb..d8c45c7a 100644--- a/src/managed/Nota.App/ArrangementView.Groups.cs+++ b/src/managed/Nota.App/ArrangementView.Groups.cs@@ -9,6 +9,7 @@using System.Collections.Generic;using System.Linq;+using Nota.Application.Editing;namespace Nota.App;@@ -117,6 +118,22 @@ public sealed partial class ArrangementViewprivate void ClearTrackMultiSelection() => _selTracks.Clear();+ // Where a Shift-click range starts: the last plain- or Ctrl/Cmd-clicked header (#249).+ private int _trackAnchorId = -1;++ // Shift-click: every row from the anchor to this one, as shown (a folded group is one row+ // that brings its children along); the clicked track becomes the primary.+ private void SelectTrackRange(int trackId)+ {+ int anchor = _tracks.Any(t => t.Id == _trackAnchorId) ? _trackAnchorId : SelTrackId;+ var ids = ArrangementMoves.Range(_tracks.Select(t => t.Id).ToList(), anchor, trackId);+ if (ids.Count == 0) return;+ _selTracks.Clear();+ foreach (int id in ids) _selTracks.Add(id);+ if (_trackAnchorId <= 0) _trackAnchorId = anchor;+ Select(trackId, -1, keepTrackSet: true);+ }+// ---- create / ungroup -------------------------------------------------/// <summary>Group the current multi-selection (or <paramref name="fallbackTrackId"/> when/// nothing is multi-selected) under a new group track. Returns the group id or -1.</summary>diff --git a/src/managed/Nota.App/ArrangementView.KeyMoves.cs b/src/managed/Nota.App/ArrangementView.KeyMoves.csnew file mode 100644index 00000000..24fad456--- /dev/null+++ b/src/managed/Nota.App/ArrangementView.KeyMoves.cs@@ -0,0 +1,115 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Keyboard clip moves (specs/039-arrangement-keyboard-moves): ←/→ nudge the selected clips by+// the grid step, ⌥←/⌥→ by a 64th (#302); ⌥↑/⌥↓ move them to the next track that takes them,+// keeping their exact position (#301's comment). Each key press is one undo step.++using System;+using System.Collections.Generic;+using System.Linq;+using Nota.Application.Editing;++namespace Nota.App;++public partial class ArrangementView+{+ /// <summary>←/→: nudges the clip selection by the grid step (<paramref name="fine"/>: a 64th)+ /// as one block, stopping at the song start. False when no clip is selected.</summary>+ public bool NudgeSelectedClips(int dir, bool fine)+ {+ if (_engine is null || _sel.Count == 0) return false;+ // Starts come from the engine, not the drawn clips: a clip on a folded group's child is+ // still selected and moves with the block, like Duplicate and Copy already take it.+ var block = SelectedClipStarts();+ if (block.Count == 0) return false;+ double delta = ArrangementMoves.NudgeDelta(block.Min(b => b.start), fine ? ArrangementMoves.FineNudgeBeats : SnapStepBeats, dir);+ if (delta == 0) return true; // already at the song start: the key is still ours+ if (MoveBlock(block.Select(b => (b.track, b.clip, b.track, b.start + delta)).ToArray()) is not { } move) return true;+ Refresh();+ ReselectPlaced();+ ClipsMoved?.Invoke(move); // open editors follow their clips (index and START read-out)+ return true;+ }++ /// <summary>⌥↑/⌥↓: moves the clip selection to the nearest tracks above / below that take+ /// every clip (audio on audio, MIDI on instrument tracks), at the same beats. False when no+ /// clip is selected.</summary>+ public bool MoveSelectedClipsToTrack(int dir)+ {+ if (_engine is null || _sel.Count == 0) return false;+ var block = SelectedClipStarts().Select(b => (b.track, b.clip, b.start, row: RowOfTrack(b.track))).ToList();+ if (block.Count == 0) return false;+ if (block.Any(b => b.row < 0))+ {+ // Rows are what ⌥↑/⌥↓ step through, and a folded group's children have none: moving+ // only the shown clips would split the block, so the whole move is refused.+ StatusMessage?.Invoke("Unfold the group to move these clips across tracks");+ return true;+ }+ int shift = ArrangementMoves.RowShift(block.Select(b => b.row).Distinct().ToList(), _tracks.Count, dir, TakesClipsFrom);+ if (shift == 0)+ {+ StatusMessage?.Invoke(dir < 0 ? "No track above takes these clips" : "No track below takes these clips");+ return true;+ }+ var moves = block.Select(b => (b.track, b.clip, _tracks[b.row + shift].Id, b.start)).ToArray();+ if (MoveBlock(moves) is not { } move) return true;+ if (_engine.LastMoveKeptDeviceAutomation())+ StatusMessage?.Invoke("Moved across tracks — device automation stayed on the source");+ Refresh();+ ReselectPlaced();+ ClipsMoved?.Invoke(move);+ if (SelTrackId > 0) RevealTrack(SelTrackId);+ AnnounceSelectedTrack(); // the destination track is now the active one+ return true;+ }++ /// <summary>Raised after a block of clips moved (drag, keys, drop onto new tracks) with where+ /// each clip of the touched tracks now is (null: carved away). Open editors hold clip indices,+ /// which a move can shift, so they re-target from this.</summary>+ public event Action<ClipBlockMove>? ClipsMoved;++ // One MoveClipBlock, plus where every clip of the touched tracks ended up; null if refused.+ internal ClipBlockMove? MoveBlock(+ (int trackId, int clipIndex, int destTrackId, double newStartBeat)[] moves)+ {+ if (_engine is null) return null;+ var touched = moves.SelectMany(m => new[] { m.trackId, m.destTrackId }).Distinct().ToList();+ var before = touched.ToDictionary(t => t, ClipStarts);+ if (!_engine.MoveClipBlock(moves)) return null;+ var after = touched.ToDictionary(t => t, ClipStarts);+ return new ClipBlockMove(ArrangementMoves.Reindex(before, moves.Select(m => (m.trackId, m.clipIndex)).ToList(),+ _engine.LastPlacedClips(), after), before, after);+ }++ internal void RaiseClipsMoved(ClipBlockMove move) => ClipsMoved?.Invoke(move);++ /// <summary>Each given track's clip starts, by index (a snapshot to compare after undo / redo).</summary>+ internal IReadOnlyDictionary<int, IReadOnlyList<double>> ClipStartsOf(IEnumerable<int> tracks)+ => tracks.ToDictionary(t => t, ClipStarts);++ private IReadOnlyList<double> ClipStarts(int trackId)+ {+ var starts = new List<double>();+ while (_engine!.TryGetClipInfo(trackId, starts.Count, out var ci)) starts.Add(ci.StartBeat);+ return starts;+ }++ // Every selected clip with its start, shown or not (a folded group hides its children's rows).+ private List<(int track, int clip, double start)> SelectedClipStarts()+ {+ var block = new List<(int, int, double)>();+ foreach (var (track, clip) in _sel)+ if (_engine!.TryGetClipInfo(track, clip, out var ci)) block.Add((track, clip, ci.StartBeat));+ return block;+ }++ // A row takes another row's clips when it holds the same kind of clip (a group or a return holds none).+ private bool TakesClipsFrom(int from, int to)+ {+ var src = _tracks[from];+ var dst = _tracks[to];+ return !dst.IsGroup && !dst.IsReturn && dst.IsInstrument == src.IsInstrument;+ }+}diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex b690ec9a..8ce54cc2 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -108,6 +108,9 @@ public sealed partial class ArrangementViewprivate double _grabOrigStart; // grabbed clip's original start (delta reference)private int _grabRow; // grabbed clip's row (vertical delta reference)private int _moveRowDelta; // rows to shift the group (instrument→instrument only)+ // Held below the last track (#301): each source track gets a new track like it, shown+ // as ghost rows under the lanes; the ids are the sources, top to bottom.+ private List<int>? _newTrackSources;// Audio clip → instrument (see ArrangementView.ClipDrag): the grabbed clip, the// sample-taking instrument row it's held over (-1 none: a plain move), and the press@@ -489,6 +492,8 @@ public sealed partial class ArrangementViewforeach (var m in _groupMove) m.vm.StartBeat = m.origStart;_moveRowDelta = 0;}+ SetNewTrackRows(_loadRow < 0 && _o._tracks.Count > 0 && pos.Y >= _o.RowsHeight);+ if (_newTrackSources is not null) _moveRowDelta = 0;InvalidateVisual();return;}@@ -618,6 +623,16 @@ public sealed partial class ArrangementViewreturn;}+ if (_drag == Drag.Move && _groupMove is not null && _newTrackSources is { } sources)+ {+ var clips = _groupMove.Select(m => (m.track, m.clip, m.vm.StartBeat)).ToList();+ SetNewTrackRows(false);+ _groupMove = null; _drag = Drag.None; _moveRowDelta = 0;+ e.Pointer.Capture(null);+ _o.MoveClipsToNewTracks(sources, clips);+ return;+ }+if (_drag == Drag.Move && _groupMove is not null){int rowDelta = _moveRowDelta;@@ -625,6 +640,7 @@ public sealed partial class ArrangementView// the model, so a jiggle-and-release doesn't create a no-op undo step.bool moved = rowDelta != 0 || _groupMove.Any(m => Math.Abs(m.vm.StartBeat - m.origStart) > 1e-9);bool committed = false;+ Nota.Application.Editing.ClipBlockMove? move = null;if (eng is not null && moved){// One atomic group move: moving the clips one by one let an early clip@@ -636,11 +652,8 @@ public sealed partial class ArrangementView? _o._tracks[destRow].Id : m.track;return (m.track, m.clip, destTrack, m.vm.StartBeat);}).ToArray();- committed = eng.MoveClipBlock(moves);- // Same-track moves keep their clip index, so an open editor on one of- // them stays valid — but its START read-out is now off.- if (committed && rowDelta == 0)- foreach (var m in _groupMove) _o.RaiseClipGeometryChanged(m.track, m.clip);+ move = _o.MoveBlock(moves);+ committed = move is not null;if (committed && eng.LastMoveKeptDeviceAutomation()) // explicit hint: only Volume/Pan followed across tracks (req 8.3.4)_o.StatusMessage?.Invoke("Moved across tracks — device automation stayed on the source");}@@ -649,7 +662,8 @@ public sealed partial class ArrangementViewif (moved){_o.Refresh(); // also restores the preview if the engine rejected the move- if (committed) _o.ReselectPlaced(); // cross-track moves change indices+ if (committed) _o.ReselectPlaced(); // a move can change clip indices+ if (move is not null) _o.RaiseClipsMoved(move); // so can open editors' clipsif (committed && rowDelta != 0) _o.AnnounceSelectedTrack(); // the destination track is now the active one}else InvalidateVisual();@@ -698,6 +712,7 @@ public sealed partial class ArrangementView_rangeTrack = null;_adsrDrag = AdsrHandle.None; _adsrClip = null;SetLoadRow(-1);+ SetNewTrackRows(false);_autoScroll?.Stop();SetResizeCursor(false);_o.Refresh(); // reload authoritative clip/automation positions, discarding the preview@@ -1397,6 +1412,8 @@ public sealed partial class ArrangementViewDrawClipBody(ctx, dest.ColorIndex, dest.Name, m.vm, RowTop(destRow), RowH(destRow), true, pitches: pitches);}+ if (_groupMove is not null && _newTrackSources is { } srcs) DrawNewTrackGhosts(ctx, w, srcs);+// Clip marquee (plain drag on empty space).if (_marquee is { } mq) ctx.DrawRectangle(MarqueeFill, MarqueePen, mq);@@ -1595,7 +1612,47 @@ public sealed partial class ArrangementView}private bool IsDraggingCrossTrack(int track, int clip)- => _groupMove is not null && _moveRowDelta != 0 && _groupMove.Any(m => m.track == track && m.clip == clip);+ => _groupMove is not null && (_moveRowDelta != 0 || _newTrackSources is not null)+ && _groupMove.Any(m => m.track == track && m.clip == clip);++ // Shows or drops the new-track ghost rows below the lanes (#301), growing the lanes+ // so the rows can be scrolled to and drawn.+ private void SetNewTrackRows(bool on)+ {+ List<int>? sources = on && _groupMove is not null+ ? _groupMove.OrderBy(m => m.origRow).Select(m => m.track).Distinct().ToList()+ : null;+ if (sources is { Count: 0 }) sources = null;+ if ((sources?.Count ?? 0) == (_newTrackSources?.Count ?? 0)) { _newTrackSources = sources; return; }+ _newTrackSources = sources;+ Height = Math.Max(DefaultRowHeight, _o.RowsHeight) + (sources?.Count ?? 0) * DefaultRowHeight;+ _o._overlay.Height = Height;+ }++ // The rows a drop below the last track creates: a drop ring per new track, with the+ // dragged clips previewed in it at their new beats.+ private void DrawNewTrackGhosts(DrawingContext ctx, double w, List<int> sources)+ {+ double top = _o.RowsHeight;+ for (int k = 0; k < sources.Count; k++)+ {+ var r = new Rect(0, top + k * DefaultRowHeight, w, DefaultRowHeight);+ ctx.FillRectangle(DropWash, r);+ ctx.DrawRectangle(null, DropEdgePen, r.Deflate(1));+ var ft = new FormattedText("New track", CultureInfo.InvariantCulture, FlowDirection.LeftToRight,+ Typeface.Default, 11, RulerText);+ ctx.DrawText(ft, new Point(Math.Max(8, w - ft.Width - 12), r.Y + 4)); // clear of clips at the song start+ }+ using (ctx.PushOpacity(0.5))+ foreach (var m in _groupMove!)+ {+ int k = sources.IndexOf(m.track);+ var src = _o._tracks.FirstOrDefault(t => t.Id == m.track);+ if (k < 0 || src is null) continue;+ DrawClipBody(ctx, src.ColorIndex, src.Name, m.vm, top + k * DefaultRowHeight, DefaultRowHeight, true,+ pitches: TrackPitchRange(new[] { m.vm }));+ }+ }// Draws one clip (fill + border + name strip + notes/waveform) at row-y with// the given track colour. Reused for the live cross-track drag preview.diff --git a/src/managed/Nota.App/ArrangementView.NewTrackDrop.cs b/src/managed/Nota.App/ArrangementView.NewTrackDrop.csnew file mode 100644index 00000000..3b1d3465--- /dev/null+++ b/src/managed/Nota.App/ArrangementView.NewTrackDrop.cs@@ -0,0 +1,44 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Dropping clips below the last track (#301): each source track gets a new track like it+// (same kind, instrument and devices; no clips), inserted after the last regular track,+// and its clips move there at the beats they were dropped at. One undo step.++using System.Collections.Generic;+using System.Linq;++namespace Nota.App;++public partial class ArrangementView+{+ internal void MoveClipsToNewTracks(IReadOnlyList<int> sourceTracks, IReadOnlyList<(int track, int clip, double start)> clips)+ {+ if (_engine is null || sourceTracks.Count == 0 || clips.Count == 0) { Refresh(); return; }+ var newIds = new Dictionary<int, int>();+ Nota.Application.Editing.ClipBlockMove? move = null;+ bool ok = true;+ _engine.BeginUndoGroup();+ try+ {+ foreach (var src in sourceTracks)+ {+ int id = _engine.AddTrackLike(src);+ if (id < 0) { ok = false; break; }+ newIds[src] = id;+ }+ ok = ok && (move = MoveBlock(clips.Select(c => (c.track, c.clip, newIds[c.track], c.start)).ToArray())) is not null;+ }+ finally { _engine.EndUndoGroup(); }+ // Half-done (a source the engine wouldn't copy, or a refused move): take the tracks back.+ if (!ok && newIds.Count > 0) _engine.Undo();+ Refresh();+ if (!ok) { StatusMessage?.Invoke("Couldn't move the clips to new tracks"); return; }+ if (_engine.LastMoveKeptDeviceAutomation())+ StatusMessage?.Invoke("Moved to new tracks — device automation stayed on the source");+ ReselectPlaced();+ ClipsMoved?.Invoke(move!);+ RevealTrack(newIds[sourceTracks[^1]]);+ AfterTrackEdit();+ }+}diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex 6e17b6b6..4430d163 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -2308,13 +2308,17 @@ public sealed partial class ArrangementView : UserControltry { _engine?.OpenPluginEditor(t.Id, -1); } catch { /* builtin/no editor: no-op */ }return;}- // Shift- (or Ctrl/Cmd-) click adds the track to the multi-selection; again removes it.- if (e.GetCurrentPoint(card).Properties.IsLeftButtonPressed- && (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0)+ // Shift-click selects the range from the anchor; Ctrl/Cmd-click adds or removes one (#249).+ if (e.GetCurrentPoint(card).Properties.IsLeftButtonPressed){- ToggleTrackInSelection(t.Id); e.Handled = true; return;+ if ((e.KeyModifiers & KeyModifiers.Shift) != 0) { SelectTrackRange(t.Id); e.Handled = true; return; }+ if ((e.KeyModifiers & (KeyModifiers.Control | KeyModifiers.Meta)) != 0)+ {+ ToggleTrackInSelection(t.Id); _trackAnchorId = t.Id; e.Handled = true; return;+ }}_selTracks.Clear(); // a plain click resets the multi-selection to just this track+ _trackAnchorId = t.Id; // and is where a Shift-click range starts// Grab the title strip (top row, clear of the M/S/arm chips + faders below) to// start a reorder drag; selection is deferred to release so the capture survives// (Select rebuilds the headers). Returns aren't reorderable — select them outright.diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.csindex 71e7378d..d3658d28 100644--- a/src/managed/Nota.App/MainWindow.Detail.cs+++ b/src/managed/Nota.App/MainWindow.Detail.cs@@ -651,6 +651,118 @@ public partial class MainWindow}}+ // A block of clips moved in the arrangement (drag, ←/→, ⌥↑/⌥↓, a drop onto new tracks). The+ // editors address clips by index, and a move can re-index them: a landing that carves away a+ // clip in front shifts the ones after it, and a cross-track move appends. The open editors+ // follow their clips (RetargetEditors); the move is kept so an undo / redo of exactly it+ // takes them along (FollowMoveThroughHistory).+ private void OnClipsMoved(ClipBlockMove move)+ {+ _blockMoves.RemoveRange(_blockMovesDone, _blockMoves.Count - _blockMovesDone); // a new step drops the redo side+ _blockMoves.Add(move);+ if (_blockMoves.Count > 64) _blockMoves.RemoveAt(0);+ _blockMovesDone = _blockMoves.Count;+ RetargetEditors(move.Map);+ }++ // Recent block moves, oldest first; the first _blockMovesDone are done, the rest undone.+ private readonly List<ClipBlockMove> _blockMoves = new();+ private int _blockMovesDone;++ // After an undo / redo: when it took back the latest done block move (redid the earliest+ // undone one) — the touched tracks' clips are exactly as before (after) it — the editors'+ // indices go back (forward) with it. Any other step leaves those tracks otherwise and the+ // editors alone.+ private void FollowMoveThroughHistory()+ {+ if (_blockMovesDone > 0 && _blockMoves[_blockMovesDone - 1] is var undo+ && ArrangementMoves.SameStarts(Timeline.ClipStartsOf(undo.StartsBefore.Keys), undo.StartsBefore))+ {+ _blockMovesDone--;+ RetargetEditors(ArrangementMoves.Invert(undo.Map, undo.StartsAfter));+ }+ else if (_blockMovesDone < _blockMoves.Count && _blockMoves[_blockMovesDone] is var redo+ && ArrangementMoves.SameStarts(Timeline.ClipStartsOf(redo.StartsAfter.Keys), redo.StartsAfter))+ {+ _blockMovesDone++;+ RetargetEditors(redo.Map);+ }+ }++ // An editor whose clips kept their indices only re-reads their geometry; one whose clips+ // changed index is rebuilt on the new indices (dropping clips that no longer exist), so a+ // later note edit never lands in another clip.+ private void RetargetEditors(IReadOnlyDictionary<(int Track, int Clip), (int Track, int Clip)?> map)+ {+ (int Track, int Clip)? Where(int t, int c) => map.TryGetValue((t, c), out var to) ? to : (t, c);++ if (_editorRoll is { } roll && _clipEditor is not null && _editorTrackId > 0)+ {+ var open = roll.Clips.Clips;+ if (open.All(c => Where(c.TrackId, c.ClipIndex) == (c.TrackId, c.ClipIndex)))+ foreach (var c in open.Where(c => map.ContainsKey((c.TrackId, c.ClipIndex))).ToList())+ OnClipGeometryChanged(c.TrackId, c.ClipIndex);+ else+ {+ var now = open.Select(c => Where(c.TrackId, c.ClipIndex)).OfType<(int Track, int Clip)>().ToList();+ if (now.Count == 0) InvalidateClipEditor();+ else+ {+ var active = Where(roll.ActiveClip.TrackId, roll.ActiveClip.ClipIndex) ?? now[0];+ bool shown = ClipEditorShown(_clipEditor);+ BuildClipEditor(now, active.Track, active.Clip);+ if (shown) ShowClipPanel();+ }+ }+ }++ if (_audioEditor is { } audio && _audioEditorTrackId > 0 && SessionClip.SceneOf(_audioEditorClipIndex) < 0)+ {+ var to = Where(_audioEditorTrackId, _audioEditorClipIndex);+ if (to == (_audioEditorTrackId, _audioEditorClipIndex))+ {+ if (map.ContainsKey((_audioEditorTrackId, _audioEditorClipIndex))) audio.Reload();+ }+ else+ {+ bool shown = ClipEditorShown(audio);+ if (to is { } a)+ {+ BuildAudioClipEditor(a.Track, a.Clip);+ if (shown) ShowAudioClipPanel();+ }+ else+ {+ _audioEditor = null;+ _audioEditorTrackId = -1;+ _audioEditorClipIndex = -1;+ if (shown && DetailFloating) SetHost(_detailWindow!.ClipHost, ClipPlaceholder());+ else if (shown) DetailPanel.IsVisible = false;+ }+ }+ }++ if (_patternView is not null && _patternTrackId > 0 && _patternScene < 0)+ {+ var to = Where(_patternTrackId, _patternClipIndex);+ if (to is not { } p) InvalidatePatternView();+ else if (p == (_patternTrackId, _patternClipIndex))+ {+ if (map.ContainsKey(p)) _patternView.Reload(); // a carve can shorten it+ }+ else+ {+ bool shown = ClipEditorShown(_patternView);+ BuildPatternView(p.Track, p.Clip, -1);+ if (shown) ShowPatternPanel();+ }+ }+ }++ // Whether this editor is the one on screen (the docked detail panel, or the floating window's top pane).+ private bool ClipEditorShown(Control editor)+ => ReferenceEquals(ClipDetailHost.Content, editor) && (DetailFloating || DetailPanel.IsVisible);+private void ReloadEditorNotes(){_patternView?.Reload(); // the step grid is a second view of the same notesdiff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.csindex 72ce27bb..0d4cab54 100644--- a/src/managed/Nota.App/MainWindow.Files.cs+++ b/src/managed/Nota.App/MainWindow.Files.cs@@ -447,6 +447,8 @@ public partial class MainWindowTimeline.ClearPendingImports();Timeline.ForgetAutoTargets(); // lane targets are per-project track/device indicesResetClipEditor(); // every clip editor points into the old graph+ _blockMoves.Clear(); // ...and the clip moves it remembers are the old project's+ _blockMovesDone = 0;CloseDetail(); // collapse the docked row too, not just hide the panel_deviceChain?.ForgetCardState(); // per-track preset labels belong to the old projectTimeline.Refresh();diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.csindex 17a28cbe..8293d9b4 100644--- a/src/managed/Nota.App/MainWindow.Input.cs+++ b/src/managed/Nota.App/MainWindow.Input.cs@@ -290,6 +290,21 @@ public partial class MainWindowif (e.Key == Key.V && Timeline.PasteClipboard()) { _session?.Refresh(); _vm.StatusText = "Pasted clip(s)"; e.Handled = true; return; }}+ // ←/→ nudge the selected arrangement clips by the grid step (⌥: a 64th); ⌥↑/⌥↓ move them+ // to the next track that takes them (#302). Only with clips selected, and not while the+ // piano roll, the detail panel or the floating detail window has the keys.+ if (e.Key is Key.Left or Key.Right or Key.Up or Key.Down && Timeline.IsVisible && !_detailWasLastFocused+ && _detailWindow?.IsActive != true+ && _editorRoll is not { GridFocused: true }+ && (e.KeyModifiers & (KeyModifiers.Control | KeyModifiers.Meta | KeyModifiers.Shift)) == 0)+ {+ bool alt = (e.KeyModifiers & KeyModifiers.Alt) != 0;+ bool done = e.Key is Key.Left or Key.Right+ ? Timeline.NudgeSelectedClips(e.Key == Key.Right ? 1 : -1, fine: alt)+ : alt && Timeline.MoveSelectedClipsToTrack(e.Key == Key.Down ? 1 : -1);+ if (done) { _session?.Refresh(); e.Handled = true; return; }+ }+// Delete/Backspace = clear the selected automation range (automation mode), else// remove the selected arrangement clip. Only consumed when something is actually// selected, so the piano roll (which has focus + its own Delete handler) keepsdiff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.csindex 230497b5..ffe1f177 100644--- a/src/managed/Nota.App/MainWindow.Menu.cs+++ b/src/managed/Nota.App/MainWindow.Menu.cs@@ -67,9 +67,15 @@ public partial class MainWindow// chain is showing, which isn't always the selected one (a peek, the master, nothing// selected) — rebuilding the selected track's chain there showed the wrong devices.if (_deviceChain is { TrackId: > 0 } chain)- chain.Show(chain.TrackId == Engine.MasterTrackId || TrackExists(chain.TrackId)- ? chain.TrackId : Timeline.SelectedTrackId); // its track was undone away+ {+ if (chain.TrackId == Engine.MasterTrackId || TrackExists(chain.TrackId)) chain.Show(chain.TrackId);+ // Its track was undone away: follow the selection, or empty the chain when that+ // track went too (undoing a drop onto a new track) instead of naming a dead one.+ else if (TrackExists(Timeline.SelectedTrackId)) chain.Show(Timeline.SelectedTrackId);+ else ShowDevices(-1);+ }if (_modular?.IsVisible == true) _modular.Refresh();+ FollowMoveThroughHistory(); // undoing a clip move re-indexes clipsReloadEditorNotes(); // reflect clip/note edits// Volume / pan / master steps (specs/009): the master volume lives on the view model// (MST, Master row, Mixer and Remote follow it), the track strips in the Mixer rebuild.diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex d462e2b8..55dc9f95 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -423,6 +423,7 @@ public partial class MainWindow : Window_deviceChain.AddDeviceRequested += Browser.FocusEffectSearch; // the chain's "+" (#97)Timeline.TrackSelected += OnTrackSelected;Timeline.ClipGeometryChanged += OnClipGeometryChanged; // clip trimmed/moved → follow it in the open editor+ Timeline.ClipsMoved += OnClipsMoved; // a block move can re-index the open editor's clipsTimeline.StatusMessage += msg => { if (_vm is not null) _vm.StatusText = msg; }; // automation-follow hints etc._session = new SessionView(vm.Engine)diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex eadfa1ea..46c23f89 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1176,6 +1176,10 @@ public sealed partial class PreferencesWindow : NotaWindow("⌘E", "Split at the playhead · at the range edges"),("⌘J", "Consolidate the selection into one clip per track"),("0", "Deactivate / activate the selected clip(s)"),+ ("← →", "Nudge the selected clips by the grid step · stops at the song start"),+ ("⌥← ⌥→", "Nudge the selected clips by a 64th note"),+ ("⌥↑ ⌥↓", "Move the selected clips to the next track that takes them, at the same beats"),+ ("Drag below the last track", "Move the clips to a new track like their own · one per source track"),("Delete", "Delete the selected clip / range"),}),("Grid (Arrangement or clip editor — whichever you used last)", new[]@@ -1190,6 +1194,7 @@ public sealed partial class PreferencesWindow : NotaWindow("Tracks (after a click in the track headers)", new[]{("⌘A", "Select all tracks"),+ ("⇧-click ⌘-click", "Select a range of tracks / add or remove one track"),("⌘C ⌘X ⌘V", "Copy / cut / paste the selected tracks · paste lands after the last one"),("⌘D", "Duplicate the selected tracks"),("Delete", "Delete the selected tracks · a group goes with its tracks"),diff --git a/src/managed/Nota.Application/Editing/ArrangementMoves.cs b/src/managed/Nota.Application/Editing/ArrangementMoves.csnew file mode 100644index 00000000..73f7eaa9--- /dev/null+++ b/src/managed/Nota.Application/Editing/ArrangementMoves.cs@@ -0,0 +1,123 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Keyboard moves in the Arrangement (specs/039-arrangement-keyboard-moves): how far ←/→ nudge+// a clip selection (#302), which rows ⌥↑/⌥↓ move it to, and the track range a Shift-click on+// a header selects (#249). 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 committed block move: where each clip of the touched tracks went (<see+/// cref="ArrangementMoves.Reindex"/>), and the touched tracks' clip starts before and after —+/// which tell an undo or redo of exactly this move apart from any other step.</summary>+public sealed record ClipBlockMove(+ IReadOnlyDictionary<(int Track, int Clip), (int Track, int Clip)?> Map,+ IReadOnlyDictionary<int, IReadOnlyList<double>> StartsBefore,+ IReadOnlyDictionary<int, IReadOnlyList<double>> StartsAfter);++public static class ArrangementMoves+{+ /// <summary>The fine nudge (⌥←/⌥→): a 64th note, whatever the grid.</summary>+ public const double FineNudgeBeats = 1.0 / 16;++ /// <summary>The beat shift for nudging a selection whose earliest clip starts at+ /// <paramref name="firstStart"/> by <paramref name="step"/> in direction <paramref name="dir"/>+ /// (-1 left, +1 right). The block moves as one and stops at the song start, so a nudge left+ /// that would cross it moves only as far as it goes; 0 when nothing can move.</summary>+ public static double NudgeDelta(double firstStart, double step, int dir)+ {+ if (step <= 0 || dir == 0) return 0;+ double d = Math.Sign(dir) * step;+ if (firstStart + d < 0) d = -Math.Max(0, firstStart);+ return Math.Abs(d) < 1e-9 ? 0 : d;+ }++ /// <summary>The row shift that moves clips on <paramref name="rows"/> to the nearest rows in+ /// direction <paramref name="dir"/> where every one of them lands on a row that takes it+ /// (<paramref name="accepts"/>(from, to)) — so an audio clip skips over instrument tracks.+ /// 0 when no such rows exist before the edge.</summary>+ public static int RowShift(IReadOnlyCollection<int> rows, int rowCount, int dir, Func<int, int, bool> accepts)+ {+ if (rows.Count == 0 || dir == 0) return 0;+ int step = Math.Sign(dir);+ for (int d = step; ; d += step)+ {+ if (rows.Any(r => r + d < 0 || r + d >= rowCount)) return 0;+ if (rows.All(r => accepts(r, r + d))) return d;+ }+ }++ /// <summary>The tracks a Shift-click on <paramref name="targetId"/> selects: every id from the+ /// anchor (the last plain- or ⌘-clicked track) to the target in <paramref name="order"/>+ /// (the rows as shown), in either direction. Just the target when the anchor isn't shown.</summary>+ public static IReadOnlyList<int> Range(IReadOnlyList<int> order, int anchorId, int targetId)+ {+ int a = IndexOf(order, anchorId), t = IndexOf(order, targetId);+ if (t < 0) return Array.Empty<int>();+ if (a < 0) return new[] { targetId };+ int lo = Math.Min(a, t), hi = Math.Max(a, t);+ var ids = new int[hi - lo + 1];+ for (int i = lo; i <= hi; i++) ids[i - lo] = order[i];+ return ids;+ }++ /// <summary>Where each clip of the tracks a block move touched is afterwards. Clips are+ /// addressed by index, and a move re-indexes them: a landing carves away or splits clips in+ /// front of others, and a clip arriving from another track is appended. A moved clip is where+ /// the engine placed it (<paramref name="moved"/>[i] → <paramref name="placed"/>[i]); a clip+ /// that stayed is found by its start, which a carve of its tail keeps; null when it was carved+ /// away or lost its head. <paramref name="startsBefore"/> / <paramref name="startsAfter"/>:+ /// each touched track's clip starts, by index.</summary>+ public static Dictionary<(int Track, int Clip), (int Track, int Clip)?> Reindex(+ IReadOnlyDictionary<int, IReadOnlyList<double>> startsBefore,+ IReadOnlyList<(int Track, int Clip)> moved, IReadOnlyList<(int Track, int Clip)> placed,+ IReadOnlyDictionary<int, IReadOnlyList<double>> startsAfter)+ {+ var map = new Dictionary<(int, int), (int, int)?>();+ for (int i = 0; i < moved.Count && i < placed.Count; i++) map[moved[i]] = placed[i];+ var taken = new HashSet<(int, int)>(placed);+ foreach (var (track, starts) in startsBefore)+ {+ var after = startsAfter.TryGetValue(track, out var a) ? a : Array.Empty<double>();+ for (int c = 0; c < starts.Count; c++)+ {+ if (map.ContainsKey((track, c))) continue;+ (int, int)? to = null;+ for (int j = 0; j < after.Count; j++)+ if (!taken.Contains((track, j)) && Math.Abs(after[j] - starts[c]) < 1e-9) { to = (track, j); break; }+ map[(track, c)] = to;+ }+ }+ return map;+ }++ /// <summary>The way back: where each clip is after undoing a move that re-indexed with+ /// <paramref name="map"/>. A clip the move didn't produce on a touched track (a carve's right+ /// piece) has no place before it: null. Clips of other tracks are not in either map.</summary>+ public static Dictionary<(int Track, int Clip), (int Track, int Clip)?> Invert(+ IReadOnlyDictionary<(int Track, int Clip), (int Track, int Clip)?> map,+ IReadOnlyDictionary<int, IReadOnlyList<double>> startsAfter)+ {+ var back = new Dictionary<(int, int), (int, int)?>();+ foreach (var (track, starts) in startsAfter)+ for (int c = 0; c < starts.Count; c++) back[(track, c)] = null;+ foreach (var (from, to) in map)+ if (to is { } t) back[t] = from;+ return back;+ }++ /// <summary>Whether two snapshots of track clip starts are the same.</summary>+ public static bool SameStarts(IReadOnlyDictionary<int, IReadOnlyList<double>> a, IReadOnlyDictionary<int, IReadOnlyList<double>> b)+ => a.Count == b.Count && a.All(kv => b.TryGetValue(kv.Key, out var o) && o.Count == kv.Value.Count+ && o.Zip(kv.Value).All(p => Math.Abs(p.First - p.Second) < 1e-9));++ private static int IndexOf(IReadOnlyList<int> order, int id)+ {+ for (int i = 0; i < order.Count; i++) if (order[i] == id) return i;+ return -1;+ }+}diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 87b4b492..34c85fea 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -67,6 +67,7 @@ public interface IAudioEngine : IDisposablevoid SetTrackSolo(int trackId, bool solo);int TrackCount { get; }int DuplicateTrack(int trackId); // deep copy after the source; new id or -1+ int AddTrackLike(int trackId); // empty track with the source's instrument, devices and mix, before the returns; new id or -1bool RemoveTrack(int trackId);void MoveTrack(int trackId, int toIndex); // reorder a non-return track within the regular listint AddGroupTrack(); // empty top-level group (submix) trackdiff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.csindex a8aece8d..bf896fbc 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs@@ -33,6 +33,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_duplicate_track")]internal static partial int DuplicateTrack(IntPtr engine, int trackId);+ [LibraryImport(Lib, EntryPoint = "nota_engine_add_track_like")]+ internal static partial int AddTrackLike(IntPtr engine, int trackId);+[LibraryImport(Lib, EntryPoint = "nota_engine_remove_track")]internal static partial NotaResult RemoveTrack(IntPtr engine, int trackId);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.csindex 3ece3bcc..9595dcff 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs@@ -31,6 +31,10 @@ public sealed partial class NotaEngine/// <summary>Duplicate a track (deep copy) after the source; returns the new id or -1.</summary>public int DuplicateTrack(int trackId) { ThrowIfDisposed(); return NativeMethods.DuplicateTrack(_handle, trackId); }+ /// <summary>A new last track built like <paramref name="trackId"/>: its instrument, devices,+ /// mixer and sends, but no clips, Session clips or automation (#301). New id, or -1 for an+ /// unknown id, a return, a group, or an instrument / device that didn't copy. One undo step.</summary>+ public int AddTrackLike(int trackId) { ThrowIfDisposed(); return NativeMethods.AddTrackLike(_handle, trackId); }/// <summary>Remove a track. False if the id is unknown.</summary>public bool RemoveTrack(int trackId) { ThrowIfDisposed(); return NativeMethods.RemoveTrack(_handle, trackId) == NativeMethods.NotaResult.Ok; }/// <summary>Reorder a non-return track to toIndex within the regular track list.</summary>diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex ecfa43c5..198289e8 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -521,6 +521,11 @@ NOTA_API int32_t nota_engine_track_count(const NotaEngine* engine);* source and returns the new id (-1 on failure); remove drops the track. */NOTA_API int32_t nota_engine_duplicate_track(NotaEngine* engine, int32_t track_id);NOTA_API NotaResult nota_engine_remove_track(NotaEngine* engine, int32_t track_id);+/* A new last regular track built like track_id: same instrument, MIDI effects, devices,+ * mixer and sends, but no clips, session clips or automation; top level, default name and+ * colour, not armed. Returns the new id, -1 for an unknown id, a return, a group, or an+ * instrument / device that didn't copy (a plugin that won't load again). One undo step. */+NOTA_API int32_t nota_engine_add_track_like(NotaEngine* engine, int32_t track_id);/* Reorders a non-return track to to_index within the regular (non-return) track list;* returns/master keep their trailing slots. No-op for return tracks. Checkpoints undo. */NOTA_API NotaResult nota_engine_move_track(NotaEngine* engine, int32_t track_id, int32_t to_index);diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cppindex fd9fe23e..1b6610f7 100644--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp@@ -51,6 +51,9 @@ int32_t nota_engine_track_count(const NotaEngine* e) {int32_t nota_engine_duplicate_track(NotaEngine* e, int32_t track_id) {return e ? ENG(e)->duplicateTrack(track_id) : -1;}+int32_t nota_engine_add_track_like(NotaEngine* e, int32_t track_id) {+ return e ? ENG(e)->addTrackLike(track_id) : -1;+}NotaResult nota_engine_remove_track(NotaEngine* e, int32_t track_id) {if (!e) return NOTA_ERR_INVALID_ARG;return ENG(e)->removeTrack(track_id) ? NOTA_OK : NOTA_ERR_INVALID_ARG;diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 232d4953..91f25f65 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -336,6 +336,11 @@ class Engine {// plugins re-instantiate with state) and inserts the copy after the source;// returns the new id (or -1). removeTrack drops it. Both checkpoint undo.int32_t duplicateTrack(int32_t trackId);+ // A new last regular track built like trackId: the same instrument, MIDI effects, devices,+ // mixer and sends, but no clips, Session clips or automation, top level, default name and+ // colour, not armed. Where clips dragged below the last track land (#301). New id or -1+ // (unknown id, a return, a group, or an instrument / device that didn't copy). Checkpoints undo.+ int32_t addTrackLike(int32_t trackId);bool removeTrack(int32_t trackId);// Reorders a non-return track to toIndex within the regular (non-return) track list;// returns/master keep their slots. Checkpoints undo. No-op for return tracks.@@ -1343,7 +1348,7 @@ class Engine {SessionSlot slotFromAudioClip(const AudioClip& a);// Build a fully independent copy of a track (fresh id + cloned instrument/devices).- std::shared_ptr<Track> deepCloneTrack(const Track& src, int32_t newId);+ std::shared_ptr<Track> deepCloneTrack(const Track& src, int32_t newId, bool withContent = true);// The tracks in ids plus every descendant of a group among them, in engine order.std::vector<std::shared_ptr<Track>> expandTrackSet(const int32_t* ids, int32_t n) const;void compactReturns(Graph& g) const; // renumber return buses 0..n-1 + remap sends (after a delete)diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cppindex c73d653e..570b4cbe 100644--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp@@ -3068,7 +3068,8 @@ bool Engine::deleteClip(int32_t trackId, int32_t clipIndex) {// Fully independent copy of a track: cloned instrument/MIDI-FX/insert devices (own DSP// state), copied clips/automation with fresh warp stretchers, and the UI metadata.-std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId) {+// withContent = false leaves out what it plays: clips, Session slots and automation.+std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId, bool withContent) {auto nt = std::make_shared<Track>(newId, src.type());nt->setVolume(src.volume());nt->setPan(src.pan());@@ -3081,10 +3082,12 @@ std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId) {nt->setMonitor(src.monitor());nt->setMidiFromTrackId(src.midiFromTrackId());for (int b = 0; b < kMaxReturns; ++b) nt->setSend(b, src.send(b));- nt->clips = src.clips; // sample buffers are shared_ptr (immutable) — fine- nt->midiClips = src.midiClips;- nt->sessionSlots = src.sessionSlots;- nt->automation = src.automation;+ if (withContent) {+ nt->clips = src.clips; // sample buffers are shared_ptr (immutable) — fine+ nt->midiClips = src.midiClips;+ nt->sessionSlots = src.sessionSlots;+ nt->automation = src.automation;+ }nt->name = src.name;nt->colorIndex = src.colorIndex;nt->instrument = cloneInstrument(src);@@ -3119,6 +3122,41 @@ int32_t Engine::duplicateTrack(int32_t trackId) {return newId;}+int32_t Engine::addTrackLike(int32_t trackId) {+ if (trackId == kMasterTrackId) return -1;+ auto src = findTrackAuthoring(trackId);+ if (!src || src->type() == TrackType::Return || src->type() == TrackType::Group) return -1;+ const int32_t newId = nextTrackId_++;+ auto nt = deepCloneTrack(*src, newId, /*withContent=*/false); // publish sizes the Session slots, all empty+ // The source's clips move onto this track, so it must sound the same: refuse it when the+ // instrument or any device didn't copy (a plugin that won't load a second instance).+ if (static_cast<bool>(src->instrument) != static_cast<bool>(nt->instrument)+ || src->midiEffects.size() != nt->midiEffects.size() || src->devices.size() != nt->devices.size())+ return -1;+ nt->setGroupId(-1);+ nt->setArmed(false);+ nt->name.clear();+ nt->colorIndex = -1;++ // After the last regular track. Returns aren't always trailing in the graph (a track+ // added later is appended after them), so place it by the last regular track, not+ // in front of the first return.+ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, *authoring_);+ g->tracks.reserve(authoring_->tracks.size() + 1);+ std::ptrdiff_t lastRegular = -1;+ for (std::size_t i = 0; i < authoring_->tracks.size(); ++i)+ if (authoring_->tracks[i]->type() != TrackType::Return) lastRegular = static_cast<std::ptrdiff_t>(i);+ if (lastRegular < 0) g->tracks.push_back(nt);+ for (std::size_t i = 0; i < authoring_->tracks.size(); ++i) {+ g->tracks.push_back(authoring_->tracks[i]);+ if (static_cast<std::ptrdiff_t>(i) == lastRegular) g->tracks.push_back(nt);+ }+ publish(std::move(g));+ recomputePdc();+ return newId;+}+bool Engine::removeTrack(int32_t trackId) {auto rt = findTrackAuthoring(trackId);if (!rt) return false;diff --git a/tests/Nota.SmokeTest/ArrangementMovesTests.cs b/tests/Nota.SmokeTest/ArrangementMovesTests.csnew file mode 100644index 00000000..93c9cbe6--- /dev/null+++ b/tests/Nota.SmokeTest/ArrangementMovesTests.cs@@ -0,0 +1,138 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Arrangement keyboard moves and drop-below-the-last-track (specs/039-arrangement-keyboard-moves):+// the nudge step stops at the song start (#302), ⌥↑/⌥↓ skip rows that can't take the clips,+// a Shift-click selects the header range (#249), and a track "like" a source copies its+// instrument and devices but nothing it played, ahead of the returns, in one undo step (#301).++using Nota.Application;+using Nota.Application.Editing;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class ArrangementMovesTests+{+ private const int Utility = 4;++ public static IEnumerable<(bool ok, string label)> Run()+ {+ // Nudge: a full step, clamped at 0, nothing at 0.+ yield return (ArrangementMoves.NudgeDelta(4, 1, +1) == 1 && ArrangementMoves.NudgeDelta(4, 1, -1) == -1,+ "moves: ←/→ nudge by the grid step");+ yield return (ArrangementMoves.NudgeDelta(0.25, 1, -1) == -0.25, "moves: a nudge left stops at the song start");+ yield return (ArrangementMoves.NudgeDelta(0, 1, -1) == 0, "moves: nothing moves left of the song start");++ // Row shift: rows 0 (audio) 1 (instrument) 2 (audio) 3 (audio); audio only on audio.+ bool[] audio = { true, false, true, true };+ bool Accepts(int from, int to) => audio[from] == audio[to];+ yield return (ArrangementMoves.RowShift(new[] { 0 }, 4, +1, Accepts) == 2, "moves: ⌥↓ skips a track that can't take the clip");+ yield return (ArrangementMoves.RowShift(new[] { 2, 3 }, 4, +1, Accepts) == 0, "moves: ⌥↓ at the last track does nothing");+ // Rows 0 1 audio, 2 instrument, 3 4 audio: a block on 3+4 can't stop half on row 2.+ bool[] five = { true, true, false, true, true };+ yield return (ArrangementMoves.RowShift(new[] { 3, 4 }, 5, -1, (f, t) => five[f] == five[t]) == -3,+ "moves: a two-row block moves until every clip lands on a track that takes it");+ yield return (ArrangementMoves.RowShift(new[] { 2, 3 }, 4, -1, Accepts) == 0,+ "moves: no shift when the block can't fit on matching tracks");++ // Header range: either direction, unknown anchor → just the target.+ int[] order = { 10, 11, 12, 13 };+ yield return (ArrangementMoves.Range(order, 13, 11).SequenceEqual(new[] { 11, 12, 13 }), "moves: Shift-click selects up to the anchor");+ yield return (ArrangementMoves.Range(order, 99, 12).SequenceEqual(new[] { 12 }), "moves: no anchor selects just the clicked track");+ yield return (ArrangementMoves.Range(order, 10, 99).Count == 0, "moves: a hidden target selects nothing");++ // Re-indexing after a block move: a nudge of clip 1 over all of clip 0 carves clip 0+ // away, so clip 1 becomes clip 0 and clip 2 becomes clip 1 (Greptile on #324: an open+ // editor kept the old index and its next edit went into another clip).+ using (var re = new NotaEngine())+ {+ int t = re.AddInstrumentTrack();+ re.AddMidiClip(t, 4.0, 1.0);+ re.AddMidiClip(t, 5.0, 2.0);+ re.AddMidiClip(t, 12.0, 2.0);+ IReadOnlyList<double> Starts()+ {+ var l = new List<double>();+ while (re.TryGetClipInfo(t, l.Count, out var ci)) l.Add(ci.StartBeat);+ return l;+ }+ var before = new Dictionary<int, IReadOnlyList<double>> { [t] = Starts() };+ bool ok = re.MoveClipBlock(new[] { (t, 1, t, 4.0) });+ var map = ArrangementMoves.Reindex(before, new[] { (t, 1) }, re.LastPlacedClips(),+ new Dictionary<int, IReadOnlyList<double>> { [t] = Starts() });+ yield return (ok && map[(t, 1)] == (t, 0) && map[(t, 0)] is null && map[(t, 2)] == (t, 1),+ $"moves: after a move that carves a clip away, clips are found at their new indices ({string.Join(", ", map.Select(kv => $"{kv.Key.Clip}→{kv.Value?.Clip.ToString() ?? "gone"}"))})");+ // Undo brings the carved clip back: an editor on the moved clip (now 0) goes back to+ // 1, and one on the clip behind it (now 1) back to 2 (Greptile on #324, round 2).+ var after = new Dictionary<int, IReadOnlyList<double>> { [t] = Starts() };+ var inverse = ArrangementMoves.Invert(map, after);+ bool undone = re.Undo();+ var restored = new Dictionary<int, IReadOnlyList<double>> { [t] = Starts() };+ yield return (undone && ArrangementMoves.SameStarts(restored, before) && !ArrangementMoves.SameStarts(restored, after)+ && inverse[(t, 0)] == (t, 1) && inverse[(t, 1)] == (t, 2),+ "moves: undoing the move is recognised, and sends the clips back to their old indices");+ yield return (re.Redo() && ArrangementMoves.SameStarts(new Dictionary<int, IReadOnlyList<double>> { [t] = Starts() }, after),+ "moves: redoing it is recognised too");+ }+ var cross = ArrangementMoves.Reindex(+ new Dictionary<int, IReadOnlyList<double>> { [1] = new[] { 0.0, 8.0 }, [2] = new[] { 0.0 } },+ new[] { (1, 0) }, new[] { (2, 1) },+ new Dictionary<int, IReadOnlyList<double>> { [1] = new[] { 8.0 }, [2] = new[] { 0.0, 4.0 } });+ yield return (cross[(1, 0)] == (2, 1) && cross[(1, 1)] == (1, 0) && cross[(2, 0)] == (2, 0),+ "moves: a clip moved to another track is where it landed, and the ones left behind close up");++ // A track like the source.+ using var eng = new NotaEngine();+ int inst = eng.AddInstrumentTrack();+ eng.AddBuiltinDevice(inst, Utility);+ eng.SetTrackVolume(inst, 0.5f);+ int clip = eng.AddMidiClip(inst, 4.0, 4.0);+ eng.AddAutomationLane(inst, AutomationTarget.Pan, -1, -1);+ int ret = eng.AddReturnTrack();+ int kind = eng.TrackInstrumentKind(inst);++ int like = eng.AddTrackLike(inst);+ int idx = IndexOf(eng, like);+ yield return (like > 0 && idx == IndexOf(eng, ret) - 1, $"moves: the new track lands before the returns (row {idx})");+ eng.TryGetTrackInfo(idx, out var info);+ yield return (info.IsInstrument && eng.TrackInstrumentKind(like) == kind && eng.TrackDeviceCount(like) == eng.TrackDeviceCount(inst),+ "moves: it has the source's instrument and devices");+ yield return (info.ClipCount == 0 && eng.AutomationLaneCount(like) == 0 && info.GroupId == -1,+ "moves: it has no clips, automation or group");+ yield return (Math.Abs(info.Volume - 0.5f) < 1e-4, "moves: it keeps the source's mix");++ // Track + clip move undo together.+ int track0 = eng.TrackCount;+ eng.BeginUndoGroup();+ int like2 = eng.AddTrackLike(inst);+ bool moved = eng.MoveClipBlock(new[] { (inst, clip, like2, 8.0) });+ eng.EndUndoGroup();+ eng.TryGetClipInfo(like2, 0, out var ci);+ yield return (moved && Math.Abs(ci.StartBeat - 8.0) < 1e-9, "moves: a clip moves onto the new track at its drop beat");+ yield return (eng.Undo() && eng.TrackCount == track0 && eng.TryGetClipInfo(inst, clip, out var back) && Math.Abs(back.StartBeat - 4.0) < 1e-9,+ "moves: one undo takes back the move and the new track");++ // A track added after the returns exist sits after them in the graph; the new track+ // still goes below the last regular track, not above it (Mac check of #324).+ int late = eng.AddInstrumentTrack();+ int like3 = eng.AddTrackLike(inst);+ yield return (like3 > 0 && IndexOf(eng, like3) == IndexOf(eng, late) + 1,+ $"moves: the new track lands below the last track added (row {IndexOf(eng, like3)}, last track row {IndexOf(eng, late)})");++ // Only regular tracks have a "like".+ int grp = eng.CreateGroup(new[] { inst });+ yield return (eng.AddTrackLike(ret) == -1 && eng.AddTrackLike(grp) == -1 && eng.AddTrackLike(9999) == -1,+ "moves: no new track like a return, a group or an unknown id");+ int child = eng.AddTrackLike(inst);+ eng.TryGetTrackInfo(IndexOf(eng, child), out var ci2);+ yield return (child > 0 && ci2.GroupId == -1, "moves: a track like a group member is top-level");+ }++ private static int IndexOf(NotaEngine eng, int id)+ {+ for (int i = 0; i < eng.TrackCount; i++)+ if (eng.TryGetTrackInfo(i, out var t) && t.Id == id) return i;+ return -1;+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 6e736f2b..7a7266a4 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -337,6 +337,15 @@ if (args.Length >= 1 && args[0] == "--template")Console.WriteLine(failures == 0 ? "TEMPLATE PASSED" : $"TEMPLATE FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Arrangement keyboard moves / new tracks from a drop alone: `--moves`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--moves")+{+ Console.WriteLine("-- arrangement moves --");+ foreach (var (ok, label) in ArrangementMovesTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "MOVES PASSED" : $"MOVES FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}+// Linux desktop robustness alone: `--linux-desktop`. Also part of the full run.if (args.Length >= 1 && args[0] == "--linux-desktop"){@@ -15077,6 +15086,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("-- arrangement moves --");+foreach (var (ok, label) in ArrangementMovesTests.Run()) Check(ok, label);+Console.WriteLine("-- linux desktop --");foreach (var (ok, label) in LinuxDesktopTests.Run()) Check(ok, label);