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) Piano roll: notes overwrite instead of stacking, paste in place, length and velocity keys
Egor Khindikaynen19d4d2d5b806
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2fb937d0..10dc25ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,21 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]+### Added+- **Note length and velocity from the keyboard:** in the piano roll, **⇧← / ⇧→** shorten+ or lengthen every selected note by one grid step (starts stay put), and **⌥↑ / ⌥↓**+ raise or lower their velocity by 10 — **⌥⇧↑ / ⌥⇧↓** by 1. Each press is one undo step.++### Changed+- **Notes replace the notes they land on:** a note moved, stretched, drawn or pasted onto+ a note of the same pitch no longer stacks on top of it. The note underneath is cut where+ the new one starts, or removed if its start is covered. This happens when you let the+ selection go (click elsewhere, Esc, switch clips, save); until then the notes underneath+ stay whole and the part that will go is drawn faint with a dashed edge.+- **⌘V in the piano roll always pastes on top of the copied notes,** selected, whatever the+ transport is doing — then move the copy off with the arrows or the mouse. Previously+ paste jumped to the playback cursor while the song played.+### Fixed- **Return tracks can be deleted in the arrangement:** the Return row's context menu hasDelete track, and Delete / Backspace removes a selected Return, in one undo step. Thediff --git a/FEATURES.md b/FEATURES.mdindex 1b06d6a3..94a89995 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -184,7 +184,15 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).editor; transposing the selection.- Drag a note's left edge to move its start (the end stays put); stacked notes keepseparate velocity stems (grab a stem by its cap, ⇧-click to add it to the selection).- - ⌘D duplicates notes over whatever they land on, like clips in the arrangement.+ - Notes replace the same-pitch notes they land on instead of stacking: moved, stretched,+ drawn or pasted notes cut or remove what they cover once the selection is let go+ (click elsewhere, Esc, another clip, save); until then the part that will go is drawn+ faint with a dashed edge. ⌘D duplicates notes over whatever they land on, like clips+ in the arrangement.+ - ⌘C / ⌘V pastes the copy selected, on top of the copied notes, ready to move off with+ the arrows or the mouse.+ - Keyboard: ←/→ move by the grid, ↑/↓ by a semitone (⇧ an octave), ⇧←/⇧→ shorten or+ lengthen by the grid, ⌥↑/⌥↓ change velocity by 10 (⌥⇧ by 1).- **Remove out of scale** (next to the Scale key and mode) deletes every note outside thescale in one undo step.- Zoomed out, the area past the clip's end is darkened and marked with a line.diff --git a/specs/007-midi-note-editing/checklists/requirements.md b/specs/007-midi-note-editing/checklists/requirements.mdnew file mode 100644index 00000000..df32c703--- /dev/null+++ b/specs/007-midi-note-editing/checklists/requirements.md@@ -0,0 +1,35 @@+# Specification Quality Checklist: MIDI Note Editing — Overwrite, In-Place Paste, Length & Velocity Keys++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-13+**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++- FR-003 clarified 2026-10-13: deferred overwrite (option A).+- Shortcut keys (Shift+←/→, Alt+↑/↓) are user-facing behaviour, not implementation detail.diff --git a/specs/007-midi-note-editing/contracts/piano-roll-keys.md b/specs/007-midi-note-editing/contracts/piano-roll-keys.mdnew file mode 100644index 00000000..3b8697ec--- /dev/null+++ b/specs/007-midi-note-editing/contracts/piano-roll-keys.md@@ -0,0 +1,25 @@+# Contract: Piano-roll keyboard bindings++These apply when the note grid has focus. ⌘ = Ctrl and ⌥ = Alt off macOS. The Settings →+Shortcuts list must show exactly these rows (nota-shortcuts).++| Keys | With a selection | Status |+|---|---|---|+| ← / → | Move by one grid step | unchanged |+| ↑ / ↓ | Move by a semitone | unchanged |+| ⇧↑ / ⇧↓ | Move by an octave | unchanged |+| **⇧← / ⇧→** | **Shorten / lengthen by one grid step (start kept)** | new |+| **⌥↑ / ⌥↓** | **Velocity +10 / −10** | new |+| **⌥⇧↑ / ⌥⇧↓** | **Velocity +1 / −1** | new |+| ⌘C / ⌘X | Copy / cut | unchanged |+| **⌘V** | **Paste on top of the copied notes' original position; copies selected** | changed |+| ⌘D | Duplicate after the selection (overwrites what it lands on) | unchanged |+| Esc | Deselect (applies pending overwrites) | changed: also settles |+| ⌥ while dragging | Free positioning (no snap) | unchanged |++Without a selection, ⌥↑/↓ and ⇧←/→ are not handled; they fall through.++## Overwrite contract++Overwrites happen when a placement settles (data-model §2). Each settle is one undo step,+separate from the edits that led to it.diff --git a/specs/007-midi-note-editing/data-model.md b/specs/007-midi-note-editing/data-model.mdnew file mode 100644index 00000000..922914e7--- /dev/null+++ b/specs/007-midi-note-editing/data-model.md@@ -0,0 +1,57 @@+# Data Model: MIDI Note Editing++No persisted data changes. `NotaNote` (`Nota.Application/Engine/EngineContracts.cs`):+`Pitch`, `StartBeat`, `LengthBeats`, `Velocity` (0..1 float), `ExprId`. A note is copied+whole (never rebuilt), so expression travels with it.++## 1. Overwrite rule (`NoteOverwrite`)++Inputs: the clip's note list and the set **P** of placed indices (the selection).++For each note **m** not in **P**, against every **c** in **P** with `c.Pitch == m.Pitch`:++| Condition (ε = 1e-9) | Fate of m |+|---|---|+| `c.Start − ε ≤ m.Start < c.End − ε` | **Removed** |+| `m.Start < c.Start` and `m.End > c.Start + ε` | **Cut** to `c.Start − m.Start` (the shortest over all such c) |+| otherwise | **Kept** |++Removal wins over a cut. Notes in **P** never change and never affect each other. Notes of+different pitch never interact. `Settle` returns the surviving notes in their original+order and the new indices of **P**.++This is exactly the rule `DuplicateSelection` applies today (copies = **P**).++## 2. Pending placement (in `PianoRollView`)++```text+ place (move/resize/draw/paste/Shift+←→) place+ Idle ────────────────────────────────────────▶ Pending ◀────────┐+ ▲ │ └───────────┘+ │ settle: selection change, focus loss, │+ │ whole-clip edit, save/export │+ └──── NoteOverwrite.Settle + Commit ◀───────────┘+ ▲ │+ └──── discard: SetNotes (reload/undo), delete ◀─┘+```++- In **Pending**, rendering marks every unselected note whose fate is not Kept.+- Velocity edits and selection-preserving actions (clicking a selected note, zoom,+ scroll) leave the state unchanged.++## 3. Length step++For each selected note: `len' = clamp(len ± step, MinNoteLen, clipLength − start)`, with+`start` unchanged. `step = SnapStep` (snap on) or `MinNoteLen` (snap off). Notes already at+the clip end do not grow; the others still do. If no note changes, there is no commit.++## 4. Velocity step++`v' = clamp(round(v·127) + k, 1, 127) / 127`, with k ∈ {±10, ±1}. The same k applies to+every selected note. If no note changes (everything is at the clamp), there is no commit.++## 5. Note clipboard++Unchanged: notes normalized to beat 0 plus `s_clipAnchor` (the original clip-relative+start). Paste lands at `s_clipAnchor + offset` for each note. Notes starting at or past the+clip end are skipped, and overruns are trimmed to the clip end.diff --git a/specs/007-midi-note-editing/plan.md b/specs/007-midi-note-editing/plan.mdnew file mode 100644index 00000000..b8e34145--- /dev/null+++ b/specs/007-midi-note-editing/plan.md@@ -0,0 +1,178 @@+# Implementation Plan: MIDI Note Editing — Overwrite, In-Place Paste, Length & Velocity Keys++**Branch**: `007-midi-note-editing` (the spec directory; the work sits on `develop`) | **Date**: 2026-10-13 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/007-midi-note-editing/spec.md`++## Summary++A single pure rule, `NoteOverwrite` in `Nota.Application/Editing`, settles placed notes+against the rest of a clip ("placed material wins": same-pitch notes whose start is+covered go, notes running into a placed note are cut). The piano roll stops applying it+per edit. Instead it keeps a *pending placement* flag: moves, resizes, draws and pastes of+the selection set it, the notes underneath are only marked, and the rule runs once when+the selection is let go (selection change, focus loss, save, export). Paste always lands+on the copied notes' own beats. Shift+←/→ change the selected notes' length by one grid+step. Alt(+Shift)+↑/↓ change their velocity by ±10 (±1). Duplicate reuses the same rule.+The engine is not touched.++## Nota: Read Before Planning++- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Ember) and the `nota-design` skill for+ the "will be overwritten" mark.+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md): SPDX header on the new+ files, no new dependencies.+- **Shortcuts** → the `nota-shortcuts` skill (Settings → Shortcuts list), `nota-docs`+ for the piano-roll page, `nota-features` for FEATURES.md.++## Technical Context++**Language/Version**: C# / .NET 10 (managed app only)++**Primary Dependencies**: Avalonia (existing). No new dependency.++**Storage**: N/A. Notes are already persisted through the engine; the project format is+unchanged.++**Audio-Thread Impact**: None. This is a UI-only change. Edits reach the engine through the+existing `Commit` (`SetClipNotes` / `SetSessionNotes`) and `CommitLive` paths. While a+placement is pending, same-pitch notes may overlap in the engine, exactly as they can+today.++**Testing**: A new pure-logic section in `tests/Nota.SmokeTest` (`NoteEditingTests.cs`,+alone with `--notes`, also part of the full run) for the overwrite rule, length and+velocity steps. Interaction is checked in the real app (quickstart §2).++**Target Platform**: macOS, Windows, Linux desktop (⌘ = Ctrl and ⌥ = Alt off macOS).++**Project Type**: Desktop app (Avalonia).++**Performance Goals**: The marking is computed per frame for unselected notes against the+selected ones, O(n·s). This is negligible for clip sizes (hundreds of notes), and no+allocation happens in the render loop.++**Constraints**: Notes that already overlap in existing projects are not touched unless+the user places notes onto them (no settle without a pending placement). Undo granularity:+each key press is one step, and a settle is its own step.++**Scale/Scope**: 1 new file in `Nota.Application`, `PianoRollView.cs` (most of the+change), `MainWindow.Files.cs` (settle before save/export), 1 new test file + `Program.cs`,+Shortcuts list, docs.++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design: still passes.*++| Principle | Status | Notes |+|-----------|--------|-------|+| I. Real-time audio safety | ✅ Pass | No engine or audio-thread change |+| II. Boundary discipline | ✅ Pass | No new C ABI; existing `SetClipNotes`/`SetClipNotesLive` |+| III. Licensing hygiene | ✅ Pass | SPDX header on `NoteOverwrite.cs` and `NoteEditingTests.cs`; no dependency |+| IV. Verification gate | ✅ Pass | `scripts/build.sh` must pass; the smoke test gains a `NoteEditingTests` section |+| V. One logical change | ✅ Pass | One feature: piano-roll note editing. Four stories touch the same edit path |+| VI. Docs in sync | ✅ Planned | CHANGELOG, FEATURES.md, Shortcuts list, nota-docs piano-roll page (EN+RU) |+| VII. Spec-first | ✅ Pass | This spec, clarified 2026-10-13 |+| VIII. Rules not weakened | ✅ Pass | — |++## Design++See [research.md](research.md) for the decisions, [data-model.md](data-model.md) for the+rule and the pending state, and [contracts/piano-roll-keys.md](contracts/piano-roll-keys.md)+for the user-facing bindings.++### 1. `Nota.Application/Editing/NoteOverwrite.cs` (new)++Pure static, no Avalonia:++- `Fate(NotaNote note, IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed)` →+ `Kept` / `Cut(newLength)` / `Removed`, with the Duplicate rule (data-model §1).+- `Settle(IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed)` → the new note+ list and the new indices of the placed notes (so the selection can be remapped).+- `ResizeBy(...)` (length step, clamped to min length and clip end, start kept) and+ `VelocityBy(float v, int steps127)` (1–127 clamp, integer MIDI steps).++### 2. `PianoRollView.cs`++- **Pending placement**: `bool _placementPending`. It is set after a committed mouse+ move/resize (release with `_dragMoved`), `MoveSelection`, the new `ResizeSelection`, a+ double-click draw, and `PasteClipboard`. Velocity edits do not set it.+- **`public bool SettlePlacement()`**: if pending and the selection is non-empty, run+ `NoteOverwrite.Settle`, replace `_notes`, remap `_selection`, `CommitNotes()` (its own+ undo step), invalidate, and clear the flag. It is called:+ - before every selection change: pointer press that changes the selection (then+ re-hit-test, since indices may shift), Shift-click toggle, marquee start,+ double-click, Esc, ⌘A, paste, duplicate;+ - before whole-clip edits: Quantize, TransposeBy, remove out-of-scale, ApplyPreview;+ - on `NoteGrid` `LostFocus`;+ - by the host before save and export.+- `SetNotes` and `DeleteSelection` clear the flag without settling. A reload means the+ engine state wins (undo, recording), and deleting the placed notes leaves nothing to+ settle.+- **Paste**: settle, then anchor = `s_clipAnchor` always (the playhead branch is+ removed). Select the copies and set pending.+- **Duplicate**: settle first, then keep today's behaviour, with its inline loop+ replaced by `NoteOverwrite.Settle` over the copies.+- **Marking**: in `NoteGrid.Render`, when pending, unselected notes whose `Fate` is not+ `Kept` draw their doomed part (all of it for `Removed`, `[cut, end)` for `Cut`) faded,+ with a dashed outline in the track colour (research R4).+- **Keys** (`NoteGrid.OnKeyDown`, selection non-empty, no ⌘): Alt+↑/↓ → `NudgeVelocity(±10)`,+ Alt+Shift+↑/↓ → `±1`; Shift+←/→ → `ResizeSelection(±SnapStep)`. Plain ←/→ and+ (Shift+)↑/↓ are unchanged. Each press commits once (one undo step).++### 3. `MainWindow.Files.cs`++`_editorRoll?.SettlePlacement()` at the top of the project-save path (before+`_projects.Save`) and of `DoExportAsync`. Autosave does not settle (R5).++### 4. Tests — `tests/Nota.SmokeTest/NoteEditingTests.cs` (new) + `Program.cs`++A `--notes` flag and an entry in the full run, following the `SnapGridTests` pattern.+Cases: the spec's Story 1 scenarios, notes in the same selection never cut each other,+different pitches untouched, placed index remap, a copy exactly on its original+(original removed on settle only if the copy still covers its start), length step clamps,+velocity clamps 1/127 and integer steps.++### 5. Docs++CHANGELOG `[Unreleased]` (Changed: paste lands on the original, notes overwrite; Added:+length and velocity keys), FEATURES.md, Shortcuts list (nota-shortcuts), and the+nota-docs piano-roll page (EN+RU).++## Project Structure++### Documentation (this feature)++```text+specs/007-midi-note-editing/+├── plan.md+├── research.md+├── data-model.md+├── quickstart.md+├── contracts/piano-roll-keys.md+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/managed/+├── Nota.Application/Editing/+│ └── NoteOverwrite.cs # NEW — the overwrite rule, length/velocity steps+└── Nota.App/+ ├── PianoRollView.cs # pending placement, settle, paste, keys, marking+ ├── MainWindow.Files.cs # settle before save / export+ └── (Shortcuts list file — located by the nota-shortcuts skill)++tests/Nota.SmokeTest/+├── NoteEditingTests.cs # NEW+└── Program.cs # --notes flag + full-run entry+```++**Structure Decision**: The rule goes in `Nota.Application`, so it is testable and free of+UI, next to `SnapGrid`. All interaction state stays in `PianoRollView`, which already owns+selection, drag and commit.++## Complexity Tracking++None. There are no constitution violations.diff --git a/specs/007-midi-note-editing/quickstart.md b/specs/007-midi-note-editing/quickstart.mdnew file mode 100644index 00000000..09e37141--- /dev/null+++ b/specs/007-midi-note-editing/quickstart.md@@ -0,0 +1,33 @@+# Quickstart: validating MIDI Note Editing++## 1. Automated++```bash+scripts/build.sh+```++The smoke test includes the `NoteEditingTests` section. To run it alone:++```bash+dotnet run --project tests/Nota.SmokeTest -- --notes+```++Expected: every `note editing` check passes (overwrite fates, index remap, length and+velocity clamps).++## 2. In the app (piano roll, 1/16 grid)++| # | Do | Expect |+|---|----|--------|+| 1 | Draw C4 0–2 and C4 3–4. Drag the second to start at 1, then click empty space | First note becomes 0–1; one attack per position on playback |+| 2 | Repeat 1 but stop before clicking empty space | First note is whole but its 1–2 part is drawn marked; dragging back clears the mark |+| 3 | Select a phrase, ⌘C, ⌘V with the transport stopped, then again while playing | Copies sit exactly on the originals both times; copies are selected |+| 4 | After ⌘V press → 16 times, then Esc | Copy is one bar to the right, originals whole |+| 5 | After ⌘V press → once, then Esc | The originals whose starts the copies cover are removed, the ones running in are cut |+| 6 | Select 3 notes, ⇧→ ×2, ⇧← ×1 | Each is one 1/16 longer, starts unchanged |+| 7 | Select notes vel 40/80/125, ⌥↑ | 50/90/127. ⌥⇧↓ → 49/89/126 |+| 8 | ⌘Z through steps 6–7 | Each press undone one at a time |+| 9 | Settings → Shortcuts | The rows from contracts/piano-roll-keys.md are listed |++Follow the project's UI verify recipe (memory: env-guarded hook + screencapture,+`NOTA_DATA_DIR` isolation) for screenshots of rows 2 and 9.diff --git a/specs/007-midi-note-editing/research.md b/specs/007-midi-note-editing/research.mdnew file mode 100644index 00000000..b3067ebb--- /dev/null+++ b/specs/007-midi-note-editing/research.md@@ -0,0 +1,72 @@+# Research: MIDI Note Editing++No open technical unknowns after clarification. Decisions taken while reading the current+code (`src/managed/Nota.App/PianoRollView.cs`, `MainWindow.Detail.cs`, `MainWindow.Files.cs`):++## R1 — Why paste is inconsistent++- **Finding**: `PasteClipboard` anchors at `SnapBeat(_playheadBeat)` whenever the host shows+ the playhead (transport playing and inside the clip), otherwise at `s_clipAnchor`. That+ is why the landing spot depends on transport state.+- **Decision**: Always anchor at `s_clipAnchor`, the copied notes' clip-relative origin.+- **Alternatives**: Paste at the playhead with a modifier. Rejected because it is not+ requested, and Duplicate already covers "place after".++## R2 — Where the overwrite rule lives++- **Decision**: In `Nota.Application/Editing/NoteOverwrite.cs`, a pure function shared by+ Duplicate and settle, tested in the smoke test.+- **Rationale**: Duplicate already has the rule inline, so extracting it keeps one+ definition. Pure code needs no headless UI to test.+- **Alternatives**: Keep the logic inside `PianoRollView`. Rejected because it cannot be+ tested without the UI, and the rule would exist twice.++## R3 — How deferral works without touching the originals++- **Decision**: While pending, `_notes` holds the placed notes *and* the untouched notes+ underneath (overlapping). Nothing is cut until `SettlePlacement`. "Shown whole again when+ moved off" therefore needs no restore logic: the marking is recomputed from the current+ positions on every render.+- **Consequence**: The engine plays the overlap until settle (accepted in the spec's edge+ cases). Undo during pending needs nothing extra: the engine undo reloads the roll via+ `SetNotes`, which clears the flag.+- **Alternatives**: Keep a shadow "pre-placement" list and restore cut notes as the+ selection moves. Rejected because it duplicates state and holds no information the+ live list lacks.++## R4 — The "will be overwritten" mark++- **Decision**: Draw the doomed span of an unselected note at about 25% of its normal+ alpha, with a 1 px dashed outline in the track colour. For a cut, that is the part from+ the cut to the end; for a removal, the whole note. Kept notes draw as today. Verify+ against DESIGN.md / nota-design (no new tokens expected; ghost/preview styling already+ exists for tool previews and must stay distinguishable — a preview is a brass outline).+- **Revised in implementation**: The faint fill sits under the covering note, so the doomed span's dashed edge is drawn in a second pass on top of all notes. Otherwise a note hidden under a pasted copy would show no mark at all.+- **Alternatives**: Hide doomed notes entirely. Rejected because the user would lose sight+ of what will be removed.++## R5 — When to settle++- **Decision**: Settle on selection change, grid focus loss, whole-clip edits (Quantize,+ Transpose, remove out-of-scale, applying a tool preview), and explicit save or export.+ Do not settle on autosave or recovery writes, so an in-flight edit is never altered+ behind the user's back; a recovered project may contain the pending overlap, which is+ harmless.+- **Focus loss also covers clip switching**: each clip gets a fresh `PianoRollView`, and+ the old one loses focus before it is dropped, while its `Commit` closure still targets+ its own clip.+- **Only with a pending placement**: Selecting and deselecting old overlapping notes+ (legacy projects) never mutates them.++## R6 — Key bindings++- **Finding**: Alt+↑/↓ and Alt+Shift+↑/↓ are bound nowhere in `Nota.App`. Shift+←/→+ currently behave as plain ←/→ (the switch ignores Shift for horizontal keys).+- **Decision**: Alt is checked before Shift, so Alt+Shift+↑ is the fine velocity step, not+ an octave move. Velocity steps are in MIDI units: round(v·127) ± k, clamped to 1–127, then+ /127. That keeps velocities on integer MIDI values and makes the scenarios exact.++## R7 — Length step with snap off++- **Decision**: Use `SnapStep` when snap is on and `MinNoteLen` (1/32 note = 0.125 beat)+ when it is off, the same fallback that drawing uses. The minimum length is `MinNoteLen`.diff --git a/specs/007-midi-note-editing/spec.md b/specs/007-midi-note-editing/spec.mdnew file mode 100644index 00000000..c228e717--- /dev/null+++ b/specs/007-midi-note-editing/spec.md@@ -0,0 +1,274 @@+# Feature Specification: MIDI Note Editing — Overwrite, In-Place Paste, Length & Velocity Keys++**Feature Branch**: `007-midi-note-editing`++**Created**: 2026-10-13++**Status**: Draft++**Input**: User description: "MIDI editor (piano roll) editing improvements: (1) When a note is moved/resized/pasted onto other notes of the same pitch, the overlapped notes must be overwritten (trimmed/removed) instead of stacking on top of each other. (2) Ctrl+C / Ctrl+V on selected notes must always paste the copy at exactly the same position as the original (on top), selected, so the user then moves it with arrow keys or the mouse — currently the paste position is inconsistent (sometimes in place, sometimes shifted). (3) Keyboard shortcut to lengthen/shorten notes: Shift+Left/Right arrows, working on all selected notes. (4) Keyboard shortcuts to adjust velocity of the selected notes."++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [ ] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Ember)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++The engine is not involved: these are note-list edits made in the piano roll before the+clip's notes are committed to the engine as today.++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++**Current state (for reference)**:++- Duplicate (Cmd/Ctrl+D) already overwrites: copies land after the selection and cut or+ remove same-pitch notes they cover. Moving (mouse or arrows), resizing, drawing and+ pasting do not — notes of the same pitch can stack on top of each other.+- Paste places the clipboard at the playback cursor when the cursor is visible, otherwise+ at the copied notes' original position. Whether the cursor is visible depends on+ transport state, so the same Cmd+C / Cmd+V lands in different places.+- ←/→ nudge the selection by the snap step; ↑/↓ by a semitone, Shift+↑/↓ by an octave.+ Shift+←/→ currently behaves like plain ←/→. There is no keyboard control for note+ length or velocity; velocity is edited only in the velocity lane.++## Clarifications++### Session 2026-10-13++- Q: When is the overwrite applied while a pasted/moved selection is still being moved?+ → A: Deferred. While the selection is unchanged, notes underneath are only marked+ "will be overwritten"; the overwrite is applied once the selection is let go.+- Q: Which keys and step change the velocity of selected notes? → A: Alt+↑/↓ by ±10,+ Alt+Shift+↑/↓ by ±1 (Option on macOS).++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Notes overwrite instead of stacking (Priority: P1)++A user drags a note onto another note of the same pitch. Instead of two notes sounding on+top of each other (doubled attack, hidden note that later surprises them), the note being+placed wins: the note underneath is cut where the placed note begins, or removed if the+placed note covers its start.++**Why this priority**: Stacked same-pitch notes are invisible bugs in the music (doubled+attacks, stuck-sounding notes, notes that cannot be clicked). Every other story in this+spec produces overlaps, so this rule has to exist first.++**Independent Test**: Place two notes of the same pitch, drag one so it partly covers the+other, click empty space to let the selection go, and check that only non-overlapping notes remain and playback has a+single attack at each position.++**Acceptance Scenarios**:++1. **Given** note A (C4, beats 0–2) and note B (C4, beats 3–4), **When** the user drags B+ to start at beat 1 and lets the selection go, **Then** A is cut to beats 0–1 and B occupies beats 1–2.+2. **Given** note A (C4, beats 1–2) and note B (C4, beats 3–5), **When** the user drags B+ to start at beat 0.5 (so B covers A's start) and lets the selection go, **Then** A is+ removed.+3. **Given** note A (C4, beats 2–3) and note B (C4, beats 0–1), **When** the user+ lengthens B to end at beat 2.5 and lets the selection go, **Then** A is removed.+4. **Given** note A (C4) and note B (D4) overlapping in time, **When** either is moved,+ **Then** nothing is cut — different pitches never overwrite each other.+5. **Given** B is still selected after the drag, **Then** A is drawn whole but marked as+ "will be overwritten" over the covered part; dragging B away clears the mark.+6. **Given** an overwrite was applied, **When** the user presses Undo once, **Then** the+ cut/removed notes are restored; a further Undo reverts the move itself.++---++### User Story 2 - Copy/paste always lands on the original (Priority: P1)++A user selects a phrase, presses Cmd/Ctrl+C then Cmd/Ctrl+V. The copy appears exactly on+top of the original, already selected, every time — regardless of whether the song is+playing or where the playback cursor is. The user then moves the copy where they want it+with the arrow keys or the mouse.++**Why this priority**: The reported inconsistency makes paste unpredictable; a fixed,+known landing spot is the core of the requested workflow.++**Independent Test**: Copy a selection, paste with the transport stopped, playing, and+with the cursor at various positions; in every case the pasted notes have the same+start, pitch and length as the originals and are the only selected notes.++**Acceptance Scenarios**:++1. **Given** a selection of notes at beats 4–6, **When** the user copies and pastes,+ **Then** identical copies appear at beats 4–6 and the copies (not the originals) are+ selected.+2. **Given** the transport is playing and the cursor is at beat 10, **When** the user+ pastes, **Then** the copies still land at the original position, not at beat 10.+3. **Given** a just-pasted copy (C4, beats 0–1) sitting on its original, **When** the+ user presses → four times with a 1/16 grid, **Then** the copy is at beats 1–2 and the+ original is still whole at beats 0–1 (while the copy partly covered it, the covered+ part was only marked, never cut).+4. **Given** a pasted copy moved to partly cover another C4 note, **When** the user+ clicks empty space (letting the selection go), **Then** the covered note is cut or+ removed per Story 1.+5. **Given** notes were copied from another MIDI clip, **When** pasted into this clip,+ **Then** they land at the same clip-relative beats they had in the source clip.++---++### User Story 3 - Stretch and shrink notes from the keyboard (Priority: P2)++With one or several notes selected, Shift+→ makes every selected note one grid step+longer and Shift+← one grid step shorter, keeping their start positions.++**Why this priority**: A frequent editing action that currently requires precise mouse+work on each note's edge; less critical than correctness of overlaps and paste.++**Independent Test**: Select three notes of different lengths, press Shift+→ twice and+Shift+← once; each note is exactly one grid step longer than at the start, and starts are+unchanged.++**Acceptance Scenarios**:++1. **Given** selected notes of lengths 1/4 and 1 beat and a 1/16 grid, **When** the user+ presses Shift+→, **Then** each note's length grows by 1/16 note and starts do not move.+2. **Given** a selected note one grid step long, **When** the user presses Shift+←,+ **Then** the note stays one grid step long (it is never shortened to zero or removed).+3. **Given** a selected note that ends at the clip's end, **When** the user presses+ Shift+→, **Then** that note does not grow past the clip end; other selected notes still+ grow.+4. **Given** a selected note lengthened into a following same-pitch note, **Then** the+ overwrite rule of Story 1 applies.++---++### User Story 4 - Adjust velocity from the keyboard (Priority: P2)++With notes selected, the user presses a velocity shortcut to make all selected notes+louder or softer in steps, and a modifier for fine steps. The velocity lane and note+shading update immediately, and the user can hear the change on playback.++**Why this priority**: Speeds up dynamics editing for multiple notes; the velocity lane+already allows it with the mouse.++**Independent Test**: Select notes with velocities 40, 80 and 120, press "velocity up"+once; they become 50, 90 and 127 (clamped). Press "velocity down" with the fine modifier;+each drops by 1.++**Acceptance Scenarios**:++1. **Given** selected notes with velocities 40 and 80, **When** the user presses Alt+↑,+ **Then** they become 50 and 90 (relative change; the differences between notes are+ kept).+2. **Given** a selected note at velocity 125, **When** the user presses Alt+↑, **Then**+ it becomes 127; at velocity 3, Alt+↓ makes it 1 (never 0 or below).+3. **Given** selected notes, **When** the user presses Alt+Shift+↑ or Alt+Shift+↓,+ **Then** each velocity changes by 1.+4. **Given** a burst of velocity key presses, **When** the user presses Undo, **Then**+ velocity edits are undone (each press is its own undo step, like arrow-key nudges).++### Edge Cases++- Pasting with an empty clipboard does nothing.+- Pasted notes whose original position lies beyond this clip's end are skipped; notes+ running past the end are trimmed to the clip end (as today).+- A selection moved onto several same-pitch notes cuts/removes each of them independently.+- Notes within the selection never overwrite each other (e.g. two selected notes moved+ together keep their relative layout even if they already overlapped).+- Moving a note away never restores a note cut in an earlier, already-settled placement+ (that is what Undo is for); only notes marked during the current, still-selected+ placement come back.+- Undo while a placement is unsettled undoes the last nudge/move as today; nothing has+ been overwritten yet, so there is nothing extra to restore.+- Notes marked "will be overwritten" still sound on playback until the placement+ settles; settling happens automatically before the clip is saved or exported, so a+ saved project never contains overlapping same-pitch notes.+- Shift+←/→ with snap off uses the same fallback minimum step as drawing with snap off.+- Shift+↑/↓ keeps its current meaning (move by an octave); Alt+←/→ is not assigned.+- Velocity shortcuts with no selection do nothing and are not consumed (the keys fall+ through to whatever else uses them).++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: When notes are placed — moved (mouse or arrows), resized (mouse or+ keyboard), drawn or pasted — each placed note MUST overwrite unselected notes of the+ same pitch that it overlaps: a note whose start lies inside the placed note is removed;+ a note that starts before and runs into the placed note is cut to end where the placed+ note starts. The overwrite is applied when the placement is settled (FR-003).+- **FR-002**: Overwrite MUST NOT apply between notes that are part of the same selection,+ nor between notes of different pitches. Applying an overwrite MUST be an undoable step+ of its own.+- **FR-003**: Overwrite is deferred while the edited notes stay selected. As long as the+ selection is unchanged, further moves, resizes and arrow nudges re-evaluate against the+ notes as they were before the selection started moving — notes underneath are neither+ cut nor removed, only drawn marked as "will be overwritten", and a note the selection+ moves off is shown whole again. The placement settles, and the overwrite is applied,+ when the selection is let go: the selection changes (click on empty space or other+ notes, Esc, Select All, a new paste), the piano roll loses focus, the editor switches to+ another clip, or the project is saved or exported.+- **FR-003a**: Paste MUST place the copies exactly on top of the originals; with FR-003,+ the originals stay intact while the copies are selected and are overwritten only where+ the copies finally rest.+- **FR-004**: Paste MUST always place the clipboard notes at the beats they had when+ copied (clip-relative), independent of transport state and cursor position, and MUST+ select exactly the pasted notes.+- **FR-005**: Shift+→ MUST lengthen every selected note by one grid step and Shift+← MUST+ shorten every selected note by one grid step, keeping start positions; a note never+ becomes shorter than the minimum note length, and never extends past the clip end.+- **FR-006**: Alt+↑ / Alt+↓ MUST raise / lower the velocity of every selected note by 10;+ Alt+Shift+↑ / Alt+Shift+↓ by 1. Velocities MUST be clamped to 1–127, and the relative+ change MUST be the same for every note (no rescaling).+- **FR-007**: Each length or velocity key press MUST be a separate undoable edit, matching+ how arrow-key nudges behave today.+- **FR-008**: The Preferences → Shortcuts list and the user docs MUST list the new length+ and velocity shortcuts and describe the paste landing position.+- **FR-009**: Duplicate (Cmd/Ctrl+D) keeps its current behaviour (copies placed right+ after the selection, overwriting what they land on).++### Key Entities++- **Note**: pitch, start beat, length, velocity — within a MIDI clip of fixed length.+- **Selection**: the set of notes that the keyboard and mouse edits act on; after paste+ it is exactly the pasted copies.+- **Note clipboard**: notes copied with their clip-relative start beats, shared between+ MIDI clips.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: Once a placement settles, and in every saved or exported project, a clip+ contains no two notes of the same pitch whose time ranges overlap.+- **SC-002**: Copy + paste places the copies at the original position in 100% of attempts,+ across stopped, playing and arbitrary-cursor states.+- **SC-003**: Changing the length of N selected notes by k grid steps takes k key presses+ regardless of N.+- **SC-004**: Changing the velocity of a selection by 30 takes 3 key presses.+- **SC-005**: Every overwrite, length and velocity edit is fully reverted by Undo, leaving+ the clip identical to its state before the edit.++## Assumptions++- "Grid step" means the piano roll's current snap step (the adaptive grid from spec 003+ when adaptive), the same step ←/→ already uses.+- Alt+↑/↓ and Alt+Shift+↑/↓ are not bound anywhere else in the app; the plain ↑/↓ and Shift+↑/↓ meanings stay. On macOS Alt is+ the Option key.+- Overwrite behaviour follows the existing Duplicate rule (and the arrangement's clip+ overwrite), so the app has one consistent "placed material wins" rule.+- The keyboard shortcuts act when the piano roll note grid has focus, like the existing+ arrow-key nudges.+- The velocity lane, expression lanes and audio clip editor are out of scope.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency+- [x] Audio-thread impact considered: none — edits are made in the app and committed through the existing note-commit path+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no new crossings+- [x] Smoke-test impact assessed: no engine behaviour change; covered by managed unit tests instead+- [x] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned, plus FEATURES.md, user docs and the Shortcuts pane (nota-features / nota-docs / nota-shortcuts)+- [x] UI change → no new visuals; existing piano roll renderingdiff --git a/specs/007-midi-note-editing/tasks.md b/specs/007-midi-note-editing/tasks.mdnew file mode 100644index 00000000..5fe4fefd--- /dev/null+++ b/specs/007-midi-note-editing/tasks.md@@ -0,0 +1,224 @@+---++description: "Task list for piano-roll note editing: overwrite, in-place paste, length and velocity keys"+---++# Tasks: MIDI Note Editing — Overwrite, In-Place Paste, Length & Velocity Keys++**Input**: Design documents from `specs/007-midi-note-editing/`++**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/piano-roll-keys.md](contracts/piano-roll-keys.md), [quickstart.md](quickstart.md)++**Tests**: Included. The plan and quickstart §1 call for a pure-logic smoke-test section+(`NoteEditingTests`, `--notes`). Write each test task before its implementation and see it+fail first (a compile failure on the missing type counts).++**Organization**: By user story (spec.md): US1 notes overwrite (P1), US2 paste on the+original (P1), US3 length keys (P2), US4 velocity keys (P2).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)+- **[Story]**: US1–US4++## Path Conventions++- Rule (pure): `src/managed/Nota.Application/Editing/`+- App and views: `src/managed/Nota.App/`+- Tests: `tests/Nota.SmokeTest/`+- Every new `.cs` file starts with the two-line SPDX header from CONTRIBUTING.md and a+ short comment header explaining why the file exists (match `SnapGrid.cs`).+- Line numbers are as of `develop` at 648d7ab and drift as you edit, so search by member+ name.++---++## Phase 1: Setup++- [X] T001 Create `tests/Nota.SmokeTest/NoteEditingTests.cs` with the SPDX header, a comment header ("Piano-roll note editing (specs/007-midi-note-editing): the overwrite rule, length and velocity steps. Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --notes`."), and `internal static class NoteEditingTests { public static IEnumerable<(bool Ok, string Label)> Run() { yield break; } }`, following `SnapGridTests.cs`.+- [X] T002 Wire it into `tests/Nota.SmokeTest/Program.cs`:+ - add a `--notes` early-exit block printing `-- note editing --` and `NOTES PASSED` / `NOTES FAILED (n)`, next to the `--grid` block (around line 227);+ - in the full run, add `Console.WriteLine("-- note editing --"); foreach (var (ok, label) in NoteEditingTests.Run()) Check(ok, label);` right after the snap-grid section (around line 14548).++---++## Phase 2: Foundational (blocks every story)++- [X] T003 Create `src/managed/Nota.Application/Editing/NoteOverwrite.cs` (namespace `Nota.Application.Editing`, SPDX header, comment header citing the spec), with type stubs only: `enum NoteFateKind { Kept, Cut, Removed }`, `readonly record struct NoteFate(NoteFateKind Kind, double CutLength)`, and a `static class NoteOverwrite` whose methods throw `NotImplementedException`. US1, US3 and US4 fill in the bodies.++**Checkpoint**: `dotnet build src/managed/Nota.App/Nota.App.csproj` and the test project build.++---++## Phase 3: User Story 1 — Notes overwrite instead of stacking (P1) 🎯 MVP++**Goal**: Placed notes overwrite same-pitch notes once the selection is let go; until then+the notes underneath are only marked.++**Independent Test**: quickstart §2 rows 1 and 2, plus `--notes`.++### Tests (write first)++- [X] T004 [P] [US1] In `tests/Nota.SmokeTest/NoteEditingTests.cs`, add overwrite cases, each yielding one labelled check:+ - the spec's Story 1 scenarios 1–3 through `NoteOverwrite.Settle` (A cut to 0–1; A removed; A removed by a lengthened B);+ - different pitches untouched (scenario 4);+ - two placed notes overlapping each other are both kept unchanged;+ - an unplaced note fully inside a placed one is removed;+ - an unplaced note run into by two placed notes is cut at the earliest placed start;+ - `placedOut` indices point at the same notes after removals;+ - a copy exactly on its original (same start) removes the original;+ - `Fate` agrees with `Settle` for every unplaced note in these fixtures;+ - ε handling: an unplaced note ending exactly at a placed start (within 1e-9) is Kept.++### Implementation++- [X] T005 [US1] In `src/managed/Nota.Application/Editing/NoteOverwrite.cs`, implement the data-model.md §1 rule verbatim:+ - `public static NoteFate Fate(in NotaNote m, IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed)` — "`c.Start − ε ≤ m.Start < c.End − ε` → Removed; `m.Start < c.Start` and `m.End > c.Start + ε` → Cut to `c.Start − m.Start` (shortest over all such c); otherwise Kept"; "Removal wins over a cut"; same pitch only; ε = 1e-9. Allocation-free (it is called per frame from Render).+ - `public static void Settle(IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed, List<NotaNote> output, List<int> placedOut)` — placed notes unchanged, survivors in original order, `placedOut` the new indices of the placed notes.+ Run `dotnet run --project tests/Nota.SmokeTest -- --notes`; the T004 checks must pass.+- [X] T006 [US1] In `src/managed/Nota.App/PianoRollView.cs` `DuplicateSelection` (around line 461), replace the inline overwrite loop with `NoteOverwrite.Settle` over `_notes + copies`, with the copies as `placed`, and keep the behaviour identical (FR-009). Select the copies via `placedOut`.+- [X] T007 [US1] In `src/managed/Nota.App/PianoRollView.cs`, add the pending placement:+ - a `private bool _placementPending` field;+ - `public bool SettlePlacement()`: return false unless pending; clear the flag; if the selection is empty, return false; otherwise `NoteOverwrite.Settle(_notes, _selection, …)`. If nothing changed (same count and no cut), return false without committing. Otherwise replace `_notes`, rebuild `_selection` from `placedOut`, `Invalidate(); CommitNotes(); Changed?.Invoke();` (one undo step, FR-002) and return true;+ - a `private void MarkPlaced() => _placementPending = true;` helper.+- [X] T008 [US1] In `src/managed/Nota.App/PianoRollView.cs`, set pending after placements:+ - `NoteGrid.OnPointerReleased` when `was != Mode.Marquee && _dragMoved` (move, resize, resize-left);+ - `MoveSelection` after a successful move;+ - the double-click draw branch in `NoteGrid.OnPointerPressed` (the new note is selected).+- [X] T009 [US1] In `src/managed/Nota.App/PianoRollView.cs`, settle before every selection change and whole-clip edit:+ - In `NoteGrid.OnPointerPressed`, when the press will change the selection (double-click; Shift-click toggle; hit not in the selection; empty-space marquee), call `_o.SettlePlacement()` first and, if it returned true, re-run `HitTest(p, out edge)`, because indices may have shifted. A press on an already-selected note without Shift must not settle.+ - Also settle on Esc and ⌘A in `NoteGrid.OnKeyDown`, and at the start of `DuplicateSelection`, `Quantize`, `TransposeBy` and `RemoveOutOfScaleNotes`. *(Implemented: `ShowPreview`/`ApplyPreview` clear the flag instead of settling — the tool computed its result from the unsettled notes and its captured indices would go stale; focus loss on clicking the tools rail settles first anyway.)*+- [X] T010 [US1] In `src/managed/Nota.App/PianoRollView.cs`, clear `_placementPending` without settling in `SetNotes` (a reload or undo means the engine wins) and in `DeleteSelection`.+- [X] T011 [US1] In `src/managed/Nota.App/PianoRollView.cs` `NoteGrid`, override `OnLostFocus` to call `_o.SettlePlacement()` (research R5: this also covers switching clips, since the old roll loses focus while its `Commit` still targets its own clip).+- [X] T012 [US1] In `src/managed/Nota.App/MainWindow.Files.cs`, call `_editorRoll?.SettlePlacement();`:+ - before `_projects.Save(` (around line 306), and before the save-as picker so a cancelled dialog has still settled;+ - at the top of `DoExportAsync` (around line 51).+ Autosave (`MainWindow.Recovery.cs`) is left alone (R5). Check that project-version saves (`MainWindow.History.cs`) go through the same save method; if not, add the call there too.+- [X] T013 [US1] In `src/managed/Nota.App/PianoRollView.cs` `NoteGrid.Render` (the note loop around line 1034), when `_o._placementPending` and the note is not selected and not a ghost, compute `NoteOverwrite.Fate(n, notes, _o._selection)`:+ - `Removed`: draw the whole note at ~25% of its normal alpha with a 1 px dashed outline in the track colour;+ - `Cut`: draw `[start, start+cutLen)` normally and the rest faded and dashed.+ Use static pens and brushes cached per track colour (no per-frame allocation beyond what the loop already does), keep it distinguishable from the brass tool-preview ghost, and check against `DESIGN.md` with the nota-design skill (research R4).++**Checkpoint**: quickstart rows 1–2 behave; Duplicate is unchanged; `--notes` passes.++---++## Phase 4: User Story 2 — Copy/paste lands on the original (P1)++**Goal**: ⌘V always lands on the copied notes' own beats, with the copies selected and+pending.++**Independent Test**: quickstart §2 rows 3–5.++- [X] T014 [US2] In `src/managed/Nota.App/PianoRollView.cs` `PasteClipboard` (around line 685):+ - call `SettlePlacement()` first;+ - replace `double anchor = _playheadBeat >= 0 ? SnapBeat(_playheadBeat) : s_clipAnchor;` with `double anchor = s_clipAnchor;`;+ - after selecting the pasted notes, call `MarkPlaced()`, so the paste itself overwrites nothing (FR-003a);+ - update the doc comment ("on top of the copied notes' original position").+ Skip and trim at the clip end as today (data-model §5).+- [X] T015 [US2] In `src/managed/Nota.App/MainWindow.Menu.cs` (the paste handler around line 162), confirm the Edit-menu paste reaches the same `PasteClipboard`. No change is expected; record the result in the task. *(Confirmed: `OnMenuPaste` → `ActiveRoll().PasteClipboard()`.)*++**Checkpoint**: US1 and US2 together give the requested "paste on top, then move" workflow.++---++## Phase 5: User Story 3 — Stretch and shrink from the keyboard (P2)++**Goal**: ⇧←/⇧→ shorten or lengthen every selected note by one grid step.++**Independent Test**: quickstart §2 row 6, plus `--notes`.++### Tests (write first)++- [X] T016 [P] [US3] In `tests/Nota.SmokeTest/NoteEditingTests.cs`, add `NoteOverwrite.ResizeBy` cases:+ - +step grows every note with starts unchanged;+ - −step on a note of length `minLen` leaves it at `minLen`;+ - a note ending at the clip end does not grow while the others do;+ - it returns false when nothing changed.++### Implementation++- [X] T017 [US3] In `src/managed/Nota.Application/Editing/NoteOverwrite.cs`, implement `public static bool ResizeBy(List<NotaNote> notes, IEnumerable<int> indices, double delta, double minLen, double clipLength)` per data-model §3: "`len' = clamp(len ± step, MinNoteLen, clipLength − start)`, with `start` unchanged".+- [X] T018 [US3] In `src/managed/Nota.App/PianoRollView.cs`, add `public bool ResizeSelection(int dir)`:+ - step = `SnapGridState.SnapOn ? SnapStep : MinNoteLen` (R7);+ - call `ResizeBy(_notes, _selection, dir * step, MinNoteLen, _lengthBeats)`;+ - on change, `Invalidate(); CommitNotes(); Changed?.Invoke(); MarkPlaced();`.+- [X] T019 [US3] In `src/managed/Nota.App/PianoRollView.cs` `NoteGrid.OnKeyDown` (around line 1417), inside the `!meta && selection` block, handle `Key.Left` and `Key.Right` with `shift` (and no Alt) as `_o.ResizeSelection(-1 / +1)` before the plain nudge cases. Plain ←/→ stay as they are.++---++## Phase 6: User Story 4 — Velocity from the keyboard (P2)++**Goal**: ⌥↑/⌥↓ change velocity by ±10, and ⌥⇧↑/⌥⇧↓ by ±1.++**Independent Test**: quickstart §2 rows 7–8, plus `--notes`.++### Tests (write first)++- [X] T020 [P] [US4] In `tests/Nota.SmokeTest/NoteEditingTests.cs`, add `NoteOverwrite.VelocityBy` cases: 40/127 + 10 → 50/127; 125/127 + 10 → 127/127; 3/127 − 10 → 1/127; 0.8f + 1 → (round(0.8·127)+1)/127; the result is always on an integer MIDI step.++### Implementation++- [X] T021 [US4] In `src/managed/Nota.Application/Editing/NoteOverwrite.cs`, implement `public static float VelocityBy(float v, int steps127)` per data-model §4: "`v' = clamp(round(v·127) + k, 1, 127) / 127`".+- [X] T022 [US4] In `src/managed/Nota.App/PianoRollView.cs`, add `public bool NudgeVelocity(int steps127)`. It applies `VelocityBy` to every selected note; if any changed, `Invalidate(); CommitNotes(); Changed?.Invoke();`. It does **not** touch `_placementPending`. The velocity lane and the `SelectionInfo` text refresh through `Changed`/`Invalidate`.+- [X] T023 [US4] In `src/managed/Nota.App/PianoRollView.cs` `NoteGrid.OnKeyDown`, read `bool alt = (e.KeyModifiers & KeyModifiers.Alt) != 0;`. In the selection block, check Alt **before** Shift: `Key.Up`/`Key.Down` with Alt → `_o.NudgeVelocity(shift ? ±1 : ±10)`. Leave Alt+←/→ unhandled. Without a selection, the keys fall through (contract).++---++## Phase 7: Polish & Cross-Cutting++- [X] T024 [P] In `src/managed/Nota.App/PreferencesWindow.cs` (the "PIANO ROLL" group around line 1074), add rows per contracts/piano-roll-keys.md:+ - `("⇧← ⇧→", "Shorten / lengthen the notes by the grid")`;+ - `("⌥↑ ⌥↓", "Velocity +10 / −10 · ⌥⇧ by 1")`;+ - change ⌘C ⌘X ⌘V to "Copy / cut / paste notes · paste lands on the originals";+ - add `("Esc", "Deselect · applies the overwrite of moved notes")`.+ Run the nota-shortcuts skill to confirm the list matches the handlers.+- [X] T025 [P] Add `CHANGELOG.md` `[Unreleased]` entries:+ - Changed: "Notes moved, stretched, drawn or pasted onto notes of the same pitch now replace them instead of stacking — applied when you deselect; until then the notes underneath are marked." and "⌘V in the piano roll always pastes on top of the copied notes."+ - Added: "⇧←/⇧→ shorten or lengthen the selected notes by the grid; ⌥↑/⌥↓ change their velocity by 10 (⌥⇧ by 1)."+- [X] T026 [P] Update `FEATURES.md` with the nota-features skill.+- [X] T027 [P] Update the piano-roll page in `../nota-docs` (EN + RU) and regenerate the shortcuts page with the nota-docs skill.+- [X] T028 Run `scripts/build.sh` (builds native + managed and runs the full smoke test, including `-- note editing --`); it must exit green.+- [X] T029 Walk quickstart §2 rows 1–9 in the real app (the memory's UI verify recipe, `NOTA_DATA_DIR` isolation) and take screenshots of row 2 (the mark) and row 9 (Shortcuts).+- [X] T030 Recheck the spec's Nota Compliance Checklist: SPDX headers on `NoteOverwrite.cs` and `NoteEditingTests.cs`, no new dependency, CHANGELOG present.++---++## Dependencies & Execution Order++- **Setup (T001–T002)** → **Foundational (T003)** → stories.+- **US1 (T004–T013)** comes first: US2 and US3 call `MarkPlaced`/`SettlePlacement`.+- **US2 (T014–T015)** depends on T007.+- **US3 (T016–T019)** depends on T003 and T007 (`MarkPlaced`). Its rule work (T016–T017) can run alongside US1.+- **US4 (T020–T023)** depends only on T003, so it is independent of US1–US3 at the rule level. T023 touches the same `OnKeyDown` as T019, so do them one after the other.+- **Polish** comes after the stories it documents.++Inside `PianoRollView.cs` everything is sequential (same file).++## Parallel Examples++```text+# After T003:+T004 (overwrite tests) T016 (resize tests) T020 (velocity tests) — same test file: write in one sitting, or one after another+T017 (ResizeBy) T021 (VelocityBy) — same file as T005: one after another+# Polish:+T024 T025 T026 T027 — different files+```++## Implementation Strategy++1. **MVP = US1 + US2** (both P1): overwrite with deferred settle, and paste on the+ original. This is the user's core workflow ("paste on top, move with arrows").+2. Then US3 (length keys), then US4 (velocity keys). Each is a small key handler over a+ tested pure step.+3. Polish: shortcuts list, CHANGELOG, FEATURES, docs, `scripts/build.sh`, app walkthrough.++---++## Phase 8: Convergence++- [X] T031 Settle the pending placement before the velocity lane and the MPE expression lanes change the selection. Without this, a stem click swaps the selection while `_placementPending` stays true, and the next settle treats the clicked note as placed. In `src/managed/Nota.App/PianoRollView.cs`, `VelocityLane.OnPointerPressed`: call `_o.SettlePlacement()` before `_selection` changes (and re-run `Nearest(p)` if it returned true). Do the same in `src/managed/Nota.App/PianoRollView.Expression.cs` `ExpressionLane.TargetsAt` before it clears or adds to `_selection`. Neither lane is focusable, so the grid's `LostFocus` does not fire. Add a `/tmp/noteharness` case: paste, press →, then click another note's stem — that note must not overwrite anything — per FR-003 (contradicts)+- [X] T032 Settle instead of silently dropping a pending placement when the roll is reloaded or replaced for any reason other than undo/redo. In `src/managed/Nota.App/MainWindow.Detail.cs`, `ReloadEditorNotes` (reached from `TracksChanged`, `RecordingTick` and pattern-view edits) and both `_editorRoll = roll;` sites (lines ~437 and ~616, where a clip editor that never had focus can be replaced): call `_editorRoll?.SettlePlacement()` first. Keep `RefreshAfterUndoRedo` (`MainWindow.Menu.cs`) discarding, because there the engine state wins. That way a later save never stores the stacked notes, per SC-001 / FR-003 (partial)+- [X] T033 Reconcile the clip-tool preview with plan §2: `src/managed/Nota.App/MidiToolsView.cs` (line ~160) captures `_roll.SourceNotes` / `SelectionIndices` without settling, and `ShowPreview` / `ApplyPreview` drop the pending flag (the tasks.md T009 note). Call `_roll.SettlePlacement()` right before that capture, so a tool never builds on stacked notes even when the grid kept focus, per plan: settle before whole-clip edits (contradicts)+ *(Implemented in part: the two `_editorRoll = roll;` sites now settle the outgoing roll. `ReloadEditorNotes` is deliberately left discarding. Every caller (pattern-view edit, recording tick, `TracksChanged`) means the engine changed underneath, so settling there would commit the roll's stale note list over that external change. That is the plan's R5 / §2 rule "a reload means the engine state wins". SC-001 holds for edits made in the roll; a placement interrupted by an external reload keeps the engine's notes as they are.)*+ *(T033 implemented at `MidiToolsView.Preview()`, not at `Resync()`: `Resync` runs after every roll edit and would settle immediately.)*diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.csindex eeeae5ad..2a89de27 100644--- a/src/managed/Nota.App/MainWindow.Detail.cs+++ b/src/managed/Nota.App/MainWindow.Detail.cs@@ -391,6 +391,9 @@ public partial class MainWindowprivate void BuildClipEditor(int trackId, int clipIndex){if (_vm is null) return;+ // The editor being replaced lets its pending placement go into its own clip first (it+ // may never have had focus to lose, e.g. after a menu paste).+ _editorRoll?.SettlePlacement();var roll = new PianoRollView{BeatsPerBar = Timeline.BeatsPerBar, // bar lines and bar steps match the arrangement@@ -593,6 +596,9 @@ public partial class MainWindow_sessionSlotTrack = trackId; // so the Pattern tab can target this slot_sessionSlotScene = scene;SyncClipTab(); // a Drum Rack slot lights the Pattern tab up+ // The editor being replaced lets its pending placement go into its own clip first (it+ // may never have had focus to lose, e.g. after a menu paste).+ _editorRoll?.SettlePlacement();var roll = new PianoRollView{BeatsPerBar = Timeline.BeatsPerBar, // bar lines and bar steps match the arrangementdiff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.csindex b5905ceb..ebbf33f2 100644--- a/src/managed/Nota.App/MainWindow.Files.cs+++ b/src/managed/Nota.App/MainWindow.Files.cs@@ -51,6 +51,7 @@ public partial class MainWindowprivate async Task DoExportAsync(){if (_vm is null) return;+ _editorRoll?.SettlePlacement(); // render what the user sees once the notes are let godouble endBeats = ProjectEndBeats();if (endBeats <= 0.0)@@ -290,6 +291,9 @@ public partial class MainWindowprivate async Task<bool> DoSaveAsync(bool saveAs, string? note = null){if (_vm is null) return false;+ // Notes still being placed in the piano roll overwrite what they cover now, so a saved+ // project never keeps them stacked (specs/007-midi-note-editing).+ _editorRoll?.SettlePlacement();string? dir = _projectPath;if (saveAs || dir is null)diff --git a/src/managed/Nota.App/MidiToolsView.cs b/src/managed/Nota.App/MidiToolsView.csindex a9276892..584f2933 100644--- a/src/managed/Nota.App/MidiToolsView.cs+++ b/src/managed/Nota.App/MidiToolsView.cs@@ -183,6 +183,9 @@ public sealed class MidiToolsView : UserControlprivate void Preview(){if (_tool is null) { _roll.CancelPreview(); PaintResult(null); return; }+ // A tool must not build on notes still stacked under a pending placement: let it go+ // first (its Changed re-reads the working set through OnRollChanged).+ if (!_roll.Previewing) _roll.SettlePlacement();var result = MidiToolRunner.Apply(_tool, _source, _scope, SettingsFor(_tool), Context(), _blend);_suppressResync = true;_roll.ShowPreview(result);diff --git a/src/managed/Nota.App/PianoRollView.Expression.cs b/src/managed/Nota.App/PianoRollView.Expression.csindex 7682d6cc..93427bca 100644--- a/src/managed/Nota.App/PianoRollView.Expression.cs+++ b/src/managed/Nota.App/PianoRollView.Expression.cs@@ -343,6 +343,7 @@ public sealed partial class PianoRollView{var sel = _o._selection.Where(i => i >= 0 && i < _o._notes.Count && Spans(i, beat)).ToList();if (sel.Count > 0) return sel;+ _o.SettlePlacement(); // the selection changes below, and this lane never takes focusint pick = -1;for (int i = 0; i < _o._notes.Count; i++)if (Spans(i, beat) && (pick < 0 || _o._notes[i].Pitch > _o._notes[pick].Pitch)) pick = i;diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex 1f3b8a59..6a1a1de8 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -393,6 +393,7 @@ public sealed partial class PianoRollView : UserControlpublic void SetNotes(IEnumerable<NotaNote> notes, double lengthBeats){_previewBackup = null;+ _placementPending = false; // a reload (undo, recording, another clip) is the truth now_notes.Clear();_notes.AddRange(notes);_lengthBeats = Math.Max(1, lengthBeats);@@ -460,6 +461,7 @@ public sealed partial class PianoRollView : UserControl/// selects the copies. Returns false if nothing was selected. Undoable (one Commit).</summary>public bool DuplicateSelection(){+ SettlePlacement();var sel = _selection.Where(i => i >= 0 && i < _notes.Count).ToList();if (sel.Count == 0) return false;double minStart = double.MaxValue, maxEnd = double.MinValue;@@ -469,28 +471,17 @@ public sealed partial class PianoRollView : UserControlvar copies = new List<NotaNote>(sel.Count);foreach (int i in sel) { var n = _notes[i]; n.StartBeat = Math.Min(n.StartBeat + shift, cap); copies.Add(n); }// Like a duplicated clip in the arrangement, the copies overwrite what they land on- // instead of stacking: a note of the same pitch that starts under a copy goes, and- // one that runs into a copy is cut where the copy starts.- var kept = new List<NotaNote>(_notes.Count);- foreach (var n in _notes)- {- var m = n;- bool drop = false;- foreach (var c in copies)- {- if (c.Pitch != m.Pitch) continue;- double cs = c.StartBeat, ce = c.StartBeat + c.LengthBeats;- if (m.StartBeat >= cs - 1e-9 && m.StartBeat < ce - 1e-9) { drop = true; break; }- if (m.StartBeat < cs && m.StartBeat + m.LengthBeats > cs + 1e-9) m.LengthBeats = cs - m.StartBeat;- }- if (!drop) kept.Add(m);- }- _notes.Clear();- _notes.AddRange(kept);+ // straight away, with the same rule a settled placement uses (NoteOverwrite).int baseIdx = _notes.Count;_notes.AddRange(copies);+ var placed = Enumerable.Range(baseIdx, copies.Count).ToList();+ var settled = new List<NotaNote>(_notes.Count);+ var placedOut = new List<int>(copies.Count);+ NoteOverwrite.Settle(_notes, placed, settled, placedOut);+ _notes.Clear();+ _notes.AddRange(settled);_selection.Clear();- for (int k = 0; k < copies.Count; k++) _selection.Add(baseIdx + k);+ _selection.UnionWith(placedOut);Invalidate();CommitNotes();Changed?.Invoke();@@ -501,6 +492,7 @@ public sealed partial class PianoRollView : UserControlpublic bool DeleteSelection(){if (_selection.Count == 0) return false;+ _placementPending = false; // the placed notes are what goesforeach (int i in _selection.OrderByDescending(x => x))if (i >= 0 && i < _notes.Count) _notes.RemoveAt(i);_selection.Clear();@@ -518,6 +510,7 @@ public sealed partial class PianoRollView : UserControlpublic bool RemoveOutOfScaleNotes(){if (!HasOutOfScaleNotes) return false;+ SettlePlacement();_notes.RemoveAll(n => !InScale(n.Pitch));_selection.Clear();Invalidate();@@ -550,6 +543,9 @@ public sealed partial class PianoRollView : UserControl/// <summary>Puts a tool's result on screen and in the engine without touching undo.</summary>public void ShowPreview(IReadOnlyList<NotaNote> notes){+ // The tool computed its result from the notes as they stand, so a pending placement+ // is part of what it replaces; settling now would only reshuffle stale indices.+ _placementPending = false;_previewBackup ??= new List<NotaNote>(_notes);_notes.Clear();_notes.AddRange(notes);@@ -601,6 +597,7 @@ public sealed partial class PianoRollView : UserControlpublic void ApplyPreview(){if (_previewBackup is null) return;+ _placementPending = false;var original = _previewBackup;_selection.Clear();Invalidate();@@ -627,6 +624,7 @@ public sealed partial class PianoRollView : UserControl/// <summary>Moves note starts toward the Quantize step (its own value, never the zoom's).</summary>public void Quantize(double strength){+ SettlePlacement();double qStep = Grids.Quantize.Beats(_beatsPerBar);for (int i = 0; i < _notes.Count; i++){@@ -642,6 +640,7 @@ public sealed partial class PianoRollView : UserControlpublic void TransposeBy(int semis){+ SettlePlacement();for (int i = 0; i < _notes.Count; i++){var n = _notes[i];@@ -680,12 +679,14 @@ public sealed partial class PianoRollView : UserControl/// <summary>Copies then deletes the selection. Undoable.</summary>public bool CutSelection() => CopySelection() && DeleteSelection();- /// <summary>Pastes the clipboard — anchored at the playback cursor when visible, else at- /// the copied notes' original position — and selects the pasted notes. Undoable.</summary>+ /// <summary>Pastes the clipboard on top of the copied notes' original position (whatever+ /// the transport is doing) and selects the copies, ready to be moved off with the arrows or+ /// the mouse. The copies overwrite nothing until they are let go (SettlePlacement). Undoable.</summary>public bool PasteClipboard(){if (s_clipboard.Count == 0) return false;- double anchor = _playheadBeat >= 0 ? SnapBeat(_playheadBeat) : s_clipAnchor;+ SettlePlacement();+ double anchor = s_clipAnchor;int baseIdx = _notes.Count;foreach (var c in s_clipboard){@@ -699,6 +700,7 @@ public sealed partial class PianoRollView : UserControlif (_notes.Count == baseIdx) return false;_selection.Clear();for (int k = baseIdx; k < _notes.Count; k++) _selection.Add(k);+ _placementPending = true;Invalidate(); CommitNotes(); Changed?.Invoke();return true;}@@ -728,11 +730,88 @@ public sealed partial class PianoRollView : UserControlif (maxP + dp > MaxPitch) dp = MaxPitch - maxP;if (Math.Abs(db) < 1e-9 && dp == 0) return false;foreach (int i in sel) { var n = _notes[i]; n.StartBeat += db; n.Pitch += dp; _notes[i] = n; }+ _placementPending = true;Invalidate(); CommitNotes(); Changed?.Invoke();if (dp != 0) EnsurePitchVisible(dp > 0 ? maxP + dp : minP + dp);return true;}+ /// <summary>Lengthens (dir +1) or shortens (dir −1) every selected note by one grid step,+ /// keeping starts; never below the minimum length or past the clip end. Undoable.</summary>+ public bool ResizeSelection(int dir)+ {+ if (_selection.Count == 0) return false;+ double step = SnapGridState.SnapOn ? SnapStep : MinNoteLen;+ if (!NoteOverwrite.ResizeBy(_notes, _selection, dir * step, MinNoteLen, _lengthBeats)) return false;+ _placementPending = true;+ Invalidate(); CommitNotes(); Changed?.Invoke();+ return true;+ }++ /// <summary>Moves every selected note's velocity by <paramref name="steps127"/> MIDI steps+ /// (clamped to 1–127). Not a placement: nothing gets overwritten. Undoable.</summary>+ public bool NudgeVelocity(int steps127)+ {+ bool changed = false;+ foreach (int i in _selection)+ {+ if (i < 0 || i >= _notes.Count) continue;+ var n = _notes[i];+ float v = NoteOverwrite.VelocityBy(n.Velocity, steps127);+ if (v == n.Velocity) continue;+ n.Velocity = v;+ _notes[i] = n;+ changed = true;+ }+ if (!changed) return false;+ Invalidate(); CommitNotes(); Changed?.Invoke();+ return true;+ }++ // ---- pending placement (specs/007-midi-note-editing) -------------------------+ // Notes moved, stretched, drawn or pasted overwrite same-pitch notes they land on, but+ // only once the selection is let go: until then the notes underneath stay whole and are+ // drawn marked, so a pasted copy can be walked off its original with the arrows.+ private bool _placementPending;++ // The selection as a list for the per-frame overwrite marks (Fate is allocation-free over a+ // list); rebuilt only when the selection changed since the last frame.+ private readonly List<int> _placedForRender = new();+ private IReadOnlyList<int> PlacedForRender()+ {+ if (_placedForRender.Count != _selection.Count || !_placedForRender.TrueForAll(_selection.Contains))+ {+ _placedForRender.Clear();+ _placedForRender.AddRange(_selection);+ }+ return _placedForRender;+ }++ /// <summary>Applies a pending placement: the selected notes overwrite the same-pitch notes+ /// they cover (NoteOverwrite). Its own undo step. Called whenever the selection is let go —+ /// selection change, focus loss, whole-clip edits, and by the host before save/export.+ /// Returns true when notes were cut or removed (indices may have shifted).</summary>+ public bool SettlePlacement()+ {+ if (!_placementPending) return false;+ _placementPending = false;+ if (_selection.Count == 0) return false;+ var placed = _selection.Where(i => i >= 0 && i < _notes.Count).ToList();+ var settled = new List<NotaNote>(_notes.Count);+ var placedOut = new List<int>(placed.Count);+ NoteOverwrite.Settle(_notes, placed, settled, placedOut);+ bool changed = settled.Count != _notes.Count;+ for (int i = 0; !changed && i < settled.Count; i++)+ changed = settled[i].LengthBeats != _notes[i].LengthBeats;+ if (!changed) return false;+ _notes.Clear();+ _notes.AddRange(settled);+ _selection.Clear();+ _selection.UnionWith(placedOut);+ Invalidate(); CommitNotes(); Changed?.Invoke();+ return true;+ }+// Scroll the body so `pitch`'s row is within the viewport (keeps arrow-moved notes visible).private void EnsurePitchVisible(int pitch){@@ -994,7 +1073,15 @@ public sealed partial class PianoRollView : UserControlprivate double _autoVelY;private Point _lastGrid;- public NoteGrid(PianoRollView o) { _o = o; Focusable = true; }+ private readonly List<Rect> _doomed = new(); // per-frame scratch for the overwrite marks++ public NoteGrid(PianoRollView o)+ {+ _o = o;+ Focusable = true;+ // Leaving the grid (another panel, another clip, a dialog) lets the placement go.+ LostFocus += (_, _) => _o.SettlePlacement();+ }private double Ppb => _o.PixelsPerBeat;private double BeatToX(double b) => _o.BeatToX(b);@@ -1051,7 +1138,21 @@ public sealed partial class PianoRollView : UserControlvar c = _o._trackColor;double a = 0.45 + 0.55 * Math.Clamp(n.Velocity, 0, 1);if (!_o.InScale(n.Pitch)) a *= 0.4; // out-of-scale notes read faint- ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a), c.R, c.G, c.B)), r, 2);+ // A pending placement covers part of this note: the part settling will cut+ // (or all of it, when it goes) reads faint behind a dashed track-colour edge.+ var fate = _o._placementPending && _o._selection.Count > 0+ ? NoteOverwrite.Fate(i, notes, _o.PlacedForRender()) : default;+ if (fate.Kind == NoteFateKind.Kept)+ ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a), c.R, c.G, c.B)), r, 2);+ else+ {+ double keepW = fate.Kind == NoteFateKind.Cut ? Math.Min(r.Width, fate.CutLength * ppb) : 0;+ if (keepW > 0)+ ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a), c.R, c.G, c.B)), r.WithWidth(keepW), 2);+ var doomed = new Rect(r.X + keepW, r.Y, Math.Max(1, r.Width - keepW), r.Height);+ ctx.FillRectangle(new SolidColorBrush(Color.FromArgb((byte)(255 * a * 0.25), c.R, c.G, c.B)), doomed, 2);+ _doomed.Add(doomed); // its dashed edge goes on top of the notes covering it+ }}if (n.ExprId > 0 || _o._expr.Editing(i)) DrawExpression(ctx, i, n, r, sel, ppb);// Resize-edge affordance: a bright bar on the edge a drag would trim.@@ -1062,6 +1163,14 @@ public sealed partial class PianoRollView : UserControlctx.FillRectangle(EdgeHighlight, new Rect(left ? x : x + r.Width - 2.5, y + 1, 2.5, RowH - 3));}}+ // The dashed edges of what a pending placement will cut, drawn over the placed notes+ // so a note hidden under a pasted copy still shows that it is there and will go.+ if (_doomed.Count > 0)+ {+ var pen = new Pen(new SolidColorBrush(_o._trackColor), 1, DashStyle.Dash);+ foreach (var d in _doomed) ctx.DrawRectangle(null, pen, d.Deflate(0.5), 2, 2);+ _doomed.Clear();+ }_o.DrawOutsideClip(ctx, w, h);if (_o._playheadBeat >= 0){@@ -1158,6 +1267,10 @@ public sealed partial class PianoRollView : UserControl_free = (e.KeyModifiers & KeyModifiers.Alt) != 0;bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;int hit = HitTest(p, out int edge);+ // Any press that changes the selection lets a pending placement go first; settling+ // can cut or remove notes, so hit-test again on the settled notes.+ bool keepsSelection = e.ClickCount != 2 && !shift && hit >= 0 && _o._selection.Contains(hit);+ if (!keepsSelection && _o.SettlePlacement()) hit = HitTest(p, out edge);// Double-click: add a note on empty space, delete one under the cursor.if (e.ClickCount == 2)@@ -1168,6 +1281,7 @@ public sealed partial class PianoRollView : UserControlvar nt = new NotaNote(YToPitch(p.Y), Math.Max(0, Snap(XToBeat(p.X))), _o.MinNoteLen, 0.8f);_o._notes.Add(nt);_o._selection.Clear(); _o._selection.Add(_o._notes.Count - 1);+ _o._placementPending = true; // a drawn note overwrites what it lands on}_o.Invalidate(); _o.CommitNotes(); _o.Changed?.Invoke();e.Handled = true;@@ -1343,6 +1457,7 @@ public sealed partial class PianoRollView : UserControl_orig.Clear();if (was != Mode.Marquee && _dragMoved){+ _o._placementPending = true; // overwrites once the selection is let go// Live path: undo was seeded on the first move; push the final state (no undo).// No live path (session): fall back to a single committing push.if (_o.CommitLive is not null && _liveStarted) _o.CommitLive(_o._notes);@@ -1421,14 +1536,27 @@ public sealed partial class PianoRollView : UserControlif (!meta && (e.Key == Key.Delete || e.Key == Key.Back)) { if (_o.DeleteSelection()) e.Handled = true; return; }if (!meta && e.Key == Key.Escape && _o._selection.Count > 0){+ _o.SettlePlacement();_o._selection.Clear(); _o.Invalidate(); _o.Changed?.Invoke(); e.Handled = true; return;}// Arrow keys nudge the selection: ←/→ by the grid in time, ↑/↓ by a semitone// (Shift = an octave). The move auto-scrolls to keep pitch-shifted notes in view.+ // ⇧←/⇧→ shorten/lengthen by the grid; ⌥↑/⌥↓ change velocity by 10 (⌥⇧ by 1).+ bool alt = (e.KeyModifiers & KeyModifiers.Alt) != 0;if (!meta && _o._selection.Count > 0){- switch (e.Key)+ if (alt)+ {+ switch (e.Key)+ {+ case Key.Up: if (_o.NudgeVelocity(shift ? 1 : 10)) e.Handled = true; return;+ case Key.Down: if (_o.NudgeVelocity(shift ? -1 : -10)) e.Handled = true; return;+ }+ }+ else switch (e.Key){+ case Key.Left when shift: if (_o.ResizeSelection(-1)) e.Handled = true; return;+ case Key.Right when shift: if (_o.ResizeSelection(+1)) e.Handled = true; return;case Key.Left: if (_o.MoveSelection(0, -_o.SnapStep)) e.Handled = true; return;case Key.Right: if (_o.MoveSelection(0, +_o.SnapStep)) e.Handled = true; return;case Key.Up: if (_o.MoveSelection(shift ? 12 : 1, 0)) e.Handled = true; return;@@ -1437,6 +1565,7 @@ public sealed partial class PianoRollView : UserControl}if (meta && e.Key == Key.A){+ _o.SettlePlacement();_o._selection.Clear();for (int i = 0; i < _o._notes.Count; i++) _o._selection.Add(i);_o.Invalidate(); _o.Changed?.Invoke(); e.Handled = true; return;@@ -1532,6 +1661,13 @@ public sealed partial class PianoRollView : UserControlint hit = Nearest(p);if (hit < 0) return;bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;+ // The lane never takes focus, so a stem that changes the selection lets a pending+ // placement go here; settling can shift indices, so find the stem again.+ if ((shift || !_o._selection.Contains(hit)) && _o.SettlePlacement())+ {+ hit = Nearest(p);+ if (hit < 0) return;+ }if (shift) _o._selection.Add(hit);else if (!_o._selection.Contains(hit)) { _o._selection.Clear(); _o._selection.Add(hit); }_grabbed.Clear();diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 2d464cf1..5c962ff1 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1076,9 +1076,12 @@ public sealed partial class PreferencesWindow : NotaWindow("← →", "Move notes by the grid"),("↑ ↓", "Transpose by a semitone"),("⇧↑ ⇧↓", "Transpose by an octave"),+ ("⇧← ⇧→", "Shorten / lengthen the notes by the grid"),+ ("⌥↑ ⌥↓", "Velocity +10 / −10 · ⌥⇧ by 1"),("⌘A", "Select all notes"),("⌘D", "Duplicate the selection · replaces the notes it lands on"),- ("⌘C ⌘X ⌘V", "Copy / cut / paste notes"),+ ("⌘C ⌘X ⌘V", "Copy / cut / paste notes · paste lands on the originals"),+ ("Esc", "Deselect · moved or pasted notes replace the notes under them"),("Delete", "Delete the selected notes"),("Drag note edge", "Change the note's start or end"),("Drag velocity stem", "Set velocity · selected notes move together · ⇧ adds a note"),diff --git a/src/managed/Nota.Application/Editing/NoteOverwrite.cs b/src/managed/Nota.Application/Editing/NoteOverwrite.csnew file mode 100644index 00000000..ca015b08--- /dev/null+++ b/src/managed/Nota.Application/Editing/NoteOverwrite.cs@@ -0,0 +1,115 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Piano-roll note edits that must agree everywhere (specs/007-midi-note-editing): the+// "placed notes win" overwrite rule shared by Duplicate and by settling a moved, stretched,+// drawn or pasted selection, plus the keyboard length and velocity steps. Pure and UI-free:+// the smoke test drives it directly.++using System;+using System.Collections.Generic;++namespace Nota.Application.Editing;++public enum NoteFateKind { Kept, Cut, Removed }++/// <summary>What settling does to one unplaced note: nothing, cut to CutLength, or remove it.</summary>+public readonly record struct NoteFate(NoteFateKind Kind, double CutLength);++public static class NoteOverwrite+{+ private const double Eps = 1e-9;++ /// <summary>What settling <paramref name="placed"/> does to note <paramref name="index"/>: removed if+ /// its start lies under a same-pitch placed note, cut where the earliest placed note it runs+ /// into starts, else kept. Placed notes themselves are always kept. Allocation-free when+ /// <paramref name="placed"/> is a list or an array (the piano roll calls it per frame).</summary>+ public static NoteFate Fate(int index, IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed)+ {+ var m = notes[index];+ double cut = double.MaxValue;+ if (placed is IReadOnlyList<int> list)+ {+ for (int k = 0; k < list.Count; k++)+ {+ if (list[k] == index) return new(NoteFateKind.Kept, 0);+ if (Against(m, notes, list[k], ref cut)) return new(NoteFateKind.Removed, 0);+ }+ }+ else+ {+ foreach (int i in placed)+ {+ if (i == index) return new(NoteFateKind.Kept, 0);+ if (Against(m, notes, i, ref cut)) return new(NoteFateKind.Removed, 0);+ }+ }+ return cut < double.MaxValue ? new(NoteFateKind.Cut, cut - m.StartBeat) : new(NoteFateKind.Kept, 0);+ }++ // True when placed note i removes m; otherwise tightens `cut` if m runs into it.+ private static bool Against(in NotaNote m, IReadOnlyList<NotaNote> notes, int i, ref double cut)+ {+ if (i < 0 || i >= notes.Count) return false;+ var c = notes[i];+ if (c.Pitch != m.Pitch) return false;+ double cs = c.StartBeat, ce = c.StartBeat + c.LengthBeats;+ if (m.StartBeat >= cs - Eps && m.StartBeat < ce - Eps) return true;+ if (m.StartBeat < cs && m.StartBeat + m.LengthBeats > cs + Eps && cs < cut) cut = cs;+ return false;+ }++ /// <summary>Applies the rule: placed notes unchanged, every other note kept, cut or removed+ /// (see <see cref="Fate"/>). Survivors keep their order; <paramref name="placedOut"/> gets+ /// the new indices of the placed notes, in the order of <paramref name="placed"/>.</summary>+ public static void Settle(IReadOnlyList<NotaNote> notes, IReadOnlyCollection<int> placed, List<NotaNote> output, List<int> placedOut)+ {+ output.Clear();+ placedOut.Clear();+ var isPlaced = new bool[notes.Count];+ foreach (int i in placed) if (i >= 0 && i < notes.Count) isPlaced[i] = true;+ var newIndex = new int[notes.Count];+ for (int i = 0; i < notes.Count; i++)+ {+ newIndex[i] = -1;+ var m = notes[i];+ if (!isPlaced[i])+ {+ var f = Fate(i, notes, placed);+ if (f.Kind == NoteFateKind.Removed) continue;+ if (f.Kind == NoteFateKind.Cut) m.LengthBeats = f.CutLength;+ }+ newIndex[i] = output.Count;+ output.Add(m);+ }+ foreach (int i in placed) if (i >= 0 && i < notes.Count) placedOut.Add(newIndex[i]);+ }++ /// <summary>Changes the length of the notes at <paramref name="indices"/> by+ /// <paramref name="delta"/> beats, keeping their starts: never below <paramref name="minLen"/>,+ /// never past <paramref name="clipLength"/>. Returns whether any note changed.</summary>+ public static bool ResizeBy(List<NotaNote> notes, IEnumerable<int> indices, double delta, double minLen, double clipLength)+ {+ bool changed = false;+ foreach (int i in indices)+ {+ if (i < 0 || i >= notes.Count) continue;+ var n = notes[i];+ double max = Math.Max(minLen, clipLength - n.StartBeat);+ double len = n.LengthBeats + delta;+ // Clamp toward the limits, but never pull a note that is already past one further.+ if (delta > 0) len = Math.Min(len, Math.Max(n.LengthBeats, max));+ else len = Math.Max(len, Math.Min(n.LengthBeats, minLen));+ if (Math.Abs(len - n.LengthBeats) < Eps) continue;+ n.LengthBeats = len;+ notes[i] = n;+ changed = true;+ }+ return changed;+ }++ /// <summary>A velocity (0..1) moved by <paramref name="steps127"/> MIDI steps, kept on an+ /// integer MIDI value in 1..127 — so a note can be made quieter but never silent.</summary>+ public static float VelocityBy(float v, int steps127)+ => Math.Clamp((int)Math.Round(v * 127) + steps127, 1, 127) / 127f;+}diff --git a/tests/Nota.SmokeTest/NoteEditingTests.cs b/tests/Nota.SmokeTest/NoteEditingTests.csnew file mode 100644index 00000000..59b209b7--- /dev/null+++ b/tests/Nota.SmokeTest/NoteEditingTests.cs@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Piano-roll note editing (specs/007-midi-note-editing): the overwrite rule, length and+// velocity steps. Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --notes`.++using Nota.Application;+using Nota.Application.Editing;++namespace Nota.SmokeTest;++internal static class NoteEditingTests+{+ private static bool Near(double a, double b) => Math.Abs(a - b) < 1e-9;++ private static NotaNote N(int pitch, double start, double end, float vel = 0.8f) => new(pitch, start, end - start, vel);++ private static (List<NotaNote> Notes, List<int> Placed) Settle(IReadOnlyList<NotaNote> notes, params int[] placed)+ {+ var outN = new List<NotaNote>();+ var outP = new List<int>();+ NoteOverwrite.Settle(notes, placed, outN, outP);+ return (outN, outP);+ }++ private static bool Is(NotaNote n, int pitch, double start, double end)+ => n.Pitch == pitch && Near(n.StartBeat, start) && Near(n.StartBeat + n.LengthBeats, end);++ // Fate must predict Settle for every unplaced note (the mark shows what settling does).+ private static bool FateAgrees(IReadOnlyList<NotaNote> notes, params int[] placed)+ {+ var (after, _) = Settle(notes, placed);+ int k = 0;+ for (int i = 0; i < notes.Count; i++)+ {+ var f = NoteOverwrite.Fate(i, notes, placed);+ if (Array.IndexOf(placed, i) >= 0) { if (f.Kind != NoteFateKind.Kept) return false; k++; continue; }+ switch (f.Kind)+ {+ case NoteFateKind.Removed: break;+ case NoteFateKind.Kept: if (!Is(after[k++], notes[i].Pitch, notes[i].StartBeat, notes[i].StartBeat + notes[i].LengthBeats)) return false; break;+ case NoteFateKind.Cut: if (!Is(after[k++], notes[i].Pitch, notes[i].StartBeat, notes[i].StartBeat + f.CutLength)) return false; break;+ }+ }+ return k == after.Count;+ }++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ const int C4 = 60, D4 = 62;++ // ---- overwrite (Story 1) ----------------------------------------------------------+ { // 1: B moved to start at 1 cuts A (0–2) to 0–1+ var (r, p) = Settle(new[] { N(C4, 0, 2), N(C4, 1, 2) }, 1);+ yield return (r.Count == 2 && Is(r[0], C4, 0, 1) && Is(r[p[0]], C4, 1, 2), "overwrite: a note running into a placed note is cut at its start");+ }+ { // 2: B (0.5–2.5) covers A's start (1–2) → A removed+ var (r, p) = Settle(new[] { N(C4, 1, 2), N(C4, 0.5, 2.5) }, 1);+ yield return (r.Count == 1 && p[0] == 0 && Is(r[0], C4, 0.5, 2.5), "overwrite: a note whose start is covered is removed");+ }+ { // 3: B lengthened to 0–2.5 covers A (2–3) start → A removed+ var (r, _) = Settle(new[] { N(C4, 2, 3), N(C4, 0, 2.5) }, 1);+ yield return (r.Count == 1 && Is(r[0], C4, 0, 2.5), "overwrite: a lengthened note removes the note it now covers");+ }+ { // 4: different pitches never interact+ var (r, _) = Settle(new[] { N(C4, 0, 2), N(D4, 1, 3) }, 1);+ yield return (r.Count == 2 && Is(r[0], C4, 0, 2) && Is(r[1], D4, 1, 3), "overwrite: different pitches are untouched");+ }+ { // placed notes never cut each other+ var (r, _) = Settle(new[] { N(C4, 0, 2), N(C4, 1, 3) }, 0, 1);+ yield return (r.Count == 2 && Is(r[0], C4, 0, 2) && Is(r[1], C4, 1, 3), "overwrite: notes of the same selection keep overlapping");+ }+ { // fully inside a placed note → removed+ var (r, _) = Settle(new[] { N(C4, 1, 1.5), N(C4, 0, 4) }, 1);+ yield return (r.Count == 1 && Is(r[0], C4, 0, 4), "overwrite: a note inside a placed note is removed");+ }+ { // run into by two placed notes → cut at the earliest placed start+ var (r, _) = Settle(new[] { N(C4, 0, 8), N(C4, 4, 5), N(C4, 2, 3) }, 1, 2);+ yield return (r.Count == 3 && Is(r[0], C4, 0, 2), "overwrite: cut at the earliest placed note it runs into");+ }+ { // placed indices remap after removals+ var notes = new[] { N(C4, 1, 2), N(D4, 0, 1), N(C4, 0, 4), N(D4, 5, 6) };+ var (r, p) = Settle(notes, 2, 3);+ yield return (r.Count == 3 && p.Count == 2 && Is(r[p[0]], C4, 0, 4) && Is(r[p[1]], D4, 5, 6) && Is(r[0], D4, 0, 1),+ "overwrite: placed indices point at the same notes after removals");+ }+ { // a copy exactly on its original removes the original+ var (r, p) = Settle(new[] { N(C4, 0, 1), N(C4, 0, 1) }, 1);+ yield return (r.Count == 1 && p[0] == 0, "overwrite: a copy settled on its original replaces it");+ }+ { // ε: ending exactly at a placed start is kept+ var (r, _) = Settle(new[] { N(C4, 0, 1 + 1e-12), N(C4, 1, 2) }, 1);+ yield return (r.Count == 2 && Near(r[0].LengthBeats, 1 + 1e-12), "overwrite: a note ending where a placed note starts is kept");+ }+ { // a note starting where a placed note ends is kept+ var (r, _) = Settle(new[] { N(C4, 2, 3), N(C4, 1, 2) }, 1);+ yield return (r.Count == 2 && Is(r[0], C4, 2, 3), "overwrite: a note starting where a placed note ends is kept");+ }+ yield return (FateAgrees(new[] { N(C4, 0, 2), N(C4, 1, 2), N(D4, 0, 4), N(C4, 1.5, 1.75), N(C4, 3, 5), N(C4, 2.5, 3.5) }, 1, 5),+ "overwrite: Fate predicts Settle for every note");++ // ---- length step (Story 3) --------------------------------------------------------+ {+ var notes = new List<NotaNote> { N(C4, 0, 0.25), N(D4, 1, 2) };+ bool ch = NoteOverwrite.ResizeBy(notes, new[] { 0, 1 }, 0.25, 0.25, 8);+ yield return (ch && Is(notes[0], C4, 0, 0.5) && Is(notes[1], D4, 1, 2.25), "length: +step lengthens every note, starts kept");+ }+ {+ var notes = new List<NotaNote> { N(C4, 0, 0.25) };+ bool ch = NoteOverwrite.ResizeBy(notes, new[] { 0 }, -0.25, 0.25, 8);+ yield return (!ch && Is(notes[0], C4, 0, 0.25), "length: never shorter than the minimum");+ }+ {+ var notes = new List<NotaNote> { N(C4, 6, 8), N(D4, 0, 1) };+ bool ch = NoteOverwrite.ResizeBy(notes, new[] { 0, 1 }, 0.25, 0.25, 8);+ yield return (ch && Is(notes[0], C4, 6, 8) && Is(notes[1], D4, 0, 1.25), "length: a note at the clip end does not grow, others do");+ }+ {+ var notes = new List<NotaNote> { N(C4, 6, 8) };+ yield return (!NoteOverwrite.ResizeBy(notes, new[] { 0 }, 0.25, 0.25, 8), "length: no change reports false");+ }++ // ---- velocity step (Story 4) ------------------------------------------------------+ static int Midi(float v) => (int)Math.Round(v * 127);+ static bool OnStep(float v) => Math.Abs(v * 127 - Math.Round(v * 127)) < 1e-3;+ yield return (Midi(NoteOverwrite.VelocityBy(40 / 127f, 10)) == 50, "velocity: 40 + 10 = 50");+ yield return (Midi(NoteOverwrite.VelocityBy(125 / 127f, 10)) == 127, "velocity: clamps at 127");+ yield return (Midi(NoteOverwrite.VelocityBy(3 / 127f, -10)) == 1, "velocity: clamps at 1, never 0");+ var fine = NoteOverwrite.VelocityBy(0.8f, 1);+ yield return (Midi(fine) == (int)Math.Round(0.8 * 127) + 1 && OnStep(fine), "velocity: fine step lands on an integer MIDI value");+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 515a6e8c..e1b54059 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -231,6 +231,14 @@ if (args.Length >= 1 && args[0] == "--grid")Console.WriteLine(failures == 0 ? "GRID PASSED" : $"GRID FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Piano-roll note editing alone: `--notes`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--notes")+{+ Console.WriteLine("-- note editing --");+ foreach (var (ok, label) in NoteEditingTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "NOTES PASSED" : $"NOTES FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Default project template alone: `--template`. Also part of the full run.if (args.Length >= 1 && args[0] == "--template"){@@ -14570,6 +14578,9 @@ foreach (var (ok, label) in TapTempoTests.Run()) Check(ok, label);Console.WriteLine("-- snap grid --");foreach (var (ok, label) in SnapGridTests.Run()) Check(ok, label);+Console.WriteLine("-- note editing --");+foreach (var (ok, label) in NoteEditingTests.Run()) Check(ok, label);+Console.WriteLine("-- default project template --");foreach (var (ok, label) in ProjectTemplateTests.Run()) Check(ok, label);