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) Rearrange the song by moving sections with their content (#192) (#464)
Egor Khindikaynenfec5fc0ca83a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c1508c8d..e585c276 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Rearrange the song by its sections** (#192): drag a section in the Sections lane and it+ moves with everything in it — audio and MIDI clips (cut at its edges), automation on every+ track and the master, take lanes — to the boundary marked while you drag; the sections in+ between close up, and the song keeps its length. A ghost follows the pointer, the landing+ place and the new order show before you let go, and Esc cancels. The section's menu adds+ **Move earlier** / **Move later**, **Duplicate with content** (a copy goes right after it,+ pushing the rest later) and **Delete with content** (the rest moves up to close the gap);+ the command palette has the same four for the section at the playhead, and MCP has+ `move_section`, `duplicate_section_with_content` and `delete_section_with_content`. Each+ is one undo step. A section that overlaps another keeps its content where it is.- **Every release opens with its own splash art**: the launch screen now shows an abstractpicture generated from the version number. It is built from piano-roll notes, rhythmrings, waveform strata, panels, a Lissajous figure or fader rails, in a few of the@@ -169,6 +179,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.the same way.### Changed+- **Dragging a section now moves its content too** (#192). To move only the section marker,+ as before, hold ⌥ (Alt on Windows and Linux) while dragging; resizing a section's edges+ still never touches the music.- **The detail panel opens on double-click, not on every selection** (#308): clicking atrack, a clip, a mixer strip or a Session slot now only selects it, so the arrangement keepsits height on a small screen. While the panel is open it still follows the selection asdiff --git a/FEATURES.md b/FEATURES.mdindex a927b35e..aa65cef1 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -132,10 +132,21 @@ docks as a panel under any of the three, or floats in its own window — seeto zoom, double-click to fit the project.- **Sections** — a lane between the Overview and the ruler names spans of the song(Intro, Verse, Drop). Drag the empty lane to mark one, click it to jump the playhead- there, double-click to rename, drag its body or edges to move and resize it (always on- whole bars). Its menu loops the section, selects it as a time range across every track,- duplicates it or deletes it. Each edit is one undo step. Saved with the project (MCP- `list_sections` / `set_sections`); View ▸ Toggle sections hides it.+ there, double-click to rename, ⌥-drag its body to move the marker alone and drag its+ edges to resize it (always on whole bars). Its menu loops the section, selects it as a+ time range across every track, duplicates it or deletes it. Each edit is one undo step.+ Saved with the project (MCP `list_sections` / `set_sections`); View ▸ Toggle sections+ hides it.+ - **Rearranging by sections** — drag a section to another place in the song and+ everything in it goes along: audio and MIDI clips (cut at its edges), automation on every+ track and the master, take lanes. It lands on the boundary between sections marked while+ dragging (a ghost follows the pointer, the others show their new places, Esc cancels);+ the sections in between close up and the song keeps its length. The section menu's+ **Move earlier** / **Move later**, **Duplicate with content** (the rest moves later) and+ **Delete with content** (the rest moves up), and the same four palette commands for the+ section at the playhead, do it without dragging. One undo step each; a section that+ overlaps another keeps its content in place. MCP `move_section`,+ `duplicate_section_with_content`, `delete_section_with_content`.- **Automatic section names** — a new section is named "Section N" for its place in thesong, left to right, custom-named sections counted, and renumbers as sections are added,moved or deleted; a custom name never changes on its own. Renaming: Return keeps the name@@ -1419,7 +1430,8 @@ Coverage:- **Transport**: play/stop, tempo, time signature, loop, metronome, loop record mode(`set_loop_record_mode`; `get_transport` reports it).- **Project**: `get_overview` (a full snapshot); the arrangement's sections- (`list_sections`, `set_sections`); version history — `list_versions` (with what+ (`list_sections`, `set_sections`) and rearranging the song by them (`move_section`,+ `duplicate_section_with_content`, `delete_section_with_content`); version history — `list_versions` (with whateach changed), `save_version` with a note, `switch_version`, `annotate_version` (name, note,star). Deleting versions stays with the user.- **Tracks**: add and remove, volume/pan/mute/solo, groups, sends.diff --git a/specs/073-section-rearrange/checklists/requirements.md b/specs/073-section-rearrange/checklists/requirements.mdnew file mode 100644index 00000000..1a6424ee--- /dev/null+++ b/specs/073-section-rearrange/checklists/requirements.md@@ -0,0 +1,41 @@+# Specification Quality Checklist: Rearrange the song by moving sections with their content++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-11-03+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs)+- [x] Focused on user value and business needs+- [x] Written for non-technical stakeholders+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic (no implementation details)+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] No implementation details leak into specification++## Notes++- The Nota Context section names existing app behaviour (Insert silence / Duplicate time,+ the Sections lane) and the template's feature-area paths by design; the requirements+ themselves stay at the user-behaviour level. FR-014 (MCP) is a user-facing capability of+ Nota, not an implementation choice.+- Choices made without a clarification marker (worth confirming in `/speckit-clarify`):+ plain drag = reorder with content and a modifier drag = marker only; drop targets are+ section boundaries, not free bars; overlapping sections fall back to marker-only; Duplicate+ / Delete with content are out of scope.diff --git a/specs/073-section-rearrange/contracts/abi.md b/specs/073-section-rearrange/contracts/abi.mdnew file mode 100644index 00000000..6c3e4b79--- /dev/null+++ b/specs/073-section-rearrange/contracts/abi.md@@ -0,0 +1,62 @@+# Contract: C ABI, managed engine API and MCP tools++## C ABI (`src/native/nota.engine/include/nota/nota_engine.h`, next to `nota_engine_set_sections`)++```c+/* Section edits that carry the arrangement with them (specs/073). Indices are into the+ * start-sorted section list. Each is one undo step covering clips (audio + MIDI, cut at the+ * edges), automation (every track, the master track, master volume), take lanes and the+ * sections; the playhead does not move. Errors (NOTA_ERR_INVALID_ARG, nothing changed):+ * index out of range, a section that overlaps another, a target inside an overlap, or a+ * no-op. Message thread only. */++/* Move section `index` to boundary `to_boundary` (0..count): before section k, or after the+ * last when == count. The sections in between shift by its length; song length unchanged. */+NOTA_API NotaResult nota_section_move(NotaEngine* engine, int32_t index, int32_t to_boundary);++/* Insert a copy of section `index` and everything in its span right after it; the rest of+ * the song moves later by its length. The copy keeps the name (automatic stays automatic). */+NOTA_API NotaResult nota_section_duplicate_with_content(NotaEngine* engine, int32_t index);++/* Remove section `index` and everything in its span; the rest moves earlier by its length. */+NOTA_API NotaResult nota_section_delete_with_content(NotaEngine* engine, int32_t index);++/* 1 when section `index` overlaps another (with-content edits unavailable), else 0. */+NOTA_API int32_t nota_section_overlaps(const NotaEngine* engine, int32_t index);+```++## Managed (`Nota.Application/Engine/IAudioEngine.cs`, `Nota.Infrastructure/Interop`)++```csharp+/// <summary>Move section <paramref name="index"/> with its content to boundary+/// <paramref name="toBoundary"/> (0..Sections.Count). False when rejected / no-op.</summary>+bool MoveSection(int index, int toBoundary);+bool DuplicateSectionWithContent(int index);+bool DeleteSectionWithContent(int index);+bool SectionOverlaps(int index);+```++`NativeMethods.Tracks.cs` (or the sections partial) gets the four `LibraryImport`s.++## MCP (`Nota.Mcp/Tools/ProjectTools.cs`)++| Tool | Params | Returns | Notes |+|---|---|---|---|+| `move_section` | `index`, `toBoundary` | the section list (as `list_sections`) | error text when rejected (overlap, out of range, no-op) |+| `duplicate_section_with_content` | `index` | section list | |+| `delete_section_with_content` | `index` | section list | |++Descriptions spell out: indices are `list_sections` order; everything in the span moves;+one undo step.++## Command palette (`Nota.Application/Palette/CommandCatalog.cs`)++| Id | Title | Acts on |+|---|---|---|+| `edit.moveSectionEarlier` | Move section earlier | section at the playhead |+| `edit.moveSectionLater` | Move section later | section at the playhead |+| `edit.duplicateSectionWithContent` | Duplicate section with content | section at the playhead |+| `edit.deleteSectionWithContent` | Delete section with content | section at the playhead |++No section at the playhead / disabled case → status text, nothing changes (as+`edit.resetSectionName`).diff --git a/specs/073-section-rearrange/data-model.md b/specs/073-section-rearrange/data-model.mdnew file mode 100644index 00000000..9e13d1b3--- /dev/null+++ b/specs/073-section-rearrange/data-model.md@@ -0,0 +1,62 @@+# Data Model: Rearrange the song by moving sections with their content++No new persisted data: the project file shape (`SectionDto`, track clips, automation lanes)+is unchanged — a move only rewrites positions. This file describes the transient model the+operations work on.++## Section (existing — `Graph::sections`, `SectionInfo`, `ArrangementSection`)++| Field | Type | Rule |+|---|---|---|+| `startBeat` | double | ≥ 0 |+| `lengthBeats` | double | > 0 |+| `name` | string | `""` = automatic ("Section N" by position, specs/058) |++Kept sorted by start. **Overlapping** (derived): its span intersects another section's span+by more than 1e-6 beats. Overlapping sections take part in no with-content operation+(FR-009).++## Section boundary (new, transient)++An index `k` in `0..n` over the start-sorted sections.++| k | beat |+|---|---|+| `0..n-1` | `sections[k].startBeat` |+| `n` | `sections[n-1].startBeat + sections[n-1].lengthBeats` |++Moving section `i` to `k ∈ {i, i+1}` is a no-op. A boundary is invalid when its beat lies+strictly inside an overlap.++## Time-range move (new, transient — research R2)++`(a, b, d)` with `L = b − a > 0`, `d ∉ (a, b)`. Mapping `f(t)` for a timeline position:++```text+d <= a: t in [a,b) → t − (a − d); t in [d,a) → t + L; else t+d >= b: t in [a,b) → t + (d − b); t in [b,d) → t − L; else t+```++Applied to: MIDI and audio clips (pieces after cutting at `a`, `b`, `d`), automation lanes+(rebuilt from slices), take origins, section starts. A section move is+`(start_i, start_i + len_i, boundary(k))`.++## Time-range removal (new, transient — research R3)++`(a, b)`: content in `[a,b)` removed (clips cut at both edges), `t >= b → t − L`, sections+inside `[a,b)` removed.++## Range duplicate with sections (extends Duplicate time)++`(a, b)`: a copy of `[a,b)` is inserted at `b`, `t >= b → t + L`; sections inside `[a,b)` are+copied with the same name (automatic stays automatic) and their copies placed `+L`.++## State transitions (UI drag, `SectionsControl`)++```text+None ──press on body──▶ Pending ──moved > 3 px──▶ Reorder (no modifier)+ └────────────▶ Move (Option/Alt, or overlapping section)+Reorder ──release on new boundary──▶ engine MoveSection ─▶ None (one undo step)+Reorder ──release on no-op boundary / Esc──▶ None (nothing changed)+Pending ──release──▶ seek to section start (existing click)+```diff --git a/specs/073-section-rearrange/plan.md b/specs/073-section-rearrange/plan.mdnew file mode 100644index 00000000..e9297063--- /dev/null+++ b/specs/073-section-rearrange/plan.md@@ -0,0 +1,130 @@+# Implementation Plan: Rearrange the song by moving sections with their content++**Branch**: `feat/section-rearrange` | **Date**: 2026-11-03 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/073-section-rearrange/spec.md` (issue+[#192](https://github.com/nota-daw/nota/issues/192))++## Summary++Dragging a section in the Sections lane reorders the song: the section's span — every clip,+automation point, take and the section itself — is lifted out and inserted at a section+boundary, with the material in between shifting by its length (Option/Alt-drag keeps today's+marker-only move). The section menu, command palette and MCP gain Move earlier / later,+Duplicate with content and Delete with content. Technically: three new engine edits built on+one piecewise time-mapping primitive (`moveTimeRange`) plus `removeTimeRange`, each producing+a single graph snapshot (one undo step, AR-5), exposed through four C ABI calls; the managed+side adds a reorder drag mode with preview, menu / palette / MCP entries.++## Nota: Read Before Planning++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-5 (one immutable snapshot+ per edit), AR-6 (nothing new on the audio thread), AR-7 (C ABI only), AR-9 (the playhead is+ the transport's — not moved).+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill: the insertion bar+ is the orange accent (it marks what is live/chosen); the ghost uses the section fill at+ reduced opacity.+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 (managed app, Avalonia)++**Primary Dependencies**: none new++**Storage**: project file unchanged (positions only); no migration++**Audio-Thread Impact**: None new. Each edit is built on the message thread from authoring+copies and published as one immutable graph snapshot (`pushUndo` + `publishRaw`), like+`insertTime`. No allocation, lock or I/O added to the audio path.++**Testing**: `tests/Nota.SmokeTest` (engine through the C ABI, render comparisons, headless+UI checks as in `ArrangementMovesTests.cs`); headless app screenshots for the drag preview++**Target Platform**: macOS, Windows, Linux desktop++**Project Type**: desktop app (native engine + managed UI)++**Performance Goals**: release-to-redraw ≤ 200 ms on 50 tracks / 500 clips (SC-004); drag+preview at display rate (C#-only computation, no engine calls while dragging)++**Constraints**: one undo step per operation; zero change outside the affected window;+no dropout when edited during playback++**Scale/Scope**: ~4 engine functions (+ helpers), 4 ABI calls, 1 view file reworked+(`ArrangementView.Sections.cs`), menu / palette / MCP / shortcuts / docs entries++## Constitution Check++| Principle | Status |+|---|---|+| 0. Approved issue | ✅ #192 `approved`. Duplicate / Delete with content were added in clarification — **post a scope note on #192 before the PR** |+| I. Real-time safety | ✅ message-thread snapshot edits only (research R7) |+| II. Boundary discipline | ✅ four new pure-C functions in `nota_engine.h`; no JUCE |+| III. Licensing | ✅ no new files without SPDX header; no dependencies |+| IV. Verification gate | ✅ smoke test extended (quickstart § 1) |+| V. One logical change | ✅ one feature: section-level edits with content |+| VI. Docs in sync | ✅ CHANGELOG `[Unreleased]`, `nota-features`, `nota-docs`, `nota-shortcuts` |+| VII. Spec-first | ✅ this run |+| VIII. Rules not weakened | ✅ |++Post-design re-check: unchanged — all gates pass.++## Project Structure++### Documentation (this feature)++```text+specs/073-section-rearrange/+├── spec.md+├── plan.md # this file+├── research.md # R1–R9 decisions+├── data-model.md # boundaries, time mapping, drag states+├── quickstart.md # validation scenarios+├── contracts/abi.md # C ABI, managed API, MCP, palette+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # + nota_section_move / _duplicate_with_content /+│ # _delete_with_content / _overlaps+├── src/engine/Engine.h # + moveSection, duplicateSectionWithContent,+│ # deleteSectionWithContent, sectionOverlaps+├── src/engine/Engine_Tracks.cpp # + moveTimeRange / removeTimeRange helpers next to+│ # insertTime (reuse midiSlice, audioSlice, laneSlice)+└── src/abi/nota_engine_track.cpp # ABI wrappers++src/managed/+├── Nota.Application/Engine/IAudioEngine.cs # + 4 members+├── Nota.Application/Palette/CommandCatalog.cs # + 4 commands+├── Nota.Infrastructure/Interop/NativeMethods*.cs # + 4 imports+├── Nota.Infrastructure/Interop/NotaEngine*.cs # + 4 wrappers+├── Nota.App/ArrangementView.Sections.cs # Reorder mode, preview, auto-scroll,+│ # CancelGesture, menu entries, commands+├── Nota.App/MainWindow.Commands.cs # palette bindings+├── Nota.App/MainWindow.Input.cs # Esc → sections CancelGesture+├── Nota.App/PreferencesWindow.cs # Shortcuts rows+├── Nota.App/Languages/*.json # new strings+└── Nota.Mcp/Tools/ProjectTools.cs # 3 MCP tools++tests/Nota.SmokeTest/Program.cs (+ a SectionRearrangeTests.cs if the block grows)+CHANGELOG.md, FEATURES.md, ../nota-docs (EN + RU)+```++**Structure Decision**: engine-first. The engine owns the edit and its validation so the+drag, menu, palette and MCP share one implementation; `ArrangementView.Sections.cs` keeps all+section UI as today.++## Complexity Tracking++No constitution violations.++## Known limitations (documented, not addressed)++- Frozen tracks keep their old frozen render until re-frozen (same as Insert silence today).+- Insert silence / Duplicate time still don't move sections or takes; a follow-up issue can+ route them through the new helpers.diff --git a/specs/073-section-rearrange/quickstart.md b/specs/073-section-rearrange/quickstart.mdnew file mode 100644index 00000000..df314b49--- /dev/null+++ b/specs/073-section-rearrange/quickstart.md@@ -0,0 +1,45 @@+# Quickstart: validate section rearranging++## Prerequisites++- A Release engine build (`build/` stays Release; a `-O0` engine hangs and xruns).+- `scripts/build.sh` green before and after — it runs `tests/Nota.SmokeTest`.++## 1. Engine, through the C ABI (smoke test — the PR gate)++The smoke test gains a `Section rearrange (specs/073)` block next to the Insert silence tests+(`tests/Nota.SmokeTest/Program.cs`). It builds three back-to-back sections A [0,8) · B [8,16) ·+C [16,24) over two instrument tracks and one audio track, with a MIDI clip crossing A|B, a+volume ramp on one track and master volume automation, then checks:++| Case | Expect |+|---|---|+| `MoveSection(2, 1)` | order A · C · B; C's content at 8, B's at 16; the crossing clip cut at 8 and its B part at 16; automation values at 0, 8⁻, 8, 16⁻, 16, 24 match the corresponding original positions; nothing ≥ 24 moved |+| `MoveSection(0, 3)` | order B · C · A; A's content at 16 |+| `MoveSection(1, 1)` / `(1, 2)` | false; no undo step |+| Undo after a move | clips, lanes, sections identical to before; Redo repeats |+| `DuplicateSectionWithContent(1)` | B · B′ with B′ at 16, C at 24, B′ automatic name stays automatic |+| `DeleteSectionWithContent(1)` | A · C, C at 8, B's content gone |+| overlapping B and C | `SectionOverlaps` true; all three ops false, nothing changed |+| render compare (SC-002/003) | offline render after move + undo equals the render before; moved section's span renders the same at its new place (deterministic WAV clip, not synth notes — synth renders drift) |++## 2. MCP++With the app running and the MCP server enabled: `list_sections` → `move_section {index: 2,+toBoundary: 1}` → `list_sections` shows the new order; `move_section` on an overlapping+section returns the error text.++## 3. UI (headless app shots, then by hand)++1. Open a project with 4 sections and content in each.+2. Drag section 3 left: the ghost follows, the insertion bar jumps boundary to boundary at+ each section's midpoint, the others preview their new places.+3. Drop before section 2 → content follows, one ⌘Z restores.+4. Start a drag, press Esc → nothing changed.+5. ⌥-drag a section by two bars → only the marker moved.+6. Right-click: Move earlier disabled on the first section, Move later on the last; Duplicate /+ Delete with content work and undo.+7. Make two sections overlap → their with-content entries are disabled, a plain drag moves+ the marker and the status bar explains.+8. Repeat 3 during playback: no dropout (DropoutCounter stays 0), playhead keeps its time.+9. Preferences → Shortcuts lists both section drags.diff --git a/specs/073-section-rearrange/research.md b/specs/073-section-rearrange/research.mdnew file mode 100644index 00000000..03ad9a28--- /dev/null+++ b/specs/073-section-rearrange/research.md@@ -0,0 +1,131 @@+# Research: Rearrange the song by moving sections with their content++All spec decisions are settled (spec § Clarifications). This file records the technical+choices the plan rests on.++## R1 — Where the move happens: one engine edit, not a managed choreography++**Decision**: the engine does each with-content operation (move, duplicate, delete) as **one**+authoring edit: build a new `Graph` with every affected track cloned, sections rewritten,+then `pushUndo()` + `publishRaw()` once — the pattern `Engine::insertTime` already uses+(`Engine_Tracks.cpp`).++**Rationale**: FR-007 needs content and sections in a single undo step. Sections already live+in the graph snapshot (`Graph::sections`, specs/016), so a graph-level edit carries them for+free. Composing existing calls from C# (`CutRange` + `InsertTime` + `SetSections`) would make+three undo steps, use the user's clipboard, and publish three snapshots during playback.++**Alternatives considered**: managed composition with an undo "transaction" wrapper — no such+mechanism exists in the engine and adding one is a larger change than the edit itself.++## R2 — The primitive: move a time range, as a piecewise shift++**Decision**: a new `Engine::moveTimeRange(a, b, d)` — move `[a,b)` so it is inserted at+original-timeline position `d` (`d <= a` or `d >= b`). With `L = b − a` the timeline maps as:++| original span | `d <= a` (move earlier) | `d >= b` (move later) |+|---|---|---|+| `[a,b)` (moved) | `− (a − d)` | `+ (d − b)` |+| between `[d,a)` / `[b,d)` | `+ L` | `− L` |+| everything else | unchanged | unchanged |++Clips are cut at the three cut points (`a`, `b`, `d`) with the existing `midiSlice` /+`audioSlice` helpers, and each piece is shifted by its region's offset. Everything outside+`[min(a,d), max(b,d))` is untouched (FR-002, SC-005); total length never changes.++**Rationale**: the same cut rule as Insert silence / Duplicate time (spec Assumptions); one+mapping function drives clips, automation, takes and sections alike, which keeps them+consistent by construction.++**Alternatives considered**: "cut range with ripple, then insert at d'" — equivalent result+but needs the intermediate coordinate shift explained twice and two passes over every lane.++## R3 — Delete with content: `removeTimeRange(a, b)`++**Decision**: a new `Engine::removeTimeRange(a, b)`: clips cut at `a` and `b`, the inside+dropped, everything at or after `b` shifted by `−L`; sections inside `[a,b)` dropped and later+ones shifted. **Duplicate with content** reuses `insertTime(b, L, duplicate=true)`'s logic,+extended to copy and shift sections (R5).++## R4 — Automation continuity at cuts and joins (FR-005)++**Decision**: rebuild each lane over the affected window from `laneSlice` pieces (which+already carry the lane's exact value at both edges and keep a partial segment's curvature),+re-based to their new positions; points outside the window are kept as they are. At each+join the incoming piece starts with an explicit point at the edge value, so the curve inside+every piece plays exactly as before. A join between two pieces with different edge values+becomes a step at the join — the same behaviour Duplicate time has, and the only faithful+choice (the music on each side changes there too).++Applies to every track lane, the master track's lanes and `Graph::masterVolume`. Empty lanes+stay empty.++## R5 — Sections in the edit; overlap rule (FR-006, FR-009)++**Decision**: the engine takes **section indices**, not beats, for the user-facing ops:+`moveSection(index, boundary)`, `duplicateSectionWithContent(index)`,+`deleteSectionWithContent(index)`. It validates (index range, no-op, overlap) and applies the+R2 mapping to every section's start. A section overlaps if its span intersects any other+section's span by more than an epsilon. A section that overlaps another, or a drop boundary+that would land inside an overlap, is rejected (`NOTA_ERR_INVALID_ARG`) — the UI checks the+same predicate first to disable menu items and fall back to a marker-only drag.++Boundary `k` (0..n over the start-sorted list): `k < n` → `sections[k].start`;+`k == n` → end of the last section. `k == i` or `k == i + 1` is a no-op (no undo step).+With a gap between X and Y, boundary "before Y" is Y's start — the gap stays after X+(spec Edge Cases).++**Rationale**: indices keep the C ABI small and make the overlap rule the engine's to+enforce, so MCP gets the same validation as the UI (FR-014).++## R6 — Takes (specs/067) and frozen tracks++**Decision**: take lanes move by the mapping of their `originBeat` (a whole take travels with+the region its start is in). Comp clips are ordinary `AudioClip`s and are cut like any clip.+Frozen tracks: their clips move like any track's, but the frozen buffer is not re-rendered —+exactly what Insert silence does on a frozen track today. Recorded as a known limitation,+unchanged by this feature.++**Note**: `insertTime` does not move takes or sections today. Fixing that for Insert silence /+Duplicate time is out of scope (separate issue), but the duplicate-with-content path shares the+new code and does move both.++## R7 — Real-time safety (AR-4/5/6)++All work happens on the message thread on authoring copies; the audio thread sees one+atomic snapshot swap (`publishRaw`). No new audio-thread code. The playhead (transport+position, AR-9) is not touched (FR-011).++## R8 — UI drag model++**Decision**: `SectionsControl` gains a `Reorder` mode (plain body drag) next to the existing+`Move` (now Option/Alt only, checked at press time and live while dragging). In `Reorder`:++- the target boundary is chosen by comparing the dragged section's middle (the ghost's centre)+ with each other section's midpoint (US2 scenario 1) — not the pointer, so the grab point+ doesn't shift where it lands;+- render: the dragged span as a ghost under the pointer, a 2 px accent insertion bar at the+ target boundary, and the other sections drawn at their preview positions (same R2 mapping,+ computed in C#);+- edge auto-scroll reuses the lane's `EnsureAutoScroll` pattern+ (`ArrangementView.LaneControl.cs`);+- Escape cancels through a `CancelGesture()` like the lane's and is routed from+ `MainWindow.Input.cs`;+- release on a no-op boundary or before the 3 px drag threshold: nothing happens (a click+ still seeks, as today).++No new engine call happens until release, so the drag itself has no audio effect.++## R9 — Surfaces++- Section menu: **Move earlier**, **Move later**, **Duplicate with content**, **Delete with+ content** (disabled at the ends / for overlapping sections).+- Command palette (`CommandCatalog.cs` + `MainWindow.Commands.cs`), section at the playhead:+ `edit.moveSectionEarlier`, `edit.moveSectionLater`, `edit.duplicateSectionWithContent`,+ `edit.deleteSectionWithContent`; each reports in the status bar like+ `edit.resetSectionName`.+- MCP (`Nota.Mcp/Tools/ProjectTools.cs`): `move_section`, `duplicate_section_with_content`,+ `delete_section_with_content`.+- Preferences → Shortcuts (`PreferencesWindow.cs`): "Drag section" → reorder with content,+ "⌥-drag section" → move the marker only.+- Strings via `Loc.T` with entries in `Nota.App/Languages/*.json`.diff --git a/specs/073-section-rearrange/spec.md b/specs/073-section-rearrange/spec.mdnew file mode 100644index 00000000..78eba9df--- /dev/null+++ b/specs/073-section-rearrange/spec.md@@ -0,0 +1,341 @@+# Feature Specification: Rearrange the song by moving sections with their content++**Feature Branch**: `feat/section-rearrange`++**Created**: 2026-11-03++**Status**: Draft++**Input**: GitHub issue [#192](https://github.com/nota-daw/nota/issues/192) (approved): "When I+move a section, everything within that section moves with it — every audio clip, MIDI clip,+automation lane and other content keeps its relative timing — and the surrounding sections+shift as needed. Restructure a song (move a verse before a chorus) by moving whole sections+instead of selecting and dragging clips."++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md), [`specs/016`](../016-device-param-section-undo/spec.md)+(sections are undoable project data), [`specs/058`](../058-section-automatic-names/spec.md)+(automatic section names follow position).++**Existing behaviour this builds on**: the Sections lane sits between the Overview and the+ruler. Dragging the empty lane draws a section; dragging a section's body moves **only the+section** (its name and span) to another whole bar — the clips under it stay where they+were; dragging an edge resizes it. Sections may leave gaps between them and may overlap.+The section menu loops it, selects its span as a time range across every track, duplicates+the section marker, or deletes it. Elsewhere the Arrangement already has whole-song time+edits that move content on every track and the master: **Insert silence** (⌘⇧I) and+**Duplicate time** (⌘⇧D) open a gap at a point, cutting clips that cross it and moving every+clip and automation point after it — but they do not move sections. The song has one tempo+and one time signature (no tempo or meter changes along the timeline).++## Clarifications++### Session 2026-11-03++- Q: Where can a dragged section be dropped — only on a boundary between sections (reorder,+ the rest closes up) or on any bar? → A: Only on section boundaries (before the first,+ between two neighbours, after the last); the others shift by the moved section's length and+ the song's length never changes. Free placement on any bar is not a content move.+- Q: Does a plain drag of a section's body move it with its content, or only the marker? →+ A: A plain drag moves it with its content; an Option/Alt drag moves only the marker (as+ today, to any whole bar).+- Q: What happens to song time not covered by any section (a gap) when a neighbouring section+ moves? → A: Only the moved section's own span travels; gaps and their content are ordinary+ song material and shift along with whatever lies between the old and new place, so the+ spacing between the other sections is preserved.+- Q: Are Duplicate and Delete a section *with its content* (rippling the rest) part of this+ issue? → A: Yes — the section menu gains **Duplicate with content** and **Delete with+ content**; the existing Duplicate / Delete keep acting on the marker only.+- Q: What happens when a section that overlaps another is moved, duplicated or deleted with+ content? → A: Content operations are unavailable for it: the drag falls back to a+ marker-only move, the with-content menu entries are disabled, and the status bar says why.++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Drag a section to reorder the song (Priority: P1)++A producer has Intro · Verse · Chorus · Verse 2 laid out as sections over a full+arrangement. They grab the Chorus in the Sections lane and drop it before the Verse. The+song now plays Intro · Chorus · Verse · Verse 2: every clip, MIDI note and automation+point that was inside the Chorus moved with it, the Verse moved right by the Chorus's+length to make room, and nothing after the two swapped sections moved at all. One Undo+puts everything back.++**Why this priority**: this is the whole request — restructuring a song in one gesture+instead of selecting clips on every track and dragging them around.++**Independent Test**: build four sections with a distinct MIDI clip, audio clip and+automation ramp in each; drag the third before the second; play it — the third's content is+heard where the second used to start, the second follows directly, the fourth is untouched;+Undo restores the original layout exactly.++**Acceptance Scenarios**:++1. **Given** sections A · B · C back to back, **When** the user drags C and drops it before+ B, **Then** the order is A · C · B, C starts where B used to start, B starts right after+ C, and everything inside each section kept its position relative to its section's start.+2. **Given** the same song, **When** the user drags A and drops it after C, **Then** the+ order is B · C · A, B starts where A used to start, and A ends where C used to end.+3. **Given** a section moved, **When** the user plays the song, **Then** audio clips,+ MIDI clips, every track's automation, the master track's automation and the master volume+ automation are heard in the new order, with no gap or overlap where content was taken+ out or put in.+4. **Given** a completed move, **When** the user presses Undo once, **Then** all clips,+ automation and sections are exactly as before the drag; Redo repeats the move.+5. **Given** a move, **When** it finishes, **Then** content outside the span from the+ earliest to the latest affected position (before the first moved section and after the+ last) did not move.+6. **Given** a drag in progress, **When** the user presses Escape, **Then** the drag is+ abandoned and nothing changes.++---++### User Story 2 - See where the section will land while dragging (Priority: P1)++While dragging, the user sees where the section will go before letting go: an insertion+marker at the boundary it will drop on, and the other sections showing the order they will+take. Dropping back where it started changes nothing and records no undo step.++**Why this priority**: moving whole chunks of a song is destructive-looking; without a clear+preview users won't trust the gesture.++**Independent Test**: start dragging a section across the lane, watch the insertion marker+snap from boundary to boundary; drop it on its own place — Undo has nothing new.++**Acceptance Scenarios**:++1. **Given** a drag over the lane, **When** the middle of the dragged section passes another+ section's middle, **Then** the insertion marker jumps to that section's other edge and the+ preview order updates. (The dragged section's middle, not the pointer, decides — so where+ the section was grabbed doesn't change where it lands.)+2. **Given** a drag, **When** the user drops on the section's original place, **Then**+ nothing changes and no undo step is added.+3. **Given** a drag near the lane's left or right edge, **When** more of the song lies+ beyond the visible range, **Then** the view scrolls so any position can be reached.++---++### User Story 3 - Move the section marker alone (Priority: P2)++Sometimes the user only wants to re-mark where a section is (fix a section placed a bar too+early) without touching the music. They hold the marker-only modifier while dragging and the+section moves the way it does today — the clips stay put. The modifier is Option (macOS) /+Alt (Windows, Linux), the Arrangement's existing "free / off the grid" modifier.++**Why this priority**: today's behaviour is still needed for correcting section markers;+the content move must not take it away.++**Independent Test**: hold the modifier and drag a section by two bars — only the section+moved, no clip or automation changed; Undo restores it.++**Acceptance Scenarios**:++1. **Given** a section, **When** the user drags it with the marker-only modifier held,+ **Then** only the section's span moves (on whole bars), as before this feature.+2. **Given** a section, **When** the user drags one of its edges, **Then** it resizes as+ before — resizing never moves content.++---++### User Story 4 - Move a section without dragging (Priority: P3)++From the section's right-click menu (and the command palette, for the section at the+playhead) the user picks **Move earlier** or **Move later**, which swaps the section with+its neighbour along with all their content — the same result as dragging it one place over.++**Why this priority**: gives a precise, keyboard-reachable way to reorder, and an easy+path for testing and MCP use; the drag covers the main need.++**Independent Test**: on A · B · C, run Move later on A — the order is B · A · C with the+content following; Move earlier on the first section is disabled.++**Acceptance Scenarios**:++1. **Given** the first section, **When** its menu opens, **Then** Move earlier is disabled;+ for the last section Move later is disabled.+2. **Given** the playhead in no section, **When** the user runs the palette command, **Then**+ it says so and changes nothing.++---++### User Story 5 - Duplicate or delete a section with its content (Priority: P2)++The user wants a second chorus: they pick **Duplicate with content** in the Chorus's menu and+a copy of the section and everything under it appears right after it, pushing the rest of+the song later. Later they drop a bridge: **Delete with content** removes the section and its+content and pulls the rest of the song earlier to close the gap. Each is one undo step.++**Why this priority**: the same "work in whole sections" idea as moving; the move covers the+issue's main need, these round out the set.++**Independent Test**: on A · B · C, Duplicate with content on B gives A · B · B′ · C with B′+playing exactly like B and C starting B's length later; Delete with content on B (from the+original) gives A · C with C starting where B started; Undo restores each.++**Acceptance Scenarios**:++1. **Given** sections A · B · C, **When** the user picks Duplicate with content on B, **Then**+ a copy B′ with B's name and naming mode and a copy of all of B's content starts at B's+ end, and everything from B's end onward (C, gaps, content) moves later by B's length.+2. **Given** sections A · B · C, **When** the user picks Delete with content on B, **Then** B+ and all content in its span are removed and everything after B's end moves earlier by B's+ length; content before B is untouched.+3. **Given** either command, **When** the user presses Undo once, **Then** content and+ sections are exactly as before; the plain Duplicate / Delete entries still act on the+ marker only.+4. **Given** the playhead inside a section, **When** the user runs the command palette's+ Duplicate section with content / Delete section with content, **Then** it acts on that+ section; with none under the playhead it says so and changes nothing.++---++### Edge Cases++- **Clips crossing a section boundary**: a clip that starts before a moved section and ends+ inside it (or starts inside and ends after it) is cut at the boundary; the inside part+ moves with the section and the outside part stays, both keeping their audio/notes in+ time — the same cut rule as Insert silence / Duplicate time. A MIDI note crossing the+ boundary is shortened to the boundary in the part it starts in.+- **Automation at a boundary**: each lane keeps its value right at both cut points and at+ both join points, so the curve inside the moved section and the curve around where it+ was taken out play exactly as they did, without a jump that wasn't there before.+- **Gaps between sections**: time not covered by any section is not a section and cannot be+ dragged. Only the moved section's span travels; a gap and its content shift with the rest+ of the material between the old and new place, so the spacing between the other sections+ is preserved. Dropping "between X and Y" with a gap between them inserts right before Y's+ start (the gap stays after X); "after the last section" inserts at its end.+- **Overlapping sections**: a section that overlaps another can't be moved, duplicated or+ deleted with content — the drag falls back to moving the marker only, the menu entries+ are disabled, and the status bar / palette says why.+- **Only one section**: dragging it has no other place to go in the order; it behaves as a+ marker-only move.+- **Empty section** (no content under it): it still moves and reorders, the other sections+ and content shift as for any move.+- **Section starting at beat 0 / ending at the end of the song**: moves work the same; the+ song's total length never changes.+- **Playback running**: the move applies while playing without a click or dropout; the+ playhead stays at the same time position (it doesn't follow the moved content).+- **Loop region and time selection**: the loop region stays where it is; an active time+ selection is cleared by a move.+- **Session clips, scenes and anything not on the arrangement timeline** are untouched.+- **Locked automation** (the automation-lock toggle): automation still moves with its+ section — a section move is a whole-song edit like Insert silence.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: Dragging a section's body in the Sections lane MUST move the section together+ with all arrangement content inside its span — audio clips, MIDI clips, every track's+ automation, the master track's content and automation and the master volume automation —+ keeping every item's position relative to the section's start.+- **FR-002**: A move MUST reorder the song: exactly the moved section's span is taken out+ and inserted at a section boundary, and everything between the old and new place shifts by the moved span's+ length to close the gap and make room. The song's total length MUST NOT change.+- **FR-003**: Drop targets MUST be section boundaries (before the first section, between+ two sections, after the last section) — never an arbitrary bar and never inside another+ section; the drag MUST show an insertion marker and the resulting section order before+ release.+- **FR-004**: Clips crossing a moved section's edges MUST be cut at those edges; the parts+ inside move with it, the parts outside stay, with audio and notes still in time.+- **FR-005**: Automation MUST read the same value just before and just after every cut and+ join it creates as it did at the corresponding place before the move.+- **FR-006**: Sections themselves MUST move with the content: the moved section and the+ sections it passes take their new positions, keeping their names and naming mode+ (automatic names renumber by position, specs/058).+- **FR-007**: Each completed move MUST be exactly one undo step covering content and+ sections together; a drop that changes nothing MUST NOT add an undo step; Escape during a+ drag MUST cancel it.+- **FR-008**: Holding Option/Alt (the marker-only modifier) while dragging a section MUST move just the+ section, as today; resizing a section's edges MUST never move content.+- **FR-009**: A section that overlaps another section MUST NOT move, duplicate or delete+ content: its drag MUST fall back to a marker-only move, its Move earlier / Move later /+ Duplicate with content / Delete with content entries MUST be disabled, and the status bar+ (or the palette, for a palette command) MUST say why. Other sections still move with+ content; overlapping sections between the old and new place shift intact, and no drop+ target is offered inside an overlap.+- **FR-010**: The section menu MUST offer **Move earlier** / **Move later** (swap with the+ previous / next section, with content), disabled at the ends; the command palette MUST+ offer the same for the section at the playhead.+- **FR-011**: A move, duplicate or delete with content during playback MUST NOT interrupt+ audio (no dropout or click from the edit itself) and MUST NOT move the playhead.+- **FR-012**: The loop region MUST stay where it is; an active arrangement time selection+ MUST be cleared by a move.+- **FR-013**: The result MUST be saved with the project and survive save / reopen.+- **FR-014**: MCP clients MUST be able to move a section (by index, to a target boundary+ index) with the same result as the drag.+- **FR-015**: The section menu and the command palette (for the section at the playhead)+ MUST offer **Duplicate with content**: insert a copy of the section and all content in its+ span right after it, moving everything from its end onward later by its length, cutting+ clips that cross its edges as a move does.+- **FR-016**: The section menu and the command palette MUST offer **Delete with content**:+ remove the section and all content in its span, cutting clips that cross its edges, and+ move everything after it earlier by its length.+- **FR-017**: Duplicate with content and Delete with content MUST each be one undo step, keep+ automation values continuous at every cut and join (as FR-005), and be available to MCP+ clients; the existing Duplicate / Delete entries MUST keep acting on the marker only.++### Key Entities++- **Section**: a named span of the arrangement (start, length, name, automatic or custom+ naming). Defines what moves.+- **Section boundary**: a drop target — the start of a section or the end of the last one;+ where the moved span is inserted.+- **Arrangement content**: everything placed on the timeline — audio and MIDI clips on every+ track and the master, automation lanes (track, device, master volume). Moves with the+ section whose span covers it.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: Moving one section of a song with 8 tracks to another place in the order+ takes one drag and under 5 seconds, versus selecting and moving every track's clips and+ automation by hand.+- **SC-002**: After any move and its Undo, a render of the song is identical to the render+ before the move (sample-exact for audio-only content).+- **SC-003**: After a move, rendering the moved section's span at its new place matches+ rendering it at its old place before the move (same clips, notes and automation values).+- **SC-004**: A move on a 50-track project with 500 clips completes and redraws within+ 200 ms of release, and audio playback during it has no dropout.+- **SC-005**: Zero content outside the affected span changes position in any move+ (checked by comparing clip and automation positions before and after).++## Assumptions++- The issue's video shows a reorder model (sections swap places, the rest closes up), not a+ free placement on any bar; that is what plain dragging does. Free placement of the marker+ stays available as the marker-only drag.+- The Preferences → Shortcuts pane lists both section drags (plain = with content,+ Option/Alt = marker only).+- Clip cutting at boundaries reuses the rules of Insert silence / Duplicate time, so clips+ look and sound the same as after those edits.+- The song has a single tempo and time signature, so moving content in beats is enough.+- Duplicate / Delete with content go beyond the issue's text (it asks for moving); they were+ added to its scope in clarification and the issue should note that before the PR.+- Unlike a move, Duplicate and Delete with content change the song's total length.+- Overlapping sections are uncommon; supporting content moves for them is out of scope.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [ ] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5)+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)+- [ ] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/073-section-rearrange/tasks.md b/specs/073-section-rearrange/tasks.mdnew file mode 100644index 00000000..24a3d247--- /dev/null+++ b/specs/073-section-rearrange/tasks.md@@ -0,0 +1,218 @@+---++description: "Tasks: Rearrange the song by moving sections with their content"+---++# Tasks: Rearrange the song by moving sections with their content++**Input**: Design documents from `specs/073-section-rearrange/`++**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),+[data-model.md](data-model.md), [contracts/abi.md](contracts/abi.md), [quickstart.md](quickstart.md)++**Tests**: included — the constitution (IV) requires engine behaviour changes to extend+`tests/Nota.SmokeTest`. Engine tests live in a new `tests/Nota.SmokeTest/SectionRearrangeTests.cs`+(`internal static class SectionRearrangeTests { public static IEnumerable<(bool ok, string label)> Run() }`,+registered in `tests/Nota.SmokeTest/Program.cs` next to `ArrangementMovesTests.Run()`).++**Organization**: grouped by user story (spec.md US1–US5).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: can run in parallel (different files, no dependency on unfinished tasks)+- **[Story]**: US1 … US5 from spec.md++---++## Phase 1: Setup++- [X] T001 Create branch `feat/section-rearrange` off `develop` (user commits; do not commit or push)+- [X] T002 Create `tests/Nota.SmokeTest/SectionRearrangeTests.cs` (SPDX two-line header, empty `Run()` yielding nothing) and register `foreach (var (ok, label) in SectionRearrangeTests.Run()) Check(ok, label);` in `tests/Nota.SmokeTest/Program.cs` beside `ArrangementMovesTests`++---++## Phase 2: Foundational (engine time-mapping primitives)++**Purpose**: the shared engine machinery every with-content operation uses (research R2–R5).++**⚠️ CRITICAL**: no user story work before this phase is done.++- [X] T003 In `src/native/nota.engine/src/engine/Engine_Tracks.cpp` (anonymous namespace next to `laneSlice` / `laneInsertGap`) add a `TimeMap` helper: given `(a, b, d)` with `L = b − a > 0`, `d ∉ (a, b)`, return the offset for a position by region — `d <= a`: `[a,b) → −(a−d)`, `[d,a) → +L`; `d >= b`: `[a,b) → +(d−b)`, `[b,d) → −L`; else 0 — plus the sorted cut points `{a, b, d}` and the affected window `[min(a,d), max(b,d))`+- [X] T004 In `Engine_Tracks.cpp` add `laneRemap(AutomationLane&, const TimeMap&)`: keep points outside the window untouched; rebuild the window from `laneSlice` pieces of each region, re-based to the region's new start, each piece starting with an explicit point at its edge value (FR-005); return false when the lane is empty or unchanged+- [X] T005 In `Engine_Tracks.cpp` add `remapTrack(const Track&, const TimeMap&)` → cloned track or null: MIDI clips and audio clips cut at the cut points with `midiSlice` / `audioSlice` (pieces keep audio and notes in time) and shifted by their region's offset; every `automation` lane through `laneRemap`; `takes` shifted by the offset of their `originBeat` (research R6); clips wholly outside the window kept as-is+- [X] T006 Add `bool Engine::moveTimeRange(double a, double b, double d)` (private, declared in `src/native/nota.engine/src/engine/Engine.h`) in `Engine_Tracks.cpp`: new `Graph`, `inheritGraphLevel`, `remapTrack` over every track and `masterTrack`, `laneRemap` on `g->masterVolume`, every section's start shifted by the same map (sections re-sorted), then one `pushUndo()` + `publishRaw()`; false (and no undo step) when nothing changed+- [X] T007 Add `bool Engine::removeTimeRange(double a, double b)` (private) in `Engine_Tracks.cpp`: clips cut at `a`/`b`, the inside dropped, everything `>= b` shifted by `−L` (clips, lanes via slices, takes, master volume); sections inside `[a,b)` removed, later ones shifted; one undo step+- [X] T008 Add `bool Engine::sectionOverlaps(int index) const` in `Engine_Tracks.cpp` / `Engine.h`: true when section `index`'s span intersects another section's by more than `1e-6` beats (data-model § Section); plus a private `boundaryBeat(int k)` — `k < n` → `sections[k].startBeat`, `k == n` → end of the last section++**Checkpoint**: primitives compile; no public surface yet.++---++## Phase 3: User Story 1 — Drag a section to reorder the song (P1) 🎯 MVP++**Goal**: a plain drag of a section's body moves it with all its content to a section boundary.++**Independent Test**: four sections with a distinct MIDI clip, audio clip and automation ramp in+each; drag the third before the second; playback and positions match; one ⌘Z restores.++### Tests for User Story 1++- [X] T009 [P] [US1] In `tests/Nota.SmokeTest/SectionRearrangeTests.cs` add the engine block from quickstart § 1: sections A [0,8) · B [8,16) · C [16,24), two instrument tracks (one MIDI clip crossing 8), one audio track, a volume ramp, master volume automation; assert `MoveSection(2, 1)` → A · C · B with C's content at 8 and B's at 16, the crossing clip cut at 8, automation values at 0, 8⁻, 8, 16⁻, 16, 24 equal the original values at the mapped positions, nothing ≥ 24 moved; `MoveSection(0, 3)` → B · C · A; `MoveSection(1, 1)` and `(1, 2)` false with no undo step; Undo restores clips, lanes and sections exactly, Redo repeats; names and automatic mode preserved+- [X] T010 [P] [US1] In `SectionRearrangeTests.cs` add the render checks (SC-002/003) with a deterministic WAV clip (not synth notes): offline render after move + undo equals the render before; the moved section's span renders the same at its new place+- [X] T011 [P] [US1] In `SectionRearrangeTests.cs` add: a take (specs/067) whose origin is inside B moves with B; the playhead position is unchanged by a move during playback (FR-011)++### Implementation for User Story 1++- [X] T012 [US1] Add public `bool Engine::moveSection(int index, int toBoundary)` in `Engine_Tracks.cpp` / `Engine.h`: reject out-of-range, `toBoundary ∈ {index, index+1}` (no-op), `sectionOverlaps(index)`, or a boundary beat strictly inside an overlap; else `moveTimeRange(start, start+len, boundaryBeat(toBoundary))`+- [X] T013 [US1] Declare `nota_section_move` and `nota_section_overlaps` in `src/native/nota.engine/include/nota/nota_engine.h` after `nota_engine_set_sections`, with the comment block from contracts/abi.md; implement them in `src/native/nota.engine/src/abi/nota_engine_core.cpp` beside `nota_engine_set_sections` (`NOTA_OK` / `NOTA_ERR_INVALID_ARG`)+- [X] T014 [US1] Add `[LibraryImport]`s `SectionMove` / `SectionOverlaps` in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs` beside `SetSections`; add `bool MoveSection(int index, int toBoundary)` and `bool SectionOverlaps(int index)` to `src/managed/Nota.Application/Engine/IAudioEngine.cs` (with doc comments) and implement them in `src/managed/Nota.Infrastructure/Interop/NotaEngine.cs` near `SetSections`+- [X] T015 [US1] In `src/managed/Nota.App/ArrangementView.Sections.cs` add `Mode.Reorder`: on press over a body without Option/Alt, and when the section does not overlap (`_engine.SectionOverlaps(index)`), enter Reorder once past the 3 px threshold (Option/Alt or an overlapping section → existing `Mode.Move`; for an overlap set the status text explaining why, FR-009)+- [X] T016 [US1] In `ArrangementView.Sections.cs` compute the target boundary while dragging: compare the pointer beat with each other section's midpoint (research R8); keep `_reorderFrom` (start-sorted index) and `_reorderTo` (0..n); skip boundaries inside an overlap+- [X] T017 [US1] In `ArrangementView.Sections.cs` on release in Reorder: if `_reorderTo` is not a no-op call `_engine.MoveSection(from, to)`, then `ClearTimeSelection()`, `Refresh()`, `ReloadSections()`, raise `SectionsChanged`; a no-op or failed call changes nothing (no seek either once the drag threshold was passed)+- [X] T018 [US1] Run the US1 smoke tests (T009–T011) via `scripts/build.sh` and fix until green++**Checkpoint**: dragging reorders with content; MVP usable without a preview.++---++## Phase 4: User Story 2 — See where the section will land (P1)++**Goal**: preview while dragging, auto-scroll, Esc cancels, a no-op drop records nothing.++**Independent Test**: drag across the lane — the insertion bar jumps at midpoints; Esc mid-drag+changes nothing; dropping on the original place adds no undo step.++- [X] T019 [US2] In `ArrangementView.Sections.cs` `Render`: while in Reorder draw the other sections at their preview positions (the R2 mapping computed in C# for `(from, to)`), the dragged section as a ghost under the pointer (section fill at reduced opacity), and a 2 px insertion bar in the accent brush at the target boundary — tokens per `DESIGN.md` / `nota-design`, no hard-coded colours+- [X] T020 [US2] In `ArrangementView.Sections.cs` add edge auto-scroll during Reorder (and Move), reusing the `EnsureAutoScroll` / `AutoScrollTick` pattern from `src/managed/Nota.App/ArrangementView.LaneControl.cs`+- [X] T021 [US2] In `ArrangementView.Sections.cs` add `internal bool CancelGesture()` on `SectionsControl` (restore the working copy via `ReloadSections()` after clearing the mode, release capture) and expose it from `ArrangementView`; route Esc to it in `src/managed/Nota.App/MainWindow.Input.cs` next to the existing `CancelGesture` calls; lost window focus cancels too, as the lane does+- [X] T022 [US2] Headless check (done in the throwaway UI harness /tmp/sections073harness, not in the smoke test — the Sections lane is a private Avalonia control) in `SectionRearrangeTests.cs` (or the existing headless UI harness): a Reorder drag dropped on its own boundary makes no engine call and adds no undo step; `CancelGesture()` mid-drag leaves sections and clips unchanged++**Checkpoint**: US1 + US2 = the full P1 experience.++---++## Phase 5: User Story 3 — Move the section marker alone (P2)++**Goal**: Option/Alt-drag keeps today's marker-only move; edge resizing never moves content.++**Independent Test**: ⌥-drag a section two bars — only the section moved; Undo restores it.++- [X] T023 [US3] In `ArrangementView.Sections.cs` make sure `Mode.Move` is reached only with Option/Alt held at press (or for an overlapping section) and behaves exactly as before (`SnapBar`, `SectionsEdited()` → one undo step); `EdgeLeft` / `EdgeRight` unchanged+- [X] T024 [P] [US3] In `src/managed/Nota.App/PreferencesWindow.cs` replace the "Drag section · its edge" row with "Drag section" → "Reorder the song: the section and everything in it move to the marked boundary", "⌥-drag section" → "Move only the section marker, snapped to bars", "Drag section edge" → "Resize it, snapped to bars" (via the `nota-shortcuts` skill)+- [X] T025 [US3] Headless check (UI harness, as T022; the engine side is covered by the smoke test) in `SectionRearrangeTests.cs`: a marker-only move changes `Sections` but no clip or automation position++---++## Phase 6: User Story 5 — Duplicate or delete a section with its content (P2)++**Goal**: menu + palette commands that ripple the rest of the song.++**Independent Test**: A · B · C → Duplicate with content on B gives A · B · B′ · C, C later by+B's length; Delete with content on B gives A · C; Undo restores each.++### Tests for User Story 5++- [X] T026 [P] [US5] In `SectionRearrangeTests.cs`: `DuplicateSectionWithContent(1)` → B′ at 16 with B's content and name (automatic stays automatic), C at 24, automation continuous at 16 and 24; `DeleteSectionWithContent(1)` → A · C, C at 8, B's content gone, a clip crossing 8 or 16 cut there; both one undo step; both false on an overlapping section++### Implementation for User Story 5++- [X] T027 [US5] Add `bool Engine::duplicateSectionWithContent(int index)` in `Engine_Tracks.cpp` / `Engine.h`: reject out-of-range / overlapping; reuse the `insertTime(b, L, duplicate=true)` track/lane logic (factor its body into a helper that takes the target `Graph`) and in the same graph copy every section inside `[a,b)` to `+L` and shift sections `>= b` by `+L`; one undo step+- [X] T028 [US5] Add `bool Engine::deleteSectionWithContent(int index)` in `Engine_Tracks.cpp` / `Engine.h`: reject out-of-range / overlapping; `removeTimeRange(start, start+len)`+- [X] T029 [US5] Declare/implement `nota_section_duplicate_with_content` and `nota_section_delete_with_content` in `nota_engine.h` / `nota_engine_core.cpp`; imports in `NativeMethods.cs`; `DuplicateSectionWithContent` / `DeleteSectionWithContent` in `IAudioEngine.cs` and `NotaEngine.cs`+- [X] T030 [US5] In `ArrangementView.Sections.cs` `ShowMenu`: add **Duplicate with content** (GlyphKind.Duplicate) next to Duplicate and **Delete with content** (`MenuKit.Danger`, GlyphKind.Trash) next to Delete; disabled when `SectionOverlaps`; after success `ClearTimeSelection()`, `Refresh()`, `ReloadSections()`, `SectionsChanged`+- [X] T031 [US5] Add `internal string DuplicateSectionWithContentAtPlayhead()` / `DeleteSectionWithContentAtPlayhead()` in `ArrangementView.Sections.cs` (status text like `ResetSectionNameAtPlayhead`, incl. "No section at the playhead" and the overlap reason); register `edit.duplicateSectionWithContent` / `edit.deleteSectionWithContent` in `src/managed/Nota.Application/Palette/CommandCatalog.cs` (category Edit, view "Arrangement") and bind them in `src/managed/Nota.App/MainWindow.Commands.cs`++---++## Phase 7: User Story 4 — Move a section without dragging (P3)++**Goal**: Move earlier / later from the menu and the palette.++**Independent Test**: A · B · C → Move later on A gives B · A · C; Move earlier disabled on the first.++- [X] T032 [US4] In `ArrangementView.Sections.cs` `ShowMenu` add **Move earlier** / **Move later** (a new group above Duplicate) calling `_engine.MoveSection(i, i-1)` / `MoveSection(i, i+2)`; disabled for the first / last section and for an overlapping one+- [X] T033 [US4] Add `MoveSectionAtPlayhead(bool later)` returning status text in `ArrangementView.Sections.cs`; register `edit.moveSectionEarlier` / `edit.moveSectionLater` in `CommandCatalog.cs` and bind them in `MainWindow.Commands.cs`+- [X] T034 [P] [US4] In `SectionRearrangeTests.cs`: `MoveSection(0, 2)` on A · B · C gives B · A · C (the "Move later" call shape); palette catalog contains the four new ids (extend `PaletteTests` if it enumerates ids)++---++## Phase 8: MCP (FR-014, serves US1/US4/US5)++- [X] T035 [P] In `src/managed/Nota.Mcp/Tools/ProjectTools.cs` add `move_section(index, toBoundary)`, `duplicate_section_with_content(index)`, `delete_section_with_content(index)` per contracts/abi.md — `Mutate(...)` returning `Listed()`, an error message when the engine call returns false (out of range, overlap, no-op); descriptions say indices are `list_sections` order and everything in the span moves in one undo step+- [X] T036 [P] Extend the MCP tests in `tests/Nota.SmokeTest` (where `list_sections` / `set_sections` are covered) for the three tools++---++## Phase 9: Polish & Cross-Cutting Concerns++- [X] T037 [P] Add every new `Loc.T` string (menu entries, palette titles / keywords, status texts, Shortcuts rows) to `src/managed/Nota.App/Languages/en.json` and `fr.json`; run the localization design-token check in the smoke test+- [X] T038 Performance check (SC-004): 50 tracks / 500 clips, move a section and time release → redraw ≤ 200 ms; during playback `DropoutCounter` stays 0+ - Measured headless (/tmp/sections073harness `perf`): the engine edit takes 0.2 ms; release → redraw is ~400 ms, almost all of it the existing full `ArrangementView.Refresh()` — Insert silence on the same project costs the same (210–370 ms). Not met at first; met by T047. Dropout during playback not measured on a device.+- [X] T039 Run quickstart.md §§ 2–3 (MCP and UI); capture before/after headless screenshots of the drag preview for the PR (`nota-pr` skill)+- [X] T040 Post a scope note on issue #192 (Duplicate / Delete with content added in clarification) — ask the user before posting+ - Posted: https://github.com/nota-daw/nota/issues/192#issuecomment-6602859981++### Nota closing tasks *(PR gates)*++- [X] T041 Run `scripts/build.sh` until native + managed + smoke test are green+- [X] T042 AGPL-3.0-only SPDX two-line header on every new source file (`SectionRearrangeTests.cs`)+- [X] T043 New dependency: N/A+- [X] T044 `CHANGELOG.md` `[Unreleased]` → Added: reorder sections with content (drag, Move earlier / later), Duplicate / Delete with content, MCP tools; Changed: plain section drag now moves content, ⌥-drag moves the marker only+- [X] T045 FEATURES.md via `nota-features` (Sections bullet); user docs EN + RU via `nota-docs`; shortcuts via `nota-shortcuts` (T024)+- [X] T046 Engine behaviour change → smoke test extended (T009–T011, T026, T034, T036) ✔ confirm all run in `scripts/build.sh`++---++## Dependencies & Execution Order++- **Phase 1 → Phase 2** → all stories.+- **US1 (Phase 3)** needs Phase 2. **US2** builds on US1's Reorder mode (same file). **US3**+ touches the same drag code — do after US1. **US5** needs Phase 2 only (engine) plus the menu+ in `ArrangementView.Sections.cs`. **US4** needs `MoveSection` from US1.+- **MCP (Phase 8)** needs T012/T014 (move) and T027–T029 (duplicate/delete).+- **Polish** last.++Within the engine, T003 → T004 → T005 → T006/T007 → T012/T027/T028. ABI (T013, T029) before+managed wrappers (T014, T029) before UI.++### Parallel Opportunities++- T009, T010, T011 (tests, one file but independent blocks — write together before T012).+- T024 (PreferencesWindow), T035/T036 (MCP), T037 (strings) touch separate files and can run+ alongside UI work once the engine API exists.+- US5 engine work (T027–T029) can proceed in parallel with US1/US2 UI work (T015–T021): different+ files after Phase 2.++## Parallel Example: after Phase 2++```text+Task: "T012–T014 moveSection engine + ABI + managed wrapper"+Task: "T027–T029 duplicate/delete with content engine + ABI + managed wrappers"+Task: "T009–T011 SectionRearrangeTests engine blocks"+```++## Implementation Strategy++1. **MVP** = Phases 1–3 (drag reorders with content, one undo step). Validate with T018.+2. Add US2 (preview, Esc, auto-scroll) — together with US1 the full P1 experience.+3. US3 (marker-only ⌥-drag + Shortcuts), then US5 (duplicate / delete with content), then US4+ (menu / palette moves), then MCP.+4. Polish and gates; one PR closing #192.++## Notes++- Same-file tasks (`ArrangementView.Sections.cs`, `Engine_Tracks.cpp`) are sequential.+- Don't commit or push — the user reviews and commits.++## Phase 10: Convergence++- [X] T047 Bring release → redraw after a section move/duplicate/delete within 200 ms on 50 tracks / 500 clips (refresh only what the edit touched instead of the full `ArrangementView.Refresh()` in `src/managed/Nota.App/ArrangementView.Sections.cs` `SectionContentEdited`), and measure dropouts while moving during playback, per SC-004 / FR-011 (partial)+ - `SectionContentEdit` refreshes with `RefreshMovedClips()` (no header rebuild; audio peaks kept by source, not index) unless a take lane came or went. Headless, 50 tracks × 10 clips: move → refresh → frame 6–14 ms (was ~400). Reused peaks match a full refresh, cut clips included (/tmp/sections073harness `peaks`). Dropouts while moving during playback not measured on a device (the edit is one snapshot swap, AR-5).+- [X] T048 Pick the drop boundary by the pointer's position against each other section's midpoint (not the ghost's centre) in `SectionsControl.TargetBoundary` (`src/managed/Nota.App/ArrangementView.Sections.cs`), or record the ghost-centre rule in the artifacts, and keep the docs' "until its middle passes" wording in step, per US2/AC1 and plan R8 (contradicts)+ - Kept the ghost-centre rule (the grab point doesn't change where it lands); recorded in spec US2/AC1 and research R8. The docs already describe it.+- [X] T049 With only one section, make a plain body drag a marker-only move (`Mode.Move`) instead of a Reorder that can never land, in `SectionsControl.OnPointerPressed` (`src/managed/Nota.App/ArrangementView.Sections.cs`), per spec Edge Cases "Only one section" (contradicts)+ - `_sections.Count < 2` → `Mode.Move`.+- [X] T050 Handle take lanes in the ripple edits: a take whose first played frame is inside a deleted section's span is removed (or documented as kept), and Duplicate with content either copies takes in the span or the spec states it doesn't, in `Engine::deleteSectionWithContent` / `duplicateSectionWithContent` (`src/native/nota.engine/src/engine/Engine_Tracks.cpp`), per FR-015 / FR-016 (partial)+ - Duplicate copies a take that starts in the section (new id and number) and points the copied comp clips at it; delete drops such a take unless a comp clip elsewhere still plays from it. Smoke-tested.+- [X] T051 Add a save → reopen check that a moved arrangement (clips, automation, sections) round-trips through the project file in `tests/Nota.SmokeTest/SectionRearrangeTests.cs`, per FR-013 (partial)+ - Save → `ProjectService.Load` / `Apply` into a fresh engine: sections, notes and automation as moved. Smoke-tested.diff --git a/src/managed/Nota.App/ArrangementView.Sections.cs b/src/managed/Nota.App/ArrangementView.Sections.csindex a5ce0b5d..7f957351 100644--- a/src/managed/Nota.App/ArrangementView.Sections.cs+++ b/src/managed/Nota.App/ArrangementView.Sections.cs@@ -6,7 +6,9 @@// spans — Intro, Verse, Drop — says where you are. Sections are authoring metadata, not// audio, but they belong to the project (specs/016): the engine holds them next to scenes,// so every edit is one undo step and project.json stores them. The view keeps a working-// copy that a drag reshapes live and commits to the engine on release.+// copy that a drag reshapes live and commits to the engine on release. Dragging a section+// rearranges the song (specs/073): it and everything in its span move to a boundary between+// sections, which the engine does as one edit; ⌥-drag moves the marker alone.using System;using System.Collections.Generic;@@ -214,6 +216,85 @@ public sealed partial class ArrangementViewreturn Loc.F("\u201C{0}\u201D is {1} again", was, now);}+ // ---- edits that carry the arrangement (specs/073) ---------------------++ private ArrangementSection? SectionAtPlayhead()+ => SectionList.LastOrDefault(x => x.StartBeat <= _playheadBeats && _playheadBeats < x.StartBeat + x.LengthBeats);++ // A section that overlaps another can't take its content anywhere: whose is the shared part?+ private bool SectionOverlapsAt(int index) => _engine is { } eng && index >= 0 && eng.SectionOverlaps(index);++ private string OverlapNote(ArrangementSection s)+ => Loc.F("{0} overlaps another section \u2014 separate them to move its content with it", SectionDisplayName(s));++ // Run an edit that carries content with a section. Afterwards a time selection no longer+ // covers the music it did, and cuts and removals re-index the clips, so a clip selection+ // would point at other clips: both go, and open clip editors re-sync as after a split.+ // Clips and sections are re-read. Clips only moved, so the track headers stay — rebuilding+ // them is what makes a big song slow (SC-004) — unless the song has take lanes: their+ // headers hold each take's place (its menu comps by it), so they are rebuilt.+ private bool SectionContentEdit(Func<IAudioEngine, bool> edit)+ {+ if (_engine is not { } eng) return false;+ int Takes() { int n = 0; foreach (var t in _tracks) n += eng.TakeCount(t.Id); return n; }+ bool takes = Takes() > 0;+ if (!edit(eng)) return false;+ takes |= Takes() > 0;+ ClearTimeSelection();+ Select(-1, -1);+ if (takes) Refresh(); else RefreshMovedClips();+ ReloadSections();+ ClipsSplit?.Invoke();+ SectionsChanged?.Invoke();+ return true;+ }++ /// <summary>Move section <paramref name="index"/> (start order) and everything in its span+ /// to boundary <paramref name="toBoundary"/> — one undo step. False when refused or a no-op.</summary>+ internal bool MoveSectionWithContent(int index, int toBoundary)+ => SectionContentEdit(eng => eng.MoveSection(index, toBoundary));++ private bool DuplicateSectionWithContent(ArrangementSection s)+ => Live(s) is { } live && SectionContentEdit(eng => eng.DuplicateSectionWithContent(SectionIndex(live)));++ private bool DeleteSectionWithContent(ArrangementSection s)+ => Live(s) is { } live && SectionContentEdit(eng => eng.DeleteSectionWithContent(SectionIndex(live)));++ /// <summary>Command palette: swap the section under the playhead with its neighbour, content+ /// and all. Returns what happened, for the status bar.</summary>+ public string MoveSectionAtPlayhead(bool later)+ {+ if (SectionAtPlayhead() is not { } s) return Loc.T("No section at the playhead");+ int i = SectionIndex(s);+ string name = SectionDisplayName(s);+ if (SectionOverlapsAt(i)) return OverlapNote(s);+ if (later && i >= _sections.Count - 1) return Loc.F("{0} is already the last section", name);+ if (!later && i == 0) return Loc.F("{0} is already the first section", name);+ if (!MoveSectionWithContent(i, later ? i + 2 : i - 1)) return Loc.F("Couldn't move {0} there", name);+ return later ? Loc.F("Moved {0} later", name) : Loc.F("Moved {0} earlier", name);+ }++ /// <summary>Command palette: duplicate the section under the playhead with its content.</summary>+ public string DuplicateSectionWithContentAtPlayhead()+ {+ if (SectionAtPlayhead() is not { } s) return Loc.T("No section at the playhead");+ if (SectionOverlapsAt(SectionIndex(s))) return OverlapNote(s);+ string name = SectionDisplayName(s);+ return DuplicateSectionWithContent(s) ? Loc.F("Duplicated {0} with its content", name) : Loc.F("Couldn't duplicate {0}", name);+ }++ /// <summary>Command palette: delete the section under the playhead with its content.</summary>+ public string DeleteSectionWithContentAtPlayhead()+ {+ if (SectionAtPlayhead() is not { } s) return Loc.T("No section at the playhead");+ if (SectionOverlapsAt(SectionIndex(s))) return OverlapNote(s);+ string name = SectionDisplayName(s);+ return DeleteSectionWithContent(s) ? Loc.F("Deleted {0} with its content", name) : Loc.F("Couldn't delete {0}", name);+ }++ /// <summary>Esc / lost focus: abandon a drag in the Sections lane. True when one was active.</summary>+ internal bool CancelSectionsGesture() => _sectionsLane.CancelGesture();+// ---- the lane ---------------------------------------------------------private sealed class SectionsControl : Control@@ -231,18 +312,29 @@ public sealed partial class ArrangementViewprivate static readonly IBrush HintInk = NotaPalette.TextDisabled;private static readonly IBrush DraftFill = NotaPalette.Wash(NotaPalette.AccentBright, 0x28);private static readonly IPen DraftPen = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0xC0), 1);+ // Where a rearranging drag will land: the accent marks the chosen boundary.+ private static readonly IBrush InsertBar = NotaPalette.AccentBright;+ // The span riding under the pointer is not the choice — where it lands is — so its outline stays neutral.+ private static readonly IPen GhostPen = new Pen(NotaPalette.BorderStrong, 1);private static readonly Cursor HandCursor = new(StandardCursorType.Hand);private static readonly Cursor EdgeCursor = new(StandardCursorType.SizeWestEast);private const double EdgeGrab = 4; // px around a span edge that grabs it- private enum Mode { None, Draft, Move, EdgeLeft, EdgeRight }+ // Reorder (specs/073): a plain drag of a span carries the song with it to a boundary;+ // Move (⌥, or an overlapping span) slides the marker alone.+ private enum Mode { None, Draft, Move, Reorder, EdgeLeft, EdgeRight }private readonly ArrangementView _o;private Mode _mode;private ArrangementSection? _active;private double _pressBeat, _grabOffset, _fixedBeat;private bool _moved;+ private int _from, _to; // Reorder: the span's start-order index → target boundary+ private double _dragBeat; // Reorder: the pointer, for the ghost+ private bool _overlapping; // the grabbed span overlaps another: marker only+ private double _lastX;+ private DispatcherTimer? _autoScroll;/// <summary>A span is being drawn, moved or resized: the working copy is ahead of the engine.</summary>public bool IsDragging => _mode != Mode.None;@@ -293,7 +385,16 @@ public sealed partial class ArrangementViewif (hit is null) _mode = Mode.Draft;else if (onLeft) { _mode = Mode.EdgeLeft; _fixedBeat = hit.StartBeat + hit.LengthBeats; }else if (onRight) { _mode = Mode.EdgeRight; _fixedBeat = hit.StartBeat; }- else { _mode = Mode.Move; _grabOffset = _pressBeat - hit.StartBeat; }+ else+ {+ _grabOffset = _pressBeat - hit.StartBeat;+ _from = _to = _o.SectionIndex(hit);+ _dragBeat = _pressBeat;+ bool markerOnly = (e.KeyModifiers & KeyModifiers.Alt) != 0;+ _overlapping = !markerOnly && _o.SectionOverlapsAt(_from);+ // A lone section has nowhere else in the order to go: its drag moves the marker.+ _mode = markerOnly || _overlapping || _o._sections.Count < 2 ? Mode.Move : Mode.Reorder;+ }e.Pointer.Capture(this);e.Handled = true;}@@ -309,9 +410,19 @@ public sealed partial class ArrangementView}double beat = BeatAt(pos.X);- if (!_moved && Math.Abs(beat - _pressBeat) * _o._pixelsPerBeat > 3) _moved = true;+ if (!_moved && Math.Abs(beat - _pressBeat) * _o._pixelsPerBeat > 3)+ {+ _moved = true;+ if (_overlapping && _active is not null) _o.StatusMessage?.Invoke(_o.OverlapNote(_active));+ }if (!_moved) return;+ _lastX = pos.X;+ if (_mode is Mode.Move or Mode.Reorder) EnsureAutoScroll();+ DragTo(beat);+ }+ private void DragTo(double beat)+ {switch (_mode){case Mode.Draft:@@ -322,6 +433,11 @@ public sealed partial class ArrangementView_active.StartBeat = _o.SnapBar(beat - _grabOffset);InvalidateVisual();break;+ case Mode.Reorder:+ _dragBeat = beat;+ _to = TargetBoundary(beat - _grabOffset);+ InvalidateVisual();+ break;case Mode.EdgeLeft when _active is not null:{double start = Math.Min(_o.SnapBar(beat), _fixedBeat - _o._beatsPerBar);@@ -345,6 +461,7 @@ public sealed partial class ArrangementViewvar active = _active;bool moved = _moved;_mode = Mode.None; _active = null; _moved = false;+ _autoScroll?.Stop();e.Pointer.Capture(null);if (mode == Mode.Draft)@@ -362,12 +479,82 @@ public sealed partial class ArrangementView}if (active is null) return;// A click (no drag) on a span jumps the playhead to its start — the gesture the- // lane exists for. A drag committed geometry instead.+ // lane exists for. A drag committed geometry instead; a rearranging drag dropped+ // where it started changes nothing.if (!moved) _o.SeekTo(active.StartBeat);+ else if (mode == Mode.Reorder) { if (_to != _from && _to != _from + 1) _o.MoveSectionWithContent(_from, _to); }else _o.SectionsEdited();InvalidateVisual();}+ /// <summary>Esc / lost window focus: drop the drag with no change — a marker drag's+ /// working copy goes back to the engine's.</summary>+ internal bool CancelGesture()+ {+ if (_mode == Mode.None) return false;+ _mode = Mode.None; _active = null; _moved = false;+ _autoScroll?.Stop();+ _o.ReloadSections();+ InvalidateVisual();+ return true;+ }++ // The boundary a rearranging drag lands on: where the ghost's middle sits among the other+ // spans' middles (0..count, before section k or after the last). A boundary inside an+ // overlap can't take it, so the last good one holds.+ private int TargetBoundary(double ghostStart)+ {+ var list = _o.SectionList;+ int n = list.Count;+ if (_from < 0 || _from >= n) return _from;+ double centre = ghostStart + list[_from].LengthBeats / 2;+ int k = 0;+ for (int i = 0; i < n; i++)+ if (i != _from && list[i].StartBeat + list[i].LengthBeats / 2 < centre) k++;+ int to = k <= _from ? k : k + 1;+ double d = BoundaryBeat(list, to);+ foreach (var s in list)+ if (d > s.StartBeat + 1e-6 && d < s.StartBeat + s.LengthBeats - 1e-6) return _to;+ return to;+ }++ private static double BoundaryBeat(IReadOnlyList<ArrangementSection> list, int k)+ => k < list.Count ? list[k].StartBeat : list.Max(s => s.StartBeat + s.LengthBeats);++ // Where span i would start if the drag ended now — the engine's own remap (specs/073+ // data-model): the grabbed span lands on the boundary, the ones it passes shift by its length.+ private double PreviewStart(IReadOnlyList<ArrangementSection> list, int i)+ {+ double t = list[i].StartBeat;+ if (_mode != Mode.Reorder || !_moved || _to == _from || _to == _from + 1) return t;+ var me = list[_from];+ double a = me.StartBeat, len = me.LengthBeats, b = a + len, d = BoundaryBeat(list, _to);+ if (i == _from) return d <= a ? d : d - len;+ if (d <= a && t >= d - 1e-6 && t < a - 1e-6) return t + len;+ if (d >= b && t >= b - 1e-6 && t < d - 1e-6) return t - len;+ return t;+ }++ // Near an edge a drag scrolls the view, as clip drags do (ArrangementView.LaneControl).+ private void EnsureAutoScroll()+ {+ if (_autoScroll is not null) { if (!_autoScroll.IsEnabled) _autoScroll.Start(); return; }+ _autoScroll = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(16) };+ _autoScroll.Tick += (_, _) => AutoScrollTick();+ _autoScroll.Start();+ }++ private void AutoScrollTick()+ {+ if (_mode is not (Mode.Move or Mode.Reorder)) { _autoScroll?.Stop(); return; }+ const double zone = 40;+ double w = Bounds.Width;+ double depth = _lastX < zone ? -(zone - _lastX) : _lastX > w - zone ? _lastX - (w - zone) : 0;+ if (depth == 0) return;+ _o.ScrollByBeats(Math.Sign(depth) * Math.Clamp(Math.Abs(depth) / zone, 0.15, 1.0) * 2.0);+ DragTo(BeatAt(_lastX));+ }+// Wheel over the lane drives the timeline exactly as it does over the ruler and lanes.protected override void OnPointerWheelChanged(PointerWheelEventArgs e){@@ -388,6 +575,16 @@ public sealed partial class ArrangementViewcopy.Name = s.Name;_o.SectionsEdited(); // one step: the copy arrives already named});+ int idx = _o.SectionIndex(s), n = _o._sections.Count;+ bool free = !_o.SectionOverlapsAt(idx); // overlapping spans keep their content where it is+ var earlier = MenuKit.Item(Loc.T("Move earlier"), GlyphKind.ChevronLeft,+ () => { if (_o.Live(s) is { } l) _o.MoveSectionWithContent(_o.SectionIndex(l), _o.SectionIndex(l) - 1); },+ enabled: free && idx > 0);+ var later = MenuKit.Item(Loc.T("Move later"), GlyphKind.ChevronRight,+ () => { if (_o.Live(s) is { } l) _o.MoveSectionWithContent(_o.SectionIndex(l), _o.SectionIndex(l) + 2); },+ enabled: free && idx < n - 1);+ var dupContent = MenuKit.Item(Loc.T("Duplicate with content"), GlyphKind.Duplicate,+ () => _o.DuplicateSectionWithContent(s), enabled: free);MenuKit.AddGroups(flyout.Items,new Control[] { MenuKit.Header(_o.SectionDisplayName(s), null, Loc.Plural(bars, "Section · {0} bar", "Section · {0} bars")) },new Control[]@@ -400,8 +597,13 @@ public sealed partial class ArrangementViewMenuKit.Item(Loc.T("Loop section"), GlyphKind.Cycle, () => _o.SetLoopRegion(s.StartBeat, s.StartBeat + s.LengthBeats)), // raises LoopChanged itselfMenuKit.Item(Loc.T("Select section"), GlyphKind.Select, () => _o.SelectSectionRange(s)),},- new Control[] { dup },- new Control[] { MenuKit.Danger(Loc.T("Delete"), GlyphKind.Trash, () => _o.RemoveSection(s)) });+ new Control[] { earlier, later },+ new Control[] { dup, dupContent },+ new Control[]+ {+ MenuKit.Danger(Loc.T("Delete"), GlyphKind.Trash, () => _o.RemoveSection(s)),+ MenuKit.Danger(Loc.T("Delete with content"), GlyphKind.Trash, () => _o.DeleteSectionWithContent(s), enabled: free),+ });}else{@@ -417,13 +619,25 @@ public sealed partial class ArrangementViewflyout.ShowAt(this, showAtPointer: true);}+ private void DrawSpan(DrawingContext ctx, ArrangementSection s, Rect r, bool warm)+ {+ ctx.DrawRectangle(warm ? WarmFill : ColdFill, null, r, 3, 3);+ ctx.FillRectangle(warm ? WarmEdge : ColdEdge, new Rect(r.X, r.Y, 2, r.Height));+ if (r.Width <= 22) return;+ var ft = new FormattedText(_o.SectionDisplayName(s), CultureInfo.InvariantCulture,+ FlowDirection.LeftToRight, Typeface.Default, 9, warm ? WarmInk : ColdInk)+ { MaxTextWidth = Math.Max(8, r.Width - 10), Trimming = TextTrimming.CharacterEllipsis };+ ctx.DrawText(ft, new Point(r.X + 7, r.Y + (r.Height - ft.Height) / 2));+ }+public override void Render(DrawingContext ctx){double w = Bounds.Width, h = Bounds.Height;if (w <= 0 || h <= 0) return;ctx.FillRectangle(LaneBg, new Rect(0, 0, w, h));- var list = _o._sections;+ // Start order while rearranging: the drag's indices are the engine's (sorted) ones.+ IReadOnlyList<ArrangementSection> list = _mode == Mode.Reorder ? _o.SectionList : _o._sections;if (list.Count == 0 && _mode != Mode.Draft){var hint = new FormattedText(Loc.T("drag here to mark a section"), CultureInfo.InvariantCulture,@@ -431,23 +645,40 @@ public sealed partial class ArrangementViewctx.DrawText(hint, new Point(8, (h - hint.Height) / 2));}- for (int i = 0; i < list.Count; i++)+ // While rearranging, every span is drawn where it will be (the grabbed one as its+ // landing slot plus a ghost under the pointer); tones alternate in that new order.+ bool reorder = _mode == Mode.Reorder && _moved && _from >= 0 && _from < list.Count;+ var starts = new double[list.Count];+ for (int i = 0; i < list.Count; i++) starts[i] = PreviewStart(list, i);+ var order = Enumerable.Range(0, list.Count).OrderBy(i => starts[i]).ToArray();+ var rank = new int[list.Count];+ for (int k = 0; k < order.Length; k++) rank[order[k]] = k;++ using (ctx.PushClip(new Rect(0, 0, w, h))){- var s = list[i];- double x0 = _o.BeatToX(s.StartBeat), x1 = _o.BeatToX(s.StartBeat + s.LengthBeats);- if (x1 < 0 || x0 > w) continue;- bool warm = (i & 1) == 0;- var r = new Rect(x0, 2, Math.Max(2, x1 - x0), h - 4);- using (ctx.PushClip(new Rect(0, 0, w, h)))+ for (int i = 0; i < list.Count; i++)+ {+ var s = list[i];+ double x0 = _o.BeatToX(starts[i]), x1 = _o.BeatToX(starts[i] + s.LengthBeats);+ if (x1 < 0 || x0 > w) continue;+ var r = new Rect(x0, 2, Math.Max(2, x1 - x0), h - 4);+ if (reorder && i == _from)+ {+ ctx.DrawRectangle(DraftFill, DraftPen, r, 3, 3); // the landing slot+ ctx.FillRectangle(InsertBar, new Rect(r.X - 1, 0, 2, h));+ continue;+ }+ DrawSpan(ctx, s, r, (rank[i] & 1) == 0);+ }+ if (reorder){- ctx.DrawRectangle(warm ? WarmFill : ColdFill, null, r, 3, 3);- ctx.FillRectangle(warm ? WarmEdge : ColdEdge, new Rect(r.X, r.Y, 2, r.Height));- if (r.Width > 22)+ var me = list[_from];+ double gx = _o.BeatToX(_dragBeat - _grabOffset);+ var g = new Rect(gx, 2, Math.Max(2, me.LengthBeats * _o._pixelsPerBeat), h - 4);+ using (ctx.PushOpacity(0.8)){- var ft = new FormattedText(_o.SectionDisplayName(s), CultureInfo.InvariantCulture,- FlowDirection.LeftToRight, Typeface.Default, 9, warm ? WarmInk : ColdInk)- { MaxTextWidth = Math.Max(8, r.Width - 10), Trimming = TextTrimming.CharacterEllipsis };- ctx.DrawText(ft, new Point(r.X + 7, r.Y + (r.Height - ft.Height) / 2));+ DrawSpan(ctx, me, g, true);+ ctx.DrawRectangle(null, GhostPen, g, 3, 3);}}}diff --git a/src/managed/Nota.App/ArrangementView.Vms.cs b/src/managed/Nota.App/ArrangementView.Vms.csindex 63a408a8..3a216d2a 100644--- a/src/managed/Nota.App/ArrangementView.Vms.cs+++ b/src/managed/Nota.App/ArrangementView.Vms.cs@@ -73,6 +73,15 @@ public sealed partial class ArrangementView/// can't be held by reference while dragging). Committed back as AutomationPoint[].</summary>internal sealed class AutoPt { public double Beat; public float Value; public float Curve; }+ /// <summary>Everything an unwarped audio clip's peaks depend on except its position (specs/073).+ /// Warped clips have no key: their warp markers shape the peaks too.</summary>+ internal readonly record struct PeakSourceKey(long SampleId, double SourceOffsetFrames, long LengthFrames, float Gain,+ float PitchSemitones, int WarpEnabled, int WarpMode, double WarpBeats, double WarpPlayStart, double WarpPlayEnd, int Reversed)+ {+ public static PeakSourceKey Of(in NotaAudioClipInfo a) => new(a.SampleId, a.SourceOffsetFrames, a.LengthFrames, a.Gain,+ a.PitchSemitones, a.WarpEnabled, a.WarpMode, a.WarpBeats, a.WarpPlayStart, a.WarpPlayEnd, a.Reversed);+ }+internal sealed class ClipVM{public int ClipIndex;@@ -81,6 +90,9 @@ public sealed partial class ArrangementViewpublic bool IsMidi;public bool Active = true; // false = deactivated (key 0): stays but silent + greyedpublic int TakeId; // the take this comp section came from (specs/067), 0 = none+ /// <summary>What the audio clip's peaks were drawn from (everything but where it sits), so a+ /// refresh after a clip only moved can keep them (specs/073). Null for MIDI.</summary>+ public PeakSourceKey? PeakSource;public float[]? Peaks;public int PeakCount;/// <summary>RMS level per bucket of <see cref="Peaks"/> (null when unknown — an import placeholder).</summary>diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex 66af9ccf..f8d69a45 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -1029,7 +1029,15 @@ public sealed partial class ArrangementView : UserControl/// take's row. Owned and updated by the window on its recording tick.</summary>internal RecordPreview? RecordPreview { get; set; }- public void Refresh(bool rebuildHeaders = true)+ public void Refresh(bool rebuildHeaders = true) => Refresh(rebuildHeaders, movedOnly: false);++ /// <summary>After an edit that only moved, cut or removed clips (a section rearrange,+ /// specs/073): reload clip and automation data without rebuilding the track headers — the+ /// slow part on a big song — and keep the peaks of every audio clip whose source is unchanged,+ /// wherever it now sits.</summary>+ internal void RefreshMovedClips() => Refresh(rebuildHeaders: false, movedOnly: true);++ private void Refresh(bool rebuildHeaders, bool movedOnly){if (rebuildHeaders) RefreshStarting?.Invoke();// Peak reuse (⑤): on a live refresh (no header rebuild) the audio content of existing@@ -1038,7 +1046,17 @@ public sealed partial class ArrangementView : UserControl// peaks over instead of recomputing 2048 buckets per clip on every 60 Hz tick. A full// Refresh (after an edit) always refetches, so trims/reverses/warps stay correct.Dictionary<(int track, int clip), ClipVM>? oldClips = null;- if (!rebuildHeaders)+ // A moved clip keeps its index only by chance (a cut adds pieces), so after a move the+ // peaks are matched by what they show — the clip's source and length — not by index.+ Dictionary<(int track, PeakSourceKey source, double length), ClipVM>? movedClips = null;+ if (movedOnly)+ {+ movedClips = new();+ foreach (var t in _tracks)+ foreach (var c in t.Clips)+ if (c.PeakSource is { } src && c.Peaks is not null) movedClips[(t.Id, src, c.LengthBeats)] = c;+ }+ else if (!rebuildHeaders){oldClips = new();foreach (var t in _tracks)@@ -1102,10 +1120,25 @@ public sealed partial class ArrangementView : UserControlActive = ci.IsActive,Name = eng.GetClipName(ti.Id, c),};+ NotaAudioClipInfo ai = default;+ bool audioInfo = !ci.IsMidi && eng.TryGetAudioClipInfo(ti.Id, c, out ai);+ // A warped clip's peaks also follow its warp markers, which the key can't see:+ // it is always re-read.+ if (audioInfo && ai.WarpEnabled == 0) cvm.PeakSource = PeakSourceKey.Of(ai);+ ClipVM? same = null;if (ci.IsMidi){cvm.Notes = eng.GetClipNotes(ti.Id, c);}+ else if (movedClips is not null && cvm.PeakSource is { } src+ && movedClips.TryGetValue((ti.Id, src, ci.LengthBeats), out same))+ {+ cvm.Peaks = same.Peaks;+ cvm.Rms = same.Rms;+ cvm.PeakCount = same.PeakCount;+ (cvm.DetailPeaks, cvm.DetailRms, cvm.DetailCount, cvm.DetailF0, cvm.DetailF1)+ = (same.DetailPeaks, same.DetailRms, same.DetailCount, same.DetailF0, same.DetailF1);+ }else if (oldClips is not null&& oldClips.TryGetValue((ti.Id, c), out var prev)&& Math.Abs(prev.StartBeat - ci.StartBeat) < 1e-9@@ -1129,7 +1162,7 @@ public sealed partial class ArrangementView : UserControlcvm.Peaks = peaks;cvm.Rms = rms;}- if (!ci.IsMidi && eng.TryGetAudioClipInfo(ti.Id, c, out var ai))+ if (audioInfo){cvm.Gain = ai.Gain;cvm.Adsr = eng.GetClipAdsr(ti.Id, c);@@ -1734,11 +1767,11 @@ public sealed partial class ArrangementView : UserControl/// <summary>Esc: cancel an in-progress lane gesture if one is active (no model change),/// otherwise clear any selection (req 1.2.6 / 2.11). Returns true if it did something.</summary>/// <summary>Abort any in-progress lane gesture with no model change (window focus loss).</summary>- public void CancelActiveGesture() { _lanes.CancelGesture(); _footerLanes.CancelGesture(); }+ public void CancelActiveGesture() { _lanes.CancelGesture(); _footerLanes.CancelGesture(); CancelSectionsGesture(); }internal bool EscapePressed(){- if (_lanes.CancelGesture() | _footerLanes.CancelGesture()) return true;+ if (_lanes.CancelGesture() | _footerLanes.CancelGesture() | CancelSectionsGesture()) return true;bool had = _sel.Count > 0 || SelTrackId > 0 || HasAutoSelection || HasTimeSelection;if (HasAutoSelection) ClearAutoSelection();if (HasTimeSelection) ClearTimeSelection();diff --git a/src/managed/Nota.App/Languages/fr.json b/src/managed/Nota.App/Languages/fr.jsonindex 0b1c58f5..3082d3f8 100644--- a/src/managed/Nota.App/Languages/fr.json+++ b/src/managed/Nota.App/Languages/fr.json@@ -654,7 +654,13 @@"Double-click section": "Double-clic sur une section","Rename it · right-click → Reset to default name for its automatic Section N": "La renommer · clic droit → « Rétablir le nom par défaut » pour sa « Section N » automatique","Return · Esc (renaming a section)": "Return · Esc (renommage d’une section)",- "Drag section · its edge": "Glisser une section · son bord",+ "Drag section": "Glisser une section",+ "Rearrange the song · it and everything in it move to the marked boundary, the sections between close up · Esc cancels": "Réorganiser le morceau · la section et tout ce qu’elle contient vont à la limite marquée, les sections entre elles se resserrent · Esc annule",+ "⌥-drag section": "⌥-glisser une section",+ "Move only the section marker, snapped to bars": "Déplacer seulement le repère de la section, calé sur les mesures",+ "Drag section edge": "Glisser le bord d’une section",+ "Right-click section": "Clic droit sur une section",+ "Move earlier / later · duplicate or delete with content": "Déplacer plus tôt / plus tard · dupliquer ou supprimer avec le contenu","Drag overview strip": "Glisser le bandeau d’aperçu","Drag overview edge": "Glisser le bord de l’aperçu","Zoom by resizing the viewport window": "Zoomer en redimensionnant la fenêtre de visualisation",@@ -1069,6 +1075,24 @@"Back to the automatic name ({0}), which follows the section's position": "Retour au nom automatique ({0}), qui suit la position de la section","No section at the playhead": "Aucune section à la tête de lecture","{0} already has its automatic name": "{0} a déjà son nom automatique",+ "Move section earlier": "Déplacer la section plus tôt",+ "Move section later": "Déplacer la section plus tard",+ "Duplicate section with content": "Dupliquer la section avec son contenu",+ "Delete section with content": "Supprimer la section avec son contenu",+ "Move earlier": "Déplacer plus tôt",+ "Move later": "Déplacer plus tard",+ "Duplicate with content": "Dupliquer avec le contenu",+ "Delete with content": "Supprimer avec le contenu",+ "{0} overlaps another section — separate them to move its content with it": "{0} chevauche une autre section — les séparer pour déplacer son contenu avec elle",+ "{0} is already the last section": "{0} est déjà la dernière section",+ "{0} is already the first section": "{0} est déjà la première section",+ "Couldn't move {0} there": "Impossible de déplacer {0} à cet endroit",+ "Moved {0} later": "{0} déplacée plus tard",+ "Moved {0} earlier": "{0} déplacée plus tôt",+ "Duplicated {0} with its content": "{0} dupliquée avec son contenu",+ "Couldn't duplicate {0}": "Impossible de dupliquer {0}",+ "Deleted {0} with its content": "{0} supprimée avec son contenu",+ "Couldn't delete {0}": "Impossible de supprimer {0}","“{0}” is {1} again": "“{0}” redevient {1}","Reset to default name": "Rétablir le nom par défaut","Loop section": "Boucler la section",@@ -1290,7 +1314,6 @@"Reveal failed: {0}": "Échec de l’affichage : {0}","Delete project": "Supprimer le projet","Move “{0}” to the Trash?": "Mettre « {0} » à la corbeille ?",- "Couldn't delete {0}": "Impossible de supprimer {0}","Moved {0} to Trash": "{0} mis à la corbeille","Delete preset": "Supprimer le préréglage","Preset name": "Nom du préréglage",@@ -1642,7 +1665,7 @@"Count-in before Play / Record: off · 1 · 2 · 4 bars": "Décompte avant Lecture / Enregistrement : désactivé · 1 · 2 · 4 mesures","A multi-selection gets its own menu: colour, height, freeze, group, copy, duplicate, delete": "Une sélection multiple a son propre menu : couleur, hauteur, gel, groupe, copie, duplication, suppression","Resize the track (header or lane) · snaps to compact / standard / large · a multi-selection resizes together": "Redimensionner la piste (en-tête ou couloir) · se cale sur compact / standard / grand · une sélection multiple se redimensionne ensemble",- "Move / resize it, snapped to bars": "La déplacer / redimensionner, calée sur les mesures",+ "Resize it, snapped to bars": "La redimensionner, calée sur les mesures","Drag sideways to scroll · up / down to zoom out / in": "Glisser latéralement pour défiler · vers le haut / le bas pour dézoomer / zoomer","Reorder devices (or right-click the header → Move left / right)": "Réordonner les appareils (ou clic droit sur l’en-tête → Déplacer à gauche / à droite)","A / B compare, move, copy, delete, presets, save preset": "Comparaison A / B, déplacer, copier, supprimer, préréglages, enregistrer le préréglage",diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.csindex 62932787..039c2ad2 100644--- a/src/managed/Nota.App/MainWindow.Commands.cs+++ b/src/managed/Nota.App/MainWindow.Commands.cs@@ -33,6 +33,9 @@ public partial class MainWindowvar r = _commands;r.ContextProvider = () => SnapshotContext(null);void B(string id, Action run, Func<PaletteContext, Availability>? can = null) => r.Bind(id, (_, _) => run(), can);+ // Section edits with content (specs/073) report in the status bar; the Session view's+ // clip lists may have changed with them.+ void SectionStatus(string status) { if (_vm is not null) _vm.StatusText = status; _session?.Refresh(); }var e = new RoutedEventArgs();static Availability Need(bool ok, string why) => ok ? Availability.Yes : Availability.No(why);@@ -82,6 +85,10 @@ public partial class MainWindowB("view.toggleOverview", () => OnMenuToggleOverview(this, e));B("view.toggleSections", () => OnMenuToggleSections(this, e));B("edit.resetSectionName", () => { string status = Timeline.ResetSectionNameAtPlayhead(); if (_vm is not null) _vm.StatusText = status; });+ B("edit.moveSectionEarlier", () => SectionStatus(Timeline.MoveSectionAtPlayhead(later: false)));+ B("edit.moveSectionLater", () => SectionStatus(Timeline.MoveSectionAtPlayhead(later: true)));+ B("edit.duplicateSectionWithContent", () => SectionStatus(Timeline.DuplicateSectionWithContentAtPlayhead()));+ B("edit.deleteSectionWithContent", () => SectionStatus(Timeline.DeleteSectionWithContentAtPlayhead()));B("view.follow", () => OnMenuToggleFollow(this, e));B("view.showPlayhead", ShowPlayhead);B("view.clipNames", () => OnMenuCycleClipNames(this, e));diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 468a7431..096cb41e 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1607,7 +1607,10 @@ public sealed partial class PreferencesWindow : NotaWindow(Loc.T("Click section"), Loc.T("Jump the playhead to its start")),(Loc.T("Double-click section"), Loc.T("Rename it · right-click → Reset to default name for its automatic Section N")),(Loc.T("Return · Esc (renaming a section)"), Loc.T("Keep the name (empty = automatic) · cancel")),- (Loc.T("Drag section · its edge"), Loc.T("Move / resize it, snapped to bars")),+ (Loc.T("Drag section"), Loc.T("Rearrange the song · it and everything in it move to the marked boundary, the sections between close up · Esc cancels")),+ (Loc.T("⌥-drag section"), Loc.T("Move only the section marker, snapped to bars")),+ (Loc.T("Drag section edge"), Loc.T("Resize it, snapped to bars")),+ (Loc.T("Right-click section"), Loc.T("Move earlier / later · duplicate or delete with content")),(Loc.T("Drag overview strip"), Loc.T("Drag sideways to scroll · up / down to zoom out / in")),(Loc.T("Drag overview edge"), Loc.T("Zoom by resizing the viewport window")),(Loc.T("Double-click overview"), Loc.T("Fit the whole project on screen")),diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 99c9e844..7e56cf56 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -1110,6 +1110,19 @@ public interface IAudioEngine : IDisposable/// <summary>Replaces the sections (sorted; zero-length dropped). <paramref name="checkpoint"/>/// = one undo step (an identical list makes none); false = baseline (project load).</summary>void SetSections(IReadOnlyList<SectionInfo> sections, bool checkpoint = true);+ /// <summary>Moves section <paramref name="index"/> (start order) with everything in its span+ /// to boundary <paramref name="toBoundary"/> (0..Count: before section k, or after the last);+ /// the sections in between shift by its length (specs/073). One undo step; false — nothing+ /// changed — when out of range, overlapping, landing inside an overlap, or a no-op.</summary>+ bool MoveSection(int index, int toBoundary);+ /// <summary>Inserts a copy of the section and everything in its span right after it, moving+ /// the rest of the song later (specs/073). One undo step; false as for <see cref="MoveSection"/>.</summary>+ bool DuplicateSectionWithContent(int index);+ /// <summary>Removes the section and everything in its span, moving the rest of the song+ /// earlier (specs/073). One undo step; false as for <see cref="MoveSection"/>.</summary>+ bool DeleteSectionWithContent(int index);+ /// <summary>True when the section overlaps another: the with-content edits are unavailable.</summary>+ bool SectionOverlaps(int index);// --- Value undo (specs/009, specs/016) -------------------------------/// <summary>Starts a gesture on volume / pan / master volume / device parameters: theirdiff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.csindex 9ac4e8da..bf6cac72 100644--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs@@ -64,6 +64,10 @@ public static class CommandCatalogC("view.toggleOverview", Loc.T("Toggle overview"), Loc.T("View"), "", "minimap", view: "Arrangement"),C("view.toggleSections", Loc.T("Toggle sections"), Loc.T("View"), "", "markers locators", view: "Arrangement"),C("edit.resetSectionName", Loc.T("Reset section name"), Loc.T("Edit"), "", "default automatic rename section at playhead", view: "Arrangement"),+ C("edit.moveSectionEarlier", Loc.T("Move section earlier"), Loc.T("Edit"), "", "rearrange reorder section content left before previous at playhead", view: "Arrangement"),+ C("edit.moveSectionLater", Loc.T("Move section later"), Loc.T("Edit"), "", "rearrange reorder section content right after next at playhead", view: "Arrangement"),+ C("edit.duplicateSectionWithContent", Loc.T("Duplicate section with content"), Loc.T("Edit"), "", "copy repeat section clips automation ripple at playhead", view: "Arrangement"),+ C("edit.deleteSectionWithContent", Loc.T("Delete section with content"), Loc.T("Edit"), "", "remove cut section clips automation ripple close gap at playhead", view: "Arrangement"),C("view.follow", Loc.T("Follow playhead"), Loc.T("View"), "", "scroll"),C("view.showPlayhead", Loc.T("Show playhead"), Loc.T("View"), Shortcut.None('P'), "find locate scroll reveal cursor position", view: "Arrangement"),C("view.clipNames", Loc.T("Cycle clip names"), Loc.T("View"), "", "labels", view: "Arrangement"),diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex da451464..f321494b 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -235,6 +235,18 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_set_sections")]internal static partial NotaResult SetSections(IntPtr engine, [In] NotaSection[] sections, int count, int checkpoint);+ [LibraryImport(Lib, EntryPoint = "nota_section_move")]+ internal static partial NotaResult SectionMove(IntPtr engine, int index, int toBoundary);++ [LibraryImport(Lib, EntryPoint = "nota_section_duplicate_with_content")]+ internal static partial NotaResult SectionDuplicateWithContent(IntPtr engine, int index);++ [LibraryImport(Lib, EntryPoint = "nota_section_delete_with_content")]+ internal static partial NotaResult SectionDeleteWithContent(IntPtr engine, int index);++ [LibraryImport(Lib, EntryPoint = "nota_section_overlaps")]+ internal static partial int SectionOverlaps(IntPtr engine, int index);+[LibraryImport(Lib, EntryPoint = "nota_mix_gesture_begin")]internal static partial int MixGestureBegin(IntPtr engine, [In] MixTarget[] targets, int count);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex 2784e275..a6688dd2 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -217,6 +217,14 @@ public sealed partial class NotaEngine : IAudioEngineforeach (var r in rows) if (r.Name != IntPtr.Zero) Marshal.FreeCoTaskMem(r.Name);}}+ public bool MoveSection(int index, int toBoundary)+ { ThrowIfDisposed(); return NativeMethods.SectionMove(_handle, index, toBoundary) == NativeMethods.NotaResult.Ok; }+ public bool DuplicateSectionWithContent(int index)+ { ThrowIfDisposed(); return NativeMethods.SectionDuplicateWithContent(_handle, index) == NativeMethods.NotaResult.Ok; }+ public bool DeleteSectionWithContent(int index)+ { ThrowIfDisposed(); return NativeMethods.SectionDeleteWithContent(_handle, index) == NativeMethods.NotaResult.Ok; }+ public bool SectionOverlaps(int index)+ { ThrowIfDisposed(); return NativeMethods.SectionOverlaps(_handle, index) != 0; }// --- Value undo (specs/009, specs/016) -------------------------------------public int BeginMixGesture(params MixTarget[] targets)diff --git a/src/managed/Nota.Mcp/Tools/ProjectTools.cs b/src/managed/Nota.Mcp/Tools/ProjectTools.csindex 5fcd480c..dd45ddfe 100644--- a/src/managed/Nota.Mcp/Tools/ProjectTools.cs+++ b/src/managed/Nota.Mcp/Tools/ProjectTools.cs@@ -2,7 +2,7 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// MCP tools — whole-project snapshot (so the AI can see before it acts), undo/redo and the-// arrangement's song sections.+// arrangement's song sections, including rearranging the song by them (specs/073).using System.ComponentModel;using ModelContextProtocol.Server;@@ -82,4 +82,46 @@ public sealed class ProjectTools(IAudioEngine engine, IEngineDispatch dispatch,s.Automatic || SectionNames.IsAutomatic(s.Name) ? "" : s.Name)).ToList());return Listed();});++ // The with-content edits refuse the same cases the Sections lane does; say which one.+ private string Refusal(int index, string what)+ {+ int n = E.Sections.Count;+ if (index < 0 || index >= n) return $"There is no section {index} (list_sections has {n}).";+ if (E.SectionOverlaps(index)) return $"Section {index} overlaps another section, so it can't {what}; separate them first with set_sections.";+ return $"Section {index} can't {what} there.";+ }++ [McpServerTool(Name = "move_section"), Description(+ "Rearrange the song: move section `index` (list_sections order) together with everything in its span — audio and MIDI "+ + "clips (cut at its edges), automation on every track and the master, take lanes — to boundary `toBoundary` "+ + "(0..count: before section k, or after the last section when it equals the count). The sections it passes shift by "+ + "its length to make room; the song's length is unchanged and nothing outside the affected span moves. "+ + "Moving to its own place (toBoundary = index or index + 1) is an error. A section that overlaps another can't be moved "+ + "with content. One undo step. Returns the sections in their new order.")]+ public Task<Section[]> MoveSection(int index, int toBoundary) => Mutate(() =>+ {+ if (toBoundary == index || toBoundary == index + 1) throw new ArgumentException($"Section {index} is already at boundary {toBoundary}.");+ if (!E.MoveSection(index, toBoundary)) throw new InvalidOperationException(Refusal(index, "move with its content"));+ return Listed();+ });++ [McpServerTool(Name = "duplicate_section_with_content"), Description(+ "Insert a copy of section `index` (list_sections order) and everything in its span — clips, automation — right after it, "+ + "with the same name (an automatic name stays automatic); the rest of the song moves later by its length. "+ + "One undo step. Returns the sections.")]+ public Task<Section[]> DuplicateSectionWithContent(int index) => Mutate(() =>+ {+ if (!E.DuplicateSectionWithContent(index)) throw new InvalidOperationException(Refusal(index, "be duplicated with its content"));+ return Listed();+ });++ [McpServerTool(Name = "delete_section_with_content"), Description(+ "Remove section `index` (list_sections order) and everything in its span — clips (cut at its edges), automation — and "+ + "move the rest of the song earlier by its length to close the gap. One undo step. Returns the remaining sections.")]+ public Task<Section[]> DeleteSectionWithContent(int index) => Mutate(() =>+ {+ if (!E.DeleteSectionWithContent(index)) throw new InvalidOperationException(Refusal(index, "be deleted with its content"));+ return Listed();+ });}diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 721e4ce1..4e254d93 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -1095,6 +1095,23 @@ NOTA_API const char* nota_engine_section_name(const NotaEngine* engine, int32_t* undo entry (project load). count 0 clears. Message thread only. */NOTA_API NotaResult nota_engine_set_sections(NotaEngine* engine, const NotaSection* sections,int32_t count, int32_t checkpoint);+/* Section edits that carry the arrangement with them (specs/073). Indices are into the+ * start-sorted section list. Each is one undo step covering clips (audio + MIDI, cut at the+ * edges), automation (every track, the master track, master volume), take lanes and the+ * sections; the playhead does not move. NOTA_ERR_INVALID_ARG (nothing changed) for an index+ * out of range, a section that overlaps another, a target inside an overlap, or a no-op.+ * Message thread only.+ * move: insert section `index` at boundary `to_boundary` (0..count: before section k, or+ * after the last when == count); the sections in between shift by its length, the song's+ * length is unchanged.+ * duplicate_with_content: a copy of the section and everything in its span goes right after+ * it (same name; automatic stays automatic); the rest of the song moves later by its length.+ * delete_with_content: the section and everything in its span go; the rest moves earlier. */+NOTA_API NotaResult nota_section_move(NotaEngine* engine, int32_t index, int32_t to_boundary);+NOTA_API NotaResult nota_section_duplicate_with_content(NotaEngine* engine, int32_t index);+NOTA_API NotaResult nota_section_delete_with_content(NotaEngine* engine, int32_t index);+/* 1 when section `index` overlaps another (the with-content edits are unavailable), else 0. */+NOTA_API int32_t nota_section_overlaps(const NotaEngine* engine, int32_t index);/* ---- Project load (M7-6) ------------------------------------------------- *//* Clear the session to an empty project: stop transport, drop all tracks,diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cppindex 407e9f01..8dd1a87f 100644--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp@@ -419,6 +419,18 @@ NotaResult nota_engine_set_sections(NotaEngine* e, const NotaSection* sections,ENG(e)->setSections(std::move(v), checkpoint != 0);return NOTA_OK;}+NotaResult nota_section_move(NotaEngine* e, int32_t index, int32_t to_boundary) {+ return e && ENG(e)->moveSection(index, to_boundary) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+NotaResult nota_section_duplicate_with_content(NotaEngine* e, int32_t index) {+ return e && ENG(e)->duplicateSectionWithContent(index) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+NotaResult nota_section_delete_with_content(NotaEngine* e, int32_t index) {+ return e && ENG(e)->deleteSectionWithContent(index) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_section_overlaps(const NotaEngine* e, int32_t index) {+ return e && CENG(e)->sectionOverlaps(index) ? 1 : 0;+}// ---- Project reset (M7-6) -------------------------------------------------diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex eb3e108e..0c32948d 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -1374,6 +1374,20 @@ class Engine {// Arrangement sections (specs/016): project-level, replaced as a whole. checkpoint =// one undo step (an identical list makes none); false = baseline (project load).void setSections(std::vector<Section> sections, bool checkpoint);+ // Section edits that carry the arrangement with them (specs/073). `index` is into the+ // start-sorted list. Each is one undo step over clips (cut at the edges), automation (every+ // track, the master track, master volume), take lanes and the sections; the playhead stays.+ // False — nothing changed — for an index out of range, a section that overlaps another, a+ // target inside an overlap, or a no-op. moveSection inserts the section at boundary+ // `toBoundary` (0..count: before section k, or after the last), shifting the sections in+ // between by its length; duplicate inserts a copy right after it and delete removes it,+ // both rippling the rest of the song.+ bool moveSection(int32_t index, int32_t toBoundary);+ bool duplicateSectionWithContent(int32_t index);+ bool deleteSectionWithContent(int32_t index);+ // True when section `index`'s span intersects another section's (with-content edits are+ // unavailable for it).+ bool sectionOverlaps(int32_t index) const;const std::vector<Section>& sections() const {static const std::vector<Section> none;return authoring_ ? authoring_->sections : none;@@ -1492,6 +1506,12 @@ class Engine {void republishWithTrack(int32_t trackId, std::shared_ptr<Track> nt); // checkpointsvoid republishWithTrackRaw(int32_t trackId, std::shared_ptr<Track> nt); // no undo entryvoid pushUndo(); // snapshot authoring_ onto the undo stack, clear redo+ // specs/073: rebuild the arrangement with [lo,hi) remapped by `regions` (which tile it),+ // set `sections`, and publish it as one undo step.+ void remapTimeline(double lo, double hi, const std::vector<TimeRegion>& regions, std::vector<Section> sections);+ // insertTime's track/lane work into a fresh graph `g` (graph-level fields already+ // inherited); false when nothing moved.+ bool insertTimeInto(Graph& g, double at, double len, bool duplicate);void reapplyRackMacros(); // after undo/redo: racks drive their shared children againvoid reapplyCcRoutes(); // after undo/redo: Arps take their restored snapshot's targetsvoid syncCcRoutes(Graph& g); // before a publish: routes of fresh tracks from their Arpsdiff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cppindex d454dc69..c22160cd 100644--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp@@ -1324,6 +1324,56 @@ double placeAudioNonOverlap(const Track& t, double start, double len, double spb// --- overwrite / comp: carve existing clips out of a timeline range ---------// Replace-on-drop: a newly placed clip (recorded / dragged) replaces the region it covers.// The parts of an existing clip outside the range survive as trimmed remainders.+// The curvature of the lane's segment running through `t` (0 before the first point).+float curveThrough(const AutomationLane& lane, double t) {+ float c = 0.0f;+ for (const auto& q : lane.points) {+ if (q.beat > t + 1e-9) break;+ c = q.curve;+ }+ return c;+}++// Append the lane from `t` up to (not including) its next point, shifted by `shift`, stopping+// before `limit`. Cut at its end a power curve keeps its shape with the same curve (t^e+// scales), but cut at its start it is no power curve any more: that partial segment is laid+// as short straight pieces, well under 0.1 % off.+void appendLaneFrom(std::vector<AutomationPoint>& out, const AutomationLane& lane, double t, double limit, double shift) {+ constexpr double eps = 1e-9;+ constexpr int pieces = 32;+ const auto& p = lane.points;+ const auto next = std::find_if(p.begin(), p.end(), [&](const AutomationPoint& q) { return q.beat > t + eps; });+ const bool before = next != p.begin(), onPoint = before && std::abs(std::prev(next)->beat - t) < eps;+ const float k = before ? std::prev(next)->curve : 0.0f;+ if (k == 0.0f || onPoint || next == p.end()) {+ out.push_back({t + shift, lane.valueAt(t), onPoint ? k : 0.0f});+ return;+ }+ out.push_back({t + shift, lane.valueAt(t), 0.0f});+ for (int i = 1; i < pieces; ++i) {+ const double b = t + (next->beat - t) * i / pieces;+ if (b >= limit - eps) break;+ out.push_back({b + shift, lane.valueAt(b), 0.0f});+ }+}++// The lane over [a,b] re-based so `a` is 0, playing as it did: the value at each edge plus+// every point strictly inside. Empty when the lane is.+std::vector<AutomationPoint> laneSliceExact(const AutomationLane& lane, double a, double b) {+ constexpr double eps = 1e-9;+ std::vector<AutomationPoint> out;+ if (lane.points.empty()) return out;+ appendLaneFrom(out, lane, a, b, -a);+ for (const auto& q : lane.points)+ if (q.beat > a + eps && q.beat < b - eps) {+ if (!out.empty() && q.beat - a <= out.back().beat + eps) continue;+ out.push_back({q.beat - a, q.value, q.curve});+ }+ out.push_back({b - a, lane.valueAt(b), 0.0f});+ return out;+}++MidiClip midiCarveLeft(const MidiClip& src, double endLocal) { // keep [start, start+endLocal)MidiClip r;r.name = src.name;@@ -1423,15 +1473,38 @@ void audioOverwriteRange(std::vector<AudioClip>& clips, double ns, double ne, do}// A clip clipped to the timeline range [ns,ne] (its intersection), timeline positions// preserved — used to lift the covered slice for a range duplicate.+// The carves keep a MIDI piece's notes and controllers only, and leave an audio piece's+// envelopes where the whole clip had them. A slice is a piece that moves on its own (range+// duplicate, insert time, section edits — specs/073), so it also keeps the clip's+// deactivation and its own share of the envelopes. (The carves themselves stay lean: a split+// is a hot edit, perf-gate edit-warp-split.)MidiClip midiSlice(const MidiClip& c, double ns, double ne) {const double cs = c.startBeat, ce = cs + c.lengthBeats;const double a = std::max(cs, ns), b = std::min(ce, ne);- return midiCarveLeft(midiCarveRight(c, a - cs), b - a);+ MidiClip r = midiCarveLeft(midiCarveRight(c, a - cs), b - a);+ r.active = c.active;+ if (!c.velocityEnvelope.points.empty()) {+ r.velocityEnvelope = c.velocityEnvelope;+ r.velocityEnvelope.points = laneSliceExact(c.velocityEnvelope, a - cs, b - cs);+ }+ if (!c.volumeEnvelope.points.empty()) {+ r.volumeEnvelope = c.volumeEnvelope;+ r.volumeEnvelope.points = laneSliceExact(c.volumeEnvelope, a - cs, b - cs);+ }+ return r;}AudioClip audioSlice(const AudioClip& c, double ns, double ne, double spb, double devSR) {const double cs = c.startBeat, ce = cs + audioDisplayLenBeats(c, spb, devSR);const double a = std::max(cs, ns), b = std::min(ce, ne);- return audioCarveLeft(audioCarveRight(c, a - cs, spb, devSR), b - a, spb, devSR);+ // Carve only the edges that are cut: a carve resets that edge's ADSR stages (attack and+ // decay at a new head, release at a new tail), and a piece that keeps the clip's own start+ // or end keeps the user's fade there.+ constexpr double eps = 1e-6;+ AudioClip r = a > cs + eps ? audioCarveRight(c, a - cs, spb, devSR) : c;+ if (b < ce - eps) r = audioCarveLeft(r, b - a, spb, devSR);+ if (!c.volumeEnvelope.points.empty()) r.volumeEnvelope.points = laneSliceExact(c.volumeEnvelope, a - cs, b - cs);+ if (!c.panEnvelope.points.empty()) r.panEnvelope.points = laneSliceExact(c.panEnvelope, a - cs, b - cs);+ return r;}} // namespace@@ -1922,21 +1995,10 @@ double Engine::duplicateRange(const std::vector<int32_t>& trackIds, double start// --- insert time (Insert Silence ⌘⇧I / Duplicate Time ⌘⇧D) ----------------------namespace {-// The lane's curve over [a,b] re-based so `a` is 0: the value at each edge plus every point-// strictly inside (a partial first segment keeps its curvature).+// The lane's curve over [a,b] re-based so `a` is 0 (laneSliceExact: the value at each edge,+// every point strictly inside, a curved segment cut at its start laid as short straight pieces).std::vector<AutomationPoint> laneSlice(const AutomationLane& lane, double a, double b) {- constexpr double eps = 1e-9;- std::vector<AutomationPoint> out;- float c0 = 0.0f;- for (const auto& q : lane.points) {- if (q.beat > a + eps) break;- c0 = q.curve;- }- out.push_back({0.0, lane.valueAt(a), c0});- for (const auto& q : lane.points)- if (q.beat > a + eps && q.beat < b - eps) out.push_back({q.beat - a, q.value, q.curve});- out.push_back({b - a, lane.valueAt(b), 0.0f});- return out;+ return laneSliceExact(lane, a, b);}// Opens a `len`-beat gap at `at`: points at or after `at` move right. With `fill` (a@@ -1976,8 +2038,17 @@ bool laneInsertGap(AutomationLane& lane, double at, double len, const std::vectobool Engine::insertTime(double at, double len, bool duplicate) {at = std::max(0.0, at);if (len <= 1e-9) return false;+ if (duplicate && at - len < -1e-9) return false;+ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, *authoring_);+ if (!insertTimeInto(*g, at, len, duplicate)) return false;+ pushUndo();+ publishRaw(std::move(g));+ return true;+}++bool Engine::insertTimeInto(Graph& g, double at, double len, bool duplicate) {const double src = at - len; // Duplicate Time copies [src, at) into the gap- if (duplicate && src < -1e-9) return false;const double spb = transport_.samplesPerBeat(), devSR = transport_.sampleRate();constexpr double eps = 1e-6;@@ -2057,23 +2128,370 @@ bool Engine::insertTime(double at, double len, bool duplicate) {};bool any = false;- auto g = std::make_shared<Graph>();- inheritGraphLevel(*g, *authoring_);- any |= shiftLane(g->masterVolume);- if (g->masterTrack)- if (auto nm = shiftTrack(*g->masterTrack)) {- g->masterTrack = nm;+ any |= shiftLane(g.masterVolume);+ if (g.masterTrack)+ if (auto nm = shiftTrack(*g.masterTrack)) {+ g.masterTrack = nm;any = true;}- g->tracks.reserve(authoring_->tracks.size());+ g.tracks.reserve(authoring_->tracks.size());for (auto& t : authoring_->tracks) {if (auto nt = shiftTrack(*t)) {- g->tracks.push_back(nt);+ g.tracks.push_back(nt);any = true;} else- g->tracks.push_back(t);+ g.tracks.push_back(t);}- if (!any) return false;+ return any;+}++// --- section edits with content (specs/073) ----------------------------------------+// Moving, duplicating or deleting a section carries everything in its span. A move is a+// remap of a window [lo,hi) tiled by regions that each shift by their own offset (the moved+// section one way, the material it passes the other), so clips, lanes, takes and sections+// all follow the same map and cannot drift apart. Clips are cut where a region ends, like+// Insert silence; each lane plays every region's own curve, stepping at a join.+namespace {++constexpr double kSecEps = 1e-6;++const TimeRegion* regionAt(const std::vector<TimeRegion>& rs, double t) {+ for (const auto& r : rs)+ if (t >= r.start - kSecEps && t < r.end - kSecEps) return &r;+ return nullptr;+}++// Cut every clip crossing a region edge and shift each piece by its region's offset (dropped+// regions lose theirs); what lies outside [lo,hi) stays. True when a clip was touched.+template <class Clip, class LenFn, class SliceFn>+bool remapClips(std::vector<Clip>& clips, double lo, double hi, const std::vector<TimeRegion>& rs, LenFn len,+ SliceFn slice) {+ std::vector<Clip> out;+ out.reserve(clips.size() + 4);+ bool changed = false;+ for (const auto& c : clips) {+ const double cs = c.startBeat, ce = cs + len(c);+ if (ce <= lo + kSecEps || cs >= hi - kSecEps) {+ out.push_back(c);+ continue;+ }+ changed = true;+ if (cs < lo - kSecEps) out.push_back(slice(c, cs, lo));+ for (const auto& r : rs) {+ const double a = std::max(cs, r.start), b = std::min(ce, r.end);+ if (r.drop || b <= a + kSecEps) continue;+ Clip piece = a <= cs + kSecEps && b >= ce - kSecEps ? c : slice(c, a, b);+ piece.startBeat += r.offset;+ out.push_back(std::move(piece));+ }+ if (ce > hi + kSecEps) out.push_back(slice(c, hi, ce));+ }+ clips.swap(out);+ return changed;+}++// Two points on one beat make a step, but AutomationLane::valueAt returns the first (outgoing)+// value exactly on that beat — so a section starting there would begin with its neighbour's+// setting for a block. The outgoing point moves a hair earlier (a millionth of a beat, under a+// sample at any tempo), so the incoming value holds from the join itself; where there is no+// room for it (beat 0, or right after another point) it goes, and an equal pair is merged.+void settleJoins(std::vector<AutomationPoint>& pts) {+ constexpr double eps = 1e-9, nudge = 1e-6;+ std::vector<AutomationPoint> out;+ out.reserve(pts.size());+ for (size_t i = 0; i < pts.size(); ++i) {+ const bool join = i + 1 < pts.size() && std::abs(pts[i + 1].beat - pts[i].beat) < eps;+ if (!join) {+ out.push_back(pts[i]);+ continue;+ }+ if (pts[i + 1].value == pts[i].value) continue; // same value: the incoming point alone+ AutomationPoint q = pts[i];+ q.beat -= nudge;+ if (q.beat < 0.0 || (!out.empty() && out.back().beat > q.beat - eps)) continue; // no room: drop it+ out.push_back(q);+ }+ pts.swap(out);+}++// Rebuild the lane over [lo,hi): points before and after keep their place, each kept region's+// curve (laneSlice: exact values at both edges) is laid at its new start, in new order. Every+// cut and join holds the value the original had there (FR-005). False when the lane is empty+// or holds one value through the window.+bool laneRemap(AutomationLane& lane, double lo, double hi, const std::vector<TimeRegion>& rs) {+ constexpr double eps = 1e-9;+ auto& p = lane.points;+ if (p.empty() || p.back().beat < lo - eps) return false;+ if (std::isfinite(hi) && p.front().beat > hi + eps) return false;++ std::vector<AutomationPoint> out;+ out.reserve(p.size() + 2 * rs.size() + 2);+ for (const auto& q : p)+ if (q.beat < lo - eps) out.push_back(q);+ out.push_back({lo, lane.valueAt(lo), 0.0f}); // the left side ends (or holds) as it did++ std::vector<const TimeRegion*> order;+ for (const auto& r : rs)+ if (!r.drop) order.push_back(&r);+ std::sort(order.begin(), order.end(),+ [](const TimeRegion* a, const TimeRegion* b) { return a->start + a->offset < b->start + b->offset; });+ for (const TimeRegion* r : order) {+ const double at = r->start + r->offset;+ if (std::isfinite(r->end)) {+ for (auto q : laneSlice(lane, r->start, r->end)) {+ q.beat += at;+ out.push_back(q);+ }+ } else { // to the end of the song: the curve from its start, then every later point+ appendLaneFrom(out, lane, r->start, std::numeric_limits<double>::infinity(), r->offset);+ for (const auto& q : p)+ if (q.beat > r->start + eps) out.push_back({q.beat + r->offset, q.value, q.curve});+ }+ }++ if (std::isfinite(hi)) {+ // The right side starts (or holds) on hi as it did, playing the rest of the segment+ // that ran through it.+ const auto right = std::find_if(p.begin(), p.end(), [&](const AutomationPoint& q) { return q.beat > hi + eps; });+ appendLaneFrom(out, lane, hi, std::numeric_limits<double>::infinity(), 0.0);+ out.insert(out.end(), right, p.end());+ }+ settleJoins(out);+ p.swap(out);+ return true;+}++// The lane with a copy of [a,b) inserted at b (Duplicate with content): the original up to b,+// the copy, then the rest from b on, later by the section's length — every piece playing as+// it did, cuts laid as in laneRemap. False when the lane is empty or holds one value from a on.+bool laneDuplicate(AutomationLane& lane, double a, double b) {+ constexpr double eps = 1e-9;+ auto& p = lane.points;+ if (p.empty() || p.back().beat < a - eps) return false;+ const double len = b - a;+ std::vector<AutomationPoint> out;+ out.reserve(p.size() * 2 + 4);+ for (const auto& q : p)+ if (q.beat < b - eps) out.push_back(q);+ out.push_back({b, lane.valueAt(b), 0.0f}); // the left side ends as it did+ for (auto q : laneSliceExact(lane, a, b)) {+ q.beat += b;+ out.push_back(q);+ }+ appendLaneFrom(out, lane, b, std::numeric_limits<double>::infinity(), len);+ for (const auto& q : p)+ if (q.beat > b + eps) out.push_back({q.beat + len, q.value, q.curve});+ settleJoins(out);+ p.swap(out);+ return true;+}++} // namespace++void Engine::remapTimeline(double lo, double hi, const std::vector<TimeRegion>& rs, std::vector<Section> sections) {+ const double spb = transport_.samplesPerBeat(), devSR = transport_.sampleRate();+ auto remapTrack = [&](const Track& t) -> std::shared_ptr<Track> {+ auto nt = cloneTrack(t);+ bool changed = false;+ if (nt->type() == TrackType::Instrument)+ changed |= remapClips(+ nt->midiClips, lo, hi, rs, [](const MidiClip& c) { return c.lengthBeats; },+ [](const MidiClip& c, double a, double b) { return midiSlice(c, a, b); });+ else if (nt->type() == TrackType::Audio)+ changed |= remapClips(+ nt->clips, lo, hi, rs, [&](const AudioClip& c) { return audioDisplayLenBeats(c, spb, devSR); },+ [&](const AudioClip& c, double a, double b) { return audioSlice(c, a, b, spb, devSR); });+ for (auto& lane : nt->automation) changed |= laneRemap(lane, lo, hi, rs);+ // A take travels with the region its first played frame is in, so the comp sections+ // still where it put them stay on it (specs/067).+ for (auto& k : nt->takes)+ if (const TimeRegion* r = regionAt(rs, k.originBeat + k.sourceOffsetFrames * k.beatsPerFrame);+ r && !r->drop && r->offset != 0.0) {+ k.originBeat += r->offset;+ changed = true;+ }+ return changed ? nt : nullptr;+ };++ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, *authoring_);+ laneRemap(g->masterVolume, lo, hi, rs);+ if (g->masterTrack)+ if (auto nm = remapTrack(*g->masterTrack)) g->masterTrack = nm;+ g->tracks.reserve(authoring_->tracks.size());+ for (auto& t : authoring_->tracks) {+ auto nt = remapTrack(*t);+ g->tracks.push_back(nt ? nt : t);+ }+ std::stable_sort(sections.begin(), sections.end(),+ [](const Section& a, const Section& b) { return a.startBeat < b.startBeat; });+ g->sections = std::move(sections);+ pushUndo();+ publishRaw(std::move(g));+}++bool Engine::sectionOverlaps(int32_t index) const {+ const auto& ss = sections();+ if (index < 0 || index >= static_cast<int32_t>(ss.size())) return false;+ const Section& s = ss[index];+ for (int32_t i = 0; i < static_cast<int32_t>(ss.size()); ++i) {+ if (i == index) continue;+ const double a = std::max(s.startBeat, ss[i].startBeat);+ const double b = std::min(s.startBeat + s.lengthBeats, ss[i].startBeat + ss[i].lengthBeats);+ if (b - a > kSecEps) return true;+ }+ return false;+}++namespace {+// True when `beat` lies strictly inside a section's span — a cut there would split it.+bool insideSection(const std::vector<Section>& ss, double beat) {+ for (const auto& s : ss)+ if (beat > s.startBeat + kSecEps && beat < s.startBeat + s.lengthBeats - kSecEps) return true;+ return false;+}+} // namespace++bool Engine::moveSection(int32_t index, int32_t toBoundary) {+ if (!authoring_) return false;+ const auto& ss = authoring_->sections;+ const auto n = static_cast<int32_t>(ss.size());+ if (index < 0 || index >= n || toBoundary < 0 || toBoundary > n) return false;+ if (toBoundary == index || toBoundary == index + 1) return false; // already there+ if (sectionOverlaps(index)) return false;+ double end = 0.0; // "after the last section": the end of the song's structure+ for (const auto& s : ss) end = std::max(end, s.startBeat + s.lengthBeats);+ const double a = ss[index].startBeat, b = a + ss[index].lengthBeats, len = b - a;+ const double d = toBoundary < n ? ss[toBoundary].startBeat : end;+ if (insideSection(ss, d)) return false;++ std::vector<TimeRegion> rs;+ double lo, hi;+ if (d <= a) { // earlier: [d,a) moves right by the section's length, the section lands on d+ lo = d;+ hi = b;+ rs.push_back({d, a, len, false});+ rs.push_back({a, b, d - a, false});+ } else { // later: [b,d) moves left, the section lands so it ends on d+ lo = a;+ hi = d;+ rs.push_back({a, b, d - b, false});+ rs.push_back({b, d, -len, false});+ }+ std::vector<Section> next = ss;+ for (auto& s : next)+ if (const TimeRegion* r = regionAt(rs, s.startBeat)) s.startBeat += r->offset;+ remapTimeline(lo, hi, rs, std::move(next));+ return true;+}++bool Engine::deleteSectionWithContent(int32_t index) {+ if (!authoring_) return false;+ const auto& ss = authoring_->sections;+ if (index < 0 || index >= static_cast<int32_t>(ss.size()) || sectionOverlaps(index)) return false;+ const double a = ss[index].startBeat, b = a + ss[index].lengthBeats, len = b - a;+ constexpr double inf = std::numeric_limits<double>::infinity();+ const std::vector<TimeRegion> rs{{a, b, 0.0, true}, {b, inf, -len, false}};+ std::vector<Section> next;+ next.reserve(ss.size());+ for (int32_t i = 0; i < static_cast<int32_t>(ss.size()); ++i) {+ if (i == index) continue;+ Section s = ss[i];+ if (s.startBeat >= b - kSecEps) s.startBeat -= len;+ next.push_back(std::move(s));+ }+ // Take lanes that start in the deleted span — picked before the remap shifts later ones in.+ std::set<int32_t> inSpan;+ for (const auto& t : authoring_->tracks)+ for (const auto& k : t->takes)+ if (const double ks = k.originBeat + k.sourceOffsetFrames * k.beatsPerFrame; ks >= a - kSecEps && ks < b - kSecEps)+ inSpan.insert(k.id);+ remapTimeline(a, inf, rs, std::move(next));+ if (inSpan.empty()) return true;+ // Such a take goes with the section, unless a comp clip still plays from it elsewhere+ // (specs/067).+ auto g = std::make_shared<Graph>(*authoring_);+ bool dropped = false;+ for (auto& t : g->tracks) {+ auto gone = [&](const AudioTake& k) {+ return inSpan.count(k.id) && std::none_of(t->clips.begin(), t->clips.end(), [&](const AudioClip& c) { return c.takeId == k.id; });+ };+ if (std::none_of(t->takes.begin(), t->takes.end(), gone)) continue;+ auto nt = cloneTrack(*t);+ std::erase_if(nt->takes, gone);+ t = nt;+ dropped = true;+ }+ if (dropped) publishRaw(std::move(g)); // part of the same undo step+ return true;+}++bool Engine::duplicateSectionWithContent(int32_t index) {+ if (!authoring_) return false;+ const auto& ss = authoring_->sections;+ if (index < 0 || index >= static_cast<int32_t>(ss.size()) || sectionOverlaps(index)) return false;+ const double a = ss[index].startBeat, b = a + ss[index].lengthBeats, len = b - a;+ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, *authoring_);+ insertTimeInto(*g, b, len, true); // nothing to copy is fine: the section still doubles+ // Automation: Duplicate time's gap closes a curved segment cut at b with a straight line, so+ // the lanes are rebuilt from the originals the way a move lays them (laneDuplicate).+ auto redoLanes = [&](std::shared_ptr<Track>& t, const Track& orig) {+ if (std::none_of(orig.automation.begin(), orig.automation.end(), [](const TrackLane& l) { return !l.points.empty(); }))+ return;+ auto nt = cloneTrack(*t);+ for (size_t j = 0; j < nt->automation.size() && j < orig.automation.size(); ++j) {+ nt->automation[j].points = orig.automation[j].points;+ laneDuplicate(nt->automation[j], a, b);+ }+ t = nt;+ };+ for (size_t i = 0; i < g->tracks.size() && i < authoring_->tracks.size(); ++i) redoLanes(g->tracks[i], *authoring_->tracks[i]);+ if (g->masterTrack && authoring_->masterTrack) redoLanes(g->masterTrack, *authoring_->masterTrack);+ g->masterVolume = authoring_->masterVolume;+ laneDuplicate(g->masterVolume, a, b);+ // Take lanes: later ones move with the song; one starting in the section gets a copy (a new+ // id and number) under the copied section, and the copied comp clips point at it so the+ // copy can be comped on its own (specs/067).+ auto takeStart = [](const AudioTake& k) { return k.originBeat + k.sourceOffsetFrames * k.beatsPerFrame; };+ for (auto& t : g->tracks) {+ if (t->takes.empty()) continue;+ auto nt = cloneTrack(*t);+ std::map<int32_t, int32_t> copied; // old take id -> its copy's+ int32_t number = 0;+ for (const auto& k : nt->takes) number = std::max(number, k.number);+ std::vector<AudioTake> copies;+ for (auto& k : nt->takes) {+ const double ks = takeStart(k);+ if (ks >= b - kSecEps) k.originBeat += len;+ else if (ks >= a - kSecEps) {+ AudioTake c = k;+ c.id = ++nextTakeId_;+ c.number = ++number;+ c.originBeat += len;+ copied[k.id] = c.id;+ copies.push_back(std::move(c));+ }+ }+ for (auto& c : copies) nt->takes.push_back(std::move(c));+ for (auto& c : nt->clips) // the copies insertTimeInto laid in [b, b+len)+ if (c.takeId != 0 && c.startBeat >= b - kSecEps && c.startBeat < b + len - kSecEps)+ if (auto it = copied.find(c.takeId); it != copied.end()) c.takeId = it->second;+ t = nt;+ }+ std::vector<Section> next;+ next.reserve(ss.size() + 1);+ for (const auto& s0 : ss) {+ Section s = s0;+ if (s.startBeat >= b - kSecEps) s.startBeat += len;+ next.push_back(std::move(s));+ }+ Section copy = ss[index];+ copy.startBeat = b;+ next.push_back(std::move(copy));+ std::stable_sort(next.begin(), next.end(),+ [](const Section& x, const Section& y) { return x.startBeat < y.startBeat; });+ g->sections = std::move(next);pushUndo();publishRaw(std::move(g));return true;diff --git a/src/native/nota.engine/src/engine/Graph.h b/src/native/nota.engine/src/engine/Graph.hindex 8560bdc6..9603af5c 100644--- a/src/native/nota.engine/src/engine/Graph.h+++ b/src/native/nota.engine/src/engine/Graph.h@@ -33,6 +33,15 @@ struct Section {bool operator==(const Section&) const = default;};+// One span of a whole-arrangement time remap (specs/073): what lies in [start,end) moves by+// `offset` beats, or is removed when `drop`. The spans of one remap tile a window exactly.+struct TimeRegion {+ double start = 0.0;+ double end = 0.0; // may be +infinity (to the end of the song)+ double offset = 0.0;+ bool drop = false;+};+struct Graph {std::vector<std::shared_ptr<Track>> tracks;int32_t sceneCount = 8; // Session view rows (M5)diff --git a/tests/Nota.SmokeTest/LocalizationAllowList.txt b/tests/Nota.SmokeTest/LocalizationAllowList.txtindex 82936348..248945fb 100644--- a/tests/Nota.SmokeTest/LocalizationAllowList.txt+++ b/tests/Nota.SmokeTest/LocalizationAllowList.txt@@ -2549,6 +2549,7 @@ Nota.Application/Palette/CommandCatalog.cs bpm beat tap # data: search keywords,Nota.Application/Palette/CommandCatalog.cs changelog release notes # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs clips grid launch # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs coarser larger snap # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/CommandCatalog.cs copy repeat section clips automation ripple at playhead # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs create blank empty # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs default automatic rename section at playhead # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs detach float pop out # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)@@ -2571,7 +2572,10 @@ Nota.Application/Palette/CommandCatalog.cs preferences theme dark light languageNota.Application/Palette/CommandCatalog.cs preferences update automatic check version # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs quantise grid snap align # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs quit close leave # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/CommandCatalog.cs rearrange reorder section content left before previous at playhead # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/CommandCatalog.cs rearrange reorder section content right after next at playhead # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs remote mobile qr # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/CommandCatalog.cs remove cut section clips automation ripple close gap at playhead # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs render bounce cpu # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs render bounce mixdown stems # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs resume continue hold # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 2e9890a4..cf56ce2b 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -403,6 +403,7 @@ if (args.Length >= 1 && args[0] == "--moves"){Console.WriteLine("-- arrangement moves --");foreach (var (ok, label) in ArrangementMovesTests.Run()) Check(ok, label);+ foreach (var (ok, label) in SectionRearrangeTests.Run()) Check(ok, label);Console.WriteLine(failures == 0 ? "MOVES PASSED" : $"MOVES FAILED ({failures})");return failures == 0 ? 0 : 1;}@@ -15482,6 +15483,9 @@ foreach (var (ok, label) in SendAutomationTests.Run()) Check(ok, label);Console.WriteLine("-- arrangement moves --");foreach (var (ok, label) in ArrangementMovesTests.Run()) Check(ok, label);+Console.WriteLine("-- section rearrange (specs/073) --");+foreach (var (ok, label) in SectionRearrangeTests.Run()) Check(ok, label);+Console.WriteLine("-- linux desktop --");foreach (var (ok, label) in LinuxDesktopTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/SectionRearrangeTests.cs b/tests/Nota.SmokeTest/SectionRearrangeTests.csnew file mode 100644index 00000000..a3213caf--- /dev/null+++ b/tests/Nota.SmokeTest/SectionRearrangeTests.cs@@ -0,0 +1,405 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Section edits that carry the arrangement with them (specs/073, #192): moving a section+// reorders the song — its clips, automation and takes travel with it and the sections it+// passes close up — and duplicate / delete with content ripple the rest. Each is one undo+// step; overlapping sections refuse them.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class SectionRearrangeTests+{+ private const double Eps = 1e-6;++ private static NotaNote N(int p, double s, double l) => new(p, s, l, 0.8f);+ private static AutomationPoint P(double b, float v) => new(b, v);++ // A · B · C on [0,4) [4,8) [8,12) ("C" automatic). Track a: one clip over all three with a+ // note in each (60 / 62 / 64); track b: a clip per section (the same notes) and one after+ // the sections at 12; a volume ramp 0 → 1 over [0,12) on b, master volume 0.2 → 0.8.+ private sealed record Song(NotaEngine E, int A, int B, int Lane);++ private static Song Build()+ {+ var e = new NotaEngine();+ e.SetBpm(120);+ int a = e.AddInstrumentTrack();+ int b = e.AddInstrumentTrack();+ int ca = e.AddMidiClip(a, 0.0, 12.0);+ e.SetClipNotes(a, ca, new[] { N(60, 1, 1), N(62, 5, 1), N(64, 9, 1) });+ int[] pitches = { 60, 62, 64 };+ for (int i = 0; i < 3; i++)+ {+ int c = e.AddMidiClip(b, i * 4.0, 4.0);+ e.SetClipNotes(b, c, new[] { N(pitches[i], 1, 1) });+ }+ int tail = e.AddMidiClip(b, 12.0, 2.0);+ e.SetClipNotes(b, tail, new[] { N(72, 0, 1) });+ int lane = e.AddAutomationLane(b, AutomationTarget.Volume, -1, -1);+ e.SetAutomationPoints(b, lane, new[] { P(0, 0.0f), P(12, 1.0f) });+ e.SetMasterVolumeAutomation(new[] { P(0, 0.2f), P(12, 0.8f) });+ e.SetSections(new[] { new SectionInfo(0, 4, "A"), new SectionInfo(4, 4, "B"), new SectionInfo(8, 4, "") });+ return new Song(e, a, b, lane);+ }++ // Every note on a track as (pitch, absolute beat), in time order.+ private static (int pitch, double at)[] Notes(NotaEngine e, int track)+ {+ var all = new List<(int, double)>();+ for (int i = 0; e.TryGetClipInfo(track, i, out var ci); i++)+ foreach (var n in e.GetClipNotes(track, i))+ all.Add((n.Pitch, ci.StartBeat + n.StartBeat));+ return all.OrderBy(x => x.Item2).ToArray();+ }++ private static bool NotesAre(NotaEngine e, int track, params (int pitch, double at)[] want)+ {+ var got = Notes(e, track);+ return got.Length == want.Length && got.Zip(want).All(p => p.First.pitch == p.Second.pitch && Math.Abs(p.First.at - p.Second.at) < Eps);+ }++ private static bool SectionsAre(NotaEngine e, params (double start, string name)[] want)+ {+ var s = e.Sections;+ return s.Count == want.Length && s.Zip(want).All(p => Math.Abs(p.First.StartBeat - p.Second.start) < Eps && p.First.Name == p.Second.name);+ }++ // The lane's value at `beat` as the engine plays it: each segment shaped by its start point's+ // curve (t^e, e = 2^(−4·curve)); at a step, the later point wins.+ private static float At(AutomationPoint[] pts, double beat)+ {+ if (pts.Length == 0) return 0;+ if (beat <= pts[0].Beat) return pts[0].Value;+ for (int i = 1; i < pts.Length; i++)+ if (beat < pts[i].Beat)+ {+ double t = (beat - pts[i - 1].Beat) / (pts[i].Beat - pts[i - 1].Beat);+ double shaped = pts[i - 1].Curve == 0 ? t : Math.Pow(t, Math.Pow(2, -pts[i - 1].Curve * 4));+ return (float)(pts[i - 1].Value + (pts[i].Value - pts[i - 1].Value) * shaped);+ }+ return pts[^1].Value;+ }++ private static float Ramp(double beat) => (float)Math.Clamp(beat / 12.0, 0.0, 1.0);+ private static float MasterRamp(double beat) => 0.2f + 0.6f * (float)Math.Clamp(beat / 12.0, 0.0, 1.0);++ // Each probe (new beat → the original beat it should now play) matches the original ramp.+ private static bool LaneFollows(AutomationPoint[] pts, Func<double, float> original, params (double now, double was)[] probes)+ => probes.All(p => Math.Abs(At(pts, p.now) - original(p.was)) < 1e-3);++ public static IEnumerable<(bool ok, string label)> Run()+ {+ // Move C before B: A · C · B; everything after the sections stays.+ {+ var s = Build();+ using var e = s.E;+ yield return (e.MoveSection(2, 1), "section move: C before B returns true");+ yield return (SectionsAre(e, (0, "A"), (4, ""), (8, "B")), "section move: order A · C · B, names and automatic mode kept");+ yield return (NotesAre(e, s.A, (60, 1), (64, 5), (62, 9)), "section move: a clip crossing the sections is cut and its parts follow them");+ yield return (NotesAre(e, s.B, (60, 1), (64, 5), (62, 9), (72, 12)), "section move: per-section clips follow, the clip after the sections stays");+ var pts = e.GetAutomationPoints(s.B, s.Lane);+ yield return (LaneFollows(pts, Ramp, (2, 2), (4.001, 8.001), (7.999, 11.999), (8.001, 4.001), (11.999, 7.999), (13, 13)),+ "section move: automation plays each section's own curve at its new place");+ yield return (LaneFollows(e.GetMasterVolumeAutomation(), MasterRamp, (1, 1), (5, 9), (9, 5), (13, 13)),+ "section move: master volume automation follows");+ yield return (!e.MoveSection(1, 1) && !e.MoveSection(1, 2) && !e.MoveSection(5, 0) && !e.MoveSection(0, 9),+ "section move: no-op and out-of-range targets are refused");+ yield return (e.Undo() && SectionsAre(e, (0, "A"), (4, "B"), (8, ""))+ && NotesAre(e, s.A, (60, 1), (62, 5), (64, 9)) && NotesAre(e, s.B, (60, 1), (62, 5), (64, 9), (72, 12))+ && LaneFollows(e.GetAutomationPoints(s.B, s.Lane), Ramp, (1, 1), (5, 5), (9, 9)),+ "section move: one undo restores clips, automation and sections (a refused move added no step)");+ yield return (e.Redo() && SectionsAre(e, (0, "A"), (4, ""), (8, "B")) && NotesAre(e, s.A, (60, 1), (64, 5), (62, 9)),+ "section move: redo repeats it");+ }++ // A curved automation segment cut by a move keeps its shape on both sides (a 0 → 1 ramp+ // over [0,16) with curve −0.25 is (b/16)²), and a cut clip keeps its deactivation and+ // its envelopes, re-based to each piece.+ {+ var s = Build();+ using var e = s.E;+ e.SetAutomationPoints(s.B, s.Lane, new[] { new AutomationPoint(0, 0f, -0.25f), new AutomationPoint(16, 1f) });+ float Sq(double b) => (float)Math.Pow(Math.Clamp(b, 0, 16) / 16.0, 2);+ e.SetClipActive(s.A, 0, false);+ e.SetMidiClipEnvelope(s.A, 0, MidiClipEnvelope.Volume, new[] { P(0, 0f), P(12, 1f) });+ string wav = Path.Combine(Path.GetTempPath(), "nota_smoke_sections_env.wav");+ WavWriter.WriteSine(wav, seconds: 6.0, freq: 220.0, sampleRate: 44100); // 12 beats at 120+ e.RenderOffline(new float[64 * 2], 64, 48000); // a sample rate, so the clip has its length in beats+ int audio = e.AddAudioTrack();+ int ac = e.AddAudioClip(audio, wav, startBeat: 0.0);+ e.SetClipVolumeEnvelope(audio, ac, new[] { P(0, 0f), P(12, 1f) });+ bool moved = e.MoveSection(2, 1); // C before B: cuts at 4, 8, 12+ yield return (moved && LaneFollows(e.GetAutomationPoints(s.B, s.Lane), Sq, (2, 2), (5, 9), (6, 10), (9, 5), (11, 7), (13, 13), (14, 14), (15.5, 15.5)),+ "section move: curved automation keeps its shape on both sides of every cut");+ var pieces = Enumerable.Range(0, 8).Select(i => e.TryGetClipInfo(s.A, i, out var ci) ? (ok: true, i, ci) : (ok: false, i, ci)).Where(x => x.ok).ToArray();+ var cPiece = pieces.FirstOrDefault(x => Math.Abs(x.ci.StartBeat - 4) < Eps);+ yield return (pieces.Length == 3 && pieces.All(x => !x.ci.IsActive)+ && Math.Abs(At(e.GetMidiClipEnvelope(s.A, cPiece.i, MidiClipEnvelope.Volume), 2) - 10 / 12f) < 1e-3,+ "section move: cut MIDI pieces stay deactivated and keep their part of the clip envelope");+ int audioC = Enumerable.Range(0, 8).FirstOrDefault(i => e.TryGetClipInfo(audio, i, out var ci) && Math.Abs(ci.StartBeat - 4) < Eps, -1);+ yield return (audioC >= 0 && Math.Abs(At(e.GetClipVolumeEnvelope(audio, audioC), 2) - 10 / 12f) < 1e-3,+ "section move: a cut audio clip's envelope is re-based to each piece");+ }++ // Duplicate with content keeps a curved lane's shape around the copy too: the quadratic+ // ramp reads at beat 16 what it read at 12 (0.5625), the copy plays B's curve.+ {+ var s = Build();+ using var e = s.E;+ e.SetAutomationPoints(s.B, s.Lane, new[] { new AutomationPoint(0, 0f, -0.25f), new AutomationPoint(16, 1f) });+ float Sq(double b) => (float)Math.Pow(Math.Clamp(b, 0, 16) / 16.0, 2);+ bool dup = e.DuplicateSectionWithContent(1); // B [4,8): copy at 8, the rest +4+ yield return (dup && LaneFollows(e.GetAutomationPoints(s.B, s.Lane), Sq, (3, 3), (6, 6), (9, 5), (11.5, 7.5), (13, 9), (16, 12), (19, 15), (21, 17)),+ "section duplicate: curved automation keeps its shape before, in and after the copy");+ }++ // At a join the incoming section's setting holds from the join itself, read through the+ // engine's own evaluator: the playhead parked there, one block rendered, the track's volume.+ // C (the ramp's 8..12) moved to the front: beat 0 plays C's start, beat 4 A's, beat 8 B's.+ {+ var s = Build();+ using var e = s.E;+ e.RenderOffline(new float[64 * 2], 64, 48000);+ bool moved = e.MoveSection(2, 0);+ float VolumeAt(double beat)+ {+ e.Seek(beat);+ e.RenderOffline(new float[128 * 2], 128);+ return Enumerable.Range(0, e.TrackCount).Select(i => e.TryGetTrackInfo(i, out var ti) && ti.Id == s.B ? ti.Volume : float.NaN).First(v => !float.IsNaN(v));+ }+ float v0 = VolumeAt(0), v4 = VolumeAt(4), v8 = VolumeAt(8);+ yield return (moved && Math.Abs(v0 - 8 / 12f) < 0.01f && Math.Abs(v4 - 0f) < 0.01f && Math.Abs(v8 - 4 / 12f) < 0.01f,+ $"section move: each section starts with its own automation value at the join (0: {v0:0.000}, 4: {v4:0.000}, 8: {v8:0.000})");+ }++ // A cut keeps the user's fade on the edges it doesn't cut: the piece with the clip's start+ // keeps its attack, the one with its end keeps its release.+ {+ var s = Build();+ using var e = s.E;+ e.RenderOffline(new float[64 * 2], 64, 48000);+ string wav = Path.Combine(Path.GetTempPath(), "nota_smoke_sections_fade.wav");+ WavWriter.WriteSine(wav, seconds: 6.0, freq: 220.0, sampleRate: 44100); // 12 beats at 120+ int audio = e.AddAudioTrack();+ int ac = e.AddAudioClip(audio, wav, startBeat: 0.0);+ e.SetClipAdsr(audio, ac, new ClipAdsr { AttackBeats = 1, ReleaseBeats = 2, Sustain = 1f });+ bool moved = e.MoveSection(2, 1); // C before B: pieces [0,4) A, [4,8) C (the clip's end), [8,12) B+ int At(double start) => Enumerable.Range(0, 8).FirstOrDefault(i => e.TryGetClipInfo(audio, i, out var ci) && Math.Abs(ci.StartBeat - start) < Eps, -1);+ int head = At(0), tail = At(4);+ var h = head >= 0 ? e.GetClipAdsr(audio, head) : default;+ var t = tail >= 0 ? e.GetClipAdsr(audio, tail) : default;+ yield return (moved && Math.Abs(h.AttackBeats - 1) < Eps && Math.Abs(t.ReleaseBeats - 2) < Eps,+ $"section move: the clip's fade-in and fade-out stay on the pieces that keep its start and end (attack {h.AttackBeats}, release {t.ReleaseBeats})");+ }++ // Move A after C: B · C · A.+ {+ var s = Build();+ using var e = s.E;+ yield return (e.MoveSection(0, 3) && SectionsAre(e, (0, "B"), (4, ""), (8, "A"))+ && NotesAre(e, s.A, (62, 1), (64, 5), (60, 9)) && NotesAre(e, s.B, (62, 1), (64, 5), (60, 9), (72, 12)),+ "section move: A after the last section gives B · C · A");+ }++ // Duplicate B with content: A · B · B · C, the rest later by 4.+ {+ var s = Build();+ using var e = s.E;+ yield return (e.DuplicateSectionWithContent(1) && SectionsAre(e, (0, "A"), (4, "B"), (8, "B"), (12, "")),+ "section duplicate: the copy follows B with its name, C moves later");+ yield return (NotesAre(e, s.A, (60, 1), (62, 5), (62, 9), (64, 13)) && NotesAre(e, s.B, (60, 1), (62, 5), (62, 9), (64, 13), (72, 16)),+ "section duplicate: B's content is copied, everything after it moves by its length");+ yield return (LaneFollows(e.GetAutomationPoints(s.B, s.Lane), Ramp, (5, 5), (9.5, 5.5), (13, 9), (17, 13)),+ "section duplicate: the automation curve is copied into the new section");+ yield return (e.Undo() && SectionsAre(e, (0, "A"), (4, "B"), (8, "")) && NotesAre(e, s.B, (60, 1), (62, 5), (64, 9), (72, 12)),+ "section duplicate: one undo restores it");+ }++ // Delete B with content: A · C, the rest earlier by 4.+ {+ var s = Build();+ using var e = s.E;+ yield return (e.DeleteSectionWithContent(1) && SectionsAre(e, (0, "A"), (4, "")),+ "section delete: B is gone, C moves up");+ yield return (NotesAre(e, s.A, (60, 1), (64, 5)) && NotesAre(e, s.B, (60, 1), (64, 5), (72, 8)),+ "section delete: B's content is removed (crossing clip cut), the rest moves earlier");+ yield return (LaneFollows(e.GetAutomationPoints(s.B, s.Lane), Ramp, (3, 3), (4.001, 8.001), (7, 11), (9, 13)),+ "section delete: automation closes the gap with each side's own values");+ yield return (e.Undo() && SectionsAre(e, (0, "A"), (4, "B"), (8, "")) && NotesAre(e, s.A, (60, 1), (62, 5), (64, 9)),+ "section delete: one undo restores it");+ }++ // Overlapping sections refuse with-content edits; others can still pass them intact.+ {+ var s = Build();+ using var e = s.E;+ e.SetSections(new[] { new SectionInfo(0, 4, "A"), new SectionInfo(3, 5, "B"), new SectionInfo(8, 4, "C") });+ yield return (e.SectionOverlaps(0) && e.SectionOverlaps(1) && !e.SectionOverlaps(2), "section overlap: detected on both sides only");+ yield return (!e.MoveSection(1, 3) && !e.DuplicateSectionWithContent(1) && !e.DeleteSectionWithContent(0)+ && SectionsAre(e, (0, "A"), (3, "B"), (8, "C")) && NotesAre(e, s.A, (60, 1), (62, 5), (64, 9)),+ "section overlap: move / duplicate / delete with content are refused and change nothing");+ yield return (!e.MoveSection(2, 1), "section overlap: no drop inside an overlap");+ yield return (e.MoveSection(2, 0) && SectionsAre(e, (0, "C"), (4, "A"), (7, "B")) && NotesAre(e, s.A, (64, 1), (60, 5), (62, 9)),+ "section overlap: another section moves past the overlapping pair, which shifts intact");+ }++ // The playhead keeps its time; a take travels with its section.+ {+ string wav = Path.Combine(Path.GetTempPath(), "nota_smoke_sections_take.wav");+ WavWriter.WriteSine(wav, seconds: 1.0, freq: 330.0, sampleRate: 44100);+ var s = Build();+ using var e = s.E;+ int audio = e.AddAudioTrack();+ int take = e.RestoreTake(audio, wav, 1, 1, originBeat: 4.0, sourceOffsetFrames: 0, lengthFrames: 22050);+ e.RenderOffline(new float[64 * 2], 64, 48000); // the first render sets the sample rate+ e.Seek(2.5);+ e.RenderOffline(new float[64 * 2], 64); // the seek lands with the next block+ bool moved = e.MoveSection(1, 3); // B after C: B now starts at 8+ e.RenderOffline(new float[64 * 2], 64);+ yield return (moved && Math.Abs(e.PositionBeats - 2.5) < Eps, "section move: the playhead does not move");+ yield return (take >= 0 && e.TryGetTakeInfo(audio, 0, out var k) && Math.Abs(k.StartBeat - 8.0) < Eps,+ "section move: a take lane in the section travels with it");+ }++ // Take lanes in the ripple edits: duplicate copies a take that starts in the section+ // (later ones move on); delete drops one that starts in it (later ones move up).+ {+ string wav = Path.Combine(Path.GetTempPath(), "nota_smoke_sections_takes.wav");+ WavWriter.WriteSine(wav, seconds: 1.0, freq: 330.0, sampleRate: 44100);+ double[] Starts(NotaEngine e, int t)+ => Enumerable.Range(0, e.TakeCount(t)).Select(i => e.TryGetTakeInfo(t, i, out var k) ? k.StartBeat : -1).OrderBy(x => x).ToArray();+ {+ var s = Build();+ using var e = s.E;+ int audio = e.AddAudioTrack();+ e.RestoreTake(audio, wav, 1, 1, originBeat: 4.0, sourceOffsetFrames: 0, lengthFrames: 22050);+ e.RestoreTake(audio, wav, 2, 1, originBeat: 8.0, sourceOffsetFrames: 0, lengthFrames: 22050);+ var st = e.DuplicateSectionWithContent(1) ? Starts(e, audio) : Array.Empty<double>();+ yield return (st.Length == 3 && Math.Abs(st[0] - 4) < Eps && Math.Abs(st[1] - 8) < Eps && Math.Abs(st[2] - 12) < Eps,+ $"section duplicate: a take in the section is copied under the copy, a later one moves on ({string.Join(", ", st)})");+ }+ {+ var s = Build();+ using var e = s.E;+ int audio = e.AddAudioTrack();+ e.RestoreTake(audio, wav, 1, 1, originBeat: 4.0, sourceOffsetFrames: 0, lengthFrames: 22050);+ e.RestoreTake(audio, wav, 2, 1, originBeat: 8.0, sourceOffsetFrames: 0, lengthFrames: 22050);+ var st = e.DeleteSectionWithContent(1) ? Starts(e, audio) : Array.Empty<double>();+ yield return (st.Length == 1 && Math.Abs(st[0] - 4) < Eps,+ $"section delete: a take in the section goes with it, a later one moves up ({string.Join(", ", st)})");+ yield return (e.Undo() && e.TakeCount(audio) == 2, "section delete: one undo brings the take back");+ }+ }++ // Save → reopen: the rearranged song is what the project file holds.+ {+ var s = Build();+ using var e = s.E;+ e.MoveSection(2, 1);+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-sections-" + Guid.NewGuid().ToString("N") + ".nota");+ var transport = new TransportState(120.0, 1.0, false, false);+ bool ok;+ try+ {+ ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), dir, e);+ using var back = new NotaEngine();+ ProjectService.Apply(ProjectService.Load(dir), back, dir);+ int Track(NotaEngine x, int i) => x.TryGetTrackInfo(i, out var ti) ? ti.Id : -1;+ int a = Track(back, 0), b = Track(back, 1);+ int lane = back.AutomationLaneCount(b) > 0 ? 0 : -1;+ ok = SectionsAre(back, (0, "A"), (4, ""), (8, "B")) && NotesAre(back, a, (60, 1), (64, 5), (62, 9))+ && NotesAre(back, b, (60, 1), (64, 5), (62, 9), (72, 12))+ && lane == 0 && LaneFollows(back.GetAutomationPoints(b, lane), Ramp, (5, 9), (9, 5));+ }+ finally { try { Directory.Delete(dir, true); } catch { } }+ yield return (ok, "section move: the rearranged song survives save and reopen");+ }++ // MCP: the same edits, with the reason when refused.+ {+ var s = Build();+ using var e = s.E;+ var proj = new Nota.Mcp.Tools.ProjectTools(e, new SyncDispatch(), new NoRefresh());+ var moved = proj.MoveSection(2, 1).GetAwaiter().GetResult();+ yield return (moved.Select(x => x.Name).SequenceEqual(new[] { "A", "Section 2", "B" }) && NotesAre(e, s.A, (60, 1), (64, 5), (62, 9)),+ "section MCP: move_section reorders with content and returns the new order");+ string? noop = null;+ try { proj.MoveSection(1, 1).GetAwaiter().GetResult(); } catch (Exception ex) { noop = ex.Message; }+ yield return (noop is not null && noop.Contains("already"), "section MCP: a move onto its own place is an error");+ var dup = proj.DuplicateSectionWithContent(0).GetAwaiter().GetResult();+ yield return (dup.Length == 4 && Math.Abs(dup[1].StartBeat - 4) < Eps && dup[1].Name == "A", "section MCP: duplicate_section_with_content");+ var del = proj.DeleteSectionWithContent(1).GetAwaiter().GetResult();+ yield return (del.Length == 3 && NotesAre(e, s.A, (60, 1), (64, 5), (62, 9)), "section MCP: delete_section_with_content");+ e.SetSections(new[] { new SectionInfo(0, 4, "A"), new SectionInfo(3, 5, "B") });+ string? overlap = null;+ try { proj.DeleteSectionWithContent(0).GetAwaiter().GetResult(); } catch (Exception ex) { overlap = ex.Message; }+ yield return (overlap is not null && overlap.Contains("overlaps"), "section MCP: an overlapping section is refused with the reason");+ }++ // Render: the moved sections sound where they land, and undo is exact (SC-002 / SC-003).+ foreach (var r in RenderChecks()) yield return r;+ }++ private static IEnumerable<(bool ok, string label)> RenderChecks()+ {+ using var e = new NotaEngine();+ e.SetBpm(120); // 4 beats = 2 s+ int t = e.AddAudioTrack();+ double[] freqs = { 220, 440, 880 };+ for (int i = 0; i < 3; i++)+ {+ string wav = Path.Combine(Path.GetTempPath(), $"nota_smoke_sections_{i}.wav");+ WavWriter.WriteSine(wav, seconds: 2.0, freq: freqs[i], sampleRate: 44100);+ e.AddAudioClip(t, wav, startBeat: i * 4.0);+ }+ e.SetSections(new[] { new SectionInfo(0, 4, ""), new SectionInfo(4, 4, ""), new SectionInfo(8, 4, "") });++ const int sr = 48000, per = sr * 2; // frames per section+ float[] Render()+ {+ var all = new float[per * 3 * 2];+ var chunk = new float[1024 * 2];+ e.RenderOffline(new float[64 * 2], 64, sr); // stopped: only sets the sample rate+ e.Seek(0);+ e.Play();+ for (int done = 0; done < per * 3; done += 1024)+ {+ int n = Math.Min(1024, per * 3 - done);+ e.RenderOffline(chunk, n);+ Array.Copy(chunk, 0, all, done * 2, n * 2);+ }+ e.StopTransport();+ return all;+ }+ // RMS of the difference between section `x` of one render and section `y` of another,+ // skipping a few ms at each edge (clip declicks).+ double Diff(float[] p, int x, float[] q, int y)+ {+ int skip = sr / 100;+ double sum = 0;+ int count = 0;+ for (int f = skip; f < per - skip; f++)+ for (int ch = 0; ch < 2; ch++)+ {+ double d = p[(x * per + f) * 2 + ch] - q[(y * per + f) * 2 + ch];+ sum += d * d;+ count++;+ }+ return Math.Sqrt(sum / count);+ }++ var before = Render();+ bool moved = e.MoveSection(2, 1); // A · C · B+ var after = Render();+ yield return (moved && Diff(after, 0, before, 0) < 1e-4 && Diff(after, 1, before, 2) < 1e-3 && Diff(after, 2, before, 1) < 1e-3,+ "section move render: each section sounds the same at its new place");+ e.Undo();+ var undone = Render();+ yield return (Diff(undone, 0, before, 0) < 1e-6 && Diff(undone, 1, before, 1) < 1e-6 && Diff(undone, 2, before, 2) < 1e-6,+ "section move render: undo renders exactly as before");+ }+}