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 Fold: only the scale's notes, or a Drum Rack's pads (#344 #345) (#356)
Chris Laupamabc8830b39bcd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 24c2e5cd..051996d6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,11 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Fold the piano roll** (nota-daw/nota#344, #345): **Fold** in the piano roll toolbar (⌥⇧F)+ shows only the scale's notes on a melodic track, or only the pads, each row named after its+ pad, on a Drum Rack. Pitches that hold notes keep their rows, so nothing is hidden. ↑/↓ and+ drags move between the visible rows, so notes stay in key. Each track remembers its Fold,+ and it's saved with the project. MCP `set_piano_fold` / `get_piano_fold`.- **Automation on return tracks**: in automation mode each return row in the arrangementfooter has a lane like a track's — pick Volume, Pan or a parameter of a device on thereturn's chain from its pill, then draw, drag, bend, select, copy and paste points. Thediff --git a/FEATURES.md b/FEATURES.mdindex e4af6e06..bd85ec3f 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -295,6 +295,10 @@ track count and closes with Escape.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.+ - **Fold** (⌥⇧F) hides the rows you don't use. On a melodic track it keeps the scale's+ notes, or the pitches in use when no scale is set. On a Drum Rack it keeps one row per pad,+ named after it. A pitch that holds a note always keeps its row, and ↑/↓ and drags move+ between the visible rows. Saved per track.- Zoomed out, the area past the clip's end is darkened and marked with a line.- **Vertical zoom**: rows from 6 to 36 px (all 88 keys fit at the smallest) with⌘⌥ + wheel (Ctrl + Alt on Windows / Linux), a drag on the keys (down taller, updiff --git a/specs/045-piano-roll-fold/checklists/requirements.md b/specs/045-piano-roll-fold/checklists/requirements.mdnew file mode 100644index 00000000..3bf85ae5--- /dev/null+++ b/specs/045-piano-roll-fold/checklists/requirements.md@@ -0,0 +1,37 @@+# Specification Quality Checklist: Piano roll Fold++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-28+**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-011 and FR-012 name the project's shortcut workflow and MCP tool names as assumptions only;+ the plan decides them.+- The three open choices (per-track memory, folding with no scale, milestone scope) were put to+ Chris with defaults in the milestone plan; the spec follows the defaults.diff --git a/specs/045-piano-roll-fold/contracts/abi-and-mcp.md b/specs/045-piano-roll-fold/contracts/abi-and-mcp.mdnew file mode 100644index 00000000..58b476ad--- /dev/null+++ b/specs/045-piano-roll-fold/contracts/abi-and-mcp.md@@ -0,0 +1,30 @@+# Contracts: Piano roll Fold++## C ABI (`include/nota/nota_engine.h`)++```c+/* Piano roll Fold (specs/045): a per-track view flag, saved with the project. Control+ thread only; never read by the audio thread. Returns 0 on success, -1 for an unknown track. */+NOTA_API int32_t nota_track_set_piano_fold(nota_engine* e, int32_t track_id, int32_t on);+/* 1 folded, 0 not, -1 unknown track. */+NOTA_API int32_t nota_track_get_piano_fold(nota_engine* e, int32_t track_id);+```++Managed: `IAudioEngine.SetTrackPianoFold(int trackId, bool on)` and `bool GetTrackPianoFold(int trackId)`.++## MCP (`Nota.Mcp`)++| Tool | Arguments | Result |+|---|---|---|+| `set_piano_fold` | `track_id`, `on` | none; an open piano roll picks it up when it next opens a clip on that track |+| `get_piano_fold` | `track_id` | `true` / `false` |++## Project file++Track object: optional `"PianoFold": true`. Absent means off. No format version change.++## UI++- The piano roll toolbar shows a **Fold** switch next to **Scale**, with the tooltip "Fold: show+ only the scale's notes (⌥⇧F)", or on a Drum Rack "Fold: show only the pads (⌥⇧F)".+- Shortcut: ⌥⇧F, or Alt+Shift+F on Windows and Linux.diff --git a/specs/045-piano-roll-fold/data-model.md b/specs/045-piano-roll-fold/data-model.mdnew file mode 100644index 00000000..ac7acc03--- /dev/null+++ b/specs/045-piano-roll-fold/data-model.md@@ -0,0 +1,41 @@+# Data model: Piano roll Fold++## Fold state (persisted)++| Where | Field | Type | Default | Notes |+|---|---|---|---|---|+| Engine track UI metadata | `pianoFold` | bool | false | Control thread only, like `colorIndex` |+| Project track (`ProjectModel`) | `PianoFold` | `bool?` | null = off | Written only when true; old projects load unfolded |++It is copied by track duplicate and track copy/paste. Undo snapshots carry it with the track, but+toggling Fold is not itself an undo step (FR-009).++## Row map (derived, never stored)++`PianoRowMap`:++| Member | Meaning |+|---|---|+| `Rows` | Visible pitches, top row first (highest pitch first) |+| `Count` | Number of rows |+| `RowOf(pitch)` | Row index, or −1 if the pitch is hidden |+| `PitchAt(row)` | Pitch of a row (clamped to the ends) |+| `Step(pitch, rows)` | The pitch `rows` visible rows above (+) or below (−); a hidden start pitch steps from the nearest row |+| `Label(row)` | Note name, or the pad name(s) on a Drum Rack |+| `Mark(row)` | `InSet`, `OutOfScale`, `NoPad` |+| `IsChromatic` | True when unfolded, or when folding found no rows (the hint is shown) |++Built by `PianoRowMap.Build(fold, kind, scaleMask?, root, pads?, usedPitches)`:++1. Not folded → chromatic A0..C8.+2. Drum Rack → the pads' notes ∪ used pitches; marked `NoPad` where there is no pad.+3. Melodic with a scale → in-scale pitches in range ∪ used pitches; marked `OutOfScale` where out+ of scale.+4. Melodic, no scale → used pitches.+5. Empty set → chromatic, `IsChromatic = true`.++## State transitions++`Unfolded ⇄ Folded` on the toolbar button, ⌥⇧F or MCP `set_piano_fold`. While folded, the map+is rebuilt on these events, never during a gesture (research R3): scale on/off/root/mode,+rack pads changed, notes committed, clip switched.diff --git a/specs/045-piano-roll-fold/plan.md b/specs/045-piano-roll-fold/plan.mdnew file mode 100644index 00000000..d23c6f3f--- /dev/null+++ b/specs/045-piano-roll-fold/plan.md@@ -0,0 +1,79 @@+# Implementation Plan: Piano roll Fold++**Branch**: `feat/piano-roll-fold` | **Date**: 2026-10-28 | **Spec**: [spec.md](spec.md)+**Input**: Feature specification from `/specs/045-piano-roll-fold/spec.md`++## Summary++One **Fold** switch in the piano roll toolbar. On a melodic track it hides out-of-scale rows; on a+Drum Rack track it shows one named row per pad. Rows that hold notes are never hidden. All vertical+layout goes through a new pure `PianoRowMap`, so folded and unfolded share one code path. Moves+step by visible rows. The flag is per track: engine track UI metadata (like the track colour),+saved as an optional project field, and exposed to MCP.++## Technical Context++**Language/Version**: C# / .NET 10 (app), C++20 (engine: one metadata field only)+**Primary Dependencies**: Avalonia (existing), no new dependency+**Storage**: Project track field `PianoFold` (optional; no format bump)+**Testing**: `tests/Nota.SmokeTest`, a new `FoldTests` (`--piano-fold`); macOS hands-on check+**Target Platform**: macOS, Windows, Linux desktop+**Project Type**: Desktop app over a native engine+**Performance Goals**: A fold of 2,000 notes rebuilds and redraws within 16 ms+**Constraints**: No audio-thread involvement; the flag is control-thread-only+**Scale/Scope**: `PianoRowMap` (new), `PianoRollView` (12 mapping sites, drag, transpose, keys+column), `ClipEditorView` toolbar, `DrumPatternView` pad scan (shared), engine/ABI/Managed/MCP+getters and setters, `ProjectService`, docs EN+RU++## Constitution Check++| Principle | Status |+|---|---|+| I. Real-time audio safety | Pass: the flag is never read on the audio thread; no graph change |+| II. Boundary discipline | Pass: two plain C functions on `nota_engine.h` |+| III. Licensing | Pass: new files carry the SPDX header; no dependency |+| IV. Verification gate | Pass: `FoldTests` added to the smoke run |+| V. One logical change | Pass: one feature (Fold for both modes, per #344/#345's one-button rule) |+| VI. Docs in sync | Plan: piano roll page EN+RU, shortcuts pane, FEATURES.md, CHANGELOG |+| VII. Spec first | This spec |+| VIII. Safety rules | Not touched |++Re-check after design: no change.++## Project Structure++### Documentation (this feature)++```text+specs/045-piano-roll-fold/+├── plan.md+├── research.md+├── data-model.md+├── quickstart.md+├── contracts/abi-and-mcp.md+└── tasks.md+```++### Source Code++```text+src/native/nota.engine/src/engine/Track.h pianoFold beside colorIndex+src/native/nota.engine/src/engine/Engine*.{h,cpp} set/get + clone paths copy it+include/nota/nota_engine.h, src/abi/nota_engine_track.cpp nota_track_set/get_piano_fold+src/managed/Nota.Application/Engine/IAudioEngine.cs SetTrackPianoFold / GetTrackPianoFold+src/managed/Nota.Infrastructure/... NativeMethods + NotaEngine wrappers+src/managed/Nota.Infrastructure/Persistence/ ProjectModel.PianoFold, Capture/Apply+src/managed/Nota.Presentation/PianoRowMap.cs new: the row map (pure)+src/managed/Nota.Presentation/DrumPads.cs new: pad scan shared with DrumPatternView+src/managed/Nota.App/PianoRollView*.cs map-driven layout, row-step moves+src/managed/Nota.App/ClipEditorView.cs Fold switch beside Scale+src/managed/Nota.Mcp/Tools/ set_piano_fold / get_piano_fold+tests/Nota.SmokeTest/FoldTests.cs new+```++**Structure Decision**: The map and the pad scan live in Nota.Presentation, so the smoke test+covers them without a window. The view only consumes the map.++## Complexity Tracking++None.diff --git a/specs/045-piano-roll-fold/quickstart.md b/specs/045-piano-roll-fold/quickstart.mdnew file mode 100644index 00000000..f8b2626d--- /dev/null+++ b/specs/045-piano-roll-fold/quickstart.md@@ -0,0 +1,12 @@+# Quickstart: checking Fold by hand++1. Add a Nota Volt track and a MIDI clip. In the piano roll, turn **Scale** on: A, Minor.+2. Press **Fold**. Only A B C D E F G rows remain. Draw notes; drag one up a row (E→F, F→G).+3. Draw an F♯ with Fold off, then fold again. The F♯ row stays, marked out of scale.+4. Press ↑ with notes selected: each note moves one row. Press ⇧↑: up an octave.+5. Add a Drum Rack kit (Kompakt). Open its clip and press **Fold**. There's one row per pad,+ named Kick, Snare and so on. Click a key: the pad sounds.+6. Rename a pad in the rack. The row label changes.+7. Open another clip on the drum track; it opens folded. Save, reopen: still folded. The Volt+ track opens as you left it.+8. Smoke: `CI=true dotnet tests/Nota.SmokeTest/bin/Release/net10.0/Nota.SmokeTest.dll --piano-fold`.diff --git a/specs/045-piano-roll-fold/research.md b/specs/045-piano-roll-fold/research.mdnew file mode 100644index 00000000..5285a0db--- /dev/null+++ b/specs/045-piano-roll-fold/research.md@@ -0,0 +1,81 @@+# Research: Piano roll Fold++## R1. One vertical mapping instead of `(MaxPitch - pitch) * RowH`++- **Decision**: A pure `PianoRowMap` (Nota.Presentation) owns the vertical layout: the ordered+ visible pitches (top row first), `RowOf(pitch)` (−1 when hidden), `PitchAt(row)`, `Count`, and+ `Step(pitch, rows)`. Unfolded it is the identity over A0..C8 (88 rows). Every site in+ `PianoRollView` that computes `(MaxPitch - p) * RowH` or its inverse (12 sites: keys column, grid,+ hover, held keys, audition, `EnsurePitchVisible`, initial scroll, `RangeH`) goes through it.+- **Rationale**: Folding is purely a layout change, so one mapping keeps folded and unfolded code+ identical. A pure type can be smoke-tested without Avalonia.+- **Alternatives**: Separate "folded" drawing paths, rejected as they double the code and drift. A+ hidden-row height of 0 in the existing layout was also rejected: hit-testing and scrolling+ still see 88 rows, and arrow keys would need special cases.++## R2. Drag and transpose step by rows, not semitones++- **Decision**: With Fold on, `MoveSelection(dPitch)` and the drag compute a **row delta**. Each+ note moves to `Step(pitch, dRows)`, so a group keeps its shape in scale degrees (a third stays+ a third in key). The shared delta is clamped so no note leaves the map. Octave moves+ (⇧↑/⇧↓) stay ±12 semitones: in a scale that's the same degree, and on drums it may land on a+ pitch without a pad, which then gets a marked row (FR-003).+- **Rationale**: This matches Ableton's folded editing, and it's what FR-004 asks: moves go+ between visible rows only.+- **Alternatives**: Semitone delta then snap to the nearest visible row, rejected because notes in+ a chord collapse onto the same row.++## R3. The map is frozen during a gesture++- **Decision**: The map is rebuilt only when a gesture isn't running: on pointer-up, on commit,+ and on scale, pad or notes-changed events. A note dragged off an out-of-scale row keeps that+ row until the drag ends.+- **Rationale**: Rebuilding mid-drag would remove the row under the pointer and make the+ layout jump.++## R4. Drum Rack detection and pad names++- **Decision**: Reuse `DrumPatternView.ScanPads()`, moved into a shared helper (`DrumPads.Scan`)+ that both views call. It returns each chain's trigger note and its name (the chain's name, or its+ instrument's name). Several pads on one note are joined: "Kick / Kick 2". A track is a+ Drum Rack track when `TrackInstrumentKind(trackId) == 4`, the same check as the Clip tab's+ **Pattern** button (`MainWindow.IsDrumRackTrack`).+- **Live updates**: The map is rebuilt from whatever change signal the window raises when a rack's+ chains change, renamed or reloaded (FR-006). Task T010 finds that signal. If there is none, the+ piano roll re-scans the pads when it repaints after a chain edit.++## R5. Where Fold is stored++- **Decision**: A per-track `pianoFold` flag in the engine's track UI metadata, next to+ `colorIndex`, exposed as `nota_track_set_piano_fold` / `nota_track_get_piano_fold`. It is+ saved as an optional `PianoFold` field on the track in the project (absent = off, so no+ format bump), copied by track duplicate and copy, and read by MCP `set_piano_fold` /+ `get_piano_fold`.+- **Rationale**: Track colour already lives there for the same reasons: it survives duplicate,+ undo snapshots and save, and MCP can reach it. It is control-thread-only data, never read on the+ audio thread (Principle I). Setting it publishes without an undo checkpoint (FR-009). An undo+ of an earlier edit restores that snapshot's flag, and the editor reads the flag again the+ next time it opens a clip on the track.+- **Alternatives**: A sidecar like `modular-layout.json` was rejected, because MCP can't reach it+ and track duplicate wouldn't copy it. A static per-session dictionary in the view was rejected+ because it isn't saved.++## R6. No scale and no notes++- **Decision**: On a melodic track, Fold uses the scale's pitches when a scale is on, and+ otherwise the clip's used pitches. When that set is empty (an empty clip and no scale, or a+ Drum Rack with no pads), the map stays chromatic and the grid shows the hint "Set a scale or+ add notes to fold". Drawing on a folded keyboard with no scale is limited to existing rows.++## R7. Shortcut++- **Decision**: ⌥⇧F (Alt+Shift+F on Windows and Linux) toggles Fold while the piano roll has+ focus. Plain letters are QWERTY note keys (F plays a note), ⇧F is already "fit to notes", and+ Alt+F opens the File menu on Windows. The shortcut is added through the `nota-shortcuts` skill.++## R8. Performance++- **Decision**: Building the map is O(88 + notes). It runs only on the events in R3, never per+ frame. The draw loops already walk visible rows. There's no engine or audio-thread change, so+ the perf gate isn't affected and no benchmark is needed (constitution: benchmarks only for+ perf-affecting work). SC-005 is checked by timing a 2,000-note fold in the smoke test.diff --git a/specs/045-piano-roll-fold/spec.md b/specs/045-piano-roll-fold/spec.mdnew file mode 100644index 00000000..b2fd78e1--- /dev/null+++ b/specs/045-piano-roll-fold/spec.md@@ -0,0 +1,184 @@+# Feature Specification: Piano roll Fold++**Feature Branch**: `feat/piano-roll-fold`++**Created**: 2026-10-28++**Status**: Draft++**Input**: User description: "Piano roll Fold (nota-daw/nota#344, #345): one Fold toggle in the+piano roll. On a melodic track with a scale on, it hides every out-of-scale row. On a Drum Rack+track, it shows only the pads, each row named after its pad. Notes on hidden pitches stay visible.+Drawing, dragging and arrow-key transposing move between visible rows only. Remembered per+track."++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Fold a melodic clip to its scale (Priority: P1)++A producer writes a bassline in A minor. With the scale on, out-of-scale rows are only dimmed, so+most of the keyboard is rows they never use. They press **Fold**. The keyboard now shows only the+scale's notes, stacked without gaps, and every note they draw or drag lands in key.++**Why this priority**: #344 is the request with the widest audience, since every melodic track can+use it. It also builds the row mapping that the Drum Rack mode reuses.++**Independent Test**: Turn on a scale, press Fold, and check that only in-scale rows are drawn.+Then check that a drawn note, a dragged note and an arrow-key transpose all land on in-scale+pitches.++**Acceptance Scenarios**:++1. **Given** a MIDI clip on an instrument track with the scale set to A minor, **When** the user+ presses Fold, **Then** the keyboard shows only A, B, C, D, E, F and G rows across the range,+ with no gaps, and the scroll position keeps the notes that were on screen in view.+2. **Given** Fold on, **When** the user drags a note up by one row, **Then** it moves to the next+ in-scale pitch (for example E to F, a semitone, and F to G, a whole tone).+3. **Given** Fold on, **When** the user presses ↑ with notes selected, **Then** each note moves to+ the next visible row. **When** they press ⇧↑, **Then** each moves up an octave (same scale+ degree).+4. **Given** a clip with an F♯ note and the scale set to A minor, **When** Fold is on, **Then** the+ F♯ row stays visible and is marked as out of scale, so no note is hidden.+5. **Given** Fold on, **When** the user turns the scale off or presses Fold again, **Then** the full+ chromatic keyboard comes back with the same notes in view.++---++### User Story 2 - Fold a Drum Rack clip to its pads (Priority: P1)++On a Drum Rack track, the piano roll shows a full keyboard (C1, C♯1, D1…), and the user has to+remember which note plays which pad. They press **Fold**. The keyboard shows one row per pad that+holds a sound, each named after its pad ("Kick", "Snare", "Hat closed"). Clicking a row's key plays+that pad.++**Why this priority**: #345 makes the piano roll usable for drums. It shares the button and the+row mapping with Story 1.++**Independent Test**: On a Drum Rack track with a kit loaded, press Fold. Check that the rows equal+the kit's pads, each named after its pad, and that clicking a key auditions it.++**Acceptance Scenarios**:++1. **Given** a Drum Rack track with a 16-pad kit, **When** the user presses Fold, **Then** the+ piano roll shows 16 rows, lowest note at the bottom, each key labelled with the pad's name.+2. **Given** Fold on, **When** the user clicks a row's key, **Then** that pad sounds, as with an+ unfolded key.+3. **Given** a clip with a note on a pitch that has no pad, **When** Fold is on, **Then** that+ pitch keeps an unnamed row (its note name, marked as empty), so the note stays visible.+4. **Given** Fold on, **When** the user renames a pad or drops a new sample on it, **Then** the row+ label updates without reopening the clip.+5. **Given** Fold on, **When** a pad is added to or removed from the rack, **Then** the rows follow+ the rack.++---++### User Story 3 - Fold is remembered (Priority: P2)++The user folds a drum track, edits, switches to another clip on the same track, and later reopens+the project. The drum track's clips open folded; a melodic track they never folded opens+unfolded.++**Why this priority**: Without memory, Fold has to be pressed again on every clip, which is the+friction #344 and #345 ask to remove. It's still usable without it, so it comes after the two+modes.++**Independent Test**: Fold one track, open another clip on that track, and check it opens folded.+Save, reopen, and check again. Check that a clip on another track opens unfolded.++**Acceptance Scenarios**:++1. **Given** Fold on for a track, **When** the user opens another clip on that track, **Then** it+ opens folded.+2. **Given** Fold on for a track, **When** the project is saved and reopened, **Then** that track's+ clips open folded.+3. **Given** a project saved before this feature, **When** it is opened, **Then** every track+ opens unfolded.++---++### Edge Cases++- **Fold with no scale on a melodic track**: Fold folds to the pitches the clip already uses (each+ row a used pitch). This is useful for editing a finished part and matches Ableton's Fold. A new+ note can still only be drawn on an existing row.+- **Fold on with an empty clip and no scale**: There are no rows to show. Fold shows the scale rows+ if a scale is on. Otherwise the button is available but folding shows the full keyboard with a+ hint ("Set a scale or add notes to fold"). [Assumption: the hint wording follows `nota-design`+ copy rules.]+- **Drum Rack with no pads**: same as an empty clip; the full keyboard stays with a hint.+- **Two pads on the same note**: one row, named "Kick / Kick 2" (both names), since one note+ triggers both.+- **Instrument Rack (not Drum Rack)**: treated as melodic (scale folding), as its chains share a+ key range rather than one note each.+- **A note dragged past the top or bottom visible row**: it stops at the last visible row, as an+ unfolded drag stops at the pitch range.+- **Velocity, expression and clip-strip lanes**: unaffected; they are drawn per note, not per row.+- **Selection rectangle and lasso**: select by visible rows; hidden pitches have no notes, so+ nothing hidden can be selected.+- **Scale changed while folded**: the rows re-fold to the new scale, keeping the view centred on+ the same notes.+- **MIDI recording while folded**: recorded notes land on their played pitch; an out-of-scale+ recorded pitch gets its own marked row, like any other out-of-scale note.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: The piano roll toolbar MUST have one **Fold** toggle, shown for every MIDI clip.+- **FR-002**: On a track whose instrument is a Drum Rack, Fold MUST show one row per note that+ has a pad, each labelled with the pad's name. On any other instrument track, Fold MUST show one+ row per in-scale pitch when a scale is on, and one row per used pitch when no scale is on.+- **FR-003**: With Fold on, every pitch that has a note in the clip MUST keep a row, even when it is+ out of scale or has no pad. Such rows MUST be marked (out of scale, or no pad) so they read+ differently from the folded set.+- **FR-004**: Drawing, moving, resizing-then-moving, pasting, and the arrow-key transpose (↑/↓ one+ row, ⇧↑/⇧↓ an octave) MUST move between visible rows only while Fold is on.+- **FR-005**: Clicking a key MUST audition that row's pitch, folded or not.+- **FR-006**: Folded rows MUST follow changes live: scale or key changed, pads renamed, added or+ removed, and notes added on a new pitch.+- **FR-007**: Turning Fold off MUST restore the full keyboard with the same notes in view.+- **FR-008**: The Fold state MUST be remembered per track and saved with the project. Projects+ saved before this feature MUST open unfolded, without a project format bump.+- **FR-009**: Undo MUST be unaffected by Fold itself. Toggling Fold is a view change, not an edit,+ and an edit made while folded undoes exactly as it would unfolded.+- **FR-010**: The note grid, playhead, loop markers and the time ruler MUST behave the same folded+ and unfolded; only the vertical layout changes.+- **FR-011**: Fold MUST be reachable from the keyboard. [Assumption: an unused shortcut is picked+ in the plan and added to the shortcuts pane through the `nota-shortcuts` workflow.]+- **FR-012**: The MCP server MUST be able to read and set a track's Fold state, as it can for other+ per-track view settings. [Assumption: `get_piano_fold` / `set_piano_fold`, or a field on an+ existing per-track tool.]++### Key Entities++- **Fold state**: on or off, one per track, stored with the project.+- **Row map**: the ordered list of visible pitches for the clip on screen, each with a label (note+ name or pad name) and a mark (in set, out of scale, no pad). It is derived from the scale, the+ rack's pads and the clip's notes, and is never stored.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: With a 7-note scale on the piano roll's 88-key range, Fold shows no more than 52 rows,+ plus one row per out-of-scale pitch used in the clip.+- **SC-002**: With a 16-pad kit, Fold shows exactly 16 rows, plus one per used pitch with no pad.+- **SC-003**: In a folded clip, 100% of notes drawn, dragged or arrow-transposed land on a visible+ row's pitch, which smoke tests check against the row map.+- **SC-004**: Toggling Fold or changing the scale while folded keeps every note that was on screen+ still on screen.+- **SC-005**: Folding a clip of 2,000 notes redraws in under one frame (16 ms) on the CI machines.++## Assumptions++- "Remembered per clip / per track" in #344 is read as **per track**, the reading Chris was given in+ the milestone plan. Every clip on a drum track opens folded.+- Fold with no scale folds to the used pitches (Ableton's behaviour), rather than greying out the+ button.+- The pad name is the rack chain's own name when it has one (a kit voice or a dropped sample),+ otherwise its instrument's name, as the Drum pattern view already shows.+- Only the piano roll folds. The Drum pattern view already shows pads, and the arrangement's clip+ previews stay as they are.+- No engine change is needed: the rows are a view mapping, and pad names and trigger notes are+ already exposed.+- The existing global scale setting (shared across clips) stays as it is; only Fold is per track.diff --git a/specs/045-piano-roll-fold/tasks.md b/specs/045-piano-roll-fold/tasks.mdnew file mode 100644index 00000000..58934d8f--- /dev/null+++ b/specs/045-piano-roll-fold/tasks.md@@ -0,0 +1,66 @@+# Tasks: Piano roll Fold++**Input**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/](contracts/)++Format: `[ID] [P?] [Story] Description`. [P] = can run in parallel (different files).++## Phase 1: Foundation (blocks every story)++- [ ] T001 [P] Add `PianoRowMap` (rows, `RowOf`, `PitchAt`, `Step`, labels, marks, `IsChromatic`,+ `Build`) in `src/managed/Nota.Presentation/PianoRowMap.cs`.+- [ ] T002 [P] Move the pad scan out of `DrumPatternView.ScanPads` into+ `src/managed/Nota.Presentation/DrumPads.cs` (joins pads on one note), and call it from+ `DrumPatternView`.+- [ ] T003 Route every vertical mapping in `PianoRollView.cs` through the map: `RangeH`, the keys+ column, the grid rows, hover, held keys, audition, `EnsurePitchVisible`, the initial scroll and+ `PitchAt`/`YToPitch`. Unfolded output must be pixel-identical to develop.+- [ ] T004 Smoke: `FoldTests` (`--fold`) checks that the chromatic map matches the old formula+ for every pitch and every y; register it in `Program.cs` with the full run.++## Phase 2: User Story 1, scale fold (P1)++- [ ] T005 [US1] `PianoRowMap.Build` scale case: in-scale pitches plus used pitches, marked+ `OutOfScale`; the no-scale case uses used pitches; an empty set is chromatic with the hint.+- [ ] T006 [US1] Drag (`DragUpdate` Move) and `MoveSelection` step by rows when folded (research+ R2); ⇧↑/⇧↓ stay ±12. Freeze the map during a gesture (R3).+- [ ] T007 [US1] New-note drawing and paste land on row pitches; the selection rectangle selects+ by rows.+- [ ] T008 [US1] Fold switch in the `ClipEditorView` toolbar beside Scale, with tooltip; keep+ the view centred on the same notes when toggling or when the scale changes (SC-004).+- [ ] T009 [US1] Smoke: A-minor map rows, E→F→G drag steps, a chord keeps its shape in degrees,+ out-of-scale used pitch keeps a marked row, toggle restores chromatic.++## Phase 3: User Story 2, Drum Rack fold (P1)++- [ ] T010 [US2] Drum Rack case in `Build` (pads plus used pitches, `NoPad` marks, joined names);+ find the window's rack-changed signal and rebuild the map on it (FR-006).+- [ ] T011 [US2] Keys column draws pad names when folded on a Drum Rack; a key click auditions the+ row pitch.+- [ ] T012 [US2] Smoke: a 16-pad kit gives 16 named rows, a note with no pad keeps an unnamed row,+ and renaming a pad changes its label.++## Phase 4: User Story 3, memory (P2)++- [ ] T013 [P] [US3] Engine `pianoFold` beside `colorIndex` in `Track.h`, set/get in the engine,+ copied by every track clone path (duplicate, copy/paste, freeze-linked clones).+- [ ] T014 [P] [US3] ABI `nota_track_set/get_piano_fold` in `nota_engine.h` and+ `nota_engine_track.cpp`; managed `NativeMethods`, `NotaEngine`, `IAudioEngine`.+- [ ] T015 [US3] `ProjectModel.PianoFold` (`bool?`, written only when true), Capture and Apply in+ `ProjectService`.+- [ ] T016 [US3] The piano roll reads the track's flag on clip open and writes it on toggle.+- [ ] T017 [P] [US3] MCP `set_piano_fold` / `get_piano_fold`.+- [ ] T018 [US3] Smoke: the flag survives save and load, an old project opens unfolded, duplicate+ copies it, and the MCP round trip works.++## Phase 5: Polish++- [ ] T019 Shortcut ⌥⇧F through the `nota-shortcuts` skill (shortcuts pane + docs).+- [ ] T020 SC-005 timing check: a 2,000-note fold builds in under 16 ms (smoke, CI only budget).+- [ ] T021 Docs EN+RU: piano roll page (Fold section with both modes), FEATURES.md, CHANGELOG.+- [ ] T022 macOS hands-on check with before/after screenshots (Volt in A minor, Kompakt kit) into+ `pr-assets/pr-<N>/`.++## Dependencies++T001–T004 block everything. US1 and US2 can run in parallel after T004. US3 (T013–T018) is+independent of US1 and US2 apart from T016. Polish comes last.diff --git a/src/managed/Nota.App/ClipEditorView.cs b/src/managed/Nota.App/ClipEditorView.csindex a0f5bb3b..76b4f5c4 100644--- a/src/managed/Nota.App/ClipEditorView.cs+++ b/src/managed/Nota.App/ClipEditorView.cs@@ -98,6 +98,7 @@ public sealed class ClipEditorView : UserControlOffset = Roll.Clips.EditorStart(Roll.Clips.Active),};if (_envMode) Roll.SetOverlay(_envOverlay);+ PaintFold(); // another track's clip may be folded differently}// Note audition (#46): the speaker chip. One app-wide setting, so every open editor's@@ -180,8 +181,24 @@ public sealed class ClipEditorView : UserControl_dropOutOfScale.VerticalAlignment = VerticalAlignment.Center;ToolTip.SetTip(_dropOutOfScale, "Delete every note outside the scale");Roll.Changed += () => _dropOutOfScale.IsEnabled = Roll.HasOutOfScaleNotes;+ Roll.FoldToggled += _ => PaintScale(); // ⌥⇧F flips it from the keyboard too+ Roll.FoldChanged += PaintFold; // …and the host switches it with the active clip's track+ // Fold (specs/045): the scale's rows, or a Drum Rack's pads, and nothing else.+ _fold = SwitchRow("Fold", () => Roll.Folded, () => { Roll.SetFold(!Roll.Folded, user: true); PaintScale(); }, out _syncFold);PaintScale();- return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { sw, key, mode, _dropOutOfScale } };+ return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { sw, key, mode, _fold, _dropOutOfScale } };+ }++ private Action _syncFold = () => { };+ private Control _fold = null!;++ private void PaintFold()+ {+ _syncFold();+ string what = Roll.FoldShowsPads ? "only the pads" : Roll.ScaleOn ? "only the scale's notes" : "only the notes in use";+ string tip = MenuKit.Keys($"Fold: show {what} (⌥⇧F)");+ if (Roll.FoldHasNothing) tip += Roll.FoldShowsPads ? "\nThe rack has no pads yet" : "\nSet a scale or add notes to fold";+ ToolTip.SetTip(_fold, tip);}private void PaintScale()@@ -193,6 +210,7 @@ public sealed class ClipEditorView : UserControl_keyText.Foreground = ink;_modeText.Foreground = ink;_dropOutOfScale.IsEnabled = Roll.HasOutOfScaleNotes;+ PaintFold();}// ---- envelope overlay: a wash over the notes, the curve, a target picker ----------diff --git a/src/managed/Nota.App/DrumPatternView.cs b/src/managed/Nota.App/DrumPatternView.csindex f10b5629..79ad0d1f 100644--- a/src/managed/Nota.App/DrumPatternView.cs+++ b/src/managed/Nota.App/DrumPatternView.cs@@ -126,23 +126,7 @@ public sealed class DrumPatternView : UserControl// ---- pads -------------------------------------------------------------private List<Pad> ScanPads()- {- var pads = new List<Pad>();- int n = _e.RackChainCount(TrackId);- for (int c = 0; c < n; c++)- {- int note = _e.RackChainTriggerNote(TrackId, c);- // Prefer the pad's own name (kit voice / dropped sample) — every Sampler pad- // reports the same instrument name, which makes the grid unreadable.- if (note >= 0)- {- string nm = _e.RackChainName(TrackId, c);- pads.Add(new Pad(c, note, nm.Length > 0 ? nm : _e.RackChainInstrumentName(TrackId, c)));- }- }- pads.Sort((x, y) => x.Note.CompareTo(y.Note)); // kick (lowest pad) on top, as on the pad grid- return pads;- }+ => Nota.Presentation.DrumPads.Scan(_e, TrackId).ConvertAll(p => new Pad(p.Chain, p.Note, p.Name)); // kick (lowest pad) on top, as on the pad gridprivate bool SamePads(List<Pad> pads){diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.csindex 976bd419..1d0a16a2 100644--- a/src/managed/Nota.App/MainWindow.Commands.cs+++ b/src/managed/Nota.App/MainWindow.Commands.cs@@ -130,6 +130,7 @@ public partial class MainWindowB("roll.octaveUp", () => _editorRoll?.TransposeBy(12), Roll);B("roll.octaveDown", () => _editorRoll?.TransposeBy(-12), Roll);B("roll.fitNotes", () => _editorRoll?.FitToNotes(), Roll);+ B("roll.fold", () => { if (_editorRoll is { } r) r.SetFold(!r.Folded, user: true); }, Roll);B("roll.editSelected", () => EditSelectedClips(),_ => Need(Timeline.SelectedMidiClips().Count >= 2, "Select two or more MIDI clips"));B("roll.removeOutOfScale", () => _editorRoll?.RemoveOutOfScaleNotes(),diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.csindex 80bff992..3371f634 100644--- a/src/managed/Nota.App/MainWindow.Detail.cs+++ b/src/managed/Nota.App/MainWindow.Detail.cs@@ -540,6 +540,7 @@ public partial class MainWindowroll.SetTrackColor(TrackBrush(set.ActiveClip.TrackId));if (!set.IsMulti) roll.SetClipIdentity(set.ActiveClip.TrackId, set.ActiveClip.ClipIndex);roll.SetClips(set, ClipNotesOf(set), TrackBrush);+ WireFold(roll, () => roll.ActiveClip.TrackId);_editorTrackId = set.ActiveClip.TrackId;_editorClipIndex = set.ActiveClip.ClipIndex;@@ -556,6 +557,37 @@ public partial class MainWindow};}+ // Fold (specs/045) follows the track: its pads on a Drum Rack, and the switch is saved on+ // the track, so every clip of a folded drum track opens folded.+ private void WireFold(PianoRollView roll, Func<int> track)+ {+ // The rows are laid out for one track at a time: the one whose Fold the editor shows.+ // It follows the active clip only when the switch lands, so a press that makes another+ // track's clip active doesn't re-read pads under the note it grabbed.+ int shown = track();+ roll.FoldPads = () => IsDrumRackTrack(shown)+ ? Nota.Presentation.DrumPads.ByNote(Nota.Presentation.DrumPads.Scan(Engine, shown)) : null;+ roll.FoldToggled += on => Engine.SetTrackPianoFold(shown, on);+ if (Engine.GetTrackPianoFold(shown))+ {+ roll.SetFold(true);+ roll.EnsureNotesVisible();+ }+ // A multi-clip editor's active clip can move to another track: take that track's+ // Fold, and its pads. Raised from inside a press on another track's note, before its+ // drag starts: switch once the press is handled, so the roll sees the drag and waits+ // for the release instead of moving the rows under the grabbed note.+ roll.ActiveClipChanged += () =>+ {+ if (track() == shown) return;+ Dispatcher.UIThread.Post(() =>+ {+ int t = track();+ if (t != shown) roll.SwitchFoldTrack(() => shown = t, Engine.GetTrackPianoFold(t));+ }, DispatcherPriority.Input);+ };+ }+// Every open clip's notes, as the engine holds them.private List<ClipNotes> ClipNotesOf(ClipSet set)=> set.Clips.Select(c => new ClipNotes(c.TrackId, c.ClipIndex, Engine.GetClipNotes(c.TrackId, c.ClipIndex))).ToList();@@ -914,6 +946,7 @@ public partial class MainWindowroll.SetTrackColor(TrackBrush(trackId));roll.SetClipIdentity(trackId, -(scene + 2)); // distinct key from arrangement clipsroll.SetNotes(Engine.GetSessionNotes(trackId, scene), slotLen > 0 ? slotLen : 4);+ WireFold(roll, () => trackId);_editorRoll = roll;_editorTrackId = -1; // session slot: recording-tick reload N/Adiff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 948c9dec..141ff74d 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -417,7 +417,7 @@ public partial class MainWindow : Window_deviceChain = new DeviceChainView(vm.Engine, _factory, App.Services.GetService<IPluginCatalog>(), _kits, App.Services.GetService<IMosaicPacks>());InitMosaic();// A pad added / removed / renamed in the Drum Rack card changes the pattern grid's rows.- _deviceChain.Changed += () => { Timeline.Refresh(); _patternView?.Reload(); SyncClipTab(); if (_modular?.IsVisible == true) _modular.Refresh(); };+ _deviceChain.Changed += () => { Timeline.Refresh(); _patternView?.Reload(); _editorRoll?.RefreshFold(); SyncClipTab(); if (_modular?.IsVisible == true) _modular.Refresh(); };_deviceChain.DevicesRemapped += Timeline.RemapAutoTargets;_deviceChain.PresetSaveRequested += OnSavePreset;_deviceChain.RackPresetSaveRequested += OnSaveRackChainPreset;diff --git a/src/managed/Nota.App/PianoRollView.Fold.cs b/src/managed/Nota.App/PianoRollView.Fold.csnew file mode 100644index 00000000..06f9c03e--- /dev/null+++ b/src/managed/Nota.App/PianoRollView.Fold.cs@@ -0,0 +1,230 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Fold (specs/045, #344 #345): one switch that folds the keyboard to the rows that matter —+// the scale's pitches on a melodic track, the pads on a Drum Rack — keeping every pitch a+// note sits on. The rows are a PianoRowMap; this part builds it and keeps it current. The+// map is never rebuilt mid-gesture, so a row under the pointer can't vanish during a drag.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia.Controls;+using Nota.Application.Midi;+using Nota.Presentation;++namespace Nota.App;++public sealed partial class PianoRollView+{+ private const double FoldedPadKeysW = 96; // room for "Hat closed" beside the rows+ private const double MaxPadRowH = 24; // a fitted kit's rows stop growing here++ private PianoRowMap _rows = PianoRowMap.Chromatic(MinPitch, MaxPitch);+ private bool _rowsArePads; // the rows are a Drum Rack's pads+ private bool _fold;+ private double? _rowHBeforePadFit; // the row height to go back to when unfolding+ private bool _padFit; // a kit's rows follow the editor's height (off once zoomed by hand)+ private readonly List<ColumnDefinition> _keyColumns = new();++ /// <summary>The host's pad scan for the clip's track: note → pad name on a Drum Rack+ /// track, null on any other track. Asked whenever the rows are rebuilt.</summary>+ public Func<IReadOnlyDictionary<int, string>?>? FoldPads { get; set; }++ /// <summary>Fires when the user toggles Fold, so the host stores it on the track.</summary>+ public event Action<bool>? FoldToggled;+ /// <summary>Fold changed, by the user or the host (another track's clip became active), so+ /// the toolbar switch can follow.</summary>+ public event Action? FoldChanged;++ public bool Folded => _fold;+ /// <summary>The rows the keyboard shows now (for the toolbar's tooltip and the smoke test).</summary>+ internal PianoRowMap Rows => _rows;+ /// <summary>Whether a folded keyboard shows a Drum Rack's pads (else scale rows).</summary>+ public bool FoldShowsPads => FoldPads?.Invoke() is not null;+ /// <summary>Folded but with nothing to fold to: the keyboard stays whole, with a hint.</summary>+ public bool FoldHasNothing => _fold && _rows.IsChromatic;++ /// <summary>Sets Fold; <paramref name="user"/> raises <see cref="FoldToggled"/>.</summary>+ public void SetFold(bool on, bool user = false)+ {+ // Not mid-drag: the grabbed notes' rows would change under the pointer (as row zoom).+ // A switch that arrives during one (another track's note grabbed in a multi-clip+ // editor) lands when the drag ends.+ if (_gridControl.Dragging) { if (!user) _foldAfterDrag = on; return; }+ _foldAfterDrag = null;+ if (on == _fold) return;+ _fold = on;+ RebuildRows(force: true);+ // A kit is a handful of rows: fit them to the editor (and keep them fitted as it+ // resizes, until the user zooms), and give the keyboard its own row height back on+ // unfolding.+ if (_rowsArePads)+ {+ _rowHBeforePadFit ??= _rowH;+ // A reopened editor takes the kit zoom saved with the clip; else the kit fits.+ if (!user && SavedPadRowH() is { } ph) UsePadRowH(ph);+ else+ {+ _padFit = true;+ if (_bodyScroll.Viewport.Height <= 0) FitPadsWhenLaidOut(); // a reopened editor+ else FitPads();+ }+ }+ else+ {+ _padFit = false;+ if (!on && _rowHBeforePadFit is { } h0)+ {+ _rowHBeforePadFit = null;+ SetRowHeightAt(h0, 0);+ }+ }+ if (user) FoldToggled?.Invoke(on);+ FoldChanged?.Invoke();+ }++ private bool? _foldAfterDrag;+ private (Action Adopt, bool On)? _trackAfterDrag;++ /// <summary>The rows are to follow another track (a multi-clip editor's active clip moved):+ /// <paramref name="adopt"/> makes the host's pads and Fold read that track, and+ /// <paramref name="on"/> is its Fold. Mid-drag this waits for the release.</summary>+ public void SwitchFoldTrack(Action adopt, bool on)+ {+ if (_gridControl.Dragging) { _trackAfterDrag = (adopt, on); return; }+ _trackAfterDrag = null;+ adopt();+ if (on != _fold) SetFold(on);+ else if (_fold)+ {+ // Kit to kit keeps a row zoom the user chose; rows that just became a kit fit it.+ bool wasPads = _rowsArePads;+ RebuildRows(force: true);+ if (_rowsArePads && (!wasPads || _padFit)) { _rowHBeforePadFit ??= _rowH; _padFit = true; FitPads(); }+ else if (wasPads && !_rowsArePads && _rowHBeforePadFit is { } h0)+ {+ // Kit to scale rows: the keyboard's own row height comes back, as on unfolding.+ _rowHBeforePadFit = null;+ _padFit = false;+ SetRowHeightAt(h0, 0);+ }+ FoldChanged?.Invoke();+ }+ else FoldChanged?.Invoke();+ }++ internal void ApplyDeferredFold()+ {+ if (_gridControl.Dragging) return;+ if (_trackAfterDrag is { } t) SwitchFoldTrack(t.Adopt, t.On);+ else if (_foldAfterDrag is { } on) SetFold(on);+ }++ // Fold restored before the editor has a height (a reopened project or clip): fit the kit+ // on the first layout that gives it one.+ private void FitPadsWhenLaidOut()+ {+ void Once(object? sender, EventArgs e)+ {+ double vh = _bodyScroll.Viewport.Height;+ if (vh <= 0) return;+ _bodyScroll.LayoutUpdated -= Once;+ if (_fold && _rowsArePads && _padFit) FitPads();+ }+ _bodyScroll.LayoutUpdated += Once;+ }++ // A kit row height the user zoomed to: kept, and no fitting from here on.+ private void UsePadRowH(double h)+ {+ _padFit = false;+ _rowH = Math.Clamp(h, MinRowH, MaxRowH);+ _keys.Height = RangeH;+ _gridControl.Height = RangeH;+ Invalidate();+ }++ private double? SavedPadRowH() =>+ _clipKey.Item1 != int.MinValue && s_view.TryGetValue(_clipKey, out var vs) ? vs.PadRowH : null;++ private void FitPads() => FitToNotes();++ /// <summary>The user zoomed the rows: a fitted kit stays at their height from now on.</summary>+ internal void PadRowsZoomed() => _padFit = false;++ // A fitted kit follows the editor's height, both ways (docked panel ↔ pop-out, a window+ // maximized or restored), until the user zooms rows.+ private void RefitPadsOnResize()+ {+ if (!_fold || !_rowsArePads || !_padFit || _gridControl.Dragging) return;+ FitPads();+ }++ // Another clip loaded with its saved (keyboard) row height: a folded kit keeps that as+ // the height to unfold to, and takes the kit zoom saved with the clip, or fits its pads.+ private void RefitPadsOnClipLoad(double? padRowH)+ {+ if (!_fold) return;+ if (!_rowsArePads) { _rowHBeforePadFit = null; _padFit = false; return; }+ _rowHBeforePadFit = _rowH;+ if (padRowH is { } ph) { UsePadRowH(ph); return; }+ _padFit = true;+ if (_bodyScroll.Viewport.Height <= 0) FitPadsWhenLaidOut();+ else FitPads();+ }++ /// <summary>The rack's pads may have changed (renamed, added, a new sample): re-read them.</summary>+ public void RefreshFold() { if (_fold) Invalidate(); }++ internal bool HasRow(int pitch) => _rows.RowOf(pitch) >= 0;+ internal double PitchY(int pitch) => _rows.NearestRow(pitch) * RowH;+ internal int PitchAtY(double y) => _rows.PitchAt((int)Math.Floor(y / RowH));++ /// <summary>Rebuilds the rows from the scale, the pads and the notes, keeping the row at+ /// the top of the view on screen. Skipped mid-gesture unless forced.</summary>+ private void RebuildRows(bool force = false)+ {+ if (!force && _gridControl.Dragging) return;+ PianoRowMap next;+ var pads = _fold ? FoldPads?.Invoke() : null;+ if (!_fold) next = PianoRowMap.Chromatic(MinPitch, MaxPitch);+ else next = PianoRowMap.Folded(MinPitch, MaxPitch, pads,+ pads is null && _scaleOn ? ScaleMasks[_scaleIndex] : null, _scaleRoot, UsedPitches());+ bool padRows = pads is not null && !next.IsChromatic;+ if (!force && SameRows(next) && padRows == _rowsArePads) { _rows = next; return; } // labels may change++ // Keep the pitch at the top of the view where it is.+ double rowH = RowH, top = _bodyScroll.Offset.Y;+ int anchor = _rows.PitchAt((int)Math.Floor(top / rowH));+ bool kitResized = !force && padRows && _rowsArePads && next.Count != _rows.Count;+ _rows = next;+ _rowsArePads = padRows;+ double keysW = padRows ? FoldedPadKeysW : KeysW;+ foreach (var c in _keyColumns) c.Width = new GridLength(keysW);+ _overlayHost.Margin = new Avalonia.Thickness(keysW, 0, 0, 0);+ _keys.Height = RangeH;+ _gridControl.Height = RangeH;+ _pendingCenter = false;+ _pendingVOffset = Math.Max(0, _rows.NearestRow(anchor) * rowH);+ ApplyPendingVOffset();+ // A fitted kit that gained or lost pads fits again (a zoom the user chose stays).+ if (kitResized && _padFit) FitPads();+ }++ // The pitches a folded keyboard keeps: every note's, and the keys held into a recording+ // take, which aren't notes until they are released.+ private List<int> UsedPitches()+ {+ var ps = _notes.Select(n => n.Pitch).ToList();+ if (_recPreview is { } rp) foreach (var h in rp.Held) ps.Add(h.Pitch);+ return ps;+ }++ private bool SameRows(PianoRowMap m)+ {+ if (m.Count != _rows.Count) return false;+ for (int r = 0; r < m.Count; r++) if (m.PitchAt(r) != _rows.PitchAt(r)) return false;+ return true;+ }+}diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex 799f2ddf..7a67b25e 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -12,6 +12,8 @@// the row height is per-clip view state like the horizontal zoom.// With note audition on (the clip editor's speaker chip, #46) a note sounds on the track's// instrument while it is placed, pressed or dragged; the keys column plays its keys (#47).+// Rows come from a PianoRowMap (specs/045 Fold): every pitch ↔ y goes through it, so a+// folded keyboard (scale rows, or a Drum Rack's pads) uses the same drawing and editing code.using System;using System.Collections.Generic;@@ -27,6 +29,7 @@ using Avalonia.Threading;using Nota.Application;using Nota.Application.Editing;using Nota.Application.Midi;+using Nota.Presentation;namespace Nota.App;@@ -111,6 +114,7 @@ public sealed partial class PianoRollView : UserControlif (preview is null && _recPreview is null) return;_recPreview = preview;_recClipStart = clipStart;+ if (_fold) RebuildRows(); // a held key on a pitch with no folded row gets one_gridControl.InvalidateVisual();}/// <summary>A note's recorded MPE by <see cref="NotaNote.ExprId"/>, drawn over the note.@@ -132,9 +136,11 @@ public sealed partial class PianoRollView : UserControlprivate DispatcherTimer? _heldTimer;// --- per-clip view persistence (scroll/zoom don't reset when you re-enter a clip) ------- private readonly record struct ViewState(double Ppb, double Scroll, double VOffset, bool HasV, double RowH);+ // RowH is the keyboard's row height; PadRowH a folded kit's, when zoomed by hand (null: fitted).+ private readonly record struct ViewState(double Ppb, double Scroll, double VOffset, bool HasV, double RowH, double? PadRowH = null);private static readonly Dictionary<(int, int), ViewState> s_view = new();private (int, int) _clipKey = (int.MinValue, int.MinValue);+ private (int, int) _loadedKey = (int.MinValue, int.MinValue); // the clip Load last showedprivate double? _pendingVOffset; // absolute vertical offset to apply once the body is laid outprivate bool _pendingCenter; // instead: centre on the clip's notes once laid outprivate bool _restoringView; // suppress view-saves while we programmatically restore@@ -372,7 +378,7 @@ public sealed partial class PianoRollView : UserControlprivate static readonly IBrush PressureShade = NotaPalette.Wash(NotaPalette.SurfaceAbyss, 0x66);private static readonly Typeface Mono = NotaFonts.Mono;- private double RangeH => (MaxPitch - MinPitch + 1) * RowH;+ private double RangeH => _rows.Count * RowH;public PianoRollView(){@@ -389,6 +395,7 @@ public sealed partial class PianoRollView : UserControl// Body: keys pinned left, grid fills; both scroll vertically together.// Top-aligned: zoomed out past the viewport, the 88 rows stay pinned to the top.var body = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*"), VerticalAlignment = VerticalAlignment.Top };+ _keyColumns.Add(body.ColumnDefinitions[0]);body.Children.Add(_keys);Avalonia.Controls.Grid.SetColumn(_gridControl, 1);body.Children.Add(_gridControl);@@ -402,6 +409,7 @@ public sealed partial class PianoRollView : UserControl// Ruler row (corner + ruler) pinned above; velocity row pinned below.var rulerRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*"), Height = RulerH };+ _keyColumns.Add(rulerRow.ColumnDefinitions[0]);var corner = new Border { Background = KeysBg, BorderBrush = Divider, BorderThickness = new Thickness(0, 0, 1, 1) };rulerRow.Children.Add(corner);Avalonia.Controls.Grid.SetColumn(_ruler, 1);@@ -409,12 +417,14 @@ public sealed partial class PianoRollView : UserControl// The clip strip (several clips open): corner + strip, under the ruler.var stripRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*") };+ _keyColumns.Add(stripRow.ColumnDefinitions[0]);stripRow.Children.Add(new Border { Background = KeysBg, BorderBrush = Divider, BorderThickness = new Thickness(0, 0, 1, 1) });Avalonia.Controls.Grid.SetColumn(_strip, 1);stripRow.Children.Add(_strip);stripRow.Bind(IsVisibleProperty, _strip.GetObservable(IsVisibleProperty));var velRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*"), Height = VelH };+ _keyColumns.Add(velRow.ColumnDefinitions[0]);_laneRow = velRow;// The lane's gutter picks what it edits: velocity, or a recorded-MPE dimension.var velLabelHost = new Border { Background = KeysBg, BorderBrush = Divider, BorderThickness = new Thickness(0, 1, 1, 0) };@@ -426,6 +436,7 @@ public sealed partial class PianoRollView : UserControl// Horizontal zoom scrollbar pinned below the velocity lane, aligned under the// grid (56px keys gutter on the left).var scrollRow = new Grid { ColumnDefinitions = new ColumnDefinitions($"{KeysW},*") };+ _keyColumns.Add(scrollRow.ColumnDefinitions[0]);_hScroll = new ScrollBar { Orientation = Orientation.Horizontal, Height = 10, IsVisible = false, Minimum = 0 };_hScroll.Scroll += (_, _) => SetScrollBeats(_hScroll.Value);Avalonia.Controls.Grid.SetColumn(_hScroll, 1);@@ -450,6 +461,7 @@ public sealed partial class PianoRollView : UserControl// Persist vertical scroll per clip; apply a pending restore once the body is laid out._bodyScroll.ScrollChanged += (_, _) => { if (!_restoringView) SaveView(); };_bodyScroll.LayoutUpdated += (_, _) => ApplyPendingVOffset();+ _bodyScroll.SizeChanged += (_, e) => { if (e.HeightChanged) RefitPadsOnResize(); };// Poll the pressed key(s) ~40 Hz while the editor is on screen.AttachedToVisualTree += (_, _) =>@@ -486,7 +498,9 @@ public sealed partial class PianoRollView : UserControlprivate void SaveView(){if (_clipKey.Item1 == int.MinValue || _pixelsPerBeat <= 0) return;- s_view[_clipKey] = new ViewState(_pixelsPerBeat, _scrollBeats, _bodyScroll.Offset.Y, true, _rowH);+ // A fitted kit's height is refit on reopening; keep the keyboard's own for unfolding.+ double? padRowH = _fold && _rowsArePads && !_padFit ? _rowH : null;+ s_view[_clipKey] = new ViewState(_pixelsPerBeat, _scrollBeats, _bodyScroll.Offset.Y, true, _rowHBeforePadFit ?? _rowH, padRowH);}private void ApplyPendingVOffset()@@ -513,6 +527,7 @@ public sealed partial class PianoRollView : UserControlif (_gridControl.Dragging) return;double h0 = _rowH, h1 = Math.Clamp(h, MinRowH, MaxRowH);if (Math.Abs(h1 - h0) < 1e-9) return;+ PadRowsZoomed(); // a fitted kit keeps the height the user chose (a clamped no-op doesn't count)double c = (_pendingVOffset ?? _bodyScroll.Offset.Y) + viewportY;_rowH = h1;_keys.Height = RangeH;@@ -532,17 +547,19 @@ public sealed partial class PianoRollView : UserControl=> (m & (KeyModifiers.Control | KeyModifiers.Meta)) != 0 && (m & KeyModifiers.Alt) != 0;/// <summary>Fit to notes (⇧F): every note of the clip in view, one row of margin above- /// and below, centred; an empty clip goes back to the default height around C5.</summary>+ /// and below, centred; an empty clip goes back to the default height around C5. Folded to a+ /// Drum Rack's pads, it fits every pad row instead, so the kit fills the editor.</summary>public void FitToNotes(){if (_gridControl.Dragging) return;double vh = _bodyScroll.Viewport.Height;double h = DefaultRowH;- if (_notes.Count > 0 && vh > 0)+ if (_rowsArePads && vh > 0) h = Math.Min(MaxPadRowH, vh / _rows.Count);+ else if (_notes.Count > 0 && vh > 0){int minP = int.MaxValue, maxP = int.MinValue;foreach (var n in _notes) { if (n.Pitch < minP) minP = n.Pitch; if (n.Pitch > maxP) maxP = n.Pitch; }- h = vh / (maxP - minP + 1 + 2);+ h = vh / (_rows.NearestRow(minP) - _rows.NearestRow(maxP) + 1 + 2);}_rowH = Math.Clamp(h, MinRowH, MaxRowH);_keys.Height = RangeH;@@ -711,7 +728,12 @@ public sealed partial class PianoRollView : UserControl// length horizontally and centre vertically on the clip's own notes at the default// row height. Row heights are per clip: zooming one never changes another.bool saved = s_view.TryGetValue(_clipKey, out var vs) && vs.HasV;- _rowH = saved ? Math.Clamp(vs.RowH, MinRowH, MaxRowH) : DefaultRowH;+ // The same clip reloaded (undo, a recording pass): a folded kit keeps the rows it has,+ // fitted or zoomed by hand. The saved height is the keyboard's, for unfolding.+ bool reload = _clipKey.Item1 != int.MinValue && _clipKey == _loadedKey;+ _loadedKey = _clipKey;+ bool keepKitRows = reload && _fold && _rowsArePads;+ if (!keepKitRows) _rowH = saved ? Math.Clamp(vs.RowH, MinRowH, MaxRowH) : DefaultRowH;_keys.Height = RangeH;_gridControl.Height = RangeH;if (saved)@@ -727,6 +749,7 @@ public sealed partial class PianoRollView : UserControl_pendingVOffset = null; _pendingCenter = true;}Invalidate();+ if (!keepKitRows) RefitPadsOnClipLoad(saved ? vs.PadRowH : null); // another clip: a folded kit fits (or takes its zoom) againChanged?.Invoke();ApplyPendingVOffset(); // apply now if laid out; LayoutUpdated retries otherwise}@@ -740,10 +763,10 @@ public sealed partial class PianoRollView : UserControl{int minP = int.MaxValue, maxP = int.MinValue;foreach (var n in _notes) { if (n.Pitch < minP) minP = n.Pitch; if (n.Pitch > maxP) maxP = n.Pitch; }- double mid = (minP + maxP) * 0.5;- return Math.Max(0, (MaxPitch - mid) * RowH - vh * 0.5);+ double mid = (_rows.NearestRow(minP) + _rows.NearestRow(maxP) + 1) * 0.5;+ return Math.Max(0, mid * RowH - vh * 0.5);}- return Math.Max(0, (MaxPitch - 72) * RowH); // C5 near the top+ return Math.Max(0, _rows.NearestRow(72) * RowH); // C5 near the top}public string SelectionInfo@@ -945,7 +968,7 @@ public sealed partial class PianoRollView : UserControldouble top = _bodyScroll.Offset.Y, bottom = top + vh;foreach (var n in _notes){- double y = (MaxPitch - n.Pitch) * RowH;+ double y = PitchY(n.Pitch);if (y >= top && y + RowH <= bottom) return;}_pendingVOffset = CenterOffsetForNotes();@@ -1171,10 +1194,11 @@ public sealed partial class PianoRollView : UserControlreturn (Math.Min(lo, 0), Math.Max(hi, 0));}- /// <summary>Nudges the selection by dPitch semitones and/or dBeat beats, clamped to the- /// pitch range and clip bounds (moves as a block, stopping at the edge). A note whose start- /// crosses into a neighbouring open clip of its track moves into that clip. Undoable.- /// Scrolls vertically to keep pitch-moved notes in view.</summary>+ /// <summary>Nudges the selection by dPitch and/or dBeat beats, clamped to the pitch range+ /// and clip bounds (moves as a block, stopping at the edge). ±12 is an octave in semitones;+ /// any other dPitch counts rows, which is semitones unfolded and the next visible row when+ /// folded (specs/045). A note whose start crosses into a neighbouring open clip of its+ /// track moves into that clip. Undoable. Scrolls vertically to keep pitch-moved notes in view.</summary>public bool MoveSelection(int dPitch, double dBeat){var sel = _selection.Where(i => i >= 0 && i < _notes.Count).ToList();@@ -1187,21 +1211,41 @@ public sealed partial class PianoRollView : UserControl}var (lo, hi) = ShiftRange(sel, i => (_notes[i].StartBeat, _notes[i].LengthBeats, _owner[i]), endsInside: true);double db = Math.Clamp(dBeat, lo, hi);+ bool octave = Math.Abs(dPitch) == 12;int dp = dPitch;- if (minP + dp < MinPitch) dp = MinPitch - minP;- if (maxP + dp > MaxPitch) dp = MaxPitch - maxP;+ if (octave)+ {+ if (minP + dp < MinPitch) dp = MinPitch - minP;+ if (maxP + dp > MaxPitch) dp = MaxPitch - maxP;+ }+ else dp = ClampRows(sel.Select(i => _notes[i].Pitch), dp);if (Math.Abs(db) < 1e-9 && dp == 0) return false;+ int edge = -1;foreach (int i in sel){- var n = _notes[i]; n.StartBeat += db; n.Pitch += dp; _notes[i] = n;+ var n = _notes[i]; n.StartBeat += db; n.Pitch = octave ? n.Pitch + dp : _rows.Step(n.Pitch, dp); _notes[i] = n;_owner[i] = _set.OwnerAfterMove(_owner[i], n.StartBeat);+ if (edge < 0 || (dp > 0 ? n.Pitch > edge : n.Pitch < edge)) edge = n.Pitch;}_placementPending = true;Invalidate(); CommitNotes(); Changed?.Invoke();- if (dp != 0) EnsurePitchVisible(dp > 0 ? maxP + dp : minP + dp);+ if (dp != 0) EnsurePitchVisible(edge);return true;}+ /// <summary>A row delta clamped so every one of <paramref name="pitches"/> stays on the map:+ /// the group moves as a block and keeps its shape (in scale degrees when folded).</summary>+ internal int ClampRows(IEnumerable<int> pitches, int rows)+ {+ int lo = int.MinValue, hi = int.MaxValue;+ foreach (int p in pitches)+ {+ var (down, up) = _rows.Reach(p);+ lo = Math.Max(lo, down); hi = Math.Min(hi, up);+ }+ return lo > hi ? 0 : Math.Clamp(rows, lo, hi);+ }+/// <summary>Lengthens (dir +1) or shortens (dir −1) every selected note by one grid step,/// keeping starts; never below the minimum length or past its clip's end. Undoable.</summary>public bool ResizeSelection(int dir)@@ -1285,7 +1329,7 @@ public sealed partial class PianoRollView : UserControlvar sv = _bodyScroll;double viewH = sv.Viewport.Height;if (viewH <= 0) return;- double y = (MaxPitch - pitch) * RowH, top = sv.Offset.Y, margin = RowH;+ double y = PitchY(pitch), top = sv.Offset.Y, margin = RowH;if (y < top + margin) sv.Offset = new Vector(sv.Offset.X, Math.Max(0, y - margin));else if (y + RowH > top + viewH - margin) sv.Offset = new Vector(sv.Offset.X, y + RowH - viewH + margin);}@@ -1361,6 +1405,7 @@ public sealed partial class PianoRollView : UserControlprivate void Invalidate(){+ if (_fold) RebuildRows(); // notes, scale or pads may have moved the folded rows_overlayHost.Child?.InvalidateVisual();_ruler.InvalidateVisual();_strip.InvalidateVisual();@@ -1615,7 +1660,7 @@ public sealed partial class PianoRollView : UserControlprivate Press _press;private double _pressY, _pressRowH;- private int PitchAt(double y) => (int)Math.Clamp(MaxPitch - Math.Floor(y / RowH), MinPitch, MaxPitch);+ private int PitchAt(double y) => _o.PitchAtY(y);private const float KeyVelocity = 0.8f;protected override void OnPointerPressed(PointerPressedEventArgs e)@@ -1690,46 +1735,62 @@ public sealed partial class PianoRollView : UserControl{double w = Bounds.Width;ctx.FillRectangle(KeysBg, new Rect(0, 0, w, Bounds.Height));- for (int p = MinPitch; p <= MaxPitch; p++)+ var rows = _o._rows;+ // Folded, every row is labelled (there are few, and they aren't a keyboard any more).+ bool labelAll = !rows.IsChromatic;+ for (int r = 0; r < rows.Count; r++){- double y = (MaxPitch - p) * RowH;- ctx.FillRectangle(IsBlack(p) ? KeyBlack : KeyWhite, new Rect(0, y, w, RowH));- if (_o._scaleOn)+ int p = rows.PitchAt(r);+ double y = r * RowH;+ ctx.FillRectangle(IsBlack(p) && rows.IsChromatic ? KeyBlack : KeyWhite, new Rect(0, y, w, RowH));+ if (rows.Mark(r) == PianoRowMark.NoPad) ctx.FillRectangle(OutScaleWash, new Rect(0, y, w, RowH));+ else if (_o._scaleOn && !_o._rowsArePads){if (_o.IsRoot(p)) ctx.FillRectangle(RootTint, new Rect(0, y, w, RowH));else if (!_o.InScale(p)) ctx.FillRectangle(OutScaleWash, new Rect(0, y, w, RowH));}- ctx.DrawLine(p % 12 == 0 ? KeyOctaveLine : KeyLine, new Point(0, y + RowH - 0.5), new Point(w, y + RowH - 0.5));- if (p % 12 == 0) DrawKeyLabel(ctx, p, y, w, KeyLabel);+ bool octave = rows.IsChromatic ? p % 12 == 0 : r == rows.Count - 1 || rows.PitchAt(r + 1) / 12 != p / 12;+ ctx.DrawLine(octave ? KeyOctaveLine : KeyLine, new Point(0, y + RowH - 0.5), new Point(w, y + RowH - 0.5));+ if (labelAll || p % 12 == 0) DrawKeyLabel(ctx, p, y, w, KeyLabel);}// Currently-pressed keys (computer keyboard / MIDI): light the key solid + label it.if (_o._held.Count > 0)foreach (int hp in _o._held){- if (hp < MinPitch || hp > MaxPitch) continue;- double y = (MaxPitch - hp) * RowH;+ if (!_o.HasRow(hp)) continue;+ double y = _o.PitchY(hp);ctx.FillRectangle(HeldKeyFill, new Rect(0, y, w, RowH - 1));DrawKeyLabel(ctx, hp, y, w, KeyLabelOnAccent);}// The key the roll itself is sounding (a pressed key, an auditioned note).- if (_o._auditionPitch >= MinPitch && !_o._held.Contains(_o._auditionPitch))+ if (_o._auditionPitch >= MinPitch && !_o._held.Contains(_o._auditionPitch) && _o.HasRow(_o._auditionPitch)){- double y = (MaxPitch - _o._auditionPitch) * RowH;+ double y = _o.PitchY(_o._auditionPitch);ctx.FillRectangle(HeldKeyFill, new Rect(0, y, w, RowH - 1));DrawKeyLabel(ctx, _o._auditionPitch, y, w, KeyLabelOnAccent);}// Hovered key: highlight it and label its note name (works for black keys too,// where the octave-C label wouldn't otherwise show).- if (_hover >= MinPitch && _hover != _o._auditionPitch)+ if (_hover >= MinPitch && _hover != _o._auditionPitch && _o.HasRow(_hover)){- double hy = (MaxPitch - _hover) * RowH;+ double hy = _o.PitchY(_hover);ctx.FillRectangle(KeyHover, new Rect(0, hy, w, RowH - 1));DrawKeyLabel(ctx, _hover, hy, w, KeyLabelHot);}}+ // The note name, right-aligned; on a folded Drum Rack the pad's name instead, left-aligned+ // and cut to the column.private void DrawKeyLabel(DrawingContext ctx, int pitch, double y, double w, IBrush ink){+ string? pad = _o._rows.Label(_o._rows.NearestRow(pitch));+ if (pad is not null)+ {+ var name = new FormattedText(pad, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, ink)+ { MaxTextWidth = Math.Max(1, w - 8), MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis };+ ctx.DrawText(name, new Point(4, y + (RowH - name.Height) / 2));+ return;+ }var ft = new FormattedText(NoteName(pitch), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, ink);ctx.DrawText(ft, new Point(w - ft.Width - 5, y + (RowH - ft.Height) / 2));}@@ -1802,8 +1863,8 @@ public sealed partial class PianoRollView : UserControlprivate double BeatToX(double b) => _o.BeatToX(b);private double XToBeat(double x) => _o.XToBeat(x);private double RowH => _o.RowH;- private double PitchToY(int p) => (MaxPitch - p) * RowH;- private int YToPitch(double y) => (int)Math.Clamp(MaxPitch - Math.Floor(y / RowH), MinPitch, MaxPitch);+ private double PitchToY(int p) => _o.PitchY(p);+ private int YToPitch(double y) => _o.PitchAtY(y);// Alt held during the gesture positions freely, as in the arrangement (FR-009).private bool _free;private double Snap(double b) => _free ? b : _o.SnapBeat(b);@@ -1814,22 +1875,26 @@ public sealed partial class PianoRollView : UserControlif (w <= 0) return;_o.EnsurePpb(w);ctx.FillRectangle(Bg, new Rect(0, 0, w, h));- for (int p = MinPitch; p <= MaxPitch; p++)+ var rows = _o._rows;+ for (int r = 0; r < rows.Count; r++){- double y = PitchToY(p);- ctx.FillRectangle(IsBlack(p) ? LaneBlack : LaneWhite, new Rect(0, y, w, RowH));- if (_o._scaleOn)+ int p = rows.PitchAt(r);+ double y = r * RowH;+ ctx.FillRectangle(IsBlack(p) && rows.IsChromatic ? LaneBlack : LaneWhite, new Rect(0, y, w, RowH));+ if (rows.Mark(r) == PianoRowMark.NoPad) ctx.FillRectangle(OutScaleWash, new Rect(0, y, w, RowH));+ else if (_o._scaleOn && !_o._rowsArePads){if (_o.IsRoot(p)) ctx.FillRectangle(RootTint, new Rect(0, y, w, RowH));else if (_o.InScale(p)) ctx.FillRectangle(InScaleTint, new Rect(0, y, w, RowH));else ctx.FillRectangle(OutScaleWash, new Rect(0, y, w, RowH));}- ctx.DrawLine(p % 12 == 0 ? RowOctaveLine : RowLine, new Point(0, y + RowH - 0.5), new Point(w, y + RowH - 0.5));+ bool octave = rows.IsChromatic ? p % 12 == 0 : r == rows.Count - 1 || rows.PitchAt(r + 1) / 12 != p / 12;+ ctx.DrawLine(octave ? RowOctaveLine : RowLine, new Point(0, y + RowH - 0.5), new Point(w, y + RowH - 0.5));}// Played-key rows: a faint wash across the grid so you see where the pressed note sits.if (_o._held.Count > 0)foreach (int hp in _o._held)- if (hp >= MinPitch && hp <= MaxPitch)+ if (_o.HasRow(hp))ctx.FillRectangle(HeldRowTint, new Rect(0, PitchToY(hp), w, RowH));double ppb = Ppb;_o.DrawGridLines(ctx, w, h);@@ -1840,7 +1905,7 @@ public sealed partial class PianoRollView : UserControlfor (int i = 0; i < notes.Count; i++){var n = notes[i];- if (n.Pitch < MinPitch || n.Pitch > MaxPitch) continue;+ if (!_o.HasRow(n.Pitch)) continue;if (multi && (_o._owner[i] == _o._set.Active) != (pass == 1)) continue;double x = BeatToX(n.StartBeat), y = PitchToY(n.Pitch);double nw = Math.Max(3, n.LengthBeats * ppb);@@ -1900,7 +1965,7 @@ public sealed partial class PianoRollView : UserControlif (_o._recPreview is { } rp)foreach (var hn in rp.Held){- if (hn.Pitch < MinPitch || hn.Pitch > MaxPitch) continue;+ if (!_o.HasRow(hn.Pitch)) continue;double s = hn.StartBeat - _o._recClipStart, e = Math.Max(hn.StartBeat, rp.NowBeat) - _o._recClipStart;double hx = BeatToX(s), hw = Math.Max(3, (e - s) * ppb);if (hx + hw < 0 || hx > w) continue;@@ -1990,7 +2055,7 @@ public sealed partial class PianoRollView : UserControlfor (int i = notes.Count - 1; i >= 0; i--){var n = notes[i];- if (n.Pitch < MinPitch || n.Pitch > MaxPitch || _o.IsLocked(i)) continue;+ if (!_o.HasRow(n.Pitch) || _o.IsLocked(i)) continue;double x = BeatToX(n.StartBeat), y = PitchToY(n.Pitch), nw = Math.Max(3, n.LengthBeats * Ppb);if (!new Rect(x, y, nw, RowH).Contains(p)) continue;if (_o._owner[i] != _o._set.Active)@@ -2119,19 +2184,18 @@ public sealed partial class PianoRollView : UserControldouble targetStart = Snap(XToBeat(p.X) - _grabBeat);var pr = _orig[_primary];double dBeat = targetStart - pr.start;- int dPitch = YToPitch(p.Y) - pr.pitch;+ // Rows, not semitones: folded, the group moves between visible rows (specs/045).+ int dRows = _o._rows.NearestRow(pr.pitch) - (int)Math.Floor(p.Y / RowH);// Clamp the shared delta so the whole group stays in-bounds (keeps shape): every// start within its reach — its clip and the open clips of its track it touches.- int minP = int.MaxValue, maxP = int.MinValue;- foreach (var v in _orig.Values) { minP = Math.Min(minP, v.pitch); maxP = Math.Max(maxP, v.pitch); }var (lo, hi) = _o.ShiftRange(_orig.Keys, i => (_orig[i].start, _orig[i].len, _orig[i].owner), endsInside: false);dBeat = Math.Clamp(dBeat, lo, hi);- dPitch = Math.Clamp(dPitch, MinPitch - minP, MaxPitch - maxP);+ dRows = _o.ClampRows(_orig.Values.Select(v => v.pitch), dRows);foreach (var kv in _orig){var n = _o._notes[kv.Key];n.StartBeat = kv.Value.start + dBeat;- n.Pitch = kv.Value.pitch + dPitch;+ n.Pitch = _o._rows.Step(kv.Value.pitch, dRows);_o._notes[kv.Key] = n;_o._owner[kv.Key] = _o._set.OwnerAfterMove(kv.Value.owner, n.StartBeat);}@@ -2242,6 +2306,7 @@ public sealed partial class PianoRollView : UserControlvar was = _drag;_drag = Mode.None;e.Pointer.Capture(null);+ Avalonia.Threading.Dispatcher.UIThread.Post(_o.ApplyDeferredFold); // after the edit landsif (was is Mode.PlayheadPending or Mode.Scrub){// A click without movement on the line: what an empty-space click does — clear the selection.@@ -2338,6 +2403,7 @@ public sealed partial class PianoRollView : UserControl// ⇧F: Fit to notes. Handled here, the window's computer-keyboard note map never// sees it, so no F sounds.if (e.Key == Key.F && e.KeyModifiers == KeyModifiers.Shift) { _o.FitToNotes(); e.Handled = true; return; }+ if (e.Key == Key.F && e.KeyModifiers == (KeyModifiers.Shift | KeyModifiers.Alt)) { _o.SetFold(!_o.Folded, user: true); e.Handled = true; return; } // Fold (specs/045)if (!meta && e.Key == Key.Escape && _o._selection.Count > 0){_o.SettlePlacement();diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 3c7e539f..823ddb20 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1271,6 +1271,7 @@ public sealed partial class PreferencesWindow : NotaWindow("Drag on the keys", "Zoom rows · down taller, up shorter"),("⌥ + pinch", "Zoom rows (trackpad)"),("⇧F", "Fit to notes"),+ ("⌥⇧F", "Fold: only the scale's notes, or a Drum Rack's pads"),}),("Audio clip editor", new[]{diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 802ae4ff..28665a6e 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -317,6 +317,9 @@ public interface IAudioEngine : IDisposable/// <summary>Sets/gets a track's palette colour slot (-1 = auto by position).</summary>void SetTrackColorIndex(int trackId, int colorIndex);int GetTrackColorIndex(int trackId);+ /// <summary>Sets/gets a track's piano roll Fold (specs/045): a view flag saved with the project.</summary>+ void SetTrackPianoFold(int trackId, bool on);+ bool GetTrackPianoFold(int trackId);/// <summary>Copies a whole track to the clipboard; pastes it as a new track (-1 on fail).</summary>bool CopyTrack(int trackId);int PasteTrack();diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.csindex 8249fd51..1c0edade 100644--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs@@ -99,6 +99,7 @@ public static class CommandCatalogC("roll.octaveDown", "Transpose notes down an octave", "Piano roll", "", "pitch shift"),C("roll.removeOutOfScale", "Remove out-of-scale notes", "Piano roll", "", "key fix"),C("roll.fitNotes", "Fit to notes", "Piano roll", Shortcut.Shift('F'), "zoom vertical rows height"),+ C("roll.fold", "Fold the piano roll", "Piano roll", Shortcut.Alt('F').WithShift(), "fold scale rows drum pads names hide keys"),C("roll.editSelected", "Edit selected clips together", "Piano roll", "", "multi clip several open piano roll", view: "Arrangement"),// ---- Grid (the arrangement or the piano roll — whichever was used last) -----------diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.csindex 4151bd66..0b651744 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs@@ -282,6 +282,12 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_track_get_color")]internal static partial int TrackGetColor(IntPtr engine, int trackId);+ [LibraryImport(Lib, EntryPoint = "nota_track_set_piano_fold")]+ internal static partial NotaResult TrackSetPianoFold(IntPtr engine, int trackId, int on);++ [LibraryImport(Lib, EntryPoint = "nota_track_get_piano_fold")]+ internal static partial int TrackGetPianoFold(IntPtr engine, int trackId);+[LibraryImport(Lib, EntryPoint = "nota_track_copy")]internal static partial NotaResult TrackCopy(IntPtr engine, int trackId);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.csindex 29bf21be..47e1d8dc 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs@@ -467,6 +467,14 @@ public sealed partial class NotaEnginepublic int GetTrackColorIndex(int trackId){ ThrowIfDisposed(); return NativeMethods.TrackGetColor(_handle, trackId); }+ /// <summary>Sets a track's piano roll Fold (specs/045).</summary>+ public void SetTrackPianoFold(int trackId, bool on)+ { ThrowIfDisposed(); NativeMethods.TrackSetPianoFold(_handle, trackId, on ? 1 : 0); }++ /// <summary>Whether a track's piano roll is folded (false for an unknown track).</summary>+ public bool GetTrackPianoFold(int trackId)+ { ThrowIfDisposed(); return NativeMethods.TrackGetPianoFold(_handle, trackId) == 1; }+/// <summary>Copies a whole track (incl. devices/clips/automation) to the clipboard.</summary>public bool CopyTrack(int trackId){ ThrowIfDisposed(); return NativeMethods.TrackCopy(_handle, trackId) == NativeMethods.NotaResult.Ok; }diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex 73c2b06a..39dd1060 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -118,6 +118,7 @@ public sealed class TrackDtopublic int ReturnIndex { get; set; } = -1; // >=0 for return trackspublic int GroupId { get; set; } = -1; // parent group's doc index, or -1 (top-level)public int ColorIndex { get; set; } = -1; // palette slot; -1 = auto by position+ public bool? PianoFold { get; set; } // piano roll Fold (specs/045); written only when on// Record input: 0 hardware, -1 master, or (2 + track-list index) for another track's// output (encoded so it survives id reassignment across save/load).public int RecordInput { get; set; }diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex 89c15d75..04e2ddcd 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -103,6 +103,7 @@ public sealed class ProjectServiceReturnIndex = engine.TrackReturnIndex(ti.Id),GroupId = ti.GroupId >= 0 && idToIndex.TryGetValue(ti.GroupId, out var gix) ? gix : -1, // parent → doc indexColorIndex = engine.GetTrackColorIndex(ti.Id),+ PianoFold = engine.GetTrackPianoFold(ti.Id) ? true : null,RecordInput = engine.GetTrackRecordInput(ti.Id) is var rin && rin > 0? (idToIndex.TryGetValue(rin, out var rix) ? rix + 2 : 0) // track source → doc index + 2: rin, // 0 hardware / -1 master@@ -673,6 +674,7 @@ public sealed class ProjectServiceengine.SetTrackArmed(id, t.Armed);if (t.Name is { Length: > 0 } trackName) engine.SetTrackName(id, trackName);if (t.ColorIndex >= 0) engine.SetTrackColorIndex(id, t.ColorIndex);+ if (t.PianoFold == true) engine.SetTrackPianoFold(id, true);if (t.RecordInput != 0) recInputDeferred.Add((id, t.RecordInput)); // resolve after all tracks existif (t.Monitor) monitorDeferred.Add((id, true)); // after record inputs resolveengine.SetTrackInputChannels(id, (InputChannels)(t.InputChannels ?? 0)); // older files: the stereo pairdiff --git a/src/managed/Nota.Mcp/Tools/TrackTools.cs b/src/managed/Nota.Mcp/Tools/TrackTools.csindex 876c6a2b..aa1fa6fe 100644--- a/src/managed/Nota.Mcp/Tools/TrackTools.cs+++ b/src/managed/Nota.Mcp/Tools/TrackTools.cs@@ -32,6 +32,12 @@ public sealed class TrackTools(IAudioEngine engine, IEngineDispatch dispatch, IA[McpServerTool(Name = "set_track_color"), Description("Set a track's colour palette index (0..7).")]public Task SetTrackColor(int trackId, int colorIndex) => Mutate(() => E.SetTrackColorIndex(trackId, colorIndex));+ [McpServerTool(Name = "set_piano_fold"), Description("Fold a track's piano roll on or off: folded, it shows only the scale's notes (or, on a Drum Rack, one named row per pad), plus any pitch a note sits on.")]+ public Task SetPianoFold(int trackId, bool on) => Mutate(() => E.SetTrackPianoFold(trackId, on));++ [McpServerTool(Name = "get_piano_fold"), Description("Whether a track's piano roll is folded.")]+ public Task<bool> GetPianoFold(int trackId) => Read(() => E.GetTrackPianoFold(trackId));+[McpServerTool(Name = "set_track_volume"), Description("Set a track's fader level (0..1 linear).")]public Task SetTrackVolume(int trackId, [Description("Linear gain 0..1")] float volume)=> Mutate(() => MixEdit.Step(E, () => E.SetTrackVolume(trackId, Math.Clamp(volume, 0f, 1f)), MixTarget.Volume(trackId))); // one undo stepdiff --git a/src/managed/Nota.Presentation/DrumPads.cs b/src/managed/Nota.Presentation/DrumPads.csnew file mode 100644index 00000000..6e736eac--- /dev/null+++ b/src/managed/Nota.Presentation/DrumPads.cs@@ -0,0 +1,44 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A Drum Rack's pads as the editors show them: each chain that answers a trigger note, named+// after the pad itself (a kit voice or a dropped sample) or else its instrument. Shared by the+// Drum pattern grid and the piano roll's folded keyboard (specs/045).++using Nota.Application;++namespace Nota.Presentation;++public readonly record struct DrumPad(int Chain, int Note, string Name);++public static class DrumPads+{+ /// <summary>The track's pads, lowest note first.</summary>+ public static List<DrumPad> Scan(IAudioEngine e, int trackId)+ {+ var pads = new List<DrumPad>();+ int n = e.RackChainCount(trackId);+ for (int c = 0; c < n; c++)+ {+ int note = e.RackChainTriggerNote(trackId, c);+ // Prefer the pad's own name: every Sampler pad reports the same instrument name,+ // which would make the rows unreadable.+ if (note >= 0)+ {+ string nm = e.RackChainName(trackId, c);+ pads.Add(new DrumPad(c, note, nm.Length > 0 ? nm : e.RackChainInstrumentName(trackId, c)));+ }+ }+ pads.Sort((x, y) => x.Note.CompareTo(y.Note));+ return pads;+ }++ /// <summary>Note → row label; pads sharing a note are joined ("Kick / Kick 2").</summary>+ public static Dictionary<int, string> ByNote(IEnumerable<DrumPad> pads)+ {+ var map = new Dictionary<int, string>();+ foreach (var p in pads)+ map[p.Note] = map.TryGetValue(p.Note, out var had) ? had + " / " + p.Name : p.Name;+ return map;+ }+}diff --git a/src/managed/Nota.Presentation/PianoRowMap.cs b/src/managed/Nota.Presentation/PianoRowMap.csnew file mode 100644index 00000000..0b7b62fd--- /dev/null+++ b/src/managed/Nota.Presentation/PianoRowMap.cs@@ -0,0 +1,111 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The piano roll's vertical layout (specs/045 Fold): which pitches have a row, top row first.+// Unfolded it is every key of the range; folded it is the scale's pitches (melodic) or the+// Drum Rack's pads, plus any pitch a note sits on, so folding never hides a note. The view+// maps every y through it, so folded and unfolded share one drawing and editing path.++namespace Nota.Presentation;++public enum PianoRowMark { InSet, OutOfScale, NoPad }++public sealed class PianoRowMap+{+ private readonly int[] _rows; // pitches, highest first+ private readonly int[] _rowOf; // pitch → row, −1 when hidden (indexed 0..127)+ private readonly PianoRowMark[] _marks;+ private readonly string?[] _labels; // pad names; null = the note name++ /// <summary>True when every key of the range has a row: unfolded, or folding found nothing+ /// to fold to (no scale and no notes, or a rack without pads).</summary>+ public bool IsChromatic { get; }++ public int Count => _rows.Length;++ private PianoRowMap(List<int> pitchesDesc, Func<int, PianoRowMark> mark, Func<int, string?> label, bool chromatic)+ {+ _rows = pitchesDesc.ToArray();+ _rowOf = new int[128];+ Array.Fill(_rowOf, -1);+ _marks = new PianoRowMark[_rows.Length];+ _labels = new string?[_rows.Length];+ for (int r = 0; r < _rows.Length; r++)+ {+ _rowOf[_rows[r]] = r;+ _marks[r] = mark(_rows[r]);+ _labels[r] = label(_rows[r]);+ }+ IsChromatic = chromatic;+ }++ /// <summary>Every key from <paramref name="maxPitch"/> down to <paramref name="minPitch"/>.</summary>+ public static PianoRowMap Chromatic(int minPitch, int maxPitch)+ {+ var rows = new List<int>(maxPitch - minPitch + 1);+ for (int p = maxPitch; p >= minPitch; p--) rows.Add(p);+ return new PianoRowMap(rows, _ => PianoRowMark.InSet, _ => null, chromatic: true);+ }++ /// <summary>Builds the folded map. <paramref name="pads"/> (note → name) set means a Drum+ /// Rack track; otherwise <paramref name="scaleMask"/> (12 bits from <paramref name="root"/>)+ /// picks the rows, or with no scale the pitches in use. Used pitches always keep a row.</summary>+ public static PianoRowMap Folded(int minPitch, int maxPitch, IReadOnlyDictionary<int, string>? pads,+ ushort? scaleMask, int root, IEnumerable<int> usedPitches)+ {+ var used = new HashSet<int>();+ foreach (int p in usedPitches) if (p >= minPitch && p <= maxPitch) used.Add(p);+ bool InScale(int p) => scaleMask is { } m && (m & (1 << ((((p - root) % 12) + 12) % 12))) != 0;++ var rows = new List<int>();+ for (int p = maxPitch; p >= minPitch; p--)+ {+ bool inSet = pads is not null ? pads.ContainsKey(p) : scaleMask is not null && InScale(p);+ if (inSet || used.Contains(p)) rows.Add(p);+ }+ if (rows.Count == 0) return Chromatic(minPitch, maxPitch);+ return new PianoRowMap(rows,+ p => pads is not null ? (pads.ContainsKey(p) ? PianoRowMark.InSet : PianoRowMark.NoPad)+ : scaleMask is null || InScale(p) ? PianoRowMark.InSet : PianoRowMark.OutOfScale,+ p => pads is not null && pads.TryGetValue(p, out var n) ? n : null,+ chromatic: false);+ }++ /// <summary>Row of <paramref name="pitch"/>, or −1 when it has none.</summary>+ public int RowOf(int pitch) => pitch is >= 0 and < 128 ? _rowOf[pitch] : -1;++ /// <summary>Pitch of row <paramref name="row"/>, clamped to the first and last row.</summary>+ public int PitchAt(int row) => _rows[Math.Clamp(row, 0, _rows.Length - 1)];++ public PianoRowMark Mark(int row) => _marks[Math.Clamp(row, 0, _rows.Length - 1)];++ /// <summary>The pad name on a folded Drum Rack row, else null (show the note name).</summary>+ public string? Label(int row) => _labels[Math.Clamp(row, 0, _rows.Length - 1)];++ /// <summary>The nearest row to <paramref name="pitch"/>: its own, else the closest by pitch+ /// (the higher one on a tie).</summary>+ public int NearestRow(int pitch)+ {+ int r = RowOf(pitch);+ if (r >= 0) return r;+ int best = 0, bestD = int.MaxValue;+ for (int i = 0; i < _rows.Length; i++)+ {+ int d = Math.Abs(_rows[i] - pitch);+ if (d < bestD) { best = i; bestD = d; } // rows run high → low, so a tie keeps the higher+ }+ return best;+ }++ /// <summary>The pitch <paramref name="rows"/> rows above (+) or below (−) the row of+ /// <paramref name="pitch"/> (or its nearest row), clamped to the map.</summary>+ public int Step(int pitch, int rows) => PitchAt(NearestRow(pitch) - rows);++ /// <summary>How many rows <paramref name="pitch"/> can move up (+) and down (−) and stay+ /// on the map — the clamp a group move applies so it keeps its shape.</summary>+ public (int down, int up) Reach(int pitch)+ {+ int r = NearestRow(pitch);+ return (-(Count - 1 - r), r);+ }+}diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex ae6d2da3..0b7c6044 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -1344,6 +1344,10 @@ NOTA_API NotaResult nota_track_set_name(NotaEngine* engine, int32_t track_id, coNOTA_API int32_t nota_track_get_name(NotaEngine* engine, int32_t track_id, char* out, int32_t cap);NOTA_API NotaResult nota_track_set_color(NotaEngine* engine, int32_t track_id, int32_t color_index);NOTA_API int32_t nota_track_get_color(NotaEngine* engine, int32_t track_id);+/* Piano roll Fold (specs/045): a per-track view flag saved with the project; the audio thread+ never reads it. get returns 1 folded, 0 not, -1 for an unknown track. */+NOTA_API NotaResult nota_track_set_piano_fold(NotaEngine* engine, int32_t track_id, int32_t on);+NOTA_API int32_t nota_track_get_piano_fold(NotaEngine* engine, int32_t track_id);/* Track clipboard: copy stores independent clones (a group brings its children), paste* appends fresh copies (new ids) top-level. copy_many / paste_after are the multi-track forms:* paste_after lands the copies after after_track_id inside its group (-1 = top-level at thediff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cppindex f2a51eee..638d8d64 100644--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp@@ -659,6 +659,13 @@ NotaResult nota_track_set_color(NotaEngine* e, int32_t track_id, int32_t color_iint32_t nota_track_get_color(NotaEngine* e, int32_t track_id) {return e ? CENG(e)->trackColorIndex(track_id) : -1;}+NotaResult nota_track_set_piano_fold(NotaEngine* e, int32_t track_id, int32_t on) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setTrackPianoFold(track_id, on != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_track_get_piano_fold(NotaEngine* e, int32_t track_id) {+ return e ? CENG(e)->trackPianoFold(track_id) : -1;+}NotaResult nota_track_copy(NotaEngine* e, int32_t track_id) {if (!e) return NOTA_ERR_INVALID_ARG;return ENG(e)->copyTrack(track_id) ? NOTA_OK : NOTA_ERR_INVALID_ARG;diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex 384fbffe..b04a577c 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -576,6 +576,7 @@ std::shared_ptr<Track> Engine::cloneTrack(const Track& t) const {nt->frozenSpb = t.frozenSpb;nt->name = t.name; // UI metadatant->colorIndex = t.colorIndex;+ nt->pianoFold = t.pianoFold;return nt;}diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex db1d501f..6d742dff 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -617,6 +617,9 @@ class Engine {int32_t trackName(int32_t trackId, char* out, int32_t cap) const;bool setTrackColorIndex(int32_t trackId, int32_t colorIndex);int32_t trackColorIndex(int32_t trackId) const;+ // Piano roll Fold (specs/045): a per-track view flag, saved with the project.+ bool setTrackPianoFold(int32_t trackId, bool on);+ int32_t trackPianoFold(int32_t trackId) const; // 1 / 0, -1 unknown track// Track clipboard (copy/cut/paste). copyTracks stores fully independent clones of the// expanded set (a group brings its children); pasteTracks inserts fresh copies (new ids +diff --git a/src/native/nota.engine/src/engine/Engine_Tracks.cpp b/src/native/nota.engine/src/engine/Engine_Tracks.cppindex 9a464aa9..16e65311 100644--- a/src/native/nota.engine/src/engine/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/engine/Engine_Tracks.cpp@@ -3070,6 +3070,19 @@ int32_t Engine::trackColorIndex(int32_t trackId) const {auto t = findTrackAuthoring(trackId);return t ? t->colorIndex : -1;}+bool Engine::setTrackPianoFold(int32_t trackId, bool on) {+ auto old = findTrackAuthoring(trackId);+ if (!old) return false;+ if (old->pianoFold == on) return true;+ auto nt = cloneTrack(*old);+ nt->pianoFold = on;+ republishWithTrackRaw(trackId, nt); // a view change, not an edit: no undo step+ return true;+}+int32_t Engine::trackPianoFold(int32_t trackId) const {+ auto t = findTrackAuthoring(trackId);+ return t ? (t->pianoFold ? 1 : 0) : -1;+}bool Engine::deleteClip(int32_t trackId, int32_t clipIndex) {auto old = findTrackAuthoring(trackId);@@ -3111,6 +3124,7 @@ std::shared_ptr<Track> Engine::deepCloneTrack(const Track& src, int32_t newId, b}nt->name = src.name;nt->colorIndex = src.colorIndex;+ nt->pianoFold = src.pianoFold;nt->instrument = cloneInstrument(src);if (nt->instrument && src.instrument) nt->instrument->setBypassed(src.instrument->bypassed());for (auto& m : src.midiEffects)diff --git a/src/native/nota.engine/src/engine/Track.h b/src/native/nota.engine/src/engine/Track.hindex 3784fc34..ef0284f4 100644--- a/src/native/nota.engine/src/engine/Track.h+++ b/src/native/nota.engine/src/engine/Track.h@@ -300,6 +300,7 @@ class Track {// slot (-1 = auto: assign by position).std::string name;int32_t colorIndex = -1;+ bool pianoFold = false; // piano roll Fold (specs/045): the editor shows the folded rows// Stable across snapshots (voice/DSP state must survive structural edits).std::shared_ptr<Instrument> instrument; // instrument tracksdiff --git a/tests/Nota.SmokeTest/FoldTests.cs b/tests/Nota.SmokeTest/FoldTests.csnew file mode 100644index 00000000..79bf096c--- /dev/null+++ b/tests/Nota.SmokeTest/FoldTests.cs@@ -0,0 +1,145 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Piano roll Fold (specs/045, #344 #345): the row map the piano roll lays out with. Unfolded+// it is the old 88-key layout exactly; folded it keeps the scale's pitches or a Drum Rack's+// pads plus every pitch a note sits on, and moves step between visible rows. The Fold switch+// is saved per track.++using System.Diagnostics;+using Nota.Application;+using Nota.Application.Midi;+using Nota.Infrastructure;+using Nota.Presentation;++namespace Nota.SmokeTest;++internal static class FoldTests+{+ private const int Min = 21, Max = 108; // the piano roll's A0..C8+ private const int A = 9; // root A++ public static IEnumerable<(bool, string)> Run()+ {+ foreach (var r in Chromatic()) yield return r;+ foreach (var r in ScaleFold()) yield return r;+ foreach (var r in PadFold()) yield return r;+ foreach (var r in Remembered()) yield return r;+ }++ // Unfolded must lay out exactly as before Fold: row = MaxPitch − pitch.+ private static IEnumerable<(bool, string)> Chromatic()+ {+ var m = PianoRowMap.Chromatic(Min, Max);+ bool same = m.Count == 88;+ for (int p = Min; p <= Max; p++) same &= m.RowOf(p) == Max - p && m.PitchAt(Max - p) == p;+ yield return (same, "unfolded rows are the 88 keys, top to bottom, as before");+ yield return (m.Step(60, 1) == 61 && m.Step(60, -12) == 48 && m.Reach(Max) == (-87, 0),+ "unfolded, a row step is a semitone");+ }++ private static PianoRowMap AMinor(params int[] used)+ => PianoRowMap.Folded(Min, Max, null, MidiScales.MaskAt(1), A, used); // Natural Minor++ private static IEnumerable<(bool, string)> ScaleFold()+ {+ var m = AMinor();+ bool allIn = true;+ for (int r = 0; r < m.Count; r++)+ {+ int pc = m.PitchAt(r) % 12;+ allIn &= pc is 9 or 11 or 0 or 2 or 4 or 5 or 7 && m.Mark(r) == PianoRowMark.InSet;+ }+ yield return (allIn && m.Count <= 52 && !m.IsChromatic, $"A minor folds to its 7 notes per octave ({m.Count} rows, SC-001: at most 52)");+ yield return (m.Step(64, 1) == 65 && m.Step(65, 1) == 67 && m.Step(69, -1) == 67, "a row up from E is F, from F is G; a row down from A is G");+ // A chord keeps its shape in scale degrees: A–C–E up one row is B–D–F.+ int[] chord = { 57, 60, 64 };+ yield return (chord.Select(p => m.Step(p, 1)).SequenceEqual(new[] { 59, 62, 65 }), "a chord moved a row keeps its shape in the scale");+ var withSharp = AMinor(66); // F♯4 is out of A minor+ int fs = withSharp.RowOf(66);+ yield return (fs >= 0 && withSharp.Mark(fs) == PianoRowMark.OutOfScale && withSharp.Count == m.Count + 1,+ "a note out of the scale keeps its own row, marked out of scale");+ var none = PianoRowMap.Folded(Min, Max, null, null, 0, new[] { 60, 64, 67 });+ yield return (none.Count == 3 && none.PitchAt(0) == 67, "with no scale, Fold shows just the pitches in use");+ var empty = PianoRowMap.Folded(Min, Max, null, null, 0, Array.Empty<int>());+ yield return (empty.IsChromatic && empty.Count == 88, "nothing to fold to keeps the whole keyboard");++ // SC-005: a 2,000-note fold builds well inside a frame.+ var rnd = new Random(45);+ var notes = Enumerable.Range(0, 2000).Select(_ => rnd.Next(Min, Max + 1)).ToArray();+ var sw = Stopwatch.StartNew();+ for (int i = 0; i < 10; i++) AMinor(notes);+ double ms = sw.Elapsed.TotalMilliseconds / 10;+ yield return (ms < 16, $"folding 2,000 notes takes {ms:F2} ms (under one 16 ms frame)");+ }++ private static IEnumerable<(bool, string)> PadFold()+ {+ using var e = new NotaEngine();+ int t = e.AddDrumRackTrack();+ (string name, int note)[] kit = { ("Kick", 36), ("Snare", 38), ("Hat closed", 42), ("Kick 2", 36) };+ foreach (var (name, note) in kit)+ {+ int c = e.RackAddChain(t, 0);+ e.RackSetChainTriggerNote(t, c, note);+ e.RackSetChainName(t, c, name);+ }+ var pads = DrumPads.ByNote(DrumPads.Scan(e, t));+ yield return (pads.Count == 3 && pads[36] == "Kick / Kick 2" && pads[42] == "Hat closed", "pads on one note share a row named after both");+ var m = PianoRowMap.Folded(Min, Max, pads, null, 0, new[] { 37 });+ yield return (m.Count == 4 && m.Label(m.RowOf(38)) == "Snare" && m.PitchAt(0) == 42, "a kit folds to one named row per pad, lowest at the bottom");+ int empty = m.RowOf(37);+ yield return (empty >= 0 && m.Mark(empty) == PianoRowMark.NoPad && m.Label(empty) is null, "a note with no pad keeps an unnamed row");+ e.RackSetChainName(t, 1, "Clap");+ var renamed = PianoRowMap.Folded(Min, Max, DrumPads.ByNote(DrumPads.Scan(e, t)), null, 0, Array.Empty<int>());+ yield return (renamed.Label(renamed.RowOf(38)) == "Clap", "renaming a pad renames its row");+ }++ private static IEnumerable<(bool, string)> Remembered()+ {+ using var src = new NotaEngine();+ int drums = src.AddInstrumentTrack(), keys = src.AddInstrumentTrack();+ yield return (!src.GetTrackPianoFold(drums), "a new track opens unfolded");+ src.SetTrackPianoFold(drums, true);+ yield return (src.GetTrackPianoFold(drums) && !src.GetTrackPianoFold(keys), "Fold is per track");+ int dup = src.DuplicateTrack(drums);+ yield return (dup > 0 && src.GetTrackPianoFold(dup), "a duplicated track keeps its Fold");++ var doc = ProjectService.Capture(src, new TransportState(120.0, 1.0, false, false), new List<string>());+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-fold-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(dir);+ try+ {+ using (var dst = new NotaEngine())+ {+ ProjectService.Apply(doc, dst, dir);+ var ids = Ids(dst);+ yield return (ids.Count == 3 && dst.GetTrackPianoFold(ids[0]) && dst.GetTrackPianoFold(ids[1]) && !dst.GetTrackPianoFold(ids[2]), // drums, its duplicate, keys+ "Fold survives save and load, on the track it was set on");+ }+ foreach (var tr in doc.Tracks) tr.PianoFold = null; // as written before 0.58+ using (var old = new NotaEngine())+ {+ ProjectService.Apply(doc, old, dir);+ yield return (Ids(old).All(id => !old.GetTrackPianoFold(id)), "an older project opens unfolded");+ }+ }+ finally { Directory.Delete(dir, true); }++ // A view change, not an edit: undo after folding takes back the last edit instead.+ using var u = new NotaEngine();+ int a = u.AddInstrumentTrack();+ u.AddInstrumentTrack();+ u.SetTrackPianoFold(a, true);+ u.Undo();+ yield return (u.TrackCount == 1, $"Fold adds no undo step: undo removed the last track ({u.TrackCount} left)");+ }++ private static List<int> Ids(NotaEngine e)+ {+ var ids = new List<int>();+ for (int i = 0; i < e.TrackCount; i++)+ if (e.TryGetTrackInfo(i, out var t) && t.IsInstrument && !t.IsReturn && !t.IsGroup) ids.Add(t.Id);+ return ids;+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 32301d8e..66da1c54 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -559,6 +559,14 @@ if (args.Length >= 1 && args[0] == "--vocoder")Console.WriteLine(failures == 0 ? "VOCODER PASSED" : $"VOCODER FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Piano roll Fold alone (fast iteration): `--piano-fold`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--piano-fold")+{+ Console.WriteLine("-- piano roll fold --");+ foreach (var (ok, label) in FoldTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "FOLD PASSED" : $"FOLD FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Session launches + recording input alone (fast iteration): `--session-input`. Also part of the full run.if (args.Length >= 1 && args[0] == "--session-input"){@@ -15060,6 +15068,10 @@ Console.WriteLine("-- background audio import --");Console.WriteLine("-- browser: device categories --");foreach (var (ok, label) in BrowserCategoryTests.Run()) Check(ok, label);+// --- piano roll Fold (specs/045): scale rows, Drum Rack pads, saved per track ---+Console.WriteLine("-- piano roll fold --");+foreach (var (ok, label) in FoldTests.Run()) Check(ok, label);+// --- browser: preset audition (offline-rendered, cached, played on the preview voice) ---Console.WriteLine("-- browser: preset audition --");foreach (var (ok, label) in AuditionTests.Run()) Check(ok, label);