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 controller lane and Shift + wheel velocity (#169) (#397)
Chris Laupama8e02be0a5efb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fe711a6d..baba0a03 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -67,6 +67,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.window**) moves it into the floating window for a second screen; the window's dock buttonbrings it back. Nota remembers whether the Mixer was shown, where and how tall, and restoresit on the next launch.+- **Edit any MIDI controller in the piano roll** (#169): the lane under the notes gets a fifth+ tab for controllers. Click it to pick one — the controllers the clip already has first, then+ Sustain, Mod wheel, Pitch wheel, Channel pressure, Expression, Breath and every other CC.+ Pedals (CC64–69) draw as on/off blocks you drag, move and resize on the grid; other+ controllers are a curve you draw, with points to drag, add and delete. Each gesture is one+ undo step and plays back straight away.+- **Shift + wheel changes note velocity** (#169): over a note, ⇧ + wheel raises or lowers the+ velocity of the selected notes (or of the hovered note when it isn't selected) by one step per+ notch; a run of notches is one undo step. Elsewhere ⇧ + wheel still scrolls the roll.+ Preferences → Shortcuts sets the direction and the speed (off, 0.25× … 2×, default 1×).- **Shape a note while placing it in the piano roll** (#45): after the double-click that addsa note, keep the button down and drag to move it (pitch and time); hold ⇧ to set its lengthor ⌘ / Ctrl to drag up and down for its velocity. The next note drawn takes the shapeddiff --git a/FEATURES.md b/FEATURES.mdindex e361acdd..e4a16c5f 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -330,6 +330,9 @@ docks as a panel under any of the three, or floats in its own window — seethe arrows or the mouse.- Keyboard: ←/→ move by the grid, ↑/↓ by a semitone (⇧ an octave), ⇧←/⇧→ shorten orlengthen by the grid, ⌥↑/⌥↓ change velocity by 10 (⌥⇧ by 1).+ - ⇧ + wheel over a note changes the velocity of the selection (or of that note when it+ isn't selected), one step per notch; elsewhere ⇧ + wheel scrolls. Direction and speed+ (off, 0.25× … 2×) are in **Preferences → Shortcuts**. A run of notches is one undo step.- **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@@ -426,6 +429,13 @@ docks as a panel under any of the three, or floats in its own window — seeOperator, Pentad, Consort). The sustain pedal holds released keys on every melodic built-in(Keys and Mosaic model their own damper; drums ignore it); a re-struck held key restarts.MCP `get_clip_controllers` / `set_clip_controller`.+ - **Controller lane in the piano roll** — the fifth tab of the lane under the notes edits+ any controller: click the active tab for a picker (the clip's controllers first, then+ Sustain, Mod wheel, Pitch wheel, Channel pressure, Expression, Breath and **Other CC**).+ Pedals (CC64–69) are on/off blocks — drag to draw, move or resize one on the grid (⌘ free),+ double-click or Delete removes it; other controllers are a curve — drag to draw (⌥ for a+ straight line), drag a point, double-click to add or delete one, right-click to clear.+ Each gesture is one undo step.- **MPE (per-note expression)** — an MPE controller's notes each carry their own pitchbend, pressure and slide (CC74): channels 2–16 are per-note (lower zone, ±48 semitones bydefault; the controller's MPE Configuration and bend-range messages are honoured), channel 1diff --git a/specs/020-midi-cc-record-automate/tasks.md b/specs/020-midi-cc-record-automate/tasks.mdindex ae76c8bc..dbe2c8dc 100644--- a/specs/020-midi-cc-record-automate/tasks.md+++ b/specs/020-midi-cc-record-automate/tasks.md@@ -204,20 +204,20 @@ description: "Task list for recording and automating MIDI CC (#69)"**Independent Test**: In clips with and without recorded data, switch to Sustain, Mod wheel, Pitch wheel, Channel pressure and CC 74. Draw, move and delete, undo each step, and confirm playback follows (quickstart PR 2).-- [ ] T032 [US2] Extend `LaneMode` in `src/managed/Nota.App/PianoRollView.Expression.cs` (L33) with `Controller`, and add a `_laneCtl` field.+- [X] T032 [US2] Extend `LaneMode` in `src/managed/Nota.App/PianoRollView.Expression.cs` (L33) with `Controller`, and add a `_laneCtl` field.- **Default**: the first ctl with data in the clip, else 64. Remember it per editor session, like `_laneMode`.- **Height**: `SetLaneMode(Controller)` swaps in the new lane control at `ExprH`.- **Tab**: `LaneTabs` (L134) gains a fifth tab labelled with `MidiController.ShortName(_laneCtl)`, keeping the existing tab styling.-- [ ] T033 [US2] Add the controller picker to the fifth tab in `src/managed/Nota.App/PianoRollView.Expression.cs`. A click on the active tab or its chevron opens a menu:+- [X] T033 [US2] Add the controller picker to the fifth tab in `src/managed/Nota.App/PianoRollView.Expression.cs`. A click on the active tab or its chevron opens a menu:- first, the ctls with data in this clip, each marked with the automation picker's dot (reuse `AutoDot()` from `ArrangementView.Automation.cs:612`, or lift it into a shared helper in `ClipEditorKit.cs`);- then Sustain, Mod wheel, Pitch wheel, Channel pressure, Expression (CC11) and Breath (CC2);- then **Other CC ▸** with 0–127 in groups of 16, labelled "CC 7 — Volume", skipping reserved CCs.Labels are in sentence case.-- [ ] T034 [US2] Create `src/managed/Nota.App/PianoRollView.Controllers.cs` (SPDX header, `partial class PianoRollView`) with a `ControllerLane` control. It reads the curve through a host delegate `Func<int, NotaAutomationPoint[]>? GetController` and writes through `Action<int, NotaAutomationPoint[]>? SetController`, mirroring `CreateExpression`.+- [X] T034 [US2] Create `src/managed/Nota.App/PianoRollView.Controllers.cs` (SPDX header, `partial class PianoRollView`) with a `ControllerLane` control. It reads the curve through a host delegate `Func<int, NotaAutomationPoint[]>? GetController` and writes through `Action<int, NotaAutomationPoint[]>? SetController`, mirroring `CreateExpression`.- **Time mapping**: the same as the notes over the whole clip. A pickup before the clip start is drawn faintly.- **Ink**: neutral (`NotaPalette.VizInk`, `CurvePen`). Only the hovered point or block, and the selection, use the accent.-- [ ] T035 [US2] Switch controllers (CC64–69) in `PianoRollView.Controllers.cs`:+- [X] T035 [US2] Switch controllers (CC64–69) in `PianoRollView.Controllers.cs`:- **Drawing**: blocks where the value is ≥ 0.5. Fill height shows partial values (clarification 3).- **Drag on empty lane**: draws a block that snaps to the grid; ⌘ or Ctrl turns snap off.- **Drag an edge**: resizes the block.@@ -225,7 +225,7 @@ description: "Task list for recording and automating MIDI CC (#69)"- **Delete**: double-click, or Delete with the block selected.- **Right-click**: *Clear <name>*.- A block is serialised as two step points: on at its start, off at its end.-- [ ] T036 [US2] Continuous controllers in `PianoRollView.Controllers.cs`:+- [X] T036 [US2] Continuous controllers in `PianoRollView.Controllers.cs`:- **Drawing**: a curve with points. The range lines are 0–127 with a midline label. The pitch wheel draws a centre line and ±full travel, and points within 2% of centre snap to 0.- **Freehand drag**: replaces the points under the stretch; ⌥ draws a straight line.- **Points**: drag a point to move it between its neighbours; double-click adds or deletes a point.@@ -233,12 +233,12 @@ description: "Task list for recording and automating MIDI CC (#69)"- **Hover readout**: the value in the controller's units ("64", "+0.42", "on / off").Reuse the point-drag and freehand helpers from `PianoRollView.Expression.cs`. If they are private to the MPE lane, lift them into a shared helper.-- [ ] T037 [US2] Wire the host in `src/managed/Nota.App/ClipEditorView.cs`:+- [X] T037 [US2] Wire the host in `src/managed/Nota.App/ClipEditorView.cs`:- Set `GetController` / `SetController` to `IAudioEngine.GetMidiClipController` / `SetMidiClipController` for arrangement clips, and the `Session*` variants for slots.- `SetController` is called once on gesture release (one undo step, FR-013).- Refresh the lane after undo and redo and when the take republishes during recording, the same way notes refresh.- [ ] T038 [US2] Add a precedence note to the controller lane. When the track has a target-5 automation lane with points for `_laneCtl`, show the one-line note "Track automation overrides this lane" in `PianoRollView.Controllers.cs`. The data comes from `IAudioEngine.AutomationLaneInfo`. It is inert until US3 adds the target; no US3 dependency for compiling, because the enum value is added in T042.-- [ ] T039 [US2] Visual check following quickstart PR 2. Run the headless Avalonia render, or the env-guarded in-app capture with `NOTA_DATA_DIR`, for Sustain blocks and a CC curve in Studio Dark and Studio Light. Then run the `DesignTokenCheck*` tests in the smoke suite (labels, numbers, radius allow-lists). Fix violations, or add allow-list rows only where the design guide permits.+- [X] T039 [US2] Visual check following quickstart PR 2. Run the headless Avalonia render, or the env-guarded in-app capture with `NOTA_DATA_DIR`, for Sustain blocks and a CC curve in Studio Dark and Studio Light. Then run the `DesignTokenCheck*` tests in the smoke suite (labels, numbers, radius allow-lists). Fix violations, or add allow-list rows only where the design guide permits.**Checkpoint**: PR 2 is complete. Controllers are visible and editable.diff --git a/specs/063-event-lane-cc-velocity-wheel/plan.md b/specs/063-event-lane-cc-velocity-wheel/plan.mdnew file mode 100644index 00000000..deee5f1a--- /dev/null+++ b/specs/063-event-lane-cc-velocity-wheel/plan.md@@ -0,0 +1,80 @@+# Implementation Plan: Event lane — MIDI CC lanes and the velocity wheel++**Branch**: `063-event-lane-cc-velocity-wheel` | **Date**: 2026-10-30 | **Spec**: [spec.md](spec.md)++## Summary++Managed-only. The piano roll gains a fifth lane mode backed by the existing clip controller+store (specs/020 PR 1), and the note grid's Shift + wheel changes velocity when the pointer+is over a note. No engine, ABI or persistence change.++## Technical Context++**Language/Version**: C# / .NET 10, Avalonia 11. **Testing**: `tests/Nota.SmokeTest`+(`VelocityWheelTests`), `scripts/build.sh`. **Constraints**: no audio-thread work; controller+writes go through `IAudioEngine.SetMidiClipController` / `SetSessionController`, each an+undo checkpoint in the engine.++**Audio-thread impact**: none. Everything here runs on the UI thread. Controller writes use+the existing specs/020 path (`SetMidiClipController` / `SetSessionController`), which+publishes the clip's new controller curve to the audio thread the way every clip edit does;+velocity changes use the piano roll's existing note commit and live-preview path. No new+C ABI function, no engine code, no new allocation, lock, I/O or logging on the audio thread.++## Constitution Check++- AGPL headers on new files; no new dependency.+- UI follows `DESIGN.md` (Studio): neutral viz ink, accent only for hover and selection,+ sentence-case labels, theme tokens only.+- User-visible: `CHANGELOG.md`, `FEATURES.md`, Shortcuts pane.++## Design++### Controller lane (`App/PianoRollView.Controllers.cs`)++- Host delegates on `PianoRollView`: `ControllersInClip` (ctls with data in the active clip),+ `GetController(ctl)` and `SetController(ctl, points)` (clip-local beats). The roll caches+ curves per ctl and drops the cache on every reload (`Load`) and active-clip change, so undo,+ redo and recording refresh it the way they refresh notes.+- Time: clip-local beat ↔ editor beat through `ClipSet.ToEditor/ToLocal(Active, …)`.+- Switch controllers: the curve is read as spans where value ≥ 0.5 (blocks); gestures edit a+ block list, written back as step points (on value at start, 0 at end; a block keeps its+ stored value, so half-pedal values survive moves). Partial values draw as fill height.+- Continuous controllers: the MPE lane's stroke model over one clip-wide curve — the stroke+ replaces the stretch it covers, the old curve resumes after it; RDP thinning on release.+ Existing points keep their `Curve` shaping; new points are linear.+- One `SetController` call per gesture (on release) → one undo step.++### Lane tabs (`App/PianoRollView.Expression.cs`)++- `LaneMode.Controller` + `_laneCtl` (resolved on first use: first ctl with data, else 64).+- Five rows fit the 72 px velocity row (13 px steps). The fifth row's label is the short name+ when it fits the gutter, else "CC"; a small chevron marks the picker.+- Picker: `MenuFlyout` with the data ctls (automation glyph), the common six, and+ **Other CC ▸** in groups of 16, skipping `MidiController.IsReserved`.++### Velocity wheel++- `Nota.Application/Editing/VelocityWheel.cs`: pure step accumulator — notches × multiplier ×+ direction, carried fractions, ±2 notches cap per event; `Settings` gains+ `PianoRollVelocityWheelReversed` and `PianoRollVelocityWheelMultiplier` (0–2, default 1).+- `NoteGrid.OnPointerWheelChanged`: Shift + hit on an editable note and multiplier > 0 → the+ targets (selection if the hit is selected, else the hit). First step of a burst seeds undo+ with the pre-burst notes (as a note drag does), later steps stream live; a 0.6 s idle timer+ ends the burst (commits when there is no live path, i.e. Session slots).+- Settings reach the roll as static properties seeded by `MainWindow` (like `AuditionEnabled`)+ and updated by Preferences.++## Project Structure++```text+specs/063-event-lane-cc-velocity-wheel/ spec.md, plan.md, tasks.md+src/managed/Nota.Application/Editing/VelocityWheel.cs (new)+src/managed/Nota.Application/Settings.cs+src/managed/Nota.App/PianoRollView.Controllers.cs (new)+src/managed/Nota.App/PianoRollView.Expression.cs+src/managed/Nota.App/PianoRollView.cs+src/managed/Nota.App/MainWindow.Detail.cs, MainWindow.axaml.cs+src/managed/Nota.App/PreferencesWindow.cs+tests/Nota.SmokeTest/VelocityWheelTests.cs (new), Program.cs+```diff --git a/specs/063-event-lane-cc-velocity-wheel/spec.md b/specs/063-event-lane-cc-velocity-wheel/spec.mdnew file mode 100644index 00000000..79280b54--- /dev/null+++ b/specs/063-event-lane-cc-velocity-wheel/spec.md@@ -0,0 +1,136 @@+# Feature Specification: Event lane — MIDI CC lanes and the velocity wheel++**Feature Branch**: `063-event-lane-cc-velocity-wheel`++**Created**: 2026-10-30++**Status**: Draft++**Input**: User description: "GitHub issue nota-daw/nota#169 — Event Line Editor: add more automation source controls, plus UX improvements. Add the ability to switch the lane's automation control to any MIDI CC. Add the ability to change note velocity with Shift + mouse wheel: with notes selected the selection changes; with the cursor on one note only that note changes. Custom: a setting for the wheel direction (default: up = plus, down = minus) and a multiplier for the change (default 1, range 0–2). Optional: snap the change to the piano roll grid."++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [ ] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++**Existing behaviour this builds on**:++- The "event line editor" is the piano roll's lane under the notes, switched from its+ gutter between VEL / BEND / PRES / SLIDE (`PianoRollView.Expression.cs`).+- MIDI clips and Session slots already store, record and play one curve per instrument-wide+ controller — any CC 0–127 except the reserved ones, the pitch wheel and channel pressure+ (specs/020, PR 1: `nota_midi_clip_ctl_*`, `nota_session_ctl_*`, `IAudioEngine.Get/SetMidiClipController`).+ Nothing draws or edits them yet: specs/020 User Story 2 (tasks T032–T039,+ [contracts/ui-lanes.md](../020-midi-cc-record-automate/contracts/ui-lanes.md)) designed+ that lane and was not built. This feature builds it.+- Shift + wheel over the note grid scrolls the piano roll sideways (specs/019 FR-003); ⌥↑ / ⌥↓+ already change the selection's velocity by 10 (⌥⇧ by 1).+- An earlier attempt (PR #292) bundled this issue with tempo automation and MIDI file+ import/export and was closed. This spec covers #169 only.++## Clarifications++### Session 2026-10-30++- Q: Shift + wheel already scrolls the piano roll sideways. Where does it change velocity instead? → A: Only with the pointer over a note: that note, or the whole selection when the note under the pointer is selected. Anywhere else (empty grid, lanes, ruler) Shift + wheel keeps scrolling, so a selection never takes the scroll away.+- Q: How big is one wheel step? → A: One MIDI velocity step (1 of 127) per wheel notch at 1×; the multiplier scales it (2× = 2 per notch, 0.5× = 1 per two notches). A trackpad moves in proportion to its travel. Velocity stays within 1–127, the range ⌥↑ / ⌥↓ use.+- Q: Does the multiplier apply to both directions? → A: Yes, one multiplier for up and down; at 0× the gesture is off and Shift + wheel scrolls everywhere.+- Q: Undo granularity of the wheel? → A: One undo step per burst: wheel moves less than 0.6 s apart are one edit.+- Q: Where do the two settings live? → A: Preferences → Shortcuts, in a "Velocity wheel" section above the reference list, next to the gesture they change.+- Q: The optional "snap the velocity change to the grid (size + multiplier)" item? → A: Out of scope for this PR: the formula maps a time grid onto a value step and needs its own design; the issue marks it optional.+- Q: The controller lane's design? → A: As specs/020 [contracts/ui-lanes.md](../020-midi-cc-record-automate/contracts/ui-lanes.md) says, with one change: the gutter tab is 48 px wide, so it shows the controller's short name when it fits ("Sustain", "CC 74") and the lane's top-left corner always names it in full ("Mod wheel · CC 1"). The "Track automation overrides this lane" note waits for the CC automation target (specs/020 US3), which does not exist yet.++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Draw and edit any MIDI controller under the notes (Priority: P1)++A user records a piano part with the sustain pedal, opens the clip and switches the lane+under the notes to Sustain: the pedal shows as on/off blocks they can move, stretch, draw+and delete. They switch to Mod wheel (or any CC 0–127, the pitch wheel or channel pressure)+and draw a curve; playback follows on the next pass.++**Why this priority**: It is the first request of the issue and the clip data already exists+but cannot be seen or edited.++**Independent Test**: In a clip with and without recorded controllers, pick Sustain, Mod+wheel, Pitch wheel, Channel pressure and CC 74 from the lane's picker; draw, move and delete;+undo each gesture once; play and hear the change.++**Acceptance Scenarios**:++1. **Given** the piano roll, **When** the user clicks the fifth gutter tab, **Then** the lane shows the current controller (Sustain, or the first one with data in the clip); a click on the tab while it is shown opens the picker: controllers with data first (marked), then Sustain, Mod wheel, Pitch wheel, Channel pressure, Expression and Breath, then **Other CC ▸** with every non-reserved CC in groups of 16.+2. **Given** a switch controller (CC64–69), **When** the user drags on an empty stretch, **Then** a block is drawn on the grid (⌘/Ctrl: off the grid); dragging a block's edge resizes it, dragging its body moves it, a double-click deletes it.+3. **Given** a continuous controller, **When** the user drags across the lane, **Then** the drawn stretch replaces the points under it (⌥: a straight line); a point can be dragged between its neighbours; a double-click adds a point or deletes the one under the pointer; the pitch wheel snaps to centre within 2 %.+4. **Given** any controller lane, **When** the user right-clicks, **Then** *Clear <name>* removes that controller from the clip.+5. **Given** any controller edit, **When** the user presses Undo once, **Then** the whole gesture is undone, and the next playback pass plays the edited curve.+6. **Given** several clips open, **Then** the lane edits the active clip's controllers at that clip's position; a Session slot's editor edits the slot's.++---++### User Story 2 - Change velocity with Shift + wheel (Priority: P2)++A user hovers a note and rolls the wheel with Shift held: its velocity steps up or down,+the note's shade and stem follow. With several notes selected, hovering any of them and+rolling changes them all. The direction and the step multiplier are set in Preferences.++**Why this priority**: A faster way to shape dynamics than dragging stems, but the lane and+⌥↑ / ⌥↓ already cover the need.++**Independent Test**: Hover a lone note, Shift + wheel up three notches: velocity +3. Select+four notes, hover one, wheel down: all four go down together. Undo once: all back. Reverse+the direction and set 2× in Preferences: one notch up now lowers by 2. Over empty grid,+Shift + wheel still scrolls.++**Acceptance Scenarios**:++1. **Given** the pointer over an unselected note, **When** Shift + wheel moves one notch up, **Then** that note's velocity rises by one MIDI step and no other note changes.+2. **Given** a selection and the pointer over one of its notes, **When** Shift + wheel moves, **Then** every selected note changes by the same steps, each clamped to 1–127.+3. **Given** the pointer over empty grid (with or without a selection), **When** Shift + wheel moves, **Then** the roll scrolls sideways as before.+4. **Given** Preferences → Shortcuts → Velocity wheel set to Reverse and 2×, **When** the wheel moves one notch up over a note, **Then** its velocity falls by two steps; at 0× Shift + wheel scrolls everywhere.+5. **Given** a burst of wheel moves, **When** the user presses Undo once, **Then** the velocities return to where the burst began.++### Edge Cases++- A note of a reference (locked) clip is never changed by the wheel; the wheel scrolls there.+- A velocity already at 127 (or 1) stays; the burst still ends normally.+- A trackpad's small deltas accumulate, so a slow swipe still steps; one event never jumps more than two notches' worth.+- A controller lane on a clip that is gone (undo, project load) draws empty and writes nothing.+- A block drawn past the clip's end is cut at the end; one drawn over another block merges with it.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: The lane under the notes MUST offer a fifth mode that shows one instrument-wide controller of the active clip, picked from Sustain, Mod wheel, Pitch wheel, Channel pressure, Expression, Breath and any non-reserved CC 0–127; controllers holding data in the clip MUST be marked and listed first (specs/020 FR-010).+- **FR-002**: Switch controllers MUST draw and edit as on/off blocks; partial values show as the block's fill height (specs/020 FR-011).+- **FR-003**: Continuous controllers MUST support freehand drawing, ⌥ straight lines, point drag, double-click add/delete and right-click clear, consistent with the MPE lanes (specs/020 FR-012).+- **FR-004**: Every controller gesture MUST be one undo step and MUST be heard on the next playback pass (specs/020 FR-013).+- **FR-005**: Shift + wheel over an editable note MUST change the velocity of that note, or of the whole selection when the note is selected, by one MIDI step per notch × the multiplier, clamped to 1–127.+- **FR-006**: Shift + wheel anywhere else, and everywhere when the multiplier is 0, MUST keep scrolling sideways (specs/019 FR-003).+- **FR-007**: The wheel direction (default: up raises) and the multiplier (default 1×, 0–2×) MUST be user settings, persisted per user and editable in Preferences.+- **FR-008**: A burst of wheel moves MUST be one undo step.+- **FR-009**: The Shortcuts reference MUST list the new gestures.++## Success Criteria *(mandatory)*++- **SC-001**: Every controller shown by the picker can be drawn, edited and cleared in a clip and in a Session slot, and a single Undo reverses each gesture.+- **SC-002**: A recorded sustain pedal opens as blocks at the beats it was pressed.+- **SC-003**: Shift + wheel over empty grid still scrolls in every configuration.+- **SC-004**: The velocity-step computation (direction, multiplier, accumulation, clamping) is covered by the smoke test.++## Assumptions++- No engine or C ABI change: the controller store, its undo and playback are specs/020 PR 1.+- Copying notes does not copy controllers (specs/020 contract).diff --git a/specs/063-event-lane-cc-velocity-wheel/tasks.md b/specs/063-event-lane-cc-velocity-wheel/tasks.mdnew file mode 100644index 00000000..9abcbee7--- /dev/null+++ b/specs/063-event-lane-cc-velocity-wheel/tasks.md@@ -0,0 +1,34 @@+---++description: "Task list for the event lane CC lanes and velocity wheel"+---++# Tasks: Event lane — MIDI CC lanes and the velocity wheel++**Input**: [spec.md](spec.md), [plan.md](plan.md); the lane contract is specs/020+[contracts/ui-lanes.md](../020-midi-cc-record-automate/contracts/ui-lanes.md).++`App/` means `src/managed/Nota.App/`.++## Phase 1: User Story 1 — controller lanes (P1)++Implements specs/020 T032–T037 and T039 (T038 waits for the CC automation target, specs/020 US3).++- [X] T001 [US1] `App/PianoRollView.Expression.cs`: `LaneMode.Controller`, `_laneCtl`, a fifth gutter tab (13 px rows so five fit the 72 px row) and the picker menu (data ctls first with the automation glyph; Sustain, Mod wheel, Pitch wheel, Channel pressure, Expression, Breath; Other CC ▸ in groups of 16 without reserved ctls).+- [X] T002 [US1] New `App/PianoRollView.Controllers.cs`: host delegates `ControllersInClip` / `GetController` / `SetController`, the per-ctl cache (dropped in `Load` and on active-clip change), and the `ControllerLane` control: clip-local ↔ editor time, switch blocks (draw with snap, resize edges, move body, double-click delete, partial fill height), continuous curves (freehand stroke replacing its stretch, ⌥ line, point drag, double-click add/delete, wheel centre snap), right-click *Clear <name>*, hover readout, one write per gesture.+- [X] T003 [US1] `App/MainWindow.Detail.cs`: wire the delegates for arrangement clips (the active clip, checked live with `TryGetClipInfo`) and Session slots; refresh the arrangement / Session view after a write.+- [X] T004 [US1] Mark specs/020 T032–T037 and T039 done.++## Phase 2: User Story 2 — velocity wheel (P2)++- [X] T005 [P] [US2] New `src/managed/Nota.Application/Editing/VelocityWheel.cs` (step accumulator) and the two `Settings` properties.+- [X] T006 [P] [US2] New `tests/Nota.SmokeTest/VelocityWheelTests.cs` (direction, multiplier, 0× off, accumulation, cap, clamp 1–127) and its call in `Program.cs`.+- [X] T007 [US2] `App/PianoRollView.cs` `NoteGrid.OnPointerWheelChanged`: Shift over an editable note → velocity burst (seeded undo, live stream, 0.6 s idle end); otherwise unchanged scrolling.+- [X] T008 [US2] `App/MainWindow.axaml.cs` seeds the roll's static wheel settings; `App/PreferencesWindow.cs` Shortcuts page gets a "Velocity wheel" section (Reverse switch, multiplier 0×–2×) that saves and applies them.++## Phase 3: Polish++- [X] T009 Shortcuts pane rows (nota-shortcuts): Shift + wheel over a note; the controller lane gestures.+- [X] T010 `CHANGELOG.md` `[Unreleased]` and `FEATURES.md` (nota-features).+- [X] T011 `scripts/build-linux.sh`: native, managed and the smoke test (velocity wheel and design-token checks pass; the render-pool burst guard fails on this VM on unmodified `develop` too — rerun alone with `--perf` on both, results in the PR).+- [X] T012 Before/after screenshots of the lane gutter, a Sustain and a CC lane and the Preferences section (nota-pr), on `pr-assets` under `issue-169/`.diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.csindex 039acbb7..5a017253 100644--- a/src/managed/Nota.App/MainWindow.Detail.cs+++ b/src/managed/Nota.App/MainWindow.Detail.cs@@ -685,6 +685,16 @@ public partial class MainWindowPollHeldNotes = buf => Engine.LiveHeldNotes(buf),ExpressionOf = id => Engine.GetNoteExpression(id),CreateExpression = pts => Engine.CreateNoteExpression(pts),+ // The controller lane edits the active clip (specs/063); a clip gone since is left alone.+ ControllersInClip = () => Engine.GetMidiClipControllers(roll.ActiveClip.TrackId, roll.ActiveClip.ClipIndex),+ GetController = ctl => Engine.GetMidiClipController(roll.ActiveClip.TrackId, roll.ActiveClip.ClipIndex, ctl),+ SetController = (ctl, pts) =>+ {+ var c = roll.ActiveClip;+ if (!Engine.TryGetClipInfo(c.TrackId, c.ClipIndex, out var info) || !info.IsMidi) { PruneDeadClips(roll); return; }+ Engine.SetMidiClipController(c.TrackId, c.ClipIndex, ctl, pts);+ Timeline.Refresh(rebuildHeaders: false);+ },// A note sounds on its own clip's track; the keys column on the active clip's.AuditionOn = (pitch, vel) => AuditionNoteOn(roll.AuditionTrackId > 0 ? roll.AuditionTrackId : _editorTrackId, pitch, vel),AuditionOff = pitch => Engine.TrackNoteOff(roll.AuditionTrackId > 0 ? roll.AuditionTrackId : _editorTrackId, pitch),@@ -1330,6 +1340,13 @@ public partial class MainWindowPollHeldNotes = buf => Engine.LiveHeldNotes(buf),ExpressionOf = id => Engine.GetNoteExpression(id),CreateExpression = pts => Engine.CreateNoteExpression(pts),+ ControllersInClip = () => Engine.GetSessionControllers(trackId, scene),+ GetController = ctl => Engine.GetSessionController(trackId, scene, ctl),+ SetController = (ctl, pts) =>+ {+ Engine.SetSessionController(trackId, scene, ctl, pts);+ _session?.Refresh();+ },AuditionOn = (pitch, vel) => AuditionNoteOn(trackId, pitch, vel),AuditionOff = pitch => Engine.TrackNoteOff(trackId, pitch),IsSessionSlot = true, // no Seek: the slot plays on its own loop clockdiff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.csindex 3beec7ed..5fb45208 100644--- a/src/managed/Nota.App/MainWindow.Menu.cs+++ b/src/managed/Nota.App/MainWindow.Menu.cs@@ -47,6 +47,7 @@ public partial class MainWindowprivate void OnMenuUndo(object? sender, EventArgs e){if (_vm is null) return;+ _editorRoll?.EndVelocityWheel(); // the burst is the step about to be undoneif (Engine.Undo()) { RefreshAfterUndoRedo(); _vm.StatusText = "Undo"; }else _vm.StatusText = "Nothing to undo.";}@@ -54,6 +55,7 @@ public partial class MainWindowprivate void OnMenuRedo(object? sender, EventArgs e){if (_vm is null) return;+ _editorRoll?.EndVelocityWheel();if (Engine.Redo()) { RefreshAfterUndoRedo(); _vm.StatusText = "Redo"; }else _vm.StatusText = "Nothing to redo.";}diff --git a/src/managed/Nota.App/MainWindow.Remote.cs b/src/managed/Nota.App/MainWindow.Remote.csindex 9dfa0aa3..d23b17df 100644--- a/src/managed/Nota.App/MainWindow.Remote.cs+++ b/src/managed/Nota.App/MainWindow.Remote.cs@@ -168,6 +168,7 @@ public partial class MainWindow : IRemoteHostbool IRemoteHost.Undo(){+ _editorRoll?.EndVelocityWheel();if (!Engine.Undo()) return false;RefreshAfterUndoRedo();if (_vm is not null) _vm.StatusText = "Undo (from a phone)";diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 84e80237..11a7ca5a 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -388,6 +388,8 @@ public partial class MainWindow : WindowPianoRollView.AuditionEnabled = vm.Settings.Current.PianoRollAudition;PianoRollView.AuditionToggled -= OnAuditionToggled;PianoRollView.AuditionToggled += OnAuditionToggled;+ PianoRollView.VelocityWheelReversed = vm.Settings.Current.PianoRollVelocityWheelReversed;+ PianoRollView.VelocityWheelMultiplier = Nota.Application.Editing.VelocityWheel.ClampMultiplier(vm.Settings.Current.PianoRollVelocityWheelMultiplier);vm.Transport.CountInBars = Math.Clamp(vm.Settings.Current.CountInBars, 0, 4);vm.Transport.LoopRecordReplace = vm.Settings.Current.LoopRecordReplace;SetArmOnSelect(vm.Settings.Current.ArmOnSelect);diff --git a/src/managed/Nota.App/PianoRollView.Controllers.cs b/src/managed/Nota.App/PianoRollView.Controllers.csnew file mode 100644index 00000000..1720941b--- /dev/null+++ b/src/managed/Nota.App/PianoRollView.Controllers.cs@@ -0,0 +1,676 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The piano roll's controller lane (specs/063; designed in specs/020 contracts/ui-lanes.md):+// one instrument-wide controller of the active clip — any CC, the pitch wheel or channel+// pressure — over the whole clip, picked from the gutter's fifth tab. Switch controllers+// (CC64–69, the sustain pedal) are blocks, on where the value is at least half:+// drag on empty lane draws a block on the grid (⌘/Ctrl: off the grid);+// drag a block's edge resizes it · drag its body moves it · double-click or Delete removes it.+// The rest are a curve:+// drag across the lane draws over that stretch (⌥ draws a straight line);+// drag a point moves it (in time between its neighbours, and in value);+// double-click adds a point, or deletes the one under the pointer.+// Right-click clears the controller. A gesture is one write, one undo step in the engine.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;+using Nota.Application;++namespace Nota.App;++public sealed partial class PianoRollView+{+ /// <summary>The controllers (<see cref="MidiController"/> ids) the active clip holds data+ /// for. Set by the host with <see cref="GetController"/> / <see cref="SetController"/>.</summary>+ public Func<int[]>? ControllersInClip { get; set; }+ /// <summary>The active clip's curve for a controller, in clip-local beats.</summary>+ public Func<int, AutomationPoint[]>? GetController { get; set; }+ /// <summary>Replaces the active clip's curve for a controller (empty clears it); one undo+ /// step. Without it the lane is view-only.</summary>+ public Action<int, AutomationPoint[]>? SetController { get; set; }++ private readonly ControllerLane _ctlLane;+ private int _laneCtl = -1; // −1 until the lane is first shown+ private readonly Dictionary<int, AutomationPoint[]> _ctlCache = new();+ private int[]? _ctlInClip;++ private static readonly int[] CommonControllers =+ { MidiController.Sustain, MidiController.ModWheel, MidiController.PitchWheel, MidiController.ChannelPressure, 11, 2 };++ // Every reload (undo, recording, another clip) and active-clip change re-reads the engine.+ private void DropControllerCache()+ {+ _ctlCache.Clear();+ _ctlInClip = null;+ }++ private int[] ControllersWithData()+ => _ctlInClip ??= (ControllersInClip?.Invoke() ?? Array.Empty<int>()).Where(c => !MidiController.IsReserved(c)).ToArray();++ private int DefaultController()+ {+ var d = ControllersWithData();+ return d.Length > 0 ? d[0] : MidiController.Sustain;+ }++ private AutomationPoint[] ControllerPoints(int ctl)+ {+ if (!_ctlCache.TryGetValue(ctl, out var p))+ _ctlCache[ctl] = p = GetController?.Invoke(ctl) ?? Array.Empty<AutomationPoint>();+ return p;+ }++ private void StoreController(int ctl, List<AutomationPoint> pts)+ {+ if (SetController is null) return;+ SetController(ctl, pts.ToArray());+ DropControllerCache();+ _ctlLane.InvalidateVisual();+ _laneTabs.InvalidateVisual();+ }++ /// <summary>"Mod wheel · CC 1", "CC 3", "Pitch wheel".</summary>+ private static string ControllerLabel(int ctl)+ {+ string n = MidiController.Name(ctl);+ return ctl >= 128 || n == $"CC {ctl}" ? n : $"{n} · CC {ctl}";+ }++ private void SelectController(int ctl)+ {+ _laneCtl = ctl;+ _ctlLane.ResetGesture();+ if (_laneMode != LaneMode.Controller) SetLaneMode(LaneMode.Controller);+ _ctlLane.InvalidateVisual();+ _laneTabs.InvalidateVisual();+ }++ /// <summary>The controller picker: what the clip holds first (marked), the common+ /// controllers, then every other CC in groups of 16.</summary>+ internal void ShowControllerPicker(Control anchor)+ {+ var f = new MenuFlyout();+ var data = ControllersWithData();+ MenuItem Item(int ctl, string header)+ {+ var it = new MenuItem { Header = header };+ if (Array.IndexOf(data, ctl) >= 0) it.Icon = MenuKit.Icon(GlyphKind.Automation);+ it.Click += (_, _) => SelectController(ctl);+ return it;+ }+ foreach (int c in data) f.Items.Add(Item(c, ControllerLabel(c)));+ if (data.Length > 0) f.Items.Add(new Separator());+ foreach (int c in CommonControllers)+ if (Array.IndexOf(data, c) < 0) f.Items.Add(Item(c, MidiController.Name(c)));+ f.Items.Add(new Separator());+ var other = new MenuItem { Header = "Other CC" };+ for (int g = 0; g < 128; g += 16)+ {+ var ctls = Enumerable.Range(g, 16).Where(c => !MidiController.IsReserved(c)).ToList();+ if (ctls.Count == 0) continue;+ var grp = new MenuItem { Header = $"CC {ctls[0]}–{ctls[^1]}" };+ foreach (int c in ctls)+ {+ string n = MidiController.Name(c);+ grp.Items.Add(Item(c, n == $"CC {c}" ? n : $"CC {c} — {n}"));+ }+ other.Items.Add(grp);+ }+ f.Items.Add(other);+ f.ShowAt(anchor);+ }++ // ---- the lane ------------------------------------------------------------------------++ private sealed class ControllerLane : Control+ {+ private readonly PianoRollView _o;+ public ControllerLane(PianoRollView o) { _o = o; }++ private const double Pad = 6, EdgePx = 5, PointPx = 7;+ private const double Eps = 1.0 / 1024; // beats: where a drawn stretch meets the old curve+ private static readonly IBrush BlockFill = NotaPalette.Wash(NotaPalette.VizInk, 0x40);+ private static readonly IBrush BlockFillLow = NotaPalette.Wash(NotaPalette.VizInk, 0x1C);+ private static readonly IBrush BlockHot = NotaPalette.Wash(NotaPalette.Accent, 0x70);+ private static readonly IPen BlockEdge = new Pen(NotaPalette.VizInk, 1.5);+ private static readonly IPen BlockEdgeHot = new Pen(NotaPalette.Accent, 1.5);++ private int Ctl => _o._laneCtl < 0 ? MidiController.Sustain : _o._laneCtl;+ private bool IsSwitch => MidiController.IsSwitch(Ctl);+ private bool Editable => _o.SetController is not null;++ private enum Drag { None, Draw, Point, NewBlock, MoveBlock, BlockStart, BlockEnd }+ private Drag _drag;+ private List<AutomationPoint>? _work; // the curve while a gesture reshapes it+ private List<AutomationPoint> _orig = new(); // ... and what it started from+ private readonly List<(double Beat, float Value)> _stroke = new();+ private bool _straight, _free;+ private int _pt = -1, _hoverPt = -1;+ private Block _grab;+ private double _anchor, _grabAt, _blockStart;+ private static readonly Cursor ResizeCursor = new(StandardCursorType.SizeWestEast);+ private static readonly Cursor MoveCursor = new(StandardCursorType.SizeAll);+ private int _hoverBlock = -1, _selBlock = -1;+ private double _hoverBeat = double.NaN;++ internal void ResetGesture()+ {+ _drag = Drag.None; _work = null; _stroke.Clear();+ _pt = _hoverPt = _hoverBlock = _selBlock = -1;+ }++ private IReadOnlyList<AutomationPoint> Cur => (IReadOnlyList<AutomationPoint>?)_work ?? _o.ControllerPoints(Ctl);++ // ---- time and value ----+ private double ClipLen => _o._set.ActiveClip.LengthBeats;+ private double Ed(double local) => _o._set.ToEditor(_o._set.Active, local);+ private double XOf(double local) => _o.BeatToX(Ed(local));+ private double LocalAt(double x) => _o._set.ToLocal(_o._set.Active, _o.XToBeat(x));+ private double SnapLocal(double local)+ => _free ? local : _o._set.ToLocal(_o._set.Active, _o.SnapBeat(Ed(local)));+ private double MinBlock => _free ? 1.0 / 32 : Math.Max(1.0 / 32, _o.SnapStep);++ private double ValueToY(float v)+ {+ var (lo, hi) = MidiController.Range(Ctl);+ double h = Bounds.Height;+ return h - Pad - (Math.Clamp(v, lo, hi) - lo) / (hi - lo) * (h - 2 * Pad);+ }++ private float YToValue(double y)+ {+ var (lo, hi) = MidiController.Range(Ctl);+ double h = Bounds.Height;+ float v = (float)Math.Clamp(lo + (h - Pad - y) / (h - 2 * Pad) * (hi - lo), lo, hi);+ if (Ctl == MidiController.PitchWheel && Math.Abs(v) < 0.02f) v = 0; // the wheel's centre+ return v;+ }++ private string Readout(float v)+ {+ if (IsSwitch) return v >= 0.5f ? "on" : "off";+ if (Ctl == MidiController.PitchWheel) return v == 0 ? "0" : v.ToString("+0.00;−0.00", NotaNum.Culture);+ return ((int)Math.Round(v * 127)).ToString(NotaNum.Culture);+ }++ // The engine's reading of a curve (ControllerCurve::valueAt): held before the first and+ // after the last point; a switch steps, the rest follow each point's shaping.+ private static float ValueAt(IReadOnlyList<AutomationPoint> p, double beat, bool sw)+ {+ if (p.Count == 0) return 0;+ if (beat <= p[0].Beat) return p[0].Value;+ if (beat >= p[^1].Beat) return p[^1].Value;+ int i = 1;+ while (p[i].Beat <= beat) i++;+ var a = p[i - 1]; var b = p[i];+ if (sw) return a.Value;+ double span = b.Beat - a.Beat;+ if (span <= 0) return b.Value;+ return (float)(a.Value + (b.Value - a.Value) * Shape((beat - a.Beat) / span, a.Curve));+ }++ private static double Shape(double t, float curve) => curve == 0f ? t : Math.Pow(t, Math.Pow(2.0, -curve * 4.0));++ // Sorted, the last point given for any one beat kept; a switch keeps only its changes.+ private List<AutomationPoint> Normalize(IEnumerable<AutomationPoint> pts)+ {+ var sorted = pts.Select((p, i) => (p, i)).OrderBy(t => t.p.Beat).ThenBy(t => t.i).Select(t => t.p).ToList();+ var outp = new List<AutomationPoint>(sorted.Count);+ foreach (var p in sorted)+ {+ if (outp.Count > 0 && Math.Abs(outp[^1].Beat - p.Beat) < 1e-9) { outp[^1] = p; continue; }+ if (IsSwitch && outp.Count > 0 && outp[^1].Value == p.Value) continue;+ outp.Add(p);+ }+ return outp;+ }++ // ---- switch blocks ----+ // A span where the value is at least half: its points [First, Off), ended by point Off+ // (−1: it holds to the clip's end).+ private readonly record struct Block(double Start, double End, int First, int Off);++ private List<Block> Blocks(IReadOnlyList<AutomationPoint> p)+ {+ var list = new List<Block>();+ int i = 0;+ while (i < p.Count)+ {+ if (p[i].Value < 0.5f) { i++; continue; }+ int first = i;+ while (i < p.Count && p[i].Value >= 0.5f) i++;+ bool ended = i < p.Count;+ list.Add(new Block(p[first].Beat, ended ? p[i].Beat : Math.Max(ClipLen, p[first].Beat), first, ended ? i : -1));+ }+ return list;+ }++ private static List<AutomationPoint> Without(IReadOnlyList<AutomationPoint> p, Block b)+ {+ int end = b.Off < 0 ? p.Count : b.Off;+ var outp = new List<AutomationPoint>(p.Count);+ for (int i = 0; i < p.Count; i++) if (i < b.First || i >= end) outp.Add(p[i]);+ return outp;+ }++ private static List<AutomationPoint> PointsOf(IReadOnlyList<AutomationPoint> p, Block b)+ {+ int end = b.Off < 0 ? p.Count : b.Off;+ var outp = new List<AutomationPoint>();+ for (int i = b.First; i < end; i++) outp.Add(p[i]);+ return outp;+ }++ // `rest` with [from, to) replaced by the points of `seg` inside it; from `to` on, the+ // value that was there before resumes (a block drawn over another merges with it).+ private List<AutomationPoint> Overwrite(List<AutomationPoint> rest, double from, double to, List<AutomationPoint> seg)+ {+ float tail = 0;+ foreach (var q in rest) if (q.Beat <= to) tail = q.Value;+ var outp = rest.Where(q => q.Beat < from).ToList();+ outp.AddRange(seg.Where(q => q.Beat >= from && q.Beat < to));+ if (to < ClipLen - 1e-9 || rest.Any(q => q.Beat > to)) outp.Add(new AutomationPoint(to, tail));+ outp.AddRange(rest.Where(q => q.Beat > to));+ return Normalize(outp);+ }++ private (int Block, int Edge) BlockAt(Point p)+ {+ var blocks = Blocks(Cur);+ for (int k = blocks.Count - 1; k >= 0; k--)+ {+ double x0 = XOf(blocks[k].Start), x1 = XOf(blocks[k].End);+ if (p.X < x0 - 2 || p.X > x1 + 2) continue;+ double zone = Math.Min(EdgePx, (x1 - x0) / 3);+ return (k, p.X <= x0 + zone ? -1 : p.X >= x1 - zone ? 1 : 0);+ }+ return (-1, 0);+ }++ // ---- curve points ----+ private int PointAt(Point p)+ {+ var c = Cur;+ double best = PointPx; int hit = -1;+ for (int k = 0; k < c.Count; k++)+ {+ double d = Math.Max(Math.Abs(XOf(c[k].Beat) - p.X), Math.Abs(ValueToY(c[k].Value) - p.Y));+ if (d < best) { best = d; hit = k; }+ }+ return hit;+ }++ // The stroke replaces the curve over the stretch it covers; outside it the curve keeps its+ // values (pinned at the stroke's edges); with nothing after it, the drawn value holds.+ private void ApplyStroke(List<(double Beat, float Value)> samples)+ {+ if (samples.Count == 0) return;+ samples.Sort((a, b) => a.Beat.CompareTo(b.Beat));+ double a = samples[0].Beat, b = samples[^1].Beat;+ var outp = _orig.Where(q => q.Beat < a - Eps).ToList();+ if (outp.Count > 0) outp.Add(new AutomationPoint(a - Eps, ValueAt(_orig, a - Eps, false)));+ foreach (var (sb, sv) in samples) outp.Add(new AutomationPoint(sb, sv));+ if (_orig.Any(q => q.Beat > b + Eps))+ {+ outp.Add(new AutomationPoint(b + Eps, ValueAt(_orig, b + Eps, false)));+ outp.AddRange(_orig.Where(q => q.Beat > b + Eps));+ }+ _work = Normalize(outp);+ }++ private List<(double Beat, float Value)> StrokeSamples()+ => _straight && _stroke.Count >= 2 ? new() { _stroke[0], _stroke[^1] } : new(_stroke);++ // Ramer–Douglas–Peucker over the drawn stroke only: recorded data around it is left as is.+ private static List<(double Beat, float Value)> Thin(List<(double Beat, float Value)> p, float tol)+ {+ if (p.Count <= 2) return p;+ var keep = new bool[p.Count];+ keep[0] = keep[^1] = true;+ var stack = new Stack<(int, int)>();+ stack.Push((0, p.Count - 1));+ while (stack.Count > 0)+ {+ var (a, b) = stack.Pop();+ if (b <= a + 1) continue;+ double worst = -1; int at = a;+ for (int i = a + 1; i < b; i++)+ {+ double span = p[b].Beat - p[a].Beat;+ double t = span > 0 ? (p[i].Beat - p[a].Beat) / span : 0;+ double dev = Math.Abs(p[i].Value - (p[a].Value + (p[b].Value - p[a].Value) * t));+ if (dev > worst) { worst = dev; at = i; }+ }+ if (worst > tol) { keep[at] = true; stack.Push((a, at)); stack.Push((at, b)); }+ }+ var outp = new List<(double, float)>();+ for (int i = 0; i < p.Count; i++) if (keep[i]) outp.Add(p[i]);+ return outp;+ }++ // ---- drawing ----+ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0) return;+ _o.EnsurePpb(w);+ ctx.FillRectangle(VelBg, new Rect(0, 0, w, h));+ _o.DrawGridLines(ctx, w, h);+ var c = Cur;++ if (!IsSwitch)+ {+ double yr = Math.Round(ValueToY(Ctl == MidiController.PitchWheel ? 0f : 0.5f)) + 0.5;+ ctx.DrawLine(Ctl == MidiController.PitchWheel ? ZeroPen : NeutralPen, new Point(0, yr), new Point(w, yr));+ }++ if (IsSwitch) DrawBlocks(ctx, c, h);+ else DrawCurve(ctx, c, w);++ _o.DrawOutsideClip(ctx, w, h);++ var name = new FormattedText(ControllerLabel(Ctl), NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.Sans, 9, LabelText);+ ctx.DrawText(name, new Point(4, 3));+ if (c.Count == 0 && Editable && _drag == Drag.None)+ {+ var hint = new FormattedText(IsSwitch ? "Drag to draw a block" : "Drag to draw", NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.Sans, 9, LabelText);+ ctx.DrawText(hint, new Point((w - hint.Width) / 2, (h - hint.Height) / 2));+ }+ if (!double.IsNaN(_hoverBeat) || _drag != Drag.None)+ {+ double beat = _drag == Drag.Point && _pt >= 0 && _pt < c.Count ? c[_pt].Beat : _hoverBeat;+ if (!double.IsNaN(beat) && (c.Count > 0 || _drag != Drag.None))+ {+ var ft = new FormattedText(Readout(ValueAt(c, beat, IsSwitch)), NotaNum.Culture, FlowDirection.LeftToRight, Mono, 9, KeyLabelHot);+ ctx.DrawText(ft, new Point(w - ft.Width - 4, 3));+ }+ }+ }++ private void DrawBlocks(DrawingContext ctx, IReadOnlyList<AutomationPoint> c, double h)+ {+ // Every stretch at its value: a half pedal is a half-height block, a value under+ // half a faint shade (the pedal is up there).+ for (int i = 0; i < c.Count; i++)+ {+ if (c[i].Value <= 0) continue;+ double end = i + 1 < c.Count ? c[i + 1].Beat : Math.Max(ClipLen, c[i].Beat);+ double x0 = XOf(c[i].Beat), x1 = XOf(end);+ double y = ValueToY(c[i].Value);+ ctx.FillRectangle(c[i].Value >= 0.5f ? BlockFill : BlockFillLow, new Rect(x0, y, Math.Max(1, x1 - x0), h - Pad - y));+ }+ var blocks = Blocks(c);+ for (int k = 0; k < blocks.Count; k++)+ {+ var b = blocks[k];+ double x0 = XOf(b.Start), x1 = XOf(b.End);+ bool hot = k == _hoverBlock || k == _selBlock;+ if (hot) ctx.FillRectangle(BlockHot, new Rect(x0, Pad, Math.Max(1, x1 - x0), h - 2 * Pad));+ var pen = hot ? BlockEdgeHot : BlockEdge;+ ctx.DrawLine(pen, new Point(x0 + 0.75, Pad), new Point(x0 + 0.75, h - Pad));+ ctx.DrawLine(pen, new Point(x1 - 0.75, Pad), new Point(x1 - 0.75, h - Pad));+ }+ }++ private void DrawCurve(DrawingContext ctx, IReadOnlyList<AutomationPoint> c, double w)+ {+ if (c.Count == 0) return;+ var line = new StreamGeometry();+ using (var g = line.Open())+ {+ g.BeginFigure(new Point(XOf(c[0].Beat), ValueToY(c[0].Value)), false);+ for (int i = 1; i < c.Count; i++)+ {+ var a = c[i - 1]; var b = c[i];+ if (a.Curve != 0)+ for (int s = 1; s < 12; s++)+ {+ double t = s / 12.0;+ g.LineTo(new Point(XOf(a.Beat + (b.Beat - a.Beat) * t), ValueToY((float)(a.Value + (b.Value - a.Value) * Shape(t, a.Curve)))));+ }+ g.LineTo(new Point(XOf(b.Beat), ValueToY(b.Value)));+ }+ g.LineTo(new Point(Math.Max(XOf(c[^1].Beat), XOf(ClipLen)), ValueToY(c[^1].Value)));+ g.EndFigure(false);+ }+ ctx.DrawGeometry(null, CurvePen, line);+ for (int k = 0; k < c.Count; k++)+ {+ double px = XOf(c[k].Beat);+ if (px < -4 || px > w + 4) continue;+ bool hot = k == _hoverPt || (_drag == Drag.Point && k == _pt);+ const double r = 2.5; // hover changes colour, not size+ ctx.FillRectangle(hot ? PointHot : PointFill, new Rect(px - r, ValueToY(c[k].Value) - r, r * 2, r * 2), 1);+ }+ }++ // ---- gestures ----+ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ var pt = e.GetCurrentPoint(this);+ var p = e.GetPosition(this);+ if (pt.Properties.IsRightButtonPressed)+ {+ if (Editable && Cur.Count > 0) ShowClearMenu();+ e.Handled = true;+ return;+ }+ if (!pt.Properties.IsLeftButtonPressed || !Editable) return;+ Focus();+ _free = (e.KeyModifiers & (KeyModifiers.Control | KeyModifiers.Meta)) != 0;+ double local = Math.Clamp(LocalAt(p.X), 0, ClipLen);+ _orig = Cur.ToList();++ if (IsSwitch)+ {+ var (k, edge) = BlockAt(p);+ if (e.ClickCount == 2)+ {+ if (k >= 0) DeleteBlock(k);+ e.Handled = true;+ return;+ }+ _selBlock = k;+ if (k >= 0)+ {+ _grab = Blocks(_orig)[k];+ _grabAt = local;+ _drag = edge < 0 ? Drag.BlockStart : edge > 0 ? Drag.BlockEnd : Drag.MoveBlock;+ }+ else+ {+ _anchor = SnapLocal(local);+ _drag = Drag.NewBlock;+ UpdateBlock(local);+ }+ }+ else+ {+ int hit = PointAt(p);+ if (e.ClickCount == 2)+ {+ var c = _orig;+ if (hit >= 0) c.RemoveAt(hit);+ else c.Add(new AutomationPoint(local, YToValue(p.Y)));+ _o.StoreController(Ctl, Normalize(c));+ e.Handled = true;+ return;+ }+ _stroke.Clear();+ if (hit >= 0) { _drag = Drag.Point; _pt = hit; _work = _orig.ToList(); }+ else+ {+ _drag = Drag.Draw;+ _straight = (e.KeyModifiers & KeyModifiers.Alt) != 0;+ _stroke.Add((local, YToValue(p.Y)));+ ApplyStroke(StrokeSamples());+ }+ }+ e.Pointer.Capture(this);+ InvalidateVisual();+ e.Handled = true;+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ var p = e.GetPosition(this);+ double local = Math.Clamp(LocalAt(p.X), 0, ClipLen);+ _hoverBeat = local;+ switch (_drag)+ {+ case Drag.Point:+ {+ var c = _work!;+ double lo = _pt > 0 ? c[_pt - 1].Beat + Eps : 0, hi = _pt < c.Count - 1 ? c[_pt + 1].Beat - Eps : ClipLen;+ c[_pt] = new AutomationPoint(Math.Clamp(local, Math.Min(lo, hi), hi), YToValue(p.Y), c[_pt].Curve);+ break;+ }+ case Drag.Draw:+ {+ var s = (local, YToValue(p.Y));+ if (_straight) { if (_stroke.Count > 1) _stroke[1] = s; else _stroke.Add(s); }+ else if (Math.Abs(XOf(_stroke[^1].Beat) - p.X) >= 1) _stroke.Add(s);+ ApplyStroke(StrokeSamples());+ break;+ }+ case Drag.NewBlock or Drag.MoveBlock or Drag.BlockStart or Drag.BlockEnd:+ UpdateBlock(local);+ break;+ default:+ {+ int hp = IsSwitch ? -1 : PointAt(p);+ var (hb, edge) = IsSwitch ? BlockAt(p) : (-1, 0);+ Cursor = hb < 0 ? Cursor.Default : edge != 0 ? ResizeCursor : MoveCursor;+ _hoverPt = hp; _hoverBlock = hb;+ break;+ }+ }+ InvalidateVisual();+ }++ // The block being drawn, moved or resized, laid over the curve it started from.+ private void UpdateBlock(double local)+ {+ double len = ClipLen;+ switch (_drag)+ {+ case Drag.NewBlock:+ {+ double at = SnapLocal(local);+ double s = Math.Min(_anchor, at), e = Math.Max(_anchor, at);+ if (e - s < MinBlock) e = s + MinBlock;+ _blockStart = s;+ _work = Overwrite(_orig, s, Math.Min(e, len), new List<AutomationPoint> { new(s, 1f) });+ break;+ }+ case Drag.MoveBlock:+ {+ double s = Math.Clamp(SnapLocal(_grab.Start + local - _grabAt), 0, Math.Max(0, len - MinBlock));+ double d = s - _grab.Start;+ _blockStart = s;+ var seg = PointsOf(_orig, _grab).Select(q => new AutomationPoint(q.Beat + d, q.Value, q.Curve)).ToList();+ _work = Overwrite(Without(_orig, _grab), s, Math.Min(_grab.End + d, len), seg);+ break;+ }+ case Drag.BlockStart:+ {+ // A recorded tap can be shorter than the grid, so the min-length bound can+ // sit left of 0. Clamping onto an inverted range throws; stay inside the block.+ double cap = _grab.End - MinBlock;+ double s = cap >= 0+ ? Math.Clamp(SnapLocal(local), 0, cap)+ : Math.Clamp(SnapLocal(local), 0, Math.Max(0, _grab.End));+ _blockStart = s;+ var pts = PointsOf(_orig, _grab);+ var seg = new List<AutomationPoint> { new(s, ValueAt(pts, s, true)) };+ seg.AddRange(pts.Where(q => q.Beat > s));+ _work = Overwrite(Without(_orig, _grab), s, _grab.End, seg);+ break;+ }+ case Drag.BlockEnd:+ {+ double lo = _grab.Start + MinBlock;+ double e = lo <= len+ ? Math.Clamp(SnapLocal(local), lo, len)+ : Math.Clamp(SnapLocal(local), _grab.Start, Math.Max(_grab.Start, len));+ _blockStart = _grab.Start;+ _work = Overwrite(Without(_orig, _grab), _grab.Start, e, PointsOf(_orig, _grab));+ break;+ }+ }+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ if (_drag == Drag.None) return;+ var was = _drag;+ _drag = Drag.None;+ e.Pointer.Capture(null);+ if (was == Drag.Draw)+ {+ var samples = StrokeSamples().OrderBy(s => s.Beat).ToList();+ // A click without a drag is not a stroke. Committing it would write a point+ // that the second press of a double-click then deletes.+ if (samples.Count < 2)+ _work = _orig.ToList();+ else if (!_straight)+ {+ // Thin to what the eye can tell apart: a pixel and a half of the lane's scale.+ float tol = Math.Abs(YToValue(Bounds.Height / 2) - YToValue(Bounds.Height / 2 + 1.5));+ ApplyStroke(Thin(samples, tol));+ }+ }+ var result = _work;+ _work = null; _stroke.Clear(); _pt = -1;+ if (result is null) return;+ if (IsSwitch) _selBlock = Blocks(result).FindIndex(b => b.Start <= _blockStart + 1e-9 && b.End > _blockStart);+ if (!result.SequenceEqual(_orig)) _o.StoreController(Ctl, result);+ InvalidateVisual();+ }++ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ if (_drag != Drag.None) { _drag = Drag.None; _work = null; _stroke.Clear(); InvalidateVisual(); }+ base.OnPointerCaptureLost(e);+ }++ protected override void OnPointerExited(PointerEventArgs e)+ {+ _hoverBeat = double.NaN;+ _hoverPt = _hoverBlock = -1;+ InvalidateVisual();+ }++ protected override void OnKeyDown(KeyEventArgs e)+ {+ if (IsSwitch && _selBlock >= 0 && (e.Key == Key.Delete || e.Key == Key.Back)) { DeleteBlock(_selBlock); e.Handled = true; return; }+ if (e.Key == Key.Escape && _selBlock >= 0) { _selBlock = -1; InvalidateVisual(); e.Handled = true; return; }+ base.OnKeyDown(e);+ }++ private void DeleteBlock(int k)+ {+ var c = Cur.ToList();+ var blocks = Blocks(c);+ if (k < 0 || k >= blocks.Count) return;+ _selBlock = -1;+ _o.StoreController(Ctl, Normalize(Without(c, blocks[k])));+ }++ private void ShowClearMenu()+ {+ int ctl = Ctl;+ ClipEditorKit.ShowMenu(this, new[] { $"Clear {MidiController.Name(ctl)}" }, -1, _ =>+ {+ _selBlock = -1;+ _o.StoreController(ctl, new List<AutomationPoint>());+ });+ }+ }+}diff --git a/src/managed/Nota.App/PianoRollView.Expression.cs b/src/managed/Nota.App/PianoRollView.Expression.csindex e1874d3c..00995f7a 100644--- a/src/managed/Nota.App/PianoRollView.Expression.cs+++ b/src/managed/Nota.App/PianoRollView.Expression.cs@@ -30,7 +30,7 @@ public sealed partial class PianoRollView/// host; without it the MPE lanes are view-only.</summary>public Func<NotaExprPoint[], int>? CreateExpression { get; set; }- internal enum LaneMode { Velocity, Bend, Pressure, Slide }+ internal enum LaneMode { Velocity, Bend, Pressure, Slide, Controller }private const double ExprH = 112; // the MPE lanes are taller: a curve needs the roomprivate readonly ExpressionLane _expr;@@ -53,7 +53,8 @@ public sealed partial class PianoRollView{if (m == _laneMode) return;_laneMode = m;- _velHost.Child = m == LaneMode.Velocity ? _vel : _expr;+ if (m == LaneMode.Controller && _laneCtl < 0) _laneCtl = DefaultController();+ _velHost.Child = m switch { LaneMode.Velocity => _vel, LaneMode.Controller => _ctlLane, _ => _expr };_laneRow.Height = m == LaneMode.Velocity ? VelH : ExprH;Invalidate();_laneTabs.InvalidateVisual();@@ -131,17 +132,32 @@ public sealed partial class PianoRollViewreturn c[^1].Value;}- // ---- the gutter: VEL · BEND · PRES · SLIDE -----------------------------------------------+ // ---- the gutter: VEL · BEND · PRES · SLIDE · <controller> ----------------------------------private sealed class LaneTabs : Control{private static readonly (LaneMode Mode, string Label)[] Tabs =- { (LaneMode.Velocity, "Vel"), (LaneMode.Bend, "Bend"), (LaneMode.Pressure, "Pres"), (LaneMode.Slide, "Slide") };- private const double Top = 6, RowStep = 15;+ { (LaneMode.Velocity, "Vel"), (LaneMode.Bend, "Bend"), (LaneMode.Pressure, "Pres"), (LaneMode.Slide, "Slide"), (LaneMode.Controller, "") };+ // Five rows fit the velocity lane's 72 px.+ private const double Top = 4, RowStep = 13;+ private const double ChevronW = 7;+ private static readonly Typeface TabFace = new(NotaFonts.Mono.FontFamily, FontStyle.Normal, FontWeight.Bold);private readonly PianoRollView _o;private int _hover = -1;public LaneTabs(PianoRollView o) { _o = o; Cursor = new Cursor(StandardCursorType.Hand); }+ private FormattedText Text(string s, IBrush ink) => new(s, NotaNum.Culture, FlowDirection.LeftToRight, TabFace, 9, ink);++ // The controller tab names the controller when it fits beside the picker chevron.+ private FormattedText ControllerLabel(IBrush ink)+ {+ int ctl = _o._laneCtl >= 0 ? _o._laneCtl : _o.DefaultController();+ var ft = Text(MidiController.ShortName(ctl), ink);+ if (ft.Width <= Bounds.Width - ChevronW - 6) return ft;+ ft = Text(ctl < 128 ? $"CC{ctl}" : "CC", ink);+ return ft.Width <= Bounds.Width - ChevronW - 6 ? ft : Text("CC", ink);+ }+public override void Render(DrawingContext ctx){ctx.FillRectangle(Brushes.Transparent, new Rect(Bounds.Size));@@ -149,10 +165,17 @@ public sealed partial class PianoRollView{bool on = Tabs[i].Mode == _o._laneMode;var ink = on ? TabActive : i == _hover ? KeyLabelHot : LabelText;- var ft = new FormattedText(Tabs[i].Label, NotaNum.Culture, FlowDirection.LeftToRight,- new Typeface(NotaFonts.Mono.FontFamily, FontStyle.Normal, FontWeight.Bold), 9, ink);+ bool ctl = Tabs[i].Mode == LaneMode.Controller;+ var ft = ctl ? ControllerLabel(ink) : Text(Tabs[i].Label, ink);double y = Top + i * RowStep;- ctx.DrawText(ft, new Point((Bounds.Width - ft.Width) / 2, y));+ double x = (Bounds.Width - ft.Width - (ctl ? ChevronW : 0)) / 2;+ ctx.DrawText(ft, new Point(x, y));+ if (ctl)+ {+ // The caret marks that the tab opens the controller picker.+ double cx = x + ft.Width + 2;+ Glyph.Draw(ctx, GlyphKind.CaretDown, new Rect(cx, y + (ft.Height - 6) / 2, 6, 6), ink);+ }if (on) ctx.FillRectangle(TabActive, new Rect(0, y + 1, 2, ft.Height - 2));}}@@ -167,7 +190,8 @@ public sealed partial class PianoRollView{int i = RowAt(e.GetPosition(this));if (i < 0 || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;- _o.SetLaneMode(Tabs[i].Mode);+ if (Tabs[i].Mode == LaneMode.Controller && _o._laneMode == LaneMode.Controller) _o.ShowControllerPicker(this);+ else _o.SetLaneMode(Tabs[i].Mode);e.Handled = true;}diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex 89a96422..0d3345b0 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -401,6 +401,7 @@ public sealed partial class PianoRollView : UserControl_gridControl = new NoteGrid(this) { Height = RangeH, ClipToBounds = true };_vel = new VelocityLane(this) { ClipToBounds = true };_expr = new ExpressionLane(this) { ClipToBounds = true };+ _ctlLane = new ControllerLane(this) { ClipToBounds = true, Focusable = true };_velHost = new Border { BorderBrush = Divider, BorderThickness = new Thickness(0, 1, 0, 0), Child = _vel };// Body: keys pinned left, grid fills; both scroll vertically together.@@ -739,6 +740,7 @@ public sealed partial class PianoRollView : UserControlSettlePlacement();if (!_set.SetActive(slot)) return;_trackBrush = slot < _slotBrushes.Count ? _slotBrushes[slot] : _trackBrush;+ DropControllerCache();Invalidate();ActiveClipChanged?.Invoke();Changed?.Invoke();@@ -767,7 +769,43 @@ public sealed partial class PianoRollView : UserControl{_previewBackup = null;_placementPending = false; // a reload (undo, recording, another clip) is the truth now+ // A Session slot has no live path, so a velocity-wheel burst lives only in _notes until+ // the idle timer commits it. Recording reloads this roll ~60 Hz; dropping the burst+ // here would throw those edits away. Keep them across that reload of the same clip.+ // Undo and redo close the burst first (EndVelocityWheel), so this reload is the+ // engine's notes and the next wheel opens its own undo step. A different clip+ // commits first, then loads.+ List<(int Pitch, double Start, float Velocity)>? burstVel = null;+ bool sameClip = _clipKey.Item1 != int.MinValue && _clipKey == _loadedKey;+ if (!_velWheelBurst || !sameClip)+ {+ EndVelocityWheel(); // a Session slot commits it before the notes are replaced+ }+ else if (!HasLivePath)+ {+ burstVel = new(_notes.Count);+ for (int i = 0; i < _notes.Count; i++)+ burstVel.Add((_notes[i].Pitch, _notes[i].StartBeat, _notes[i].Velocity));+ }+ DropControllerCache();ReplaceAll(notes, owners);+ if (burstVel is not null)+ {+ var used = new bool[burstVel.Count];+ for (int i = 0; i < _notes.Count; i++)+ {+ var n = _notes[i];+ for (int k = 0; k < burstVel.Count; k++)+ {+ if (used[k]) continue;+ var (pitch, start, vel) = burstVel[k];+ if (pitch != n.Pitch || Math.Abs(start - n.StartBeat) > 1e-4) continue;+ used[k] = true;+ if (vel != n.Velocity) { n.Velocity = vel; _notes[i] = n; }+ break;+ }+ }+ }_lengthBeats = lengthBeats;_selection.Clear();_strip.Relayout();@@ -1117,6 +1155,9 @@ public sealed partial class PianoRollView : UserControl/// undo step — every editable clip goes.</summary>private void CommitNotes(IReadOnlyList<NotaNote>? notes = null, IReadOnlyList<int>? owners = null, bool seed = false){+ // Backstop: an edit that did not close the velocity burst first must not leave the+ // timer to commit it again later, nor fold it silently into this edit unannounced.+ if (_velWheelBurst && !HasLivePath) EndVelocityWheel();_previewBackup = null;_previewOwners = null;notes ??= _notes;@@ -1335,6 +1376,75 @@ public sealed partial class PianoRollView : UserControlreturn true;}+ // ---- Shift + wheel velocity (specs/063) ---------------------------------------+ /// <summary>The wheel's direction and steps-per-notch multiplier (0–2, 0 = off). App-wide,+ /// seeded from and saved to Settings by the host, like <see cref="AuditionEnabled"/>.</summary>+ public static bool VelocityWheelReversed { get; set; }+ public static double VelocityWheelMultiplier { get; set; } = 1.0;++ // Wheel moves closer together than this are one edit, one undo step.+ private static readonly TimeSpan VelocityWheelIdle = TimeSpan.FromMilliseconds(600);+ private readonly VelocityWheel _velWheel = new();+ private DispatcherTimer? _velWheelTimer;+ private bool _velWheelBurst;+ private int _velWheelNote = -1;++ /// <summary>Steps the velocity of note <paramref name="hit"/> — or of the whole selection+ /// when it is selected — for a wheel move of <paramref name="notches"/>. False when there+ /// is no editable note there or the gesture is off: the wheel scrolls instead.</summary>+ internal bool WheelVelocity(int hit, double notches)+ {+ if (hit < 0 || hit >= _notes.Count || IsLocked(hit) || !VelocityWheel.Enabled(VelocityWheelMultiplier)) return false;+ int steps = _velWheel.Steps(notches, VelocityWheelReversed, VelocityWheelMultiplier);+ if (steps != 0)+ {+ var targets = _selection.Contains(hit)+ ? _selection.Where(i => i >= 0 && i < _notes.Count && !IsLocked(i)).ToList()+ : new List<int> { hit };+ // Notes already at 1 or 127 do not move: nothing to edit, so no empty undo step.+ bool changed = targets.Any(i => NoteOverwrite.VelocityBy(_notes[i].Velocity, steps) != _notes[i].Velocity);+ if (changed && !_velWheelBurst)+ {+ // The burst's undo step: seeded with the notes before it, like a note drag.+ _velWheelBurst = true;+ if (HasLivePath) CommitNotes(_notes.ToList(), _owner.ToList(), seed: true);+ }+ if (changed)+ {+ foreach (int i in targets)+ {+ var n = _notes[i];+ n.Velocity = NoteOverwrite.VelocityBy(n.Velocity, steps);+ _notes[i] = n;+ }+ _velWheelNote = hit;+ if (HasLivePath) PushLive(_notes, _owner);+ Invalidate(); Changed?.Invoke();+ }+ }+ if (_velWheelTimer is null)+ {+ _velWheelTimer = new DispatcherTimer { Interval = VelocityWheelIdle };+ _velWheelTimer.Tick += (_, _) => EndVelocityWheel();+ }+ _velWheelTimer.Stop();+ _velWheelTimer.Start();+ return true;+ }++ /// <summary>Closes the open velocity burst. A Session slot commits it (one undo step);+ /// an arrangement clip already seeded that step. Call before Undo or Redo so the reload+ /// does not keep the burst open — the next wheel must checkpoint on its own.</summary>+ internal void EndVelocityWheel()+ {+ _velWheelTimer?.Stop();+ _velWheel.Reset();+ if (!_velWheelBurst) return;+ _velWheelBurst = false;+ if (!HasLivePath) CommitNotes(); // a Session slot: the burst lands as one push+ Remember(_velWheelNote);+ }+// ---- pending placement (specs/007-midi-note-editing) -------------------------// Notes moved, stretched, drawn or pasted overwrite same-pitch notes they land on, but// only once the selection is let go: until then the notes underneath stay whole and are@@ -1361,6 +1471,7 @@ public sealed partial class PianoRollView : UserControl/// before save/export. Returns true when notes were cut or removed (indices may have shifted).</summary>public bool SettlePlacement(){+ EndVelocityWheel(); // every edit starts here: the wheel's burst is its own undo stepif (!_placementPending) return false;_placementPending = false;if (_selection.Count == 0) return false;@@ -1470,6 +1581,7 @@ public sealed partial class PianoRollView : UserControl_gridControl.InvalidateVisual();_vel.InvalidateVisual();_expr.InvalidateVisual();+ _ctlLane.InvalidateVisual();NotifyGrid();}@@ -2142,6 +2254,7 @@ public sealed partial class PianoRollView : UserControl{Focus();if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ _o.EndVelocityWheel(); // a press starts a new edit: close the wheel's burst firstvar p = e.GetPosition(this);_free = (e.KeyModifiers & KeyModifiers.Alt) != 0;bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;@@ -2488,8 +2601,9 @@ public sealed partial class PianoRollView : UserControl}// ⌘⌥/Ctrl+Alt+wheel zooms rows around the pitch under the cursor; ⌘/Ctrl+wheel zooms- // time toward the cursor; Shift+wheel scrolls horizontally; plain wheel is left to- // the body ScrollViewer for vertical key navigation.+ // time toward the cursor; Shift+wheel changes velocity over a note and scrolls+ // horizontally elsewhere; plain wheel is left to the body ScrollViewer for vertical+ // key navigation.protected override void OnPointerWheelChanged(PointerWheelEventArgs e){var mods = e.KeyModifiers;@@ -2505,7 +2619,10 @@ public sealed partial class PianoRollView : UserControl}else if ((mods & KeyModifiers.Shift) != 0){- _o.ScrollByBeats(-WheelInput.Pixels(e.Delta.Y) / _o.PixelsPerBeat);+ // Over a note, Shift+wheel steps its velocity (specs/063); elsewhere it scrolls.+ double d = Math.Abs(e.Delta.Y) >= Math.Abs(e.Delta.X) ? e.Delta.Y : e.Delta.X;+ if (!_o.WheelVelocity(HitTest(e.GetPosition(this), out _), WheelInput.Notches(d)))+ _o.ScrollByBeats(-WheelInput.Pixels(e.Delta.Y) / _o.PixelsPerBeat);e.Handled = true;}else if (Math.Abs(e.Delta.X) > Math.Abs(e.Delta.Y))@@ -2687,6 +2804,7 @@ public sealed partial class PianoRollView : UserControlprotected override void OnPointerPressed(PointerPressedEventArgs e){if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ _o.EndVelocityWheel(); // a press starts a new edit: close the wheel's burst firstvar p = e.GetPosition(this);int hit = Nearest(p);if (hit < 0) return;diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex c7c887a7..c41ec80e 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1449,6 +1449,7 @@ public sealed partial class PreferencesWindow : NotaWindow("⇧↑ ⇧↓", "Transpose by an octave"),("⇧← ⇧→", "Shorten / lengthen the notes by the grid"),("⌥↑ ⌥↓", "Velocity +10 / −10 · ⌥⇧ by 1"),+ ("⇧ + wheel over a note", "Change its velocity · the whole selection's when the note is selected · elsewhere scroll sideways"),("⌘A", "Select all notes"),("⌘D", "Duplicate the selection · replaces the notes it lands on"),("⌘C ⌘X ⌘V", "Copy / cut / paste notes · paste lands on the originals"),@@ -1462,6 +1463,9 @@ public sealed partial class PreferencesWindow : NotaWindow("Drag velocity stem", "Set velocity · selected notes move together · ⇧ adds a note"),("Drag in the Bend / Pres / Slide lane", "Draw the selected note's MPE curve · ⌥ draws a straight line · drag a point to move it"),("Double-click in an MPE lane", "Add a point · on a point, delete it · right-click to clear the curve"),+ ("Click the controller tab", "Show a MIDI controller under the notes · click it again to pick another CC, the pitch wheel or channel pressure"),+ ("Drag in the Sustain lane", "Draw a pedal block on the grid · ⌘ off the grid · drag an edge to resize, the body to move · double-click or Delete removes it"),+ ("Drag in a controller lane", "Draw the controller's curve · ⌥ draws a straight line · drag a point to move it · double-click adds or deletes a point"),("Click a clip in the clip strip", "Make it the active clip (several clips open) · its lock keeps it as a read-only reference"),("⌘⌥ + wheel", "Zoom rows (vertical zoom)"),("Click a key", "Play it on the track's instrument · ⇧-drag glides through the keys · ⌘-click selects every note of that pitch"),@@ -1582,7 +1586,40 @@ public sealed partial class PreferencesWindow : NotaWindowfilter.TextChanged += (_, _) => { _shortcutFilter = filter.Text ?? ""; Render(); };Render();- return new StackPanel { Spacing = 18, Children = { SearchField(filter, 320), groups } };+ return new StackPanel { Spacing = 18, Children = { VelocityWheelSection(), SearchField(filter, 320), groups } };+ }++ private static readonly double[] VelocityWheelSteps = { 0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 };++ // ⇧ + wheel over a piano-roll note (specs/063): its direction and step, beside the reference.+ private Control VelocityWheelSection()+ {+ var settings = App.Services.GetService<ISettingsService>();+ var step = Combo(150);+ foreach (var m in VelocityWheelSteps) step.Items.Add(m == 0 ? "Off" : $"{m.ToString("0.##", NotaNum.Culture)}×");+ int idx = Array.FindIndex(VelocityWheelSteps, m => Math.Abs(m - PianoRollView.VelocityWheelMultiplier) < 1e-6);+ step.SelectedIndex = idx >= 0 ? idx : Array.IndexOf(VelocityWheelSteps, 1.0);+ step.SelectionChanged += (_, _) =>+ {+ int k = step.SelectedIndex;+ if (k < 0) return;+ PianoRollView.VelocityWheelMultiplier = VelocityWheelSteps[k];+ if (settings is null) return;+ settings.Current.PianoRollVelocityWheelMultiplier = VelocityWheelSteps[k];+ settings.Save();+ };+ var reverse = SwitchRow("Wheel up lowers the velocity", PianoRollView.VelocityWheelReversed, on =>+ {+ PianoRollView.VelocityWheelReversed = on;+ if (settings is null) return;+ settings.Current.PianoRollVelocityWheelReversed = on;+ settings.Save();+ });+ return Section("Velocity wheel", 8,+ Row("Direction", reverse),+ Row("Step", step),+ Row("", Caption("⇧ + wheel over a note in the piano roll changes its velocity, or the whole selection's when that note is selected: " ++ "one MIDI step per notch at 1×. Anywhere else ⇧ + wheel scrolls, and Off leaves it scrolling everywhere.")));}private static readonly HashSet<string> NamedKeys = new(StringComparer.Ordinal) { "Space", "Return", "Delete", "Tab", "Esc", "PgUp", "PgDn", "⌘Return", "⌥Return", "⇧Return", "⇧Tab", "⇧Space" };diff --git a/src/managed/Nota.Application/Editing/VelocityWheel.cs b/src/managed/Nota.Application/Editing/VelocityWheel.csnew file mode 100644index 00000000..c7f094d8--- /dev/null+++ b/src/managed/Nota.Application/Editing/VelocityWheel.cs@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Shift + wheel over a note in the piano roll steps its velocity (specs/063): one MIDI step+// per wheel notch at 1×, scaled by the user's multiplier (0–2×) and flipped by the direction+// setting. A trackpad sends fractions of a notch; they carry over, so a slow swipe still steps.++using System;++namespace Nota.Application.Editing;++public sealed class VelocityWheel+{+ public const double MaxMultiplier = 2.0;+ // One event never moves more than this many notches (a trackpad's momentum burst).+ private const double MaxNotchesPerEvent = 2.0;++ private double _carry;++ public static double ClampMultiplier(double m) => double.IsFinite(m) ? Math.Clamp(m, 0, MaxMultiplier) : 1.0;++ /// <summary>Whether the gesture does anything: a 0× multiplier turns it off.</summary>+ public static bool Enabled(double multiplier) => ClampMultiplier(multiplier) > 0;++ /// <summary>Whole velocity steps (1/127) for a wheel move of <paramref name="notches"/>+ /// (+ up); the fraction left over waits for the next move.</summary>+ public int Steps(double notches, bool reversed, double multiplier)+ {+ if (!double.IsFinite(notches)) return 0;+ double n = Math.Clamp(notches, -MaxNotchesPerEvent, MaxNotchesPerEvent);+ _carry += n * ClampMultiplier(multiplier) * (reversed ? -1 : 1);+ int steps = (int)Math.Truncate(_carry + Math.Sign(_carry) * 1e-9);+ _carry -= steps;+ return steps;+ }++ /// <summary>Drops the carried fraction: a new burst starts from a whole step.</summary>+ public void Reset() => _carry = 0;+}diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.csindex 3be6361a..24f10492 100644--- a/src/managed/Nota.Application/Settings.cs+++ b/src/managed/Nota.Application/Settings.cs@@ -172,6 +172,12 @@ public sealed class Settings/// <summary>Piano-roll note audition (#46): notes sound while they are placed, clicked or/// dragged. The speaker chip in the clip editor's header; on by default.</summary>public bool PianoRollAudition { get; set; } = true;+ /// <summary>Shift + wheel over a note in the piano roll (specs/063): false — wheel up raises+ /// the velocity; true — wheel up lowers it.</summary>+ public bool PianoRollVelocityWheelReversed { get; set; }+ /// <summary>Velocity steps per wheel notch, 0–2 (<see cref="Editing.VelocityWheel"/>); 0 turns+ /// the gesture off and Shift + wheel only scrolls.</summary>+ public double PianoRollVelocityWheelMultiplier { get; set; } = 1.0;/// <summary>Clip editor track mode (specs/059, #49): the piano roll shows every MIDI clip of/// the edited track on the arrangement's timeline. The Clip | Track switch at the top of/// the clip editor's inspector; off (clip mode) by default.</summary>diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex c6c79b67..12e2ca60 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -281,6 +281,14 @@ if (args.Length >= 1 && args[0] == "--tap")Console.WriteLine(failures == 0 ? "TAP PASSED" : $"TAP FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Piano-roll velocity wheel alone: `--velocity-wheel`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--velocity-wheel")+{+ Console.WriteLine("-- velocity wheel --");+ foreach (var (ok, label) in VelocityWheelTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "VELOCITY WHEEL PASSED" : $"VELOCITY WHEEL FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Filter knob glide alone: `--glide`. Also part of the full run.if (args.Length >= 1 && args[0] == "--glide"){@@ -15284,6 +15292,8 @@ foreach (var (ok, label) in RenderPoolTests.Run()) Check(ok, label);Console.WriteLine("-- tap tempo --");foreach (var (ok, label) in TapTempoTests.Run()) Check(ok, label);+Console.WriteLine("-- velocity wheel --");+foreach (var (ok, label) in VelocityWheelTests.Run()) Check(ok, label);Console.WriteLine("-- status bar audio format --");foreach (var (ok, label) in AudioFormatStatusTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/VelocityWheelTests.cs b/tests/Nota.SmokeTest/VelocityWheelTests.csnew file mode 100644index 00000000..010cf3f5--- /dev/null+++ b/tests/Nota.SmokeTest/VelocityWheelTests.cs@@ -0,0 +1,50 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Shift + wheel velocity steps in the piano roll (specs/063): direction, the 0–2× multiplier,+// trackpad fractions carried over, the per-event cap, and the 1–127 clamp the steps land in.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --velocity-wheel`.++using Nota.Application.Editing;++namespace Nota.SmokeTest;++internal static class VelocityWheelTests+{+ private static int Sum(VelocityWheel w, double notches, int events, bool reversed, double mult)+ {+ int s = 0;+ for (int i = 0; i < events; i++) s += w.Steps(notches, reversed, mult);+ return s;+ }++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ var w = new VelocityWheel();+ yield return (w.Steps(1, false, 1) == 1, "one notch up at 1× raises by one step");+ yield return (w.Steps(-1, false, 1) == -1, "one notch down at 1× lowers by one step");+ yield return (w.Steps(1, true, 1) == -1 && w.Steps(-1, true, 1) == 1, "reversed flips both directions");+ yield return (w.Steps(1, false, 2) == 2, "2× moves two steps per notch");+ yield return (w.Steps(1, false, 5) == 2, "the multiplier is capped at 2×");+ yield return (w.Steps(1, false, 0) == 0 && !VelocityWheel.Enabled(0) && VelocityWheel.Enabled(0.25), "0× is off");++ w = new VelocityWheel();+ yield return (Sum(w, 1, 4, false, 0.5) == 2, "0.5× steps once every two notches");++ w = new VelocityWheel();+ int first = w.Steps(0.3, false, 1);+ yield return (first == 0 && Sum(w, 0.3, 3, false, 1) == 1, "trackpad fractions carry until a whole step");++ w = new VelocityWheel();+ w.Steps(0.6, false, 1);+ w.Reset();+ yield return (w.Steps(0.6, false, 1) == 0, "a reset drops the carried fraction");++ w = new VelocityWheel();+ yield return (w.Steps(40, false, 2) == 4, "one event moves at most two notches");++ yield return (NoteOverwrite.VelocityBy(127 / 127f, 3) == 1f, "steps above 127 clamp at 127");+ yield return (NoteOverwrite.VelocityBy(2 / 127f, -5) == 1 / 127f, "steps below 1 clamp at 1");+ yield return (NoteOverwrite.VelocityBy(64 / 127f, 2) == 66 / 127f, "a step is one MIDI velocity value");+ }+}