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) Adaptive snap grid
Egor Khindikaynenfd7e98f5e859
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 460fa4ce..c2dfd2ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,8 +28,24 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.comes back when you leave full screen. The window stays as it was in normal andmaximized states. On Windows and Linux a new **View → Toggle Full Screen** command(shortcut **F11**) enters and leaves full screen; on macOS the green button does it.+- **Adaptive snap grid:** the arrangement and the piano roll now snap to the grid you see.+ In **Auto** (the new default) the step follows the zoom — zoom in for eighths and+ sixteenths, zoom out and clips move by whole bars — with **Narrow / Medium / Wide**+ density. A fixed step (1/32 … 4 bars) stays put at any zoom; when it is finer than the+ drawn lines, its label dims. **Triplets** work in both modes and both editors. New+ shortcuts act on the editor you used last: **⌘1 / ⌘2** narrow / widen the grid (in Auto,+ the density), **⌘3** triplets, **⌘4** snap on / off, **⌘5** Auto ↔ fixed (Ctrl on+ Windows and Linux; also under **Edit → Grid**). The settings are remembered app-wide,+ separately for each editor. Holding **⌥ / Alt** while dragging now moves notes freely+ in the piano roll too.### Changed+- **Grid controls:** clicking the toolbar's GRID cell (and the new grid chip in the piano+ roll's header) opens a menu with every grid option instead of cycling through five+ values. The arrangement now draws sub-beat lines when zoomed in. The piano roll's GRID+ section is now **QUANTIZE**: Quantize and the clip tools use their own step (1/16 by+ default, triplets available), which no longer changes with the zoom. Press **⌘5** to go+ back to a fixed grid.- **Drops select their track:** dropping an instrument, effect, preset, sample or MIDI filefrom the browser selects the track it landed on — a newly created track included — inboth the arrangement and the session view. Moving clips to another track, or dropping adiff --git a/FEATURES.md b/FEATURES.mdindex b6194ea6..fa37c726 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -79,7 +79,7 @@ Three top-level views, switched from the toolbar (**Arrangement · Session · Mothe mixer opens as a separate floating window (**View → Mixer**, ⌘M).- **Arrangement View** — a linear timeline, floating on the app ground as its own island:- place, move, trim and duplicate clips; grid and snap to bars/beats; scroll and zoom;+ place, move, trim and duplicate clips; the snap grid (below); scroll and zoom;recording into the arrangement (audio and MIDI); split at the cursor or across aselection (Cmd/Ctrl+E cuts every track in the selection); clip scrubbing on the ruler.⌘A selects every clip; moving several selected clips is one undo step.@@ -102,6 +102,14 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).and the name prints only at the head of each run so a repeated pattern reads as oneblock. View ▸ Clip names cycles every clip / first of a run / none; a clip named byhand always shows its name.+- **Snap grid** (arrangement and piano roll, each with its own setting, remembered+ app-wide): **Auto** follows the zoom so you snap to the lines you see — finer as you zoom+ in, whole bars zoomed out — in **Narrow / Medium / Wide** density; or a fixed step from+ 1/32 to 4 bars (its label dims when it is finer than the drawn lines). **Triplets** in+ both modes. The toolbar's GRID cell and the piano roll's header chip open a menu with+ every option; ⌘1 / ⌘2 narrow / widen (in Auto, the density), ⌘3 triplets, ⌘4 snap+ on / off, ⌘5 Auto ↔ fixed (also Edit → Grid), acting on the editor used last. Hold ⌥ to+ drag freely; clip edges still attract a dragged clip.- **Session View** — a clip grid (tracks × scenes) with an inspector: named, coloured clipswith note / waveform previews and a progress pie on the clip's own clock; selection apartfrom launching, keyboard editing (arrows, Return, ⌘C/X/V, ⌘D, ⌘I, F2, Delete) and drag@@ -163,8 +171,9 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).## MIDI and virtual instruments- **MIDI clip**: notes (pitch, start, length, velocity).-- **Piano Roll**: draw, move, stretch and delete notes; quantization; grid length; a- velocity editor; transposing the selection.+- **Piano Roll**: draw, move, stretch and delete notes on the snap grid; **QUANTIZE** with+ its own step (1/32 … 1/2, triplets; independent of the zoom) and strength; a velocity+ editor; transposing the selection.- Drag a note's left edge to move its start (the end stays put); stacked notes keepseparate velocity stems (grab a stem by its cap, ⇧-click to add it to the selection).- ⌘D duplicates notes over whatever they land on, like clips in the arrangement.diff --git a/specs/003-adaptive-snap-grid/checklists/requirements.md b/specs/003-adaptive-snap-grid/checklists/requirements.mdnew file mode 100644index 00000000..ec4d8a18--- /dev/null+++ b/specs/003-adaptive-snap-grid/checklists/requirements.md@@ -0,0 +1,39 @@+# Specification Quality Checklist: Adaptive Snap Grid++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-13+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs)+- [x] Focused on user value and business needs+- [x] Written for non-technical stakeholders+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic (no implementation details)+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] No implementation details leak into specification++## Notes++- The "Current state" block under Nota Context names existing behaviour, not a design.+ Shortcut keys (⌘1–⌘5) and pixel thresholds are user-facing behaviour, so they are kept.+- Defaults chosen without asking (documented in Assumptions): settings are app-wide rather+ than per project, each editor has its own grid setting, the ladder is 1/32 … 4 bars+ (1/64 dropped), and Medium is the default density. Each one can be revisited in+ `/speckit-clarify`.diff --git a/specs/003-adaptive-snap-grid/contracts/grid-ui.md b/specs/003-adaptive-snap-grid/contracts/grid-ui.mdnew file mode 100644index 00000000..35d3eb2e--- /dev/null+++ b/specs/003-adaptive-snap-grid/contracts/grid-ui.md@@ -0,0 +1,99 @@+# UI Contract: Snap Grid Controls and Commands++What the user and the command palette can rely on. The palette smoke test checks the+catalog side of this contract: every id is bound and every shortcut is listed in+Settings → Shortcuts.++## Catalog commands (`CommandCatalog`, category "Grid")++| Id | Title | Gesture | Aliases |+|----|-------|---------|---------|+| `grid.narrower` | Narrow Grid | ⌘1 | finer smaller snap |+| `grid.wider` | Widen Grid | ⌘2 | coarser larger snap |+| `grid.triplets` | Toggle Triplet Grid | ⌘3 | triplet 1/8T swing |+| `grid.snap` | Toggle Snap to Grid | ⌘4 | magnet free |+| `grid.adaptive` | Toggle Adaptive Grid | ⌘5 | auto zoom fixed |++- ⌘ means Cmd on macOS and Ctrl on Windows and Linux (`Commands.Parse`).+- Target editor (research R9): the piano roll if the detail area was used last and a+ MIDI clip editor is showing, otherwise the arrangement.+- Each command sets the status line to `"<Editor> grid: <control label>"`, for example+ "Arrangement grid: Auto · 1/4" or "Piano roll grid: Snap off" (FR-014).+- The commands are always available; the palette never greys them out.+- Menu: Edit → Grid submenu with the five items, in this order.++## Settings → Shortcuts++A new group `GRID (ARRANGEMENT OR PIANO ROLL — WHICHEVER YOU USED LAST)`:++| Keys | Description |+|------|-------------|+| ⌘1 ⌘2 | Narrow / widen the grid · in Auto, change the density |+| ⌘3 | Triplet grid on / off |+| ⌘4 | Snap to grid on / off |+| ⌘5 | Switch between the adaptive (Auto) and a fixed grid |+| ⌥ while dragging | Move freely, ignoring the grid |++The existing piano-roll row "← → Move notes by the grid" stays and now means the step in+effect.++## Snap control (one per editor)++| Editor | Location | Replaces |+|--------|----------|----------|+| Arrangement | The existing toolbar cell `SnapChip` / `SnapLabel` | Forward-only cycling (`OnCycleSnap`) |+| Piano roll | A new chip in the clip-editor header's right group, before Scale | The GRID dropdown's role as the snap step |++### Label states++The piano-roll chip reads the full label on one line. The arrangement's toolbar cell keeps+its two-line layout to stay narrow: the step on top ("1/8") and the caption **AUTO GRID**+(Adaptive) or **GRID** (Fixed) below it.++| State | Label | Notes |+|-------|-------|-------|+| Adaptive | `Auto · 1/8` | The step updates live while zooming |+| Adaptive, triplets | `Auto · 1/8T` | |+| Fixed | `1/8` | |+| Fixed, triplets | `1/8T` | |+| Fixed, finer than drawn | `1/32` in the dimmed (secondary) text colour | Tooltip "1/32 — finer than the visible grid · zoom in to see it" (FR-005a) |+| Snap off | Current label struck through in the disabled colour | Tooltip "Snap off — items move freely (⌘4)" |++The default tooltip lists the shortcuts: "Snap grid · ⌘1 ⌘2 narrow/widen · ⌘3 triplets ·+⌘4 snap · ⌘5 auto". Colours and type come from the Ember tokens (`DESIGN.md`).++### Menu (opens on click)++```text+✓ Auto · Narrow+ Auto · Medium+ Auto · Wide+ ─────────────+ 1/32+ 1/16+ 1/8+ 1/4+ 1/2+ 1 bar+ 2 bars+ 4 bars+ ─────────────+ Triplets ⌘3+ Snap to grid ⌘4+```++- One check mark on the active mode row (an Auto row or a fixed step). Triplets and+ Snap to grid show their own on/off check.+- With triplets on, the fixed rows read 1/32T … 1/2T; the bar rows stay unchanged.+- Picking an Auto row or a step applies immediately and turns snap on (data-model.md).++### Arrangement toolbar latch++`SnapToggle` (the magnet) stays. It mirrors and sets `ArrangementGrid.SnapOn`, so it, ⌘4+and the menu's "Snap to grid" are the same switch.++## Piano roll inspector++The clip inspector's GRID section becomes QUANTIZE: a dropdown with 1/32 … 1/2 and+1/32T … 1/2T (default 1/16), the Quantize button, and the existing STRENGTH slider.+The dropdown sets `Settings.QuantizeStep` (FR-008a) and nothing else.diff --git a/specs/003-adaptive-snap-grid/data-model.md b/specs/003-adaptive-snap-grid/data-model.mdnew file mode 100644index 00000000..8ff4d21b--- /dev/null+++ b/specs/003-adaptive-snap-grid/data-model.md@@ -0,0 +1,106 @@+# Data Model: Adaptive Snap Grid++Phase 1 of [plan.md](plan.md). All types are managed-only and UI-free unless noted.+Nothing here crosses the C ABI or is written to project files.++## GridStep (value)++One rung of the ladder (research R3).++| Field | Type | Notes |+|-------|------|-------|+| `Index` | int 0..7 | 0 = 1/32 … 4 = 1/2, 5 = 1 bar, 6 = 2 bars, 7 = 4 bars |+| `Triplet` | bool | Only meaningful for `Index` 0..4; always false for bar steps |++Derived:++- `Beats(beatsPerBar)`: straight 0.125, 0.25, 0.5, 1, 2, then 1, 2 and 4 bars ×+ `beatsPerBar`. Triplet = straight × 2/3.+- `Label`: "1/32" … "1/2", "1 bar", "2 bars", "4 bars"; triplets add "T" ("1/8T").++Validation: `Index` is clamped to 0..7. `Triplet` is forced false when `Index ≥ 5`.++## GridDensity (enum)++`Narrow` | `Medium` | `Wide`. Thresholds: 8 / 16 / 32 px (research R2).++## GridSetting (persisted, one per editor)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `Adaptive` | bool | true | false = Fixed |+| `Density` | GridDensity | Medium | Remembered while Fixed (FR-013, ⌘5) |+| `FixedIndex` | int | 3 (1/4) for the arrangement, 1 (1/16) for the piano roll | Remembered while Adaptive |+| `Triplets` | bool | false | Applies in both modes |+| `SnapOn` | bool | true | Off = free positioning; lines still drawn (FR-010) |++Stored as `Settings.ArrangementGrid` and `Settings.PianoRollGrid` in `settings.json`.+Unknown or out-of-range values fall back to the per-field default (R7). The two+instances are fully independent (FR-001, Clarification Q3).++### Transitions (SnapGrid operations; each returns a new GridSetting)++| Operation | Adaptive | Fixed |+|-----------|----------|-------|+| `Narrower` (⌘1) | Density one notch finer: Wide → Medium → Narrow; stops at Narrow | `FixedIndex − 1`; stops at 0 |+| `Wider` (⌘2) | Density one notch coarser: Narrow → Medium → Wide; stops at Wide | `FixedIndex + 1`; stops at 7 |+| `ToggleTriplets` (⌘3) | Flip `Triplets` | Flip `Triplets` |+| `ToggleSnap` (⌘4) | Flip `SnapOn`; mode untouched | Flip `SnapOn`; mode untouched |+| `ToggleAdaptive` (⌘5) | → Fixed, keeping `FixedIndex` | → Adaptive, keeping `Density` |+| Menu pick "Adaptive · X" | `Adaptive = true`, `Density = X` | same |+| Menu pick a fixed step | `Adaptive = false`, `FixedIndex = i` | same |++Picking a grid value from the menu (Adaptive · X or a fixed step) also sets+`SnapOn = true`: choosing a value while snap is off means the user wants to snap to it.+The shortcuts other than ⌘4 leave `SnapOn` as it is.++## ResolvedGrid (derived, not stored)++`SnapGrid.Resolve(GridSetting, pixelsPerBeat, beatsPerBar)` returns:++| Field | Type | Meaning |+|-------|------|---------|+| `Snap` | GridStep | The step in effect: used by `SnapBeat`, nudges and paste |+| `Draw` | GridStep | The finest drawn line step (equal to `Snap` in Adaptive mode) |+| `FinerThanVisible` | bool | Fixed only: `Draw` is coarser than `Snap` (FR-005a) |+| `SnapOn` | bool | Copied from the setting |++Rules:++- **Adaptive**: the smallest `Index` (in the setting's triplet family) whose+ `Beats × pixelsPerBeat ≥ threshold(Density)`, clamped to 0..7. `Draw = Snap`.+- **Fixed**: `Snap = (FixedIndex, Triplets)`. `Draw` is the smallest `Index ≥ FixedIndex`+ meeting the Medium threshold (16 px), clamped to 7.+- In 4/4 at the arrangement's default 28 px per beat with default settings:+ `Snap = Draw = 1/4` (FR-003).++## SnapGrid.SnapBeat (behaviour)++`SnapBeat(beat, step, beatsPerBar)` returns the nearest grid position (research R4):++- Sub-bar steps: for the bar containing `beat`, the positions are+ `barStart + n·step` (n ≥ 0, `n·step < barLength − ε`) and the next bar start.+- Bar steps: multiples of `k·beatsPerBar` from beat 0.+- Never negative. Callers keep their existing `Math.Max(0, …)` and magnetic logic.++`GridLines(viewStart, viewEnd, step, beatsPerBar)` enumerates the same positions for+drawing, so lines and snap points come from one source (FR-005).++## Quantize step (persisted, piano roll only)++`Settings.QuantizeStep`: a `GridStep` restricted to sub-bar steps (`Index` 0..4, triplet+allowed). Default 1/16 straight. It is independent of `PianoRollGrid` (FR-008a). The roll+quantizes to `Beats(beatsPerBar)` of this value. Bar steps are not offered for Quantize.++## EditorGrids (Nota.App, live state; research R8)++| Member | Notes |+|--------|-------|+| `Arrangement`, `PianoRoll` | Current `GridSetting`s |+| `Quantize` | Current Quantize step |+| `Set(EditorKind, GridSetting)`, `SetQuantize(GridStep)` | Updates, saves `Settings`, raises `Changed` |+| `event Action<EditorKind> Changed` | Views redraw; snap controls relabel |++One instance per app: `EditorGrids.Shared`, on the registered `ISettingsService` (the+toolbar view comes from XAML and rolls are built in several places, so a shared instance+replaced passing one through `MainWindow`).diff --git a/specs/003-adaptive-snap-grid/plan.md b/specs/003-adaptive-snap-grid/plan.mdnew file mode 100644index 00000000..7c6d0d6a--- /dev/null+++ b/specs/003-adaptive-snap-grid/plan.md@@ -0,0 +1,215 @@+# Implementation Plan: Adaptive Snap Grid++**Branch**: `003-adaptive-snap-grid` (the spec directory; the work currently sits on `develop`) | **Date**: 2026-10-13 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/003-adaptive-snap-grid/spec.md`++## Summary++The arrangement and the piano roll each get one grid setting: Adaptive (Narrow, Medium+or Wide) or Fixed, plus Triplets and Snap on/off. A single pure rule, `SnapGrid` in+`Nota.Application`, turns a setting and the current zoom into the step to snap to and the+step to draw. Both editors' drawing, snapping, nudging and paste go through it, so what+you see is what you snap to. A menu replaces forward cycling, ⌘1–⌘5 drive it from the+keyboard, and the piano roll's Quantize gets its own value. Settings persist app-wide in+`settings.json`. The engine is not touched.++## Nota: Read Before Planning++- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Ember) and the `nota-design` skill for+ the snap chip, its menu, the dimmed and off label states, and the QUANTIZE section.+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md): SPDX headers on the new+ files, no new dependencies.+- **Shortcuts** → the `nota-shortcuts` skill (Settings → Shortcuts list).++## Technical Context++**Language/Version**: C# / .NET 10 (managed app only)++**Primary Dependencies**: Avalonia (existing). No new dependency.++**Storage**: `settings.json` in `NotaPaths.DataDir` via `ISettingsService`. Three new+`Settings` properties (research R7). Project files are unchanged.++**Audio-Thread Impact**: None. This is a UI-only change. Snapping resolves positions+before the existing engine calls (`SetClipNotes`, clip move and resize), which are+unchanged.++**Testing**: A new pure-logic section in `tests/Nota.SmokeTest` (`SnapGridTests.cs`, run+alone with `--grid`, also part of the full run), the existing palette checks (ids bound,+shortcuts listed), and a headless Avalonia harness for screenshots (quickstart §3).++**Target Platform**: macOS, Windows, Linux desktop (⌘ = Ctrl off macOS).++**Project Type**: Desktop app (Avalonia).++**Performance Goals**: No visible snapping delay (SC-004). `Resolve` and `SnapBeat` are+O(ladder) = 8 steps, run per pointer move and per frame, allocation-free. Line+enumeration is bounded by the threshold (≤ view width / 8 lines).++**Constraints**: Must not change any stored clip or note position on load (SC-005).+Sections keep whole-bar snapping. ⌥ bypass and magnetic snap keep working.++**Scale/Scope**: About 9 touched files in `Nota.App`, 2 new and 1 touched in+`Nota.Application`, 1 new test file, docs.++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design: still passes.*++| Principle | Status | Notes |+|-----------|--------|-------|+| I. Real-time audio safety | ✅ Pass | No engine or audio-thread code touched |+| II. Boundary discipline | ✅ Pass | No new C ABI surface; no JUCE |+| III. Licensing hygiene | ✅ Pass | New files carry the two-line SPDX header; no dependency |+| IV. Verification gate | ✅ Pass | `scripts/build.sh` must pass; the smoke test gains the `SnapGridTests` section even though no engine behaviour changes |+| V. One logical change per PR | ✅ Pass | One feature, one PR. The piano-roll time-signature fix (R5) is part of FR-002/Edge Cases, not a separate change |+| VI. Docs stay in sync | ✅ Planned | CHANGELOG `[Unreleased]`, `nota-shortcuts`, `nota-features`, `nota-docs` (EN + RU) |+| VII. Spec-first | ✅ Pass | spec → clarify (4 Qs) → this plan |+| VIII. Safety rules not weakened | ✅ Pass | N/A |++No violations, so Complexity Tracking is empty.++## Design++### 1. The rule — `Nota.Application/Editing/SnapGrid.cs` (new)++Pure static functions and small value types as defined in [data-model.md](data-model.md):+`GridStep`, `GridDensity`, `GridSetting`, `ResolvedGrid`, plus++- `Resolve(setting, pixelsPerBeat, beatsPerBar)` → `ResolvedGrid` (R2, R6);+- `SnapBeat(beat, stepBeats, beatsPerBar)` and `GridLines(from, to, stepBeats,+ beatsPerBar)`, both bar-anchored and sharing one position rule (R4);+- `Narrower`, `Wider`, `ToggleTriplets`, `ToggleSnap`, `ToggleAdaptive`, `PickAdaptive`,+ `PickFixed`, each returning a new `GridSetting`;+- `Label(setting, resolved)` → "Auto · 1/8", "1/8T", "1 bar" (contract label table).++`Nota.Application/Settings.cs` gains `ArrangementGrid`, `PianoRollGrid` and+`QuantizeStep` with their FR-016 defaults.++### 2. Live state — `Nota.App/EditorGrids.cs` (new)++It holds both settings and the Quantize step, loads them from `ISettingsService` at+start-up, saves on change, and raises `Changed(EditorKind)` (R8). It is one app-wide+instance, `EditorGrids.Shared`, read by `ArrangementView`, every `PianoRollView`,+`ClipPropsView` and the snap chips. Views subscribe only while on screen.++### 3. Arrangement — `ArrangementView*.cs`++- Replace `_snapBeats` / `_snapEnabled` with a `Resolve` call cached per zoom or setting+ change (`_resolved`). The `SnapBeats` and `SnapEnabled` setters go away.+- `Snap()` → `SnapGrid.SnapBeat(beat, _resolved.Snap beats, _beatsPerBar)` when+ `SnapOn`. `SnapMaybe` and `SnapMagnetic` keep their ⌥ and magnet logic on top. All+ existing call sites (LaneControl, Controls, Automation, loop range, paste) inherit it+ (FR-007).+- The loop range's minimum length (`_loopS + _snapBeats`) uses the resolved step.+- The lane, footer and ruler grid loops (`LaneControl` around lines 1275–1285 and+ `Controls` around lines 189–200) draw from `GridLines(_resolved.Draw)` with the+ bar/beat/sub-beat pens. Today they draw only bars and beats (FR-005, FR-006).+- `SnapBar` for sections is unchanged.++### 4. Piano roll — `PianoRollView*.cs`, `ClipPropsView.cs`, `ClipEditorView.cs`, `MidiToolsView.cs`++- Remove `GridStepBeats()`, `GridLadder` and `_grid`. Add `_resolved` from+ `EditorGrids.PianoRoll`, refreshed on zoom (`SetZoom` and the fit in layout) and on+ `Changed`.+- Note snapping (`NoteGrid.Snap`), new note length, ← → nudges, paste anchor and the+ duplicate shift use `_resolved.Snap`. Drawing and the Expression lanes use+ `GridLines(_resolved.Draw)`.+- Add a `BeatsPerBar` property set from the transport at both build sites in+ `MainWindow.Detail.cs`. `GridPen` and `GridLabel` use it instead of the literal 4+ (R5).+- `Quantize(strength)` uses `EditorGrids.Quantize` (FR-008a). In `ClipPropsView`, the+ GRID section becomes QUANTIZE, with straight and triplet sub-bar values only.+ `MidiToolsView` passes the same Quantize step as `MidiToolContext.Grid` (R11).+- `ClipEditorView` header: a new `SnapChip` control before the Scale controls.++### 5. Shared snap chip — `Nota.App/SnapChip.cs` (new)++A small control used by both editors. It takes an `EditorKind` and `EditorGrids`, renders+the label states, and opens the menu from the contract (built with the app's existing+menu helpers; the same style as the `ClipPropsView` dropdowns). In the arrangement it+replaces the content and handler of the toolbar `SnapChip` cell+(`MainWindow.axaml:238`). `OnCycleSnap` and `SnapSteps` are deleted. `SnapToggle` binds+to `ArrangementGrid.SnapOn` in both directions.++### 6. Commands — `CommandCatalog.cs`, `MainWindow.Commands.cs`, `MainWindow.axaml`, `PreferencesWindow.cs`++- Five `grid.*` commands with ⌘1–⌘5 (contract). Each is bound to+ `EditorGrids.Set(target, SnapGrid.X(current))` plus the status line. The target comes+ from `_detailWasLastFocused` and whether a MIDI clip editor is showing (R9).+- Edit → Grid submenu in `MainWindow.axaml` (macOS key equivalents, plus the+ `TryMenuShortcut` path on Windows and Linux).+- A GRID group in Settings → Shortcuts. The palette smoke test enforces it.++### 7. Tests — `tests/Nota.SmokeTest/SnapGridTests.cs` (new) + `Program.cs`++A `--grid` flag and an entry in the full run, following the `TapTempoTests` pattern. The+cases are listed in quickstart §1.++## Project Structure++### Documentation (this feature)++```text+specs/003-adaptive-snap-grid/+├── spec.md+├── plan.md # this file+├── research.md # R1–R12+├── data-model.md # GridStep, GridSetting, ResolvedGrid, transitions+├── quickstart.md # validation guide+├── contracts/+│ └── grid-ui.md # commands, shortcuts, snap chip states and menu+├── checklists/+│ └── requirements.md+└── tasks.md # /speckit-tasks (not created yet)+```++### Source Code (repository root)++```text+src/managed/+├── Nota.Application/+│ ├── Editing/SnapGrid.cs # NEW — the rule (pure)+│ ├── Settings.cs # + ArrangementGrid, PianoRollGrid, QuantizeStep+│ └── Palette/CommandCatalog.cs # + grid.* commands (⌘1–⌘5)+└── Nota.App/+ ├── EditorGrids.cs # NEW — live state, persistence, Changed+ ├── SnapChip.cs # NEW — label + menu, used by both editors+ ├── ArrangementView.cs # Snap()/loop via SnapGrid; _resolved cache+ ├── ArrangementView.LaneControl.cs # grid lines from GridLines+ ├── ArrangementView.Controls.cs # ruler/footer grid lines+ ├── PianoRollView.cs # _resolved, BeatsPerBar, nudges, quantize+ ├── PianoRollView.Expression.cs # lane grid lines+ ├── MidiToolsView.cs # MidiToolContext.Grid = Quantize step (R11)+ ├── ClipPropsView.cs # GRID → QUANTIZE+ ├── ClipEditorView.cs # header SnapChip+ ├── MainWindow.axaml(.cs) # toolbar cell, SnapToggle binding, Edit → Grid+ ├── MainWindow.Commands.cs # bind grid.*+ ├── MainWindow.Detail.cs # pass EditorGrids + BeatsPerBar to rolls+ └── PreferencesWindow.cs # Shortcuts: GRID group++tests/Nota.SmokeTest/+├── SnapGridTests.cs # NEW+└── Program.cs # --grid + full-run entry+```++**Structure Decision**: The rule goes in `Nota.Application`, so it is testable and free+of UI types. The live state and controls go in `Nota.App`, next to the views that already+own snapping. Nothing is added to `Nota.Presentation`, `Nota.Infrastructure` (the existing+`SettingsService` serialises the new properties unchanged) or the engine.++## Risks++- **Toolbar width**: "Auto · 1/16T" is wider than "1/4". Check it against+ `MainWindow.TransportFit.cs` hiding order at narrow widths, and fix the cell's width to+ the longest label so the toolbar does not jitter while zooming.+- **Redraw on zoom**: the snap chip label changes during wheel zoom. Update it only when+ the resolved step actually changes.+- **Behaviour change for existing users**: the default becomes Adaptive. At the default+ zoom it matches today's 1/4 (FR-003), and the CHANGELOG entry names ⌘5 for going back to+ a fixed grid.++## Complexity Tracking++None. The Constitution Check has no violations.diff --git a/specs/003-adaptive-snap-grid/quickstart.md b/specs/003-adaptive-snap-grid/quickstart.mdnew file mode 100644index 00000000..f59bc3ca--- /dev/null+++ b/specs/003-adaptive-snap-grid/quickstart.md@@ -0,0 +1,69 @@+# Quickstart: Validate the Adaptive Snap Grid++How to prove the feature works after implementation. Rules and values are in+[data-model.md](data-model.md). Controls and shortcuts are in+[contracts/grid-ui.md](contracts/grid-ui.md).++## Prerequisites++- A working Nota build (BUILD.md § prerequisites).+- For the app checks: a scratch data folder, so the grid preference does not touch the+ real `settings.json`: `export NOTA_DATA_DIR=/tmp/nota-grid`.++## 1. Rule tests (fast loop)++```bash+dotnet run --project tests/Nota.SmokeTest -- --grid+```++Expected: `GRID PASSED`. The section covers:++- default settings at 28 px per beat in 4/4 resolve to 1/4 (FR-003);+- Narrow, Medium and Wide at a fixed zoom give strictly finer-to-coarser steps;+- clamping at 1/32 (or 1/32T) and 4 bars at the zoom extremes;+- triplet steps are 2/3 of straight ones, and bar steps ignore triplets;+- 3/4: every bar start is a snap point for 1/2 and 1/2T (research R4);+- `GridLines` and `SnapBeat` agree: every enumerated line snaps to itself and every snap+ result is an enumerated line (SC-001);+- Fixed 1/32 at 4 px per beat: `Draw` is coarser and `FinerThanVisible` is true; at+ 240 px per beat it is false (FR-005a);+- ⌘1, ⌘2, ⌘3, ⌘4 and ⌘5 transitions, including stops at the ends and remembered+ density and step (data-model.md table);+- labels: "Auto · 1/8", "1/8T", "1 bar", "4 bars";+- `Settings` without the new fields loads the FR-016 defaults; a round trip keeps both+ editors' settings and the Quantize step separate.++## 2. Full gate++```bash+scripts/build.sh+```++Expected: green, including the existing palette checks. Every `grid.*` id is bound and+every ⌘1–⌘5 shortcut is listed in Settings → Shortcuts.++## 3. In the app (headless harness or a manual run)++With `NOTA_DATA_DIR` set and a project with one MIDI track and clip:++| # | Action | Expected |+|---|--------|----------|+| 1 | Default zoom, look at the arrangement snap cell | "Auto · 1/4"; beat lines drawn |+| 2 | Zoom in until eighths appear, drag a clip | The cell reads "Auto · 1/8"; the clip lands on a drawn eighth line |+| 3 | Zoom out to the whole song, drag a clip | The cell reads "Auto · 1 bar" or coarser; the clip lands on a bar line |+| 4 | Click the cell, pick 1/32, zoom far out | The label "1/32" is dimmed with the "finer than the visible grid" tooltip; the lines are thinned |+| 5 | ⌘5, then ⌘5 again | Auto with the previous density, then back to 1/32 |+| 6 | Open the clip, press ⌘3 in the piano roll | The roll chip reads "Auto · …T"; triplet lines; notes snap to them; the arrangement cell is unchanged (Q3) |+| 7 | Set QUANTIZE to 1/8T, zoom the roll in and out, press Quantize | Notes land on 1/8T regardless of zoom (Q2) |+| 8 | Click a toolbar button, press ⌘2 | It acts on the editor used last; the status line names it (R9) |+| 9 | ⌘4 in the arrangement | The magnet latch turns off with it; clips move freely; lines stay |+| 10 | Quit and relaunch | Both editors' settings and the Quantize step are as left (Q1); opening another project does not change them |+| 11 | Hold ⌥ while dragging | Free positioning in both editors |++Take screenshots of rows 1, 4 and 6 in both Ember variants for the PR (the nota-ui-verify+recipe in the agent memory describes the headless harness).++## 4. Docs sync++- `CHANGELOG.md` `[Unreleased]` → Added and Changed entries.+- The `nota-shortcuts`, `nota-features` and `nota-docs` skills (EN + RU).diff --git a/specs/003-adaptive-snap-grid/research.md b/specs/003-adaptive-snap-grid/research.mdnew file mode 100644index 00000000..dcd299a5--- /dev/null+++ b/specs/003-adaptive-snap-grid/research.md@@ -0,0 +1,155 @@+# Research: Adaptive Snap Grid++Phase 0 of [plan.md](plan.md). Each entry resolves an open point from the spec's+Assumptions or the plan's Technical Context.++## R1 — Where the step rule lives++- **Decision**: A pure, UI-free `SnapGrid` module in `Nota.Application/Editing/`. It+ covers the ladder, step resolution, snapping a beat, labels and the shortcut+ transitions. Both editors call it, and the smoke test covers it directly.+- **Rationale**: The rule is shared by two views and is the part most likely to regress+ (FR-005, SC-001). `Nota.Application` already hosts small pure models with their own+ smoke-test sections (`TapTempo` → `TapTempoTests`, `--tap`). The smoke test does not+ reference `Nota.App`, so logic left in the views could not be tested.+- **Alternatives considered**: Keeping `GridStepBeats()` in `PianoRollView` and copying+ it into `ArrangementView` was rejected: two copies drift, and that drift is the bug+ being fixed. A shared static helper in `Nota.App` was rejected because it cannot be+ tested.++## R2 — Density thresholds (the "about 6 / 12 / 24 px" assumption)++- **Decision**: One set of thresholds for both editors. Each is the minimum on-screen+ spacing between the finest lines: Narrow 8 px, Medium 16 px, Wide 32 px. The thresholds+ double from one notch to the next, so each ⌘1/⌘2 press in Adaptive mode moves the step+ by exactly one ladder notch.+- **Rationale**: FR-003 requires 1/4 at the arrangement's default zoom (28 px per beat).+ With Medium at 16 px, 1/8 (14 px) fails and 1/4 (28 px) passes. The spec's 12 px would+ give 1/8, so it is rejected. The piano roll fits a clip to its width: a 1-bar clip in+ about 1000 px is about 250 px per beat, a 4-bar clip about 62 px per beat. These+ resolve to 1/32 and 1/8, bracketing the old fixed default 1/16 as the spec assumed.+ One set keeps "Medium" meaning the same thing in both editors.+- **Alternatives considered**: A larger base for the piano roll (24/48 px). Checked+ against the same examples, it gives the same steps (1/32 and 1/8), so it adds a second+ constant for no visible difference. A fixed 9 px, as in today's roll visuals, is denser+ and contradicts FR-003 in the arrangement.+- **Tuning**: The values are constants in `SnapGrid` and are checked against FR-003+ during implementation. If they change, update this entry.++## R3 — Ladder and triplet values++- **Decision**: The straight ladder, in beats (a beat is a quarter note): 1/32 = 0.125,+ 1/16 = 0.25, 1/8 = 0.5, 1/4 = 1, 1/2 = 2, 1 bar, 2 bars, 4 bars. A triplet step is+ 2/3 of the straight value: 1/32T = 1/12, 1/16T = 1/6, 1/8T = 1/3, 1/4T = 2/3,+ 1/2T = 4/3. Bar steps have no triplet form. The piano roll's 1/64 is dropped (spec+ Assumptions). The roll's old "1/1" becomes "1 bar".+- **Rationale**: These are the musical values in FR-002. Beats-as-quarters matches the+ engine's beat unit and the existing `GridValues` array in `ClipPropsView`.+- **Alternatives considered**: Dotted values (out of scope), and 1/64 (finer than any+ zoom can draw at the arrangement's 240 px per beat maximum: 240/16 = 15 px, borderline,+ and unused).++## R4 — Bar anchoring and odd meters++- **Decision**: Grid positions are anchored to each bar start: within a bar, the positions+ are `barStart + n·step` for every n with `n·step < barLength`, plus the next bar start.+ `SnapBeat` returns the nearest of these. Bar steps (1, 2, 4 bars) are multiples of the+ bar length counted from beat 0.+- **Rationale**: In 3/4, a 1/2 step (2 beats) or a 1/2T step (4/3 beats) does not divide+ the bar. Anchoring each bar keeps every bar line a snap point and keeps lines and+ snapping identical (FR-005). In 4/4, every ladder step divides the bar, so anchoring+ changes nothing.+- **Alternatives considered**: A global lattice from beat 0 (bar lines stop being snap+ points in odd meters). Skipping steps that do not divide the bar (adaptive would jump+ over notches, which breaks the one-notch-per-press rule in R2).++## R5 — Time signature in the piano roll++- **Decision**: Pass beats-per-bar into `PianoRollView` (the same value+ `ArrangementView.BeatsPerBar` gets from the transport). Replace the hard-coded `4` in+ `GridPen` and `GridLabel`.+- **Rationale**: "1 bar" must mean the project's bar (spec Edge Cases). The roll+ currently assumes 4/4 for bar lines and ruler labels.+- **Alternatives considered**: Leaving the roll in 4/4 (wrong bar steps in 3/4 or 6/8).++## R6 — Fixed step too fine to draw (Clarification Q4)++- **Decision**: `Resolve` returns two steps. `Snap` is the step used for snapping.+ `Draw` is the finest drawn step. In Adaptive mode they are equal. In Fixed mode,+ `Draw` is the fixed step if its spacing meets the Medium threshold (16 px). Otherwise+ it is the finest ladder step at least as coarse as the fixed step that meets the+ threshold (same triplet family while sub-bar). `FinerThanVisible = Draw > Snap` drives+ the control's mark (FR-005a).+- **Rationale**: Readable grid and honest snapping, as clarified. Medium is used as the+ threshold for the thinning because density is an Adaptive-only setting.+- **Alternatives considered**: Thinning at the remembered density (an invisible setting+ would change Fixed-mode visuals).++## R7 — Persistence (Clarification Q1)++- **Decision**: Three new properties on `Nota.Application.Settings`:+ `ArrangementGrid`, `PianoRollGrid` (both `GridSetting`), and `QuantizeStep`. They are+ saved through `ISettingsService.Save()` into `settings.json` in `NotaPaths.DataDir`.+ Missing properties deserialize to the defaults (FR-016). A value that does not parse+ falls back to the default per field.+- **Rationale**: This is the existing app-wide store. It already tolerates older or+ missing fields (`catch → new Settings()`), it is isolated in tests by `NOTA_DATA_DIR`,+ and project files are untouched (FR-017).+- **Alternatives considered**: Per-project sidecars like `sections.json` (rejected in Q1).++## R8 — Live state shared by rebuilt piano rolls and the pop-out window++- **Decision**: A small app-level `EditorGrids` object in `Nota.App` holds the two live+ `GridSetting`s and the Quantize step. It loads them from `Settings` at start-up, saves+ on every change, and raises `Changed(EditorKind)`. `ArrangementView` and every+ `PianoRollView` read from it and redraw on `Changed`. Each snap control rebuilds its+ label on `Changed`.+- **Rationale**: `MainWindow.Detail.cs` builds a new `PianoRollView` per clip (arrangement+ clips and session slots) and the editor can float in `DetailWindow`. Settings kept as+ view fields would reset on every clip switch, which is how today's GRID dropdown+ behaves (`_gridIndex = 4` per `ClipPropsView`).+- **Alternatives considered**: Pushing setters into each view from `MainWindow`, as+ `Timeline.SnapBeats` is set today (every new roll would have to be re-seeded, and the+ floating window would need its own wiring).++## R9 — Which editor a shortcut targets++- **Decision**: The shortcut acts on the piano roll when the detail panel or the detail+ window was the last area used (`_detailWasLastFocused`, already maintained for Tab) and+ a MIDI clip editor is showing. Otherwise it acts on the arrangement. The status line+ names the target: "Piano roll grid: Auto · 1/16".+- **Rationale**: This matches the spec's focus rule and its "last worked in" fallback,+ and reuses the existing signal instead of adding focus tracking.+- **Alternatives considered**: Only the keyboard-focused control (fails after a toolbar+ click, which the spec rules out).++## R10 — Shortcut keys++- **Decision**: ⌘1 narrower, ⌘2 wider, ⌘3 triplets, ⌘4 snap, ⌘5 adaptive (Ctrl on+ Windows and Linux). They are declared in `CommandCatalog` under a new "Grid" category+ and bound in `MainWindow.Commands.cs`. They appear in a new Edit → Grid submenu, which+ gives native key equivalents on macOS and the `TryMenuShortcut` path on Windows and+ Linux. They are also listed in Preferences → Shortcuts under a new GRID group.+- **Rationale**: No catalog command, menu item or key handler uses ⌘/Ctrl + 1–5 today+ (only bare 0 is bound). The palette smoke test already enforces that every catalog+ shortcut is listed in Settings → Shortcuts. These are also the keys Ableton users+ expect.+- **Alternatives considered**: ⌥-based keys (⌥ is the snap-bypass modifier while+ dragging; overloading it is confusing).++## R11 — The MIDI clip tools' grid++- **Decision**: The clip-tools panel (`MidiToolsView`) passes the Quantize step, not the+ snap step, as `MidiToolContext.Grid`. This value is used by the Warp "Snap to Grid"+ shape and a generator's fallback gap.+- **Rationale**: Like Quantize (Clarification Q2), a tool rewrites notes. Its result must+ not change with the zoom. Today both read the same `_roll.Grid`, so keeping them+ together preserves current behaviour.+- **Alternatives considered**: The snap step in effect (zoom-dependent output).++## R12 — Out-of-scope neighbours noted during research++- The audio clip editor (`AudioClipEditorView`) has its own "snap trim to whole beats"+ switch. It is not part of either editor's grid and stays as is.+- Song sections keep `SnapBar` (whole bars), per the spec.+- MCP tools and Nota Remote do not expose the snap grid; unchanged.diff --git a/specs/003-adaptive-snap-grid/spec.md b/specs/003-adaptive-snap-grid/spec.mdnew file mode 100644index 00000000..5a8b13e5--- /dev/null+++ b/specs/003-adaptive-snap-grid/spec.md@@ -0,0 +1,306 @@+# Feature Specification: Adaptive Snap Grid++**Feature Branch**: `003-adaptive-snap-grid`++**Created**: 2026-10-13++**Status**: Draft++**Input**: User description: "Adaptive snap grid for the arrangement view and the piano roll, with triplets. Problem: the snap step is fixed (default 1/4) and independent of zoom — zooming in keeps snapping to quarters while the drawn grid shows finer lines; zooming out leaves a sub-pixel snap step. Changing it means cycling a single button forward through 1/16→1/8→1/4→1/2→1 bar. Desired: (1) Adaptive snap by default — the snap step equals the visible grid step, chosen from zoom (finest step from a ladder 1/32…1/16…1/4…1 bar…4 bars keeping at least N px between lines), so what you see is what you snap to. (2) Adaptive density modes Narrow / Medium / Wide (different px thresholds). (3) Fixed mode still available: explicitly picking e.g. 1/8 keeps it regardless of zoom; the control shows the mode, e.g. "Auto · 1/8" vs "1/8". (4) Triplet grids (1/4T, 1/8T, 1/16T …) in both adaptive and fixed modes, toggleable. (5) Controls: clicking the snap control opens a menu with all values (Adaptive + density, fixed steps, triplets toggle, snap off) instead of cycling; Ableton-style shortcuts — narrow grid, widen grid, toggle triplets, toggle snap, toggle adaptive; Alt-drag still bypasses snapping. (6) Same behaviour in both arrangement view and piano roll, sharing one grid-step source (piano roll already has adaptive visual-only GridStepBeats). Drawn grid lines and snap step must stay consistent in both editors."++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [ ] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Ember)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++The engine is not involved: snapping is an editing concern resolved in the app before+any clip or note edit reaches the engine.++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++**Current state (for reference)**:++- Arrangement: a fixed snap step (default 1/4) cycled forward by one toolbar cell+ (1/16 → 1/8 → 1/4 → 1/2 → 1 bar), plus a separate Snap on/off latch. The drawn grid+ shows only bar and beat lines (beats from about 12 px per beat) and never matches a+ finer snap step. Alt while dragging already snaps freely, and nearby clip edges+ already attract the dragged clip (magnetic snap).+- Piano roll: the drawn grid already subdivides as you zoom, but snapping and Quantize+ use a fixed step picked in the clip properties GRID dropdown (1/1 … 1/64 and+ 1/4T … 1/32T, default 1/16). What you see and what you snap to differ.++## Clarifications++### Session 2026-10-13++- Q: Where are grid settings stored — app-wide, per project, or both? → A: App-wide, one setting per editor; survives restarts, identical across projects, project files unchanged.+- Q: What step does piano-roll Quantize use when the grid is adaptive? → A: Its own Quantize value in the GRID panel (default 1/16, triplets available), independent of the grid mode and zoom.+- Q: Are the arrangement and piano-roll grid settings independent or shared? → A: Independent — each editor has its own mode, density, fixed step, triplets and snap on/off.+- Q: In Fixed mode, what is drawn when the chosen step's lines would merge at a far zoom? → A: Lines are thinned to the density threshold; snapping still uses the chosen step; the snap control marks that the step is finer than the visible grid.++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Snap follows the zoom (Priority: P1)++A user arranging a song zooms in on a few bars to place a clip on an off-beat eighth. They+drag the clip and it lands on the eighth they can see, without touching any grid+control. They zoom out to the whole song, drag a section of clips, and it moves by whole+bars instead of jittering on tiny steps. The same applies when editing notes in the piano+roll.++**Why this priority**: This is the reported pain. Adaptive snapping removes the constant+manual switching on its own, without the other stories.++**Independent Test**: With default grid settings, zoom the arrangement in and out. At each zoom+level, drag a clip and check that it lands only on lines that are visible on screen.+Repeat with a note in the piano roll.++**Acceptance Scenarios**:++1. **Given** default grid settings (Adaptive · Medium) and the arrangement zoomed in+ so that eighth-note lines are drawn, **When** the user drags a clip, **Then** its+ start lands on the nearest drawn eighth-note line.+2. **Given** the arrangement zoomed out so that only bar lines are drawn, **When** the+ user drags a clip, **Then** its start lands on a bar line.+3. **Given** adaptive snap in the piano roll at a zoom that draws 1/32 lines, **When**+ the user draws or moves a note, **Then** the note's start and end land on drawn 1/32+ lines.+4. **Given** any zoom level in either editor, **When** the user looks at the snap+ control, **Then** it shows the step currently in effect (for example "Auto · 1/8"),+ and that step changes as the user zooms.+5. **Given** adaptive snap, **When** the user holds Alt while dragging, **Then** the+ item moves freely, as it does today.++---++### User Story 2 - Pick a grid quickly from a menu or the keyboard (Priority: P2)++A user wants to lock the grid to 1/16 while programming hi-hats, then return to+adaptive. They click the snap control, see every option at once and pick one. Later+they make the grid coarser or finer with the keyboard and switch snapping off and on+without reaching for the mouse.++**Why this priority**: It replaces forward-only cycling, the second half of the+complaint, and lets fixed and adaptive modes coexist.++**Independent Test**: Open the snap control's menu in each editor, pick each kind of+option, and check the result. Then repeat using only the shortcuts.++**Acceptance Scenarios**:++1. **Given** either editor, **When** the user clicks the snap control, **Then** a menu+ opens listing: Adaptive (Narrow, Medium, Wide), every fixed step, a Triplets toggle,+ and Snap off, with the current choice marked.+2. **Given** the user picks fixed 1/8, **When** they zoom in or out, **Then** the snap+ step stays 1/8 and the control reads "1/8" (no "Auto").+3. **Given** a fixed step, **When** the user presses the "narrower grid" shortcut,+ **Then** the step halves (1/8 → 1/16). The "wider grid" shortcut doubles it, and both+ stop at the ends of the range.+4. **Given** adaptive mode, **When** the user presses narrower or wider, **Then** the+ density moves one notch (Wide → Medium → Narrow, and back) and the control updates.+5. **Given** a fixed step, **When** the user presses the "toggle adaptive" shortcut,+ **Then** the editor returns to adaptive with the last used density. Pressing it again+ restores the last fixed step.+6. **Given** snap is on, **When** the user presses the "toggle snap" shortcut, **Then**+ snap turns off (items move freely and the control shows that it is off). Pressing it+ again turns snap back on with the previous mode.++---++### User Story 3 - Triplet grid (Priority: P3)++A user writing a shuffle part switches the grid to triplets. In the piano roll and in the+arrangement, lines and snapping follow triplet divisions, both in adaptive and in fixed+modes, until they switch triplets off.++**Why this priority**: Triplets are essential for some genres but are used less often+than straight grids. The piano roll already offers fixed triplet steps, so this extends+them to adaptive mode and to the arrangement.++**Independent Test**: Turn triplets on in each editor. Check that the drawn lines and the+snapped positions fall on triplet divisions at several zoom levels and with a fixed step.++**Acceptance Scenarios**:++1. **Given** triplets on and a fixed 1/8, **When** the user moves a note, **Then** it+ snaps to 1/8T (three per beat) and the control reads "1/8T".+2. **Given** triplets on and adaptive mode, **When** the user zooms, **Then** the step+ moves through triplet values (for example 1/4T → 1/8T → 1/16T), and lines and+ snapping stay in agreement.+3. **Given** triplets on, **When** the user presses the "toggle triplets" shortcut,+ **Then** the grid returns to the matching straight step (1/8T → 1/8).+4. **Given** the Quantize value set to 1/8T, **When** the user runs Quantize in the+ piano roll at any zoom and in any grid mode, **Then** notes move to 1/8T.++---++### Edge Cases++- **Extreme zoom-in**: adaptive never goes finer than 1/32 (1/32T with triplets), even if+ finer lines would fit. Lines remain drawn at that step and are simply farther apart.+- **Extreme zoom-out**: adaptive never goes coarser than 4 bars. If even 4-bar lines are+ closer than the density threshold, the step stays at 4 bars.+- **Bar-level triplets**: at bar-level steps (1 bar, 2 bars, 4 bars) adaptive snaps to+ bars even with triplets on. Triplets apply only to subdivisions of the bar.+- **Time signature**: "1 bar" means the project's current bar length (for example 3+ beats in 3/4). Bar-based steps follow the time signature; note-value steps (1/4, 1/8 …)+ are note lengths and do not change with it.+- **Zoom during a drag**: if the zoom changes in the middle of a drag (for example+ wheel-zoom while dragging), the new step applies from that moment on.+- **Magnetic snap**: nearby clip edges and markers keep attracting the dragged clip, as+ today, in both adaptive and fixed modes.+- **Fixed step too fine to draw**: at a far zoom, Fixed 1/32 draws only lines that are+ far enough apart (for example beats or bars), keeps snapping to 1/32, and the snap+ control marks the step as finer than the visible grid (FR-005, FR-005a).+- **Snap off**: drawn grid lines still follow the adaptive step, so the user keeps a+ visual reference. Only positioning becomes free.+- **Song sections**: section edges keep snapping to whole bars regardless of the grid+ setting, as today.+- **Keyboard focus**: grid shortcuts act on the editor that has focus (arrangement or+ piano roll). When neither has focus (for example after clicking a toolbar button or a+ device card), they act on the editor the user last worked in.+- **Text entry**: shortcuts do not fire while the user types in a text field.++## Requirements *(mandatory)*++### Functional Requirements++**Step resolution**++- **FR-001**: Each editor (arrangement, piano roll) MUST have a grid mode that is one of+ Adaptive (with density Narrow, Medium or Wide) or Fixed (with a chosen step), plus+ independent Triplets on/off and Snap on/off settings. The two editors' settings MUST be+ fully independent: changing any of them in one editor MUST NOT change the other.+- **FR-002**: The straight step ladder MUST be 1/32, 1/16, 1/8, 1/4, 1/2, 1 bar, 2 bars,+ 4 bars. With triplets on, the sub-bar steps become 1/32T, 1/16T, 1/8T, 1/4T, 1/2T+ (each 2/3 of its straight value), and bar steps stay unchanged.+- **FR-003**: In Adaptive mode, the step in effect MUST be the finest ladder step whose+ on-screen spacing is at least the density threshold, clamped to the ladder ends. Wide+ MUST produce coarser steps than Medium, and Medium coarser than Narrow, at the same+ zoom. With the default density (Medium) and the default zoom, the arrangement MUST+ resolve to 1/4, matching today's default behaviour.+- **FR-004**: In Fixed mode, the step in effect MUST be the chosen step (made triplet when+ triplets are on), independent of zoom.+- **FR-005**: The step in effect MUST be the single source for snapping and for the+ finest drawn grid lines in that editor. In Adaptive mode, every drawn subdivision+ line MUST be a snap position and every snap position MUST have a drawn line, at any+ zoom. In Fixed mode, lines MUST be drawn at the fixed step whenever its spacing meets+ the current density threshold; when it does not, lines MUST be drawn at the finest+ ladder step that meets the threshold (a coarser multiple of the fixed step), while+ snapping still uses the fixed step.+- **FR-005a**: While a Fixed step is finer than the drawn lines, the snap control MUST+ show that (for example a dimmed or marked label and a tooltip such as "1/32 — finer+ than the visible grid"). The mark MUST disappear once the zoom makes the step visible.+- **FR-006**: The drawn grid MUST still distinguish bar, beat and sub-beat lines visually,+ as it does today, and MUST draw triplet lines when triplets are on.++**What snaps**++- **FR-007**: In the arrangement, every operation that snaps today (moving, resizing and+ creating clips, time and loop selection, marker and automation placement, paste+ position) MUST use the step in effect.+- **FR-008**: In the piano roll, drawing, moving and resizing notes and paste position+ MUST use the step in effect.+- **FR-008a**: Piano-roll Quantize MUST use its own Quantize value, chosen in the GRID+ panel next to the Quantize button from the FR-002 straight and triplet steps (default+ 1/16). It MUST NOT depend on the grid mode, the zoom or the Snap on/off state, and it+ persists app-wide like the grid settings (FR-017).+- **FR-009**: Holding Alt during a drag MUST keep bypassing snapping in both editors, and+ magnetic snapping to nearby clip edges MUST keep working in the arrangement.+- **FR-010**: With Snap off, positions MUST be free in both editors, and drawn lines MUST+ continue to follow the step in effect.++**Controls**++- **FR-011**: Each editor MUST have a snap control showing the current state: "Auto · <step>"+ in Adaptive mode (the step updates live with zoom), "<step>" in Fixed mode, a triplet+ suffix "T" when applicable, and a clear off state when Snap is off.+- **FR-012**: Clicking the snap control MUST open a menu with: Adaptive Narrow / Medium /+ Wide, each fixed step from FR-002, a Triplets toggle, and Snap on/off, with the current+ choice marked. Choosing an item MUST apply it immediately. This menu MUST replace the+ forward-only cycling in the arrangement and, in the piano roll, the GRID dropdown's role+ as the snap step (that dropdown becomes the Quantize value, FR-008a).+- **FR-013**: The app MUST provide these shortcuts, acting on the focused editor:+ - **⌘1** narrower grid: in Fixed mode, halve the step (one notch down the ladder);+ in Adaptive mode, move density one notch finer (Wide → Medium → Narrow).+ - **⌘2** wider grid: the reverse of ⌘1.+ - **⌘3** toggle triplets.+ - **⌘4** toggle snap on/off.+ - **⌘5** toggle between Adaptive and Fixed, restoring the last-used density or step.+ (⌘ is Ctrl on Windows and Linux.)+- **FR-014**: Every grid change made by a shortcut MUST give visible feedback (the snap+ control updates, and the status line names the new state, as other toggles do today).+- **FR-015**: The new shortcuts MUST appear in Preferences → Shortcuts and in the app menu+ where editing commands are listed.++**Defaults and persistence**++- **FR-016**: On first launch (no saved preference) both editors MUST start in+ Adaptive · Medium, triplets off, snap on.+- **FR-017**: Each editor's grid settings MUST persist across app restarts as an app-wide+ preference, identical in every project. Grid settings MUST NOT be written to project+ files, and opening any project MUST NOT change them.++### Key Entities++- **Grid setting** (one per editor): mode (Adaptive or Fixed), density (Narrow, Medium,+ Wide; remembered while in Fixed), fixed step (remembered while in Adaptive), triplets+ on/off, snap on/off.+- **Quantize value** (piano roll only): a straight or triplet step used by Quantize,+ independent of the grid setting.+- **Step in effect**: derived from the grid setting and the editor's current zoom. It is+ shown on the control, drawn as the finest line, and used for snapping.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: In Adaptive mode, at every zoom level of both editors, 100% of snapped+ positions coincide with a drawn grid line, and every drawn subdivision line is+ reachable by snapping. In Fixed mode the same holds whenever the snap control does not+ carry the "finer than the visible grid" mark.+- **SC-002**: Placing a clip on an eighth-note off-beat, then moving a group of clips by+ whole bars, takes zero grid-control interactions in the default mode (zoom only).+- **SC-003**: Any grid value is reachable in at most 2 clicks (open menu, choose) or one+ shortcut press per ladder notch, compared with up to 4 clicks with today's forward+ cycling.+- **SC-004**: Snapping feels the same as today: no visible delay between the pointer+ moving and the dragged item jumping to the next grid position.+- **SC-005**: Existing projects open and edit exactly as before. No stored clip or note+ position changes because of this feature.++## Assumptions++- Density thresholds: Narrow about 6 px, Medium about 12 px, Wide about 24 px between+ finest lines. Final values are tuned during implementation so that FR-003's default+ (1/4 at the default arrangement zoom) holds.+- The piano roll's adaptive density is chosen so its default view resolves to about 1/16,+ close to its current default.+- 1/64 and 1/32T exist today only in the piano roll's fixed list. 1/64 is dropped and the+ ladder stops at 1/32 in both editors. 1/32T stays as the finest triplet step.+- The two editors share only the rule that computes the step in effect, not the setting+ itself (FR-001).+- ⌘1–⌘5 are currently unused in Nota. If the plan finds a conflict, the binding moves and+ the spec is updated.+- The MCP and Remote surfaces are out of scope. They do not expose the snap grid today.+- Groove/swing quantize is out of scope.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [x] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5) — UI-only, no engine change+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/` — no new crossings+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest` — no engine change; step resolution covered by managed unit tests+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them); new shortcuts via nota-shortcuts+- [ ] UI change → follows `DESIGN.md` (Ember design language)diff --git a/specs/003-adaptive-snap-grid/tasks.md b/specs/003-adaptive-snap-grid/tasks.mdnew file mode 100644index 00000000..897d8dd5--- /dev/null+++ b/specs/003-adaptive-snap-grid/tasks.md@@ -0,0 +1,321 @@+---++description: "Task list for the adaptive snap grid (arrangement + piano roll, with triplets)"+---++# Tasks: Adaptive Snap Grid++**Input**: Design documents from `specs/003-adaptive-snap-grid/`++**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/grid-ui.md](contracts/grid-ui.md), [quickstart.md](quickstart.md)++**Tests**: Included. The plan and quickstart §1 call for a pure-logic smoke-test section+(`SnapGridTests`, `--grid`). Write each test task before its implementation and see it+fail first.++**Organization**: By user story (spec.md): US1 snap follows zoom (P1), US2 menu and+shortcuts (P2), US3 triplets (P3).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)+- **[Story]**: US1, US2 or US3++## Path Conventions++- Rule (pure): `src/managed/Nota.Application/Editing/`+- App and views: `src/managed/Nota.App/`+- Tests: `tests/Nota.SmokeTest/`+- Every new `.cs` file starts with the two-line SPDX header from CONTRIBUTING.md and a+ short comment header explaining why the file exists (match `TapTempo.cs`).++---++## Phase 1: Setup (Shared Infrastructure)++**Purpose**: The empty test section and its runner flag, so later tasks can add cases.++- [X] T001 Create `tests/Nota.SmokeTest/SnapGridTests.cs` with `internal static class SnapGridTests { public static IEnumerable<(bool Ok, string Label)> Run() { yield break; } }`, following the `TapTempoTests.cs` pattern (header comment, `using Nota.Application.Editing;`)+- [X] T002 Wire the section into `tests/Nota.SmokeTest/Program.cs`: a `--grid` early-exit block printing `GRID PASSED` / `GRID FAILED (n)` next to the `--tap` block (around line 210), and `Console.WriteLine("-- snap grid --"); foreach (...) Check(ok, label);` in the full run after the tap-tempo section (around line 14514)++---++## Phase 2: Foundational (Blocking Prerequisites)++**Purpose**: The rule, its persistence and the live state. Every story builds on them.++**⚠️ CRITICAL**: No user story work can begin until this phase is complete.++### Tests (write first, see them fail)++- [X] T003 Add the foundational cases to `tests/Nota.SmokeTest/SnapGridTests.cs`:+ - `GridStep(Index 0..7)` beats in 4/4 = 0.125, 0.25, 0.5, 1, 2, 4, 8, 16, and in 3/4 the bar steps are 3, 6, 12;+ - `Index` is clamped to 0..7;+ - labels "1/32" … "1/2", "1 bar", "2 bars", "4 bars";+ - default `GridSetting` resolves to 1/4 at 28 px per beat in 4/4 (FR-003);+ - at a fixed zoom, Narrow < Medium < Wide (strictly finer to coarser);+ - clamps to 1/32 at 240 px per beat (Narrow) and to 4 bars at 0.5 px per beat (Wide);+ - `SnapBeat` returns the nearest position and is never negative;+ - for many zoom and step combinations, every `GridLines` position snaps to itself and every `SnapBeat` result is in `GridLines` (SC-001);+ - `Label` gives "Auto · 1/4" for Adaptive and "1/8" for Fixed 1/8.++### Implementation++- [X] T004 Create `src/managed/Nota.Application/Editing/SnapGrid.cs` with the value types from data-model.md:+ - `GridStep` with `Index` (int, "clamped to 0..7") and `Triplet` (bool, "forced false when `Index ≥ 5`"), `Beats(int beatsPerBar)` and `Label`;+ - `enum GridDensity { Narrow, Medium, Wide }` with thresholds 8, 16 and 32 px (research R2);+ - `GridSetting` as a record with `Adaptive` = true, `Density` = Medium, `FixedIndex`, `Triplets` = false, `SnapOn` = true, and static `DefaultArrangement` (`FixedIndex` 3) and `DefaultPianoRoll` (`FixedIndex` 1);+ - `ResolvedGrid` (`Snap`, `Draw`, `FinerThanVisible`, `SnapOn`).+- [X] T005 In `src/managed/Nota.Application/Editing/SnapGrid.cs`, implement `static ResolvedGrid Resolve(GridSetting s, double pixelsPerBeat, int beatsPerBar)`:+ - Adaptive: the smallest Index in the setting's triplet family with `Beats × ppb ≥ threshold(Density)`, clamped, and `Draw = Snap`;+ - Fixed: `Snap = (FixedIndex, Triplets)`, and `Draw` is the smallest `Index ≥ FixedIndex` meeting the Medium threshold (16 px), clamped to 7;+ - `FinerThanVisible = Draw.Index > Snap.Index`.+ - Allocation-free; the zero and negative ppb guard returns 1/4.+- [X] T006 In `src/managed/Nota.Application/Editing/SnapGrid.cs`, implement `static double SnapBeat(double beat, double stepBeats, int beatsPerBar)` and `static IEnumerable<double> GridLines(double from, double to, double stepBeats, int beatsPerBar)` on one shared position rule, anchored per bar (research R4):+ - sub-bar steps: `barStart + n·step` for every n with `n·step < barLength − 1e-6`, plus the next bar start;+ - bar steps: multiples of `k·beatsPerBar` from beat 0;+ - results clamped at 0.+- [X] T007 In `src/managed/Nota.Application/Editing/SnapGrid.cs`, implement `static string Label(GridSetting s, ResolvedGrid r)`: "Auto · " + `r.Snap.Label` when Adaptive, else `r.Snap.Label`.+- [X] T008 [P] Add `public GridSetting ArrangementGrid { get; set; } = GridSetting.DefaultArrangement;`, `public GridSetting PianoRollGrid { get; set; } = GridSetting.DefaultPianoRoll;` and `public GridStep QuantizeStep { get; set; } = new(1, false);` to `src/managed/Nota.Application/Settings.cs`, with doc comments ("app-wide, never written to project files", FR-017). Make the types JSON-friendly (public get/set or init, parameterless construction) for `System.Text.Json` in `SettingsService`.+- [X] T009 Add settings cases to `tests/Nota.SmokeTest/SnapGridTests.cs`:+ - deserializing `{}` into `Settings` gives the FR-016 defaults;+ - a serialize, change and deserialize round trip keeps `ArrangementGrid`, `PianoRollGrid` and `QuantizeStep` independent;+ - an out-of-range `FixedIndex` (for example 42) is clamped on resolve.+- [X] T010 Create `src/managed/Nota.App/EditorGrids.cs` (research R8):+ - `enum EditorKind { Arrangement, PianoRoll }`;+ - `sealed class EditorGrids(ISettingsService settings)` exposing `Get(EditorKind)`, `Set(EditorKind, GridSetting)`, `Quantize`, `SetQuantize(GridStep)` and `event Action<EditorKind>? Changed`;+ - it loads from `settings.Current` and saves via `settings.Save()` on each change; a no-op when the value is unchanged.+- [X] T011 Create the `EditorGrids` instance in `src/managed/Nota.App/MainWindow.axaml.cs`, next to where `_vm` and services are set up, from `App.Services.GetRequiredService<ISettingsService>()`. Expose it as `internal EditorGrids Grids` so `DetailWindow` and the detail builders can reach it.++**Checkpoint**: `dotnet run --project tests/Nota.SmokeTest -- --grid` prints GRID PASSED.++---++## Phase 3: User Story 1 - Snap follows the zoom (Priority: P1) 🎯 MVP++**Goal**: In both editors the step to snap to equals the finest drawn line, chosen from+the zoom, with Adaptive · Medium as the default. The snap controls show the step in+effect.++**Independent Test**: With default settings, zoom each editor in and out and drag a+clip or note. It lands only on drawn lines, and the control reads "Auto · <step>" and+changes with zoom (quickstart §3 rows 1–3, 11).++### Arrangement++- [X] T012 [US1] In `src/managed/Nota.App/ArrangementView.cs`:+ - replace `_snapBeats` and `_snapEnabled` (lines 41–42) and the `SnapBeats` / `SnapEnabled` properties (lines 432 and 437) with a required `EditorGrids Grids` (init or constructor), a cached `ResolvedGrid _grid` and `internal ResolvedGrid Grid => _grid`;+ - recompute `_grid` in a `RefreshGrid()` that runs on zoom changes (both `_pixelsPerBeat` writes around lines 646 and 655, plus `ArrangementView.Overview.cs:95`), on `BeatsPerBar` set (line 430) and on `Grids.Changed(Arrangement)`;+ - raise `event Action? GridChanged` only when `_grid` actually changes.+- [X] T013 [US1] In `src/managed/Nota.App/ArrangementView.cs`, change `Snap(double)` (line 1051) to `_grid.SnapOn ? SnapGrid.SnapBeat(beat, _grid.Snap.Beats(_beatsPerBar), _beatsPerBar) : beat`. Keep `SnapMaybe` (Alt bypass) and `SnapMagnetic` (magnet) as they are. Replace the two `_snapBeats` uses in the loop range (lines 561 and 588) with the resolved step's beats.+- [X] T014 [P] [US1] In `src/managed/Nota.App/ArrangementView.LaneControl.cs` (vertical grid around lines 1275–1285), draw lines from `SnapGrid.GridLines(viewStart, viewEnd, _o.Grid.Draw.Beats(_o._beatsPerBar), _o._beatsPerBar)`: `BarPen` on bar starts, `BeatPen` on whole beats, and a new sub-beat pen (`NotaPalette.GridSubBeat`, as in `PianoRollView`) otherwise. Remove the `showBeats` threshold.+- [X] T015 [P] [US1] The same grid-line change in `src/managed/Nota.App/ArrangementView.Controls.cs` (footer grid around lines 189–200).+- [X] T016 [US1] In `src/managed/Nota.App/MainWindow.axaml.cs`:+ - delete `SnapSteps`, `_snapIndex` (lines 570–574) and `OnCycleSnap` (line 656);+ - pass `Grids` to `Timeline`;+ - bind `SnapToggle` both ways to `Grids.Get(Arrangement).SnapOn` (rewrite `OnToggleSnapEnabled` at line 721 to `Grids.Set(... with { SnapOn = on })`, and update `SnapToggle.IsChecked` on `Grids.Changed`).++### Snap chip (label only in this story)++- [X] T017 [US1] Create `src/managed/Nota.App/SnapChip.cs`, a control taking `(EditorKind kind, EditorGrids grids, Func<ResolvedGrid> current)`:+ - renders `SnapGrid.Label` in the Mono style of today's `SnapLabel` (`MainWindow.axaml:240`), with the tooltip from contracts/grid-ui.md;+ - exposes `Refresh()`, called on `Grids.Changed(kind)` and on the editor's `GridChanged`;+ - fixes its width to the widest label ("Auto · 1/16T") so the toolbar does not jitter (plan Risks).+ The menu comes in US2.+- [X] T018 [US1] In `src/managed/Nota.App/MainWindow.axaml` (lines 238–240), replace the `SnapChip` button's `Click="OnCycleSnap"` cell content with the `SnapChip` control, keeping the cell classes. Check that `MainWindow.TransportFit.cs` still hides and shows the cell correctly with the wider label.++### Piano roll++- [X] T019 [US1] In `src/managed/Nota.App/PianoRollView.cs`:+ - remove `_grid` (line 72), the `Grid` property (line 348), `GridLadder` and `GridStepBeats()` (lines 761–770);+ - add a required `EditorGrids Grids`, a `BeatsPerBar` property (default 4), a cached `ResolvedGrid _resolved` with `internal ResolvedGrid ResolvedGridState`, and `GridChanged`;+ - recompute `_resolved` on every `_pixelsPerBeat` write (lines 146, 166 and 367), on `BeatsPerBar` set and on `Grids.Changed(PianoRoll)`.+- [X] T020 [US1] In `src/managed/Nota.App/PianoRollView.cs`, switch every snap use from `_grid` to the resolved snap step through `SnapGrid.SnapBeat` (honouring `SnapOn` and the existing Alt handling):+ - `NoteGrid.Snap` (line 950);+ - new-note start and length (line 1120, length = one step);+ - the duplicate shift and caps (lines 427–428, 1184, 1203, 1215);+ - the paste anchor (line 646);+ - note length minimum (line 654);+ - ← → nudges (lines 1373–1374).+- [X] T021 [US1] In `src/managed/Nota.App/PianoRollView.cs`:+ - the note-grid line loop (around line 976) iterates `SnapGrid.GridLines(..., _resolved.Draw.Beats(BeatsPerBar), BeatsPerBar)`;+ - `GridPen(b)` and `GridLabel(b)` (lines 783–799) use `BeatsPerBar` instead of the literal 4 (research R5);+ - `LabelStepBeats()` stays.+- [X] T022 [P] [US1] In `src/managed/Nota.App/PianoRollView.Expression.cs` (line 251), replace `_o.GridStepBeats()` with the resolved draw step and iterate `SnapGrid.GridLines`.+- [X] T023 [US1] In `src/managed/Nota.App/PianoRollView.cs`, change `Quantize(strength)` (line 592) to use `Grids.Quantize.Beats(BeatsPerBar)` (FR-008a). In `src/managed/Nota.App/MidiToolsView.cs` (line 170), set `Grid = _roll.Grids.Quantize.Beats(_roll.BeatsPerBar)` (research R11).+- [X] T024 [US1] In `src/managed/Nota.App/ClipPropsView.cs` (lines 20–65):+ - rename the GRID section to QUANTIZE;+ - replace `GridValues`, `GridLabels` and `_gridIndex` with the straight sub-bar steps 1/32 … 1/2 (`Index` 0..4, "Bar steps are not offered for Quantize");+ - the dropdown calls `grids.SetQuantize(...)` and shows `grids.Quantize.Label`; default 1/16 comes from Settings;+ - the Quantize button and STRENGTH slider are unchanged.+ Triplet values are added in US3.+- [X] T025 [US1] In `src/managed/Nota.App/MainWindow.Detail.cs`, at both `new PianoRollView` sites (lines 394 and 595), pass `Grids = Grids` and `BeatsPerBar = Timeline.BeatsPerBar` (or the transport's numerator), and keep `BeatsPerBar` in sync when the time signature changes (where `Timeline.BeatsPerBar` is updated today). Pass `Grids` to `ClipPropsView` via `src/managed/Nota.App/ClipEditorView.cs` (line 48).+- [X] T026 [US1] In `src/managed/Nota.App/ClipEditorView.cs`, add a `SnapChip(EditorKind.PianoRoll, roll.Grids, () => roll.ResolvedGridState)` to the header's right group, before `ScaleControls()` (line 61), with a `HeaderDivider()` between them.+- [X] T027 [US1] Build and fix every remaining reference to the removed members: `dotnet build src/managed/Nota.App/Nota.App.csproj`. Check with `grep -rn "SnapBeats\|SnapEnabled\|GridStepBeats\|_roll.Grid\b\|\._grid\b" src/managed` (expect none).++**Checkpoint**: US1 works on its own: the default is Auto, lines and snapping agree in both+editors, the chips show the live step, and ⌥ and the magnet still work.++---++## Phase 4: User Story 2 - Pick a grid quickly from a menu or the keyboard (Priority: P2)++**Goal**: The chip opens a menu with every option; ⌘1, ⌘2, ⌘4 and ⌘5 drive the grid from+the keyboard; and Fixed mode marks a step that is finer than the drawn lines.++**Independent Test**: Quickstart §3 rows 4, 5, 8, 9 and 10, plus the palette checks in+`scripts/build.sh`.++### Tests (write first)++- [X] T028 [P] [US2] Add transition cases to `tests/Nota.SmokeTest/SnapGridTests.cs` per the data-model.md transitions table:+ - `Narrower` and `Wider` in Fixed mode step `FixedIndex` and stop at 0 and 7;+ - in Adaptive mode they step the density and stop at Narrow and Wide;+ - `ToggleAdaptive` twice restores both the density and the fixed step;+ - `ToggleSnap` flips only `SnapOn`;+ - `PickAdaptive` and `PickFixed` set `SnapOn = true`;+ - Fixed 1/32 at 4 px per beat gives `FinerThanVisible` true with a coarser `Draw`; at 240 px per beat it is false (FR-005a).++### Implementation++- [X] T029 [US2] In `src/managed/Nota.Application/Editing/SnapGrid.cs`, add pure transitions returning a new `GridSetting`: `Narrower`, `Wider`, `ToggleSnap`, `ToggleAdaptive`, `PickAdaptive(GridDensity)` and `PickFixed(int index)`. The exact rules are in the data-model.md table. "The shortcuts other than ⌘4 leave `SnapOn` as it is."+- [X] T030 [US2] In `src/managed/Nota.App/SnapChip.cs`:+ - add the click menu from contracts/grid-ui.md (Auto · Narrow/Medium/Wide, separator, the 8 fixed steps, separator, Snap to grid ⌘4), with a check mark on the active row; build it with the app's existing menu helpers (the `ShowMenu` style used by `ClipPropsView`);+ - add the label states: dimmed secondary colour plus the "finer than the visible grid" tooltip when `FinerThanVisible`, and struck through in the disabled colour when `!SnapOn`;+ - follow `DESIGN.md` Ember tokens (nota-design skill).+- [X] T031 [US2] In `src/managed/Nota.Application/Palette/CommandCatalog.cs`, add a `// ---- Grid` block with `grid.narrower` "Narrow Grid" ⌘1, `grid.wider` "Widen Grid" ⌘2, `grid.snap` "Toggle Snap to Grid" ⌘4 and `grid.adaptive` "Toggle Adaptive Grid" ⌘5, with aliases from contracts/grid-ui.md. `grid.triplets` comes in US3.+- [X] T032 [US2] In `src/managed/Nota.App/MainWindow.Commands.cs`:+ - bind the four commands to `Grids.Set(target, SnapGrid.X(Grids.Get(target)))`;+ - set the status line to `"<Arrangement|Piano roll> grid: <label>"` (FR-014);+ - choose the target with a helper `EditorKind GridTarget()`: PianoRoll when `_detailWasLastFocused` and the detail area shows a `ClipEditorView`, else Arrangement (research R9).+- [X] T033 [US2] In `src/managed/Nota.App/MainWindow.axaml`, add an Edit → Grid submenu with `NativeMenuItem`s carrying `app:Commands.Id="grid.narrower"`, `"grid.wider"`, `"grid.snap"` and `"grid.adaptive"` (the gestures come from the catalog via `MainWindow.MenuKeys.cs`).+- [X] T034 [US2] In `src/managed/Nota.App/PreferencesWindow.cs` (the shortcuts table around lines 1000–1080), add the GRID group with the rows from contracts/grid-ui.md (⌘1 ⌘2, ⌘4, ⌘5, ⌥ while dragging). Use the nota-shortcuts skill to check that the list matches the handlers.+- [X] T035 [US2] Run `dotnet run --project tests/Nota.SmokeTest -- --grid` and the palette checks (`scripts/build.sh`). Confirm "every catalog shortcut is listed in Settings → Shortcuts" and that every id is bound.++**Checkpoint**: US1 and US2 both work. The grid is fully controllable without cycling.++---++## Phase 5: User Story 3 - Triplet grid (Priority: P3)++**Goal**: Triplet lines and snapping in both editors and both modes, ⌘3 to toggle, and+triplet Quantize values.++**Independent Test**: Quickstart §3 rows 6 and 7; the triplet cases in `--grid`.++### Tests (write first)++- [X] T036 [P] [US3] Add triplet cases to `tests/Nota.SmokeTest/SnapGridTests.cs`:+ - triplet beats are 2/3 of straight ones (1/8T = 1/3, 1/4T = 2/3, 1/2T = 4/3);+ - bar steps ignore `Triplet`;+ - labels "1/8T" and "Auto · 1/16T";+ - Adaptive with triplets moves through the triplet family as the zoom changes;+ - `ToggleTriplets` flips only `Triplets`;+ - in 3/4, 1/2 and 1/2T keep every bar start as a snap point and in `GridLines`;+ - line and snap agreement (SC-001) holds for all triplet steps.++### Implementation++- [X] T037 [US3] In `src/managed/Nota.Application/Editing/SnapGrid.cs`:+ - make sure `Resolve` keeps the triplet family for sub-bar steps and switches to straight bar steps once the Index reaches 5;+ - add `ToggleTriplets`;+ - `GridStep.Label` appends "T".+- [X] T038 [P] [US3] Add triplet rows to the chip menu in `src/managed/Nota.App/SnapChip.cs`: a "Triplets ⌘3" check row, with the fixed rows showing 1/32T … 1/2T when triplets are on (contract menu).+- [X] T039 [US3] Add `grid.triplets` "Toggle Triplet Grid" ⌘3 to `src/managed/Nota.Application/Palette/CommandCatalog.cs`, bind it in `src/managed/Nota.App/MainWindow.Commands.cs` the same way as T032, add it to the Edit → Grid submenu in `src/managed/Nota.App/MainWindow.axaml` (after Widen Grid), and add the ⌘3 row to the GRID group in `src/managed/Nota.App/PreferencesWindow.cs`.+- [X] T040 [P] [US3] Grid pens for triplet lines in `src/managed/Nota.App/PianoRollView.cs` (`GridPen`) and in the arrangement grid loops (`ArrangementView.LaneControl.cs` and `ArrangementView.Controls.cs`): the bar and beat tests use a tolerance, so 2/3-beat positions draw with the sub-beat pen and whole beats keep `BeatPen` (FR-006). `GridLabel` stays 1/16-based. Ruler labels never show triplet indices (`LabelStepBeats` limits them).+- [X] T041 [US3] Add the triplet Quantize values 1/32T … 1/2T (`Index` 0..4, `Triplet` true) to the QUANTIZE dropdown in `src/managed/Nota.App/ClipPropsView.cs`, after the straight values, as today's list does.++**Checkpoint**: All three stories work independently.++---++## Phase 6: Polish & Cross-Cutting Concerns++- [X] T042 [P] Add an `[Unreleased]` entry to `CHANGELOG.md`:+ - Added: the adaptive snap grid in the arrangement and piano roll, with Narrow/Medium/Wide, triplets, the grid menu, ⌘1–⌘5 and a separate Quantize value;+ - Changed: the snap cell opens a menu instead of cycling, and the piano roll's GRID becomes QUANTIZE; mention ⌘5 to get a fixed grid back.+- [X] T043 [P] Update `FEATURES.md` via the `nota-features` skill.+- [X] T044 Update the user docs (`../nota-docs`, EN + RU) via the `nota-docs` skill: the arrangement grid, the piano roll grid and Quantize pages, the regenerated shortcuts page, and re-shot screenshots of the chip and menu.+- [X] T045 Headless UI verification per quickstart §3 (the nota-ui-verify recipe, `NOTA_DATA_DIR=/tmp/nota-grid`): screenshots of the arrangement chip at default zoom, Fixed 1/32 zoomed out (dimmed), and the piano roll with triplets, in Ember Graphite and Ember Paper. Check the toolbar at narrow widths (`MainWindow.TransportFit.cs`).+- [X] T046 Check SC-004 and SC-005:+ - no allocation in `Resolve` or `SnapBeat` per pointer move (review the code; the label updates only when the step changes);+ - open an existing project and confirm no clip or note positions change.+- [X] T047 Run quickstart.md end to end.++### Nota closing tasks *(PR gates)*++- [X] T048 Run `scripts/build.sh` until native, managed and the smoke test (including `-- snap grid --`) are green+- [X] T049 Check that the AGPL-3.0-only SPDX two-line header is on `SnapGrid.cs`, `EditorGrids.cs`, `SnapChip.cs` and `SnapGridTests.cs`+- [X] T050 New dependency: N/A (none added)+- [X] T051 CHANGELOG entry: covered by T042+- [X] T052 FEATURES.md, docs and shortcuts: covered by T043, T044 and T034/T039 (nota-shortcuts)+- [X] T053 Engine behaviour change: N/A (UI only); the smoke test still gains the SnapGrid section (T001–T003, T009, T028, T036)++---++## Dependencies & Execution Order++### Phase Dependencies++- **Setup (T001–T002)**: none.+- **Foundational (T003–T011)**: after Setup; blocks every story. Inside the phase: T003 → T004 → T005, T006, T007 (same file, sequential) → T008 [P with T004–T007] → T009 → T010 → T011.+- **US1 (T012–T027)**: after Foundational.+- **US2 (T028–T035)**: after Foundational. It touches `SnapChip.cs` from T017, so do it after US1's T017–T018 in practice.+- **US3 (T036–T041)**: after Foundational. The menu rows (T038) need T030, and the command (T039) mirrors T031–T034, so do it after US2.+- **Polish (T042–T053)**: after the stories you ship.++### Within US1++T012 → T013 → (T014 ∥ T015) → T016 → T017 → T018; then T019 → T020 → T021 → (T022 ∥ T023) → T024 → T025 → T026 → T027.++### Parallel Opportunities++- T008 (Settings.cs) alongside T004–T007 (SnapGrid.cs).+- T014 and T015 (different arrangement partials).+- T022 (Expression lanes) alongside T023 (Quantize and MidiTools).+- Test tasks T028 and T036 alongside their stories' early implementation in other files.+- T040 alongside T038; T042 and T043.++## Parallel Example: User Story 1++```bash+# After T013 lands, the two arrangement grid loops are independent:+Task: "T014 grid lines from SnapGrid.GridLines in ArrangementView.LaneControl.cs"+Task: "T015 grid lines from SnapGrid.GridLines in ArrangementView.Controls.cs"++# After T021, the Expression lanes and Quantize are independent:+Task: "T022 Expression lanes use the resolved draw step in PianoRollView.Expression.cs"+Task: "T023 Quantize + MidiToolsView use Grids.Quantize"+```++---++## Implementation Strategy++### MVP first (US1)++1. Phases 1–2: the rule, its tests, persistence, `EditorGrids`.+2. Phase 3: both editors snap and draw from the rule, and the chips show "Auto · step".+3. **Stop and validate**: quickstart rows 1–3 and 11, plus `--grid`. This alone fixes the+ reported pain.++### Incremental delivery++1. + US2: the menu, ⌘1/⌘2/⌘4/⌘5 and the finer-than-visible mark.+2. + US3: triplets everywhere and ⌘3.+3. Polish: docs, screenshots, the gates. One PR for the whole feature (Constitution V).++## Notes++- Keep `SnapBar` (sections) and `AudioClipEditorView`'s own snap switch unchanged (research R12).+- Do not commit. The user reviews and commits the changes.++---++## Phase 7: Convergence++- [ ] T054 Make ⌘1–⌘5 work while the floating detail window is active on macOS: that window has no native menu, so the key equivalents never fire there. In `src/managed/Nota.App/MainWindow.Input.cs` `HandleFloatingKeyDown`, match ⌘/Ctrl + 1–5 (no Alt/Shift) and run `grid.narrower` / `grid.wider` / `grid.triplets` / `grid.snap` / `grid.adaptive` through `_commands.Run`, then mark the key handled. Keep Windows/Linux from running it twice (their `TryMenuShortcut` path). Per FR-013 and plan R9 (partial)+- [ ] T055 Snap the dragged note edge's absolute position in the piano roll, not only the drag delta. In `src/managed/Nota.App/PianoRollView.cs` (`Mode.Resize` / `Mode.ResizeLeft`, `_resizeAnchor`), the end (or start) of the grabbed note should land on `SnapBeat(XToBeat(p.X))`, and the other selected notes should move by the same delta. Today a note whose end is off the grid keeps that offset when you resize it. Per US1/AC3 and FR-008 (partial)+- [ ] T056 Decide and reconcile the arrangement toolbar label with FR-011, which requires "Auto · <step>" in Adaptive mode. The toolbar cell shows the step plus an "AUTO GRID" caption (`src/managed/Nota.App/SnapChip.cs`, `MainWindow.axaml` SnapChip cell). Either render "Auto · 1/8" in the cell, or amend FR-011 in spec.md to allow the two-line toolbar variant that is already documented in contracts/grid-ui.md. Per FR-011 (contradicts)+- [ ] T057 Ignore grid shortcuts while a text field has keyboard focus: on macOS the native menu fires ⌘1–⌘5 even in a TextBox. Add a guard at the top of `StepGrid` in `src/managed/Nota.App/MainWindow.Commands.cs`: return if the focused element is inside a `TextBox` or `NumericUpDown`. Per spec Edge Cases "Text entry" (partial)+- [ ] T058 Fix the snap controls' width to their widest label so they never shift while zooming. The toolbar value `MinWidth="46"` (`src/managed/Nota.App/MainWindow.axaml`) fits "1/16T" but not "2 bars" / "4 bars". The piano-roll chip's `MinWidth = 82` (`src/managed/Nota.App/SnapChip.cs`) is narrower than "Auto · 4 bars". Measure the widest label in the mono font, or raise the minimums. Per plan Risks (toolbar width) (partial)diff --git a/src/managed/Nota.App/ArrangementView.Controls.cs b/src/managed/Nota.App/ArrangementView.Controls.csindex 430a1d94..45ef6054 100644--- a/src/managed/Nota.App/ArrangementView.Controls.cs+++ b/src/managed/Nota.App/ArrangementView.Controls.cs@@ -186,18 +186,8 @@ public sealed partial class ArrangementViewctx.DrawLine(BeatPen, new Point(0, y + FooterRowH), new Point(w, y + FooterRowH));}- // Vertical grid (bars always; beats when zoomed in).- bool showBeats = _o._pixelsPerBeat >= 12;- int firstBeat = (int)Math.Floor(_o._scrollBeats);- for (int beat = firstBeat; ; beat++)- {- double x = _o.BeatToX(beat);- if (x > w) break;- if (x < 0) continue;- bool isBar = beat % _o._beatsPerBar == 0;- if (isBar) ctx.DrawLine(BarPen, new Point(x, 0), new Point(x, h));- else if (showBeats) ctx.DrawLine(BeatPen, new Point(x, 0), new Point(x, h));- }+ // Vertical grid: the snap grid's lines at this zoom — what you see is what you snap to.+ _o.DrawGrid(ctx, w, h);// Master row: master-volume automation (M9 follow-up) in automation mode,// else a quiet hint. Value axis 0..2 across the row.diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex 61da0628..a16867ab 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -1272,18 +1272,8 @@ public sealed partial class ArrangementViewif (_o.DropTrackIndex >= 0 && _o.DropTrackIndex < _o._tracks.Count)ctx.FillRectangle(DropWash, new Rect(0, RowTop(_o.DropTrackIndex), w, RowH(_o.DropTrackIndex)));- // Vertical grid: bars always, beats when zoomed in enough.- bool showBeats = _o._pixelsPerBeat >= 12;- int firstBeat = (int)Math.Floor(_o._scrollBeats);- for (int beat = firstBeat; ; beat++)- {- double x = _o.BeatToX(beat);- if (x > w) break;- if (x < 0) continue;- bool isBar = beat % _o._beatsPerBar == 0;- if (isBar) ctx.DrawLine(BarPen, new Point(x, 0), new Point(x, h));- else if (showBeats) ctx.DrawLine(BeatPen, new Point(x, 0), new Point(x, h));- }+ // Vertical grid: the snap grid's lines at this zoom — what you see is what you snap to.+ _o.DrawGrid(ctx, w, h);// Clips: a tinted body under a 2px colour band, with the name drawn only where a// run of clips starts (design 1a) so a repeating pattern reads as one block insteaddiff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex bb57cec0..292973f2 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -14,6 +14,7 @@ using Avalonia.Media;using Avalonia.Threading;using Avalonia.VisualTree;using Nota.Application;+using Nota.Application.Editing;using Nota.Presentation;namespace Nota.App;@@ -38,8 +39,7 @@ public sealed partial class ArrangementView : UserControlprivate double _playheadBeats;private double _totalBeats = 64;private int _beatsPerBar = 4;- private double _snapBeats = 1.0; // snap grid (1 beat) — M4-2- private bool _snapEnabled = true; // transport magnet toggle (off = free positioning)+ private ResolvedGrid _lastGrid; // what the snap chip last showed (GridChanged)internal int SelTrackId = -1, SelClipIndex = -1; // "primary" selection (Clip tab, effect target, trim)// Multi-selection of clips across tracks (marquee / group move + delete). The// primary (SelTrackId/SelClipIndex) is always one of these when non-empty.@@ -243,6 +243,7 @@ public sealed partial class ArrangementView : UserControlpublic ArrangementView(){+ EditorGrids.Shared.Changed += k => { if (k == EditorKind.Arrangement) Redraw(); };_ruler = new RulerControl(this) { Height = RulerH };_overview = new OverviewControl(this);_sectionsLane = new SectionsControl(this);@@ -428,13 +429,18 @@ public sealed partial class ArrangementView : UserControlpublic double ScrollBeats => _scrollBeats;public double PlayheadBeats => _playheadBeats;public int BeatsPerBar { get => _beatsPerBar; set { _beatsPerBar = value; Redraw(); } }- /// <summary>Clip-drag snap grid in beats (transport GRID cell, 1b).</summary>- public double SnapBeats { get => _snapBeats; set { _snapBeats = Math.Max(1.0 / 32, value); Redraw(); } }- /// <summary>Master snap on/off (the transport magnet). Off positions freely — the- /// same effect as holding Alt, but latched. The grid itself keeps its spacing, so- /// switching back resumes on the denomination the GRID cell shows.</summary>- public bool SnapEnabled { get => _snapEnabled; set { _snapEnabled = value; Redraw(); } }+ /// <summary>The snap grid at the current zoom (specs/003-adaptive-snap-grid): the step+ /// every clip edit snaps to and the finest line drawn. Resolved on demand — it is a few+ /// comparisons and allocates nothing — so zoom, time signature and setting changes can+ /// never leave a stale cache behind. Snap off (the transport magnet, ⌘4) keeps the lines.</summary>+ internal ResolvedGrid SnapGridState => SnapGrid.Resolve(EditorGrids.Shared.Get(EditorKind.Arrangement), _pixelsPerBeat, _beatsPerBar);++ /// <summary>The step in effect changed (zoom, time signature or the grid setting) — the+ /// toolbar's snap chip relabels.</summary>+ public event Action? GridChanged;++ private double SnapStepBeats => SnapGridState.Snap.Beats(_beatsPerBar);/// <summary>How many clips print their name on the lane (View ▸ Clip names). The default/// names only the head of each run, so a repeating pattern reads as one block.</summary>@@ -558,7 +564,7 @@ public sealed partial class ArrangementView : UserControl_loopDragging = true;_loopActive = true;_loopS = Math.Max(0, Snap(Math.Min(a, b)));- _loopE = Math.Max(_loopS + _snapBeats, Snap(Math.Max(a, b)));+ _loopE = Math.Max(_loopS + SnapStepBeats, Snap(Math.Max(a, b)));Redraw();}@@ -585,7 +591,7 @@ public sealed partial class ArrangementView : UserControlprivate (double Start, double End) SnapLoopRange(double a, double b){double s = Math.Max(0, Snap(Math.Min(a, b)));- return (s, Math.Max(s + _snapBeats, Snap(Math.Max(a, b))));+ return (s, Math.Max(s + SnapStepBeats, Snap(Math.Max(a, b))));}/// <summary>Loop over the beat span of the current clip selection. False if nothing selected.</summary>@@ -681,6 +687,8 @@ public sealed partial class ArrangementView : UserControl_footerLanes.InvalidateVisual();_overview.InvalidateVisual(); // the viewport window follows scroll+zoomUpdateOverviewRange();+ var g = SnapGridState;+ if (g != _lastGrid) { _lastGrid = g; GridChanged?.Invoke(); }}/// <summary>Rebuilds the track/clip model + headers from the engine. Pass@@ -1049,7 +1057,10 @@ public sealed partial class ArrangementView : UserControl}internal double Snap(double beat)- => _snapEnabled && _snapBeats > 0 ? Math.Round(beat / _snapBeats) * _snapBeats : beat;+ {+ var g = SnapGridState;+ return g.SnapOn ? SnapGrid.SnapBeat(beat, g.Snap.Beats(_beatsPerBar), _beatsPerBar) : beat;+ }/// <summary>Snap unless Alt is held (Alt = free/fine positioning). Reads the live/// modifier state so it can be toggled mid-drag (req 1.2.1/2.4/3.1/8.2.1, 7.10).</summary>@@ -2471,6 +2482,7 @@ public sealed partial class ArrangementView : UserControlprivate static readonly IBrush ChromeBg = NotaPalette.BgSunken; // Brush.BgSunkenprivate static readonly IPen BeatPen = new Pen(NotaPalette.GridBeat, 1); // Brush.GridBeatprivate static readonly IPen BarPen = new Pen(NotaPalette.GridBar, 1); // Brush.GridBar+ private static readonly IPen SubBeatPen = new Pen(NotaPalette.GridSubBeat, 1); // finer than a beat// Playhead: a 1px brass line with a 7×5 flag on the ruler, no glow (almanac § timeline).// The brush is the palette slot itself — a SolidColorBrush built from its Color froze the// playhead in one theme.@@ -2638,4 +2650,22 @@ public sealed partial class ArrangementView : UserControlprivate static IBrush Alpha(Color c, double a) => new SolidColorBrush(Color.FromArgb((byte)(a * 255), c.R, c.G, c.B));private double BeatToX(double beat) => (beat - _scrollBeats) * _pixelsPerBeat;++ /// <summary>The vertical grid over a lane-wide canvas: one line per snap position at the+ /// drawn step (SnapGrid.GridLines, the same set Snap() lands on), weighted bar › beat ›+ /// sub-beat. Shared by the lanes and the footer rows.</summary>+ private void DrawGrid(DrawingContext ctx, double w, double h)+ {+ if (_pixelsPerBeat <= 0) return;+ double step = SnapGridState.Draw.Beats(_beatsPerBar);+ double bar = _beatsPerBar > 0 ? _beatsPerBar : 4;+ foreach (double b in SnapGrid.GridLines(_scrollBeats, _scrollBeats + w / _pixelsPerBeat, step, _beatsPerBar))+ {+ double x = BeatToX(b);+ var pen = IsWhole(b / bar) ? BarPen : IsWhole(b) ? BeatPen : SubBeatPen;+ ctx.DrawLine(pen, new Point(x, 0), new Point(x, h));+ }++ static bool IsWhole(double v) => Math.Abs(v - Math.Round(v)) < 1e-6;+ }}diff --git a/src/managed/Nota.App/ClipEditorView.cs b/src/managed/Nota.App/ClipEditorView.csindex 685ab053..1fbfb3a3 100644--- a/src/managed/Nota.App/ClipEditorView.cs+++ b/src/managed/Nota.App/ClipEditorView.cs@@ -61,13 +61,21 @@ public sealed class ClipEditorView : UserControlvar right = new StackPanel{Orientation = Orientation.Horizontal, Spacing = 12,- Children = { ScaleControls(), HeaderDivider(), _toolsToggle },+ Children = { SnapControl(roll), HeaderDivider(), ScaleControls(), HeaderDivider(), _toolsToggle },};var header = Header(roll.TrackBrush, clipName, "MIDI", tabs, null, right);DockPanel.SetDock(header, Dock.Top);Content = new DockPanel { Background = NotaPalette.Gutter, Children = { header, grid } };}+ // The piano roll's snap chip: "Auto · 1/16", live with the roll's zoom; click for the grid menu.+ private static Control SnapControl(PianoRollView roll)+ {+ var (button, chip) = SnapChip.Create(EditorKind.PianoRoll, () => roll.SnapGridState);+ roll.GridChanged += chip.Refresh;+ return button;+ }+/// <summary>Follows a clip that was moved or resized in the arrangement while this editor/// stayed on screen. The roll's own length is pushed by <c>PianoRollView.SetNotes</c>/// (which also refreshes the inspector's LENGTH/LOOP); this carries the pieces thatdiff --git a/src/managed/Nota.App/ClipPropsView.cs b/src/managed/Nota.App/ClipPropsView.csindex 3469abd4..cecd94bd 100644--- a/src/managed/Nota.App/ClipPropsView.cs+++ b/src/managed/Nota.App/ClipPropsView.cs@@ -2,8 +2,8 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// The 232px inspector beside the piano roll (nota-design "Nota Clip Editor" 1a): CLIP-// (Start / Length in bars.beats.16ths, the Loop switch and its length), GRID (grid-// dropdown, Quantize, strength), TRANSPOSE (− value +) and SELECTION (the selected note's+// (Start / Length in bars.beats.16ths, the Loop switch and its length), QUANTIZE (its step,+// Quantize, strength — the snap grid itself is the header chip), TRANSPOSE (− value +) and SELECTION (the selected note's// pitch / start / length / velocity, or the range of several), ending in one hint line.// Edits drive the PianoRollView; read-outs follow its Changed event.@@ -12,17 +12,20 @@ using System.Linq;using Avalonia;using Avalonia.Controls;using Avalonia.Media;+using Nota.Application.Editing;using static Nota.App.ClipEditorKit;namespace Nota.App;public sealed class ClipPropsView : UserControl{- // Grid steps in beats (4/4, one beat = a 1/4 note). Straight divisions then triplets.- private static readonly double[] GridValues =- { 4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.0625, 2.0 / 3, 1.0 / 3, 1.0 / 6, 1.0 / 12 };- private static readonly string[] GridLabels =- { "1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/4T", "1/8T", "1/16T", "1/32T" };+ // Quantize steps (the app-wide Settings.QuantizeStep, independent of the snap grid and+ // the zoom): straight divisions coarse to fine, then triplets. No bar steps.+ private static readonly GridStep[] QuantizeSteps =+ {+ GridStep.Of(4, false), GridStep.Of(3, false), GridStep.Of(2, false), GridStep.Of(1, false), GridStep.Of(0, false),+ GridStep.Of(4, true), GridStep.Of(3, true), GridStep.Of(2, true), GridStep.Of(1, true), GridStep.Of(0, true),+ };private readonly PianoRollView _roll;private readonly TextBlock _startText = Mono("");@@ -34,7 +37,6 @@ public sealed class ClipPropsView : UserControlprivate readonly StackPanel _selRows = new();private readonly Border _selCard;private readonly Border _selEmpty;- private int _gridIndex = 4; // 1/16private int _transpose;private double _strength = 0.8;@@ -42,7 +44,7 @@ public sealed class ClipPropsView : UserControl{_roll = roll;_startText.Text = Position(startBeat);- _gridText.Text = GridLabels[_gridIndex];+ _gridText.Text = roll.Grids.Quantize.Label;// CLIP — clips always loop in this model; the switch waits for a per-clip loop.var loop = SwitchRow("Loop", () => true, () => { }, out _, _loopText);@@ -52,13 +54,14 @@ public sealed class ClipPropsView : UserControlPair(Labeled("Start", Field(_startText)), Labeled("Length", Field(_lengthText))),loop);- // GRID — the grid step, one-tap Quantize at the strength below.- var grid = Section("GRID",- Pair(Dropdown(_gridText, a => ShowMenu(a, GridLabels, _gridIndex, i =>+ // QUANTIZE — its own step (not the snap grid, which follows the zoom), one-tap+ // Quantize at the strength below.+ var grid = Section("QUANTIZE",+ Pair(Dropdown(_gridText, a => ShowMenu(a, Array.ConvertAll(QuantizeSteps, q => q.Label),+ Array.IndexOf(QuantizeSteps, _roll.Grids.Quantize), i =>{- _gridIndex = i;- _gridText.Text = GridLabels[i];- _roll.Grid = GridValues[i];+ _roll.Grids.SetQuantize(QuantizeSteps[i]);+ _gridText.Text = QuantizeSteps[i].Label;})),ClipEditorKit.Button("Quantize", () => _roll.Quantize(_strength))),SliderRow("STRENGTH", 64, () => _strength, v => _strength = v,diff --git a/src/managed/Nota.App/EditorGrids.cs b/src/managed/Nota.App/EditorGrids.csnew file mode 100644index 00000000..8cfb0887--- /dev/null+++ b/src/managed/Nota.App/EditorGrids.cs@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The live snap-grid settings of the two editors plus the piano roll's Quantize step+// (specs/003-adaptive-snap-grid). App-wide rather than per view: the piano roll is rebuilt+// for every clip and can float in the detail window, and its grid must not reset when that+// happens. Loads from and saves to Settings (settings.json), never to a project; every+// change raises Changed so views redraw and snap chips relabel.++using System;+using Microsoft.Extensions.DependencyInjection;+using Nota.Application;+using Nota.Application.Editing;++namespace Nota.App;++public enum EditorKind { Arrangement, PianoRoll }++public sealed class EditorGrids+{+ private static EditorGrids? s_shared;++ /// <summary>The app's one instance, on the registered settings service.</summary>+ public static EditorGrids Shared => s_shared ??= new EditorGrids(App.Services.GetRequiredService<ISettingsService>());++ private readonly ISettingsService _settings;++ public EditorGrids(ISettingsService settings) => _settings = settings;++ public event Action<EditorKind>? Changed;++ public GridSetting Get(EditorKind kind) => (kind == EditorKind.Arrangement+ ? _settings.Current.ArrangementGrid : _settings.Current.PianoRollGrid) ?? Default(kind);++ public void Set(EditorKind kind, GridSetting value)+ {+ if (value == Get(kind)) return;+ if (kind == EditorKind.Arrangement) _settings.Current.ArrangementGrid = value;+ else _settings.Current.PianoRollGrid = value;+ _settings.Save();+ Changed?.Invoke(kind);+ }++ /// <summary>The piano roll's Quantize step (also the clip tools' grid).</summary>+ public GridStep Quantize => _settings.Current.QuantizeStep.Normalize();++ public void SetQuantize(GridStep step)+ {+ step = step.Normalize();+ if (step == Quantize) return;+ _settings.Current.QuantizeStep = step;+ _settings.Save();+ Changed?.Invoke(EditorKind.PianoRoll);+ }++ private static GridSetting Default(EditorKind kind)+ => kind == EditorKind.Arrangement ? GridSetting.DefaultArrangement : GridSetting.DefaultPianoRoll;+}diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.csindex bc99263e..8ca5aeeb 100644--- a/src/managed/Nota.App/MainWindow.Commands.cs+++ b/src/managed/Nota.App/MainWindow.Commands.cs@@ -12,6 +12,7 @@ using Avalonia.Controls;using Avalonia.Interactivity;using Microsoft.Extensions.DependencyInjection;using Nota.Application;+using Nota.Application.Editing;using Nota.Application.Palette;using Nota.Presentation;@@ -110,6 +111,14 @@ public partial class MainWindow// ---- Piano roll: the clip open in the editorAvailability Roll(PaletteContext c) => Need(c.HasOpenMidiClip, "Open a MIDI clip first");+ // ---- Grid: the editor used last (piano roll or arrangement), status line names it+ void G(string id, Func<GridSetting, GridSetting> step) => B(id, () => StepGrid(step));+ G("grid.narrower", SnapGrid.Narrower);+ G("grid.wider", SnapGrid.Wider);+ G("grid.triplets", SnapGrid.ToggleTriplets);+ G("grid.snap", SnapGrid.ToggleSnap);+ G("grid.adaptive", SnapGrid.ToggleAdaptive);+B("roll.quantize", () => { if (_editorRoll is { } roll) { roll.Quantize(1.0); if (_vm is not null) _vm.StatusText = "Quantized notes"; } }, Roll);B("roll.octaveUp", () => _editorRoll?.TransposeBy(12), Roll);B("roll.octaveDown", () => _editorRoll?.TransposeBy(-12), Roll);@@ -175,4 +184,23 @@ public partial class MainWindow_vm.StatusText = locked ? "Envelopes locked — clip moves keep automation in place": "Envelopes follow clips";}++ // The grid shortcuts act on the piano roll when the detail area (docked or floating) was+ // used last and a MIDI clip is open in it; otherwise on the arrangement.+ private EditorKind GridTarget()+ {+ bool rollOpen = _editorRoll is { } roll && _clipEditor is not null && roll.IsEffectivelyVisible;+ bool detailLast = _detailWasLastFocused || _detailWindow?.IsActive == true;+ return rollOpen && detailLast ? EditorKind.PianoRoll : EditorKind.Arrangement;+ }++ private void StepGrid(Func<GridSetting, GridSetting> step)+ {+ var kind = GridTarget();+ var grids = EditorGrids.Shared;+ grids.Set(kind, step(grids.Get(kind)));+ var r = kind == EditorKind.PianoRoll && _editorRoll is { } roll ? roll.SnapGridState : Timeline.SnapGridState;+ string label = r.SnapOn ? SnapGrid.Label(grids.Get(kind), r) : "Snap off";+ if (_vm is not null) _vm.StatusText = $"{(kind == EditorKind.PianoRoll ? "Piano roll" : "Arrangement")} grid: {label}";+ }}diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.csindex 3372e864..eeeae5ad 100644--- a/src/managed/Nota.App/MainWindow.Detail.cs+++ b/src/managed/Nota.App/MainWindow.Detail.cs@@ -393,6 +393,7 @@ public partial class MainWindowif (_vm is null) return;var roll = new PianoRollView{+ BeatsPerBar = Timeline.BeatsPerBar, // bar lines and bar steps match the arrangementCommit = notes =>{// The roll can outlive its clip: the target track/clip may have been@@ -594,6 +595,7 @@ public partial class MainWindowSyncClipTab(); // a Drum Rack slot lights the Pattern tab upvar roll = new PianoRollView{+ BeatsPerBar = Timeline.BeatsPerBar, // bar lines and bar steps match the arrangementCommit = notes =>{var arr = new NotaNote[notes.Count];diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axamlindex ef223da5..9ffa3ffd 100644--- a/src/managed/Nota.App/MainWindow.axaml+++ b/src/managed/Nota.App/MainWindow.axaml@@ -55,6 +55,18 @@<NativeMenuItem Header="Paste Bounced Audio" app:Commands.Id="edit.pasteBounced"/><NativeMenuItem Header="Copy Clips to Session / Arrangement" app:Commands.Id="edit.copyToOtherView"/><NativeMenuItem Header="Delete" app:Commands.Id="edit.delete"/>+ <NativeMenuItemSeparator/>+ <NativeMenuItem Header="Grid">+ <NativeMenuItem.Menu>+ <NativeMenu>+ <NativeMenuItem Header="Narrow Grid" app:Commands.Id="grid.narrower"/>+ <NativeMenuItem Header="Widen Grid" app:Commands.Id="grid.wider"/>+ <NativeMenuItem Header="Triplet Grid" app:Commands.Id="grid.triplets"/>+ <NativeMenuItem Header="Snap to Grid" app:Commands.Id="grid.snap"/>+ <NativeMenuItem Header="Adaptive Grid" app:Commands.Id="grid.adaptive"/>+ </NativeMenu>+ </NativeMenuItem.Menu>+ </NativeMenuItem></NativeMenu></NativeMenuItem.Menu></NativeMenuItem>@@ -234,12 +246,13 @@<TextBlock Classes="CellLabel" Text="KEY" HorizontalAlignment="Center"/></StackPanel></Button>- <!-- Clip snap grid: click to cycle -->- <Button x:Name="SnapChip" Classes="cell" Click="OnCycleSnap" ToolTip.Tip="Cycle the clip snap grid">+ <!-- Clip snap grid (SnapChip.cs): the step in effect, live with the zoom in Auto;+ click for the grid menu. MinWidth fits the widest value (1/16T). -->+ <Button x:Name="SnapChip" Classes="cell"><StackPanel Spacing="2"><TextBlock x:Name="SnapLabel" Classes="Mono" Text="1/4" FontSize="14" LineHeight="16"- MinWidth="36" TextAlignment="Center" HorizontalAlignment="Center" Foreground="{DynamicResource Brush.TextPrimary}"/>- <TextBlock Classes="CellLabel" Text="GRID" HorizontalAlignment="Center"/>+ MinWidth="46" TextAlignment="Center" HorizontalAlignment="Center" Foreground="{DynamicResource Brush.TextPrimary}"/>+ <TextBlock x:Name="SnapCaption" Classes="CellLabel" Text="GRID" HorizontalAlignment="Center"/></StackPanel></Button></StackPanel>diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex afacd9bb..586b0b8f 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -311,6 +311,7 @@ public partial class MainWindow : WindowTimeline.ShowSections = vm.Settings.Current.ArrangementShowSections;vm.Transport.CountInBars = Math.Clamp(vm.Settings.Current.CountInBars, 0, 4);Timeline.Waveform = (WaveformStyle)Math.Clamp(vm.Settings.Current.ArrangementWaveform, 0, 1);+ InitSnapGrid();// Settings → Appearance can switch the waveform style while the arrangement is open.vm.Settings.Changed += () => Timeline.Waveform = (WaveformStyle)Math.Clamp(vm.Settings.Current.ArrangementWaveform, 0, 1);Browser.SetViewModel(vm.Browser);@@ -566,12 +567,6 @@ public partial class MainWindow : WindowSyncClipTab(); // Clip tab availability is per-context (arrangement vs session)}- // Toolbar Snap chip: cycle the arrangement's clip-drag snap grid.- private static readonly (double beats, string label)[] SnapSteps =- {- (0.25, "1/16"), (0.5, "1/8"), (1.0, "1/4"), (2.0, "1/2"), (4.0, "1 bar"),- };- private int _snapIndex = 2; // 1/4private void OnPickProjectKey(object? sender, RoutedEventArgs e){if (_vm is null) return;@@ -653,14 +648,6 @@ public partial class MainWindow : Window((Ellipse)TapDots.Children[i]).BindResource(Shape.FillProperty, i < lit ? "Brush.Accent" : "Brush.BorderStrong");}- private void OnCycleSnap(object? sender, RoutedEventArgs e)- {- _snapIndex = (_snapIndex + 1) % SnapSteps.Length;- var (beats, label) = SnapSteps[_snapIndex];- Timeline.SnapBeats = beats;- SnapLabel.Text = label;- }-// A launched scene may carry its own tempo / signature; the engine applies it on the// scene's start boundary and the transport follows here.private void SyncSceneTempo()@@ -716,15 +703,27 @@ public partial class MainWindow : Windowreturn null;}- // Snap on/off. Separate from the GRID cell, which only picks the denomination:- // the latch is what you reach for to nudge something off-grid for a while.+ // Snap on/off: the latch you reach for to nudge something off-grid for a while. The+ // same switch as ⌘4 and the grid menu's "Snap to grid" (EditorGrids.Arrangement.SnapOn).private void OnToggleSnapEnabled(object? sender, RoutedEventArgs e){bool on = SnapToggle.IsChecked == true;- Timeline.SnapEnabled = on;+ var grids = EditorGrids.Shared;+ grids.Set(EditorKind.Arrangement, grids.Get(EditorKind.Arrangement) with { SnapOn = on });if (_vm is not null) _vm.StatusText = on ? "Snap on" : "Snap off — clips position freely";}+ // The toolbar GRID cell and the magnet follow the arrangement's grid wherever it changes+ // (zoom, the menu, ⌘1–⌘5).+ private void InitSnapGrid()+ {+ var chip = Nota.App.SnapChip.Attach(SnapChip, SnapLabel, SnapCaption, EditorKind.Arrangement, () => Timeline.SnapGridState);+ Timeline.GridChanged += chip.Refresh;+ void SyncLatch() => SnapToggle.IsChecked = EditorGrids.Shared.Get(EditorKind.Arrangement).SnapOn;+ EditorGrids.Shared.Changed += k => { if (k == EditorKind.Arrangement) SyncLatch(); };+ SyncLatch();+ }+/// <summary>Whether MIDI Learn is armed — device cards with their own Learn button/// (Nota Arp) mirror it.</summary>internal bool MidiLearnArmed => _learn?.Armed == true;diff --git a/src/managed/Nota.App/MidiToolsView.cs b/src/managed/Nota.App/MidiToolsView.csindex 5d3551d2..a9276892 100644--- a/src/managed/Nota.App/MidiToolsView.cs+++ b/src/managed/Nota.App/MidiToolsView.cs@@ -167,7 +167,7 @@ public sealed class MidiToolsView : UserControlprivate MidiToolContext Context() => new(){LengthBeats = _roll.LengthBeats,- Grid = _roll.Grid,+ Grid = _roll.Grids.Quantize.Beats(_roll.BeatsPerBar), // like Quantize: never the zoom's stepScaleOn = _roll.ScaleOn,ScaleRoot = _roll.ScaleRoot,ScaleMask = MidiScales.MaskAt(_roll.ScaleIndex),diff --git a/src/managed/Nota.App/PianoRollView.Expression.cs b/src/managed/Nota.App/PianoRollView.Expression.csindex 40be1fbb..7682d6cc 100644--- a/src/managed/Nota.App/PianoRollView.Expression.cs+++ b/src/managed/Nota.App/PianoRollView.Expression.cs@@ -248,15 +248,7 @@ public sealed partial class PianoRollViewUpdateRange();ctx.FillRectangle(VelBg, new Rect(0, 0, w, h));double ppb = _o.PixelsPerBeat;- double step = _o.GridStepBeats();- double viewEnd = Math.Min(_o._lengthBeats, _o.ScrollBeats + w / Math.Max(1e-6, ppb));- double startB = Math.Max(0, Math.Floor(_o.ScrollBeats / step) * step);- for (int k = 0; ; k++)- {- double b = startB + k * step;- if (b > viewEnd + 1e-9) break;- ctx.DrawLine(_o.GridPen(b), new Point(_o.BeatToX(b) + 0.5, 0), new Point(_o.BeatToX(b) + 0.5, h));- }+ _o.DrawGridLines(ctx, w, h);// Rest line: no bend / centred slide.if (Dim != NoteExpressionDim.Pressure){diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex b4999502..6f2971e4 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -21,6 +21,7 @@ using Avalonia.Layout;using Avalonia.Media;using Avalonia.Threading;using Nota.Application;+using Nota.Application.Editing;using Nota.Application.Midi;namespace Nota.App;@@ -69,7 +70,6 @@ public sealed partial class PianoRollView : UserControlprivate readonly List<NotaNote> _notes = new();private double _lengthBeats = 4;- private double _grid = 0.25;private readonly HashSet<int> _selection = new(); // indices into _notesprivate ISolidColorBrush _trackBrush = NotaPalette.TrackBrushes[3]; // read .Color at draw time: it follows the themeprivate Color _trackColor => _trackBrush.Color;@@ -143,7 +143,11 @@ public sealed partial class PianoRollView : UserControlinternal void EnsurePpb(double viewportW){if (_pixelsPerBeat <= 0 && viewportW > 0)+ {_pixelsPerBeat = Math.Clamp(viewportW / _lengthBeats, MinPpb, MaxPpb);+ // The fit happens mid-render: tell the snap chip after it, not during.+ Dispatcher.UIThread.Post(NotifyGrid);+ }}private double MaxScrollBeats@@ -311,6 +315,12 @@ public sealed partial class PianoRollView : UserControl_heldTimer.Start();};DetachedFromVisualTree += (_, _) => { _heldTimer?.Stop(); if (_held.Count > 0) { _held.Clear(); _keys.InvalidateVisual(); _gridControl.InvalidateVisual(); } };++ // The grid setting (and Quantize step) is app-wide: follow it while on screen only —+ // a roll is rebuilt for every clip, so a lasting subscription would leak.+ void OnGrid(EditorKind k) { if (k == EditorKind.PianoRoll) Invalidate(); }+ AttachedToVisualTree += (_, _) => Grids.Changed += OnGrid;+ DetachedFromVisualTree += (_, _) => Grids.Changed -= OnGrid;}private void PollHeld()@@ -345,7 +355,37 @@ public sealed partial class PianoRollView : UserControl}public double LengthBeats => _lengthBeats;- public double Grid { get => _grid; set { _grid = Math.Max(1.0 / 32, value); Invalidate(); } }++ /// <summary>Beats per bar from the transport: bar lines, bar-based grid steps and ruler+ /// numbers follow the time signature.</summary>+ public int BeatsPerBar { get => _beatsPerBar; set { if (value > 0 && value != _beatsPerBar) { _beatsPerBar = value; Invalidate(); } } }+ private int _beatsPerBar = 4;++ /// <summary>The app-wide grid state this roll reads (its setting and the Quantize step).</summary>+ internal EditorGrids Grids => EditorGrids.Shared;++ /// <summary>The snap grid at the current zoom (specs/003-adaptive-snap-grid): the step+ /// note edits snap to and the finest line drawn. Resolved on demand (allocation-free), so+ /// zoom and setting changes never leave it stale.</summary>+ internal ResolvedGrid SnapGridState => SnapGrid.Resolve(Grids.Get(EditorKind.PianoRoll), _pixelsPerBeat, _beatsPerBar);++ /// <summary>The step in effect, in beats: nudges, minimum note length, duplicate shift.</summary>+ internal double SnapStep => SnapGridState.Snap.Beats(_beatsPerBar);++ /// <summary>The shortest note an edit leaves: one step, or a 1/32 while snap is off.</summary>+ private double MinNoteLen => SnapGridState.SnapOn ? SnapStep : 0.125;++ /// <summary>A beat on the grid (unchanged while snap is off).</summary>+ internal double SnapBeat(double b)+ {+ var g = SnapGridState;+ return g.SnapOn ? SnapGrid.SnapBeat(b, g.Snap.Beats(_beatsPerBar), _beatsPerBar) : b;+ }++ /// <summary>The step in effect changed (zoom, time signature, the setting) — the header+ /// snap chip relabels.</summary>+ public event Action? GridChanged;+ private ResolvedGrid _lastGrid;public void SetTrackColor(ISolidColorBrush b) { _trackBrush = b; Invalidate(); }public ISolidColorBrush TrackBrush => _trackBrush;@@ -424,8 +464,8 @@ public sealed partial class PianoRollView : UserControlif (sel.Count == 0) return false;double minStart = double.MaxValue, maxEnd = double.MinValue;foreach (int i in sel) { var n = _notes[i]; minStart = Math.Min(minStart, n.StartBeat); maxEnd = Math.Max(maxEnd, n.StartBeat + n.LengthBeats); }- double shift = Math.Max(_grid, maxEnd - minStart);- double cap = Math.Max(0, _lengthBeats - _grid);+ double shift = Math.Max(SnapStep, maxEnd - minStart);+ double cap = Math.Max(0, _lengthBeats - SnapStep);var copies = new List<NotaNote>(sel.Count);foreach (int i in sel) { var n = _notes[i]; n.StartBeat = Math.Min(n.StartBeat + shift, cap); copies.Add(n); }// Like a duplicated clip in the arrangement, the copies overwrite what they land on@@ -584,12 +624,14 @@ public sealed partial class PianoRollView : UserControlCommit?.Invoke(notes ?? _notes);}+ /// <summary>Moves note starts toward the Quantize step (its own value, never the zoom's).</summary>public void Quantize(double strength){+ double qStep = Grids.Quantize.Beats(_beatsPerBar);for (int i = 0; i < _notes.Count; i++){var n = _notes[i];- double q = Math.Round(n.StartBeat / _grid) * _grid;+ double q = SnapGrid.SnapBeat(n.StartBeat, qStep, _beatsPerBar);n.StartBeat += (q - n.StartBeat) * Math.Clamp(strength, 0, 1);_notes[i] = n;}@@ -643,7 +685,7 @@ public sealed partial class PianoRollView : UserControlpublic bool PasteClipboard(){if (s_clipboard.Count == 0) return false;- double anchor = _playheadBeat >= 0 ? Math.Round(_playheadBeat / _grid) * _grid : s_clipAnchor;+ double anchor = _playheadBeat >= 0 ? SnapBeat(_playheadBeat) : s_clipAnchor;int baseIdx = _notes.Count;foreach (var c in s_clipboard){@@ -651,7 +693,7 @@ public sealed partial class PianoRollView : UserControln.StartBeat = anchor + c.StartBeat;if (n.StartBeat >= _lengthBeats) continue; // past the clip end → skipif (n.StartBeat + n.LengthBeats > _lengthBeats) // trim a note that overruns- n.LengthBeats = Math.Max(_grid, _lengthBeats - n.StartBeat);+ n.LengthBeats = Math.Max(MinNoteLen, _lengthBeats - n.StartBeat);_notes.Add(n);}if (_notes.Count == baseIdx) return false;@@ -748,6 +790,13 @@ public sealed partial class PianoRollView : UserControl_gridControl.InvalidateVisual();_vel.InvalidateVisual();_expr.InvalidateVisual();+ NotifyGrid();+ }++ private void NotifyGrid()+ {+ var g = SnapGridState;+ if (g != _lastGrid) { _lastGrid = g; GridChanged?.Invoke(); }}private static bool IsBlack(int pitch) { int n = ((pitch % 12) + 12) % 12; return n is 1 or 3 or 6 or 8 or 10; }@@ -757,17 +806,21 @@ public sealed partial class PianoRollView : UserControlreturn names[((pitch % 12) + 12) % 12] + (pitch / 12 - 1);}- // --- adaptive grid (subdivides as you zoom in) ------------------------- private static readonly double[] GridLadder = { 0.0625, 0.125, 0.25, 0.5, 1, 2, 4 };+ // --- snap grid lines (the same positions SnapBeat lands on) ------------ // Finest grid step (beats) keeping ≥ ~9px between lines: bars → beats → 1/8 →- // 1/16 → 1/32 → 1/64 as the zoom increases.- internal double GridStepBeats()+ /// <summary>The vertical grid of a lane: one line per snap position at the drawn step, in+ /// the visible part of the clip. Shared by the note grid, the velocity and MPE lanes.</summary>+ internal void DrawGridLines(DrawingContext ctx, double w, double h){double ppb = _pixelsPerBeat;- if (ppb <= 0) return 1.0;- foreach (var s in GridLadder) if (s * ppb >= 9) return s;- return 4.0;+ if (ppb <= 0) return;+ double viewEnd = Math.Min(_lengthBeats, ScrollBeats + w / ppb);+ double step = SnapGridState.Draw.Beats(_beatsPerBar);+ foreach (double b in SnapGrid.GridLines(ScrollBeats, viewEnd, step, _beatsPerBar))+ {+ double x = BeatToX(b) + 0.5;+ ctx.DrawLine(GridPen(b), new Point(x, 0), new Point(x, h));+ }}// Coarser step for ruler labels (needs room for text); never finer than a 1/16.@@ -783,16 +836,16 @@ public sealed partial class PianoRollView : UserControl// Line weight for a vertical grid line at beat b: bar > beat > sub-beat.internal IPen GridPen(double b){- if (Math.Abs(b / 4 - Math.Round(b / 4)) < 1e-6) return BarPen;+ if (Math.Abs(b / _beatsPerBar - Math.Round(b / _beatsPerBar)) < 1e-6) return BarPen;if (Math.Abs(b - Math.Round(b)) < 1e-6) return BeatPen;return SubBeatPen;}// Ruler label at beat b: "bar.beat", plus a 1/16 index when mid-beat (e.g. 3.2.3).- internal static string GridLabel(double b)+ internal string GridLabel(double b){- int bar = (int)Math.Floor(b / 4) + 1;- double inBar = b - Math.Floor(b / 4) * 4;+ int bar = (int)Math.Floor(b / _beatsPerBar) + 1;+ double inBar = b - Math.Floor(b / _beatsPerBar) * _beatsPerBar;int beat = (int)Math.Floor(inBar) + 1;double frac = inBar - Math.Floor(inBar);if (frac < 1e-6) return $"{bar}.{beat}";@@ -818,17 +871,18 @@ public sealed partial class PianoRollView : UserControldouble loopStart = Math.Max(0, _o.BeatToX(0));if (loopEnd > loopStart) ctx.FillRectangle(LoopStrip, new Rect(loopStart, 0, loopEnd - loopStart, 3));// Label every beat while there is room for "12.4", else bars only.- double step = ppb >= 30 ? 1 : 4;+ double step = ppb >= 30 ? 1 : _o._beatsPerBar;double startB = Math.Max(0, Math.Floor(_o.ScrollBeats / step) * step);for (int k = 0; ; k++){double b = startB + k * step;if (b > viewEnd + 1e-9) break;double x = _o.BeatToX(b);- bool bar = Math.Abs(b / 4 - Math.Round(b / 4)) < 1e-6;+ int bpb = _o._beatsPerBar;+ bool bar = Math.Abs(b / bpb - Math.Round(b / bpb)) < 1e-6;ctx.DrawLine(bar ? BarPen : BeatPen, new Point(x + 0.5, 0), new Point(x + 0.5, h));if (b >= _o._lengthBeats - 1e-9) continue;- int barNo = (int)Math.Floor(b / 4) + 1, beatNo = (int)Math.Round(b - Math.Floor(b / 4) * 4) + 1;+ int barNo = (int)Math.Floor(b / bpb) + 1, beatNo = (int)Math.Round(b - Math.Floor(b / bpb) * bpb) + 1;string label = bar ? barNo.ToString(NotaNum.Culture) : $"{barNo}.{beatNo}";var ft = new FormattedText(label, NotaNum.Culture, FlowDirection.LeftToRight, Mono, 9, bar ? RulerBarText : LabelText);ctx.DrawText(ft, new Point(x + 4, h - 5 - ft.Height));@@ -947,7 +1001,9 @@ public sealed partial class PianoRollView : UserControlprivate double XToBeat(double x) => _o.XToBeat(x);private static double PitchToY(int p) => (MaxPitch - p) * RowH;private int YToPitch(double y) => (int)Math.Clamp(MaxPitch - Math.Floor(y / RowH), MinPitch, MaxPitch);- private double Snap(double b) => Math.Round(b / _o._grid) * _o._grid;+ // 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);public override void Render(DrawingContext ctx){@@ -973,16 +1029,7 @@ public sealed partial class PianoRollView : UserControlif (hp >= MinPitch && hp <= MaxPitch)ctx.FillRectangle(HeldRowTint, new Rect(0, PitchToY(hp), w, RowH));double ppb = Ppb;- double step = _o.GridStepBeats();- double viewEnd = Math.Min(_o._lengthBeats, _o.ScrollBeats + w / Math.Max(1e-6, ppb));- double startB = Math.Max(0, Math.Floor(_o.ScrollBeats / step) * step);- for (int k = 0; ; k++)- {- double b = startB + k * step;- if (b > viewEnd + 1e-9) break;- double x = BeatToX(b);- ctx.DrawLine(_o.GridPen(b), new Point(x + 0.5, 0), new Point(x + 0.5, h));- }+ _o.DrawGridLines(ctx, w, h);var notes = _o._notes;for (int i = 0; i < notes.Count; i++){@@ -1108,6 +1155,7 @@ public sealed partial class PianoRollView : UserControlFocus();if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;var p = e.GetPosition(this);+ _free = (e.KeyModifiers & KeyModifiers.Alt) != 0;bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;int hit = HitTest(p, out int edge);@@ -1117,7 +1165,7 @@ public sealed partial class PianoRollView : UserControlif (hit >= 0) { _o._notes.RemoveAt(hit); _o._selection.Clear(); }else{- var nt = new NotaNote(YToPitch(p.Y), Math.Max(0, Snap(XToBeat(p.X))), _o._grid * 4, 0.8f);+ var nt = new NotaNote(YToPitch(p.Y), Math.Max(0, Snap(XToBeat(p.X))), _o.MinNoteLen, 0.8f);_o._notes.Add(nt);_o._selection.Clear(); _o._selection.Add(_o._notes.Count - 1);}@@ -1163,6 +1211,7 @@ public sealed partial class PianoRollView : UserControlprotected override void OnPointerMoved(PointerEventArgs e){var p = e.GetPosition(this);+ _free = (e.KeyModifiers & KeyModifiers.Alt) != 0; // live, so Alt can toggle mid-dragif (_drag == Mode.None) { UpdateHover(p); return; }_lastGrid = p;DragUpdate(p);@@ -1181,7 +1230,7 @@ public sealed partial class PianoRollView : UserControl// Clamp the shared delta so the whole group stays in-bounds (keeps shape).double minStart = double.MaxValue; int minP = int.MaxValue, maxP = int.MinValue;foreach (var v in _orig.Values) { minStart = Math.Min(minStart, v.start); minP = Math.Min(minP, v.pitch); maxP = Math.Max(maxP, v.pitch); }- double cap = Math.Max(0, _o._lengthBeats - _o._grid);+ double cap = Math.Max(0, _o._lengthBeats - _o.MinNoteLen);dBeat = Math.Clamp(dBeat, -minStart, Math.Max(0, cap - MaxStart()));dPitch = Math.Clamp(dPitch, MinPitch - minP, MaxPitch - maxP);foreach (var kv in _orig)@@ -1200,7 +1249,7 @@ public sealed partial class PianoRollView : UserControlforeach (var kv in _orig){var n = _o._notes[kv.Key];- n.LengthBeats = Math.Max(_o._grid, kv.Value.len + dLen);+ n.LengthBeats = Math.Max(_o.MinNoteLen, kv.Value.len + dLen);_o._notes[kv.Key] = n;}_dragMoved = true;@@ -1212,7 +1261,7 @@ public sealed partial class PianoRollView : UserControl// one grid step) or the clip's start.double dStart = Snap(XToBeat(p.X)) - _resizeAnchor;foreach (var v in _orig.Values)- dStart = Math.Clamp(dStart, -v.start, Math.Max(-v.start, v.len - _o._grid));+ dStart = Math.Clamp(dStart, -v.start, Math.Max(-v.start, v.len - _o.MinNoteLen));foreach (var kv in _orig){var n = _o._notes[kv.Key];@@ -1370,8 +1419,8 @@ public sealed partial class PianoRollView : UserControl{switch (e.Key){- case Key.Left: if (_o.MoveSelection(0, -_o._grid)) e.Handled = true; return;- case Key.Right: if (_o.MoveSelection(0, +_o._grid)) e.Handled = true; return;+ case Key.Left: if (_o.MoveSelection(0, -_o.SnapStep)) e.Handled = true; return;+ case Key.Right: if (_o.MoveSelection(0, +_o.SnapStep)) e.Handled = true; return;case Key.Up: if (_o.MoveSelection(shift ? 12 : 1, 0)) e.Handled = true; return;case Key.Down: if (_o.MoveSelection(shift ? -12 : -1, 0)) e.Handled = true; return;}@@ -1413,15 +1462,7 @@ public sealed partial class PianoRollView : UserControl_o.EnsurePpb(w);ctx.FillRectangle(VelBg, new Rect(0, 0, w, h));double ppb = Ppb;- double step = _o.GridStepBeats();- double viewEnd = Math.Min(_o._lengthBeats, _o.ScrollBeats + w / Math.Max(1e-6, ppb));- double startB = Math.Max(0, Math.Floor(_o.ScrollBeats / step) * step);- for (int k = 0; ; k++)- {- double b = startB + k * step;- if (b > viewEnd + 1e-9) break;- ctx.DrawLine(_o.GridPen(b), new Point(_o.BeatToX(b) + 0.5, 0), new Point(_o.BeatToX(b) + 0.5, h));- }+ _o.DrawGridLines(ctx, w, h);// A 2px stem per note with a 6×3 cap — the cap is the drag handle.var notes = _o._notes;for (int i = 0; i < notes.Count; i++)diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex afecbd78..f5388224 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1040,6 +1040,14 @@ public sealed partial class PreferencesWindow : NotaWindow("0", "Deactivate / activate the selected clip(s)"),("Delete", "Delete the selected clip / range"),}),+ ("GRID (ARRANGEMENT OR PIANO ROLL — WHICHEVER YOU USED LAST)", new[]+ {+ ("⌘1 ⌘2", "Narrow / widen the grid · in Auto, change the density"),+ ("⌘3", "Triplet grid on / off"),+ ("⌘4", "Snap to grid on / off"),+ ("⌘5", "Switch between the adaptive (Auto) and a fixed grid"),+ ("⌥ while dragging", "Move freely, ignoring the grid"),+ }),("TRACKS (AFTER A CLICK IN THE TRACK HEADERS)", new[]{("⌘A", "Select all tracks"),diff --git a/src/managed/Nota.App/SnapChip.cs b/src/managed/Nota.App/SnapChip.csnew file mode 100644index 00000000..47047be8--- /dev/null+++ b/src/managed/Nota.App/SnapChip.cs@@ -0,0 +1,110 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The snap control of an editor (specs/003-adaptive-snap-grid, contracts/grid-ui.md): shows+// the step in effect — live while zooming in Auto — and opens one menu with every grid+// option instead of cycling. The arrangement wears it as the toolbar's GRID cell (value on+// top, AUTO GRID / GRID caption below, so the cell stays narrow); the piano roll as a header+// chip reading "Auto · 1/16". A fixed step finer than the drawn lines dims; snap off strikes+// the value through. Both read and write EditorGrids, so the shortcuts and the magnet latch+// stay in step with it.++using System;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application.Editing;++namespace Nota.App;++internal sealed class SnapChip+{+ private const string Shortcuts = "⌘1 ⌘2 narrow / widen · ⌘3 triplets · ⌘4 snap · ⌘5 auto";++ private readonly Button _button;+ private readonly TextBlock _value;+ private readonly TextBlock? _caption;+ private readonly EditorKind _kind;+ private readonly Func<ResolvedGrid> _current;+ private string? _shown;++ private static EditorGrids Grids => EditorGrids.Shared;++ private SnapChip(Button button, TextBlock value, TextBlock? caption, EditorKind kind, Func<ResolvedGrid> current)+ {+ _button = button; _value = value; _caption = caption; _kind = kind; _current = current;+ button.Click += (_, _) => OpenMenu();+ // Subscribed only while on screen: piano-roll chips come and go with every clip.+ void OnChanged(EditorKind k) { if (k == _kind) Refresh(); }+ button.AttachedToVisualTree += (_, _) => { Grids.Changed += OnChanged; Refresh(); };+ button.DetachedFromVisualTree += (_, _) => Grids.Changed -= OnChanged;+ Refresh();+ }++ /// <summary>Drives an existing two-line toolbar cell (the arrangement's GRID cell).</summary>+ public static SnapChip Attach(Button button, TextBlock value, TextBlock caption, EditorKind kind, Func<ResolvedGrid> current)+ => new(button, value, caption, kind, current);++ /// <summary>A header chip (the piano roll's), reading "Auto · 1/16".</summary>+ public static (Button Button, SnapChip Chip) Create(EditorKind kind, Func<ResolvedGrid> current)+ {+ var value = new TextBlock+ {+ FontFamily = NotaFonts.MonoFamily, FontSize = 11, VerticalAlignment = VerticalAlignment.Center,+ // Fixed to the longest label so the header doesn't shift while zooming.+ MinWidth = 82, TextAlignment = TextAlignment.Center,+ };+ var b = new Button { Classes = { "chip" }, Padding = new Avalonia.Thickness(10, 0), Content = value };+ return (b, new SnapChip(b, value, null, kind, current));+ }++ /// <summary>Relabels from the live setting and zoom; cheap, and a no-op when nothing changed.</summary>+ public void Refresh()+ {+ var s = Grids.Get(_kind);+ var r = _current();+ string text = _caption is null ? SnapGrid.Label(s, r) : r.Snap.Label;+ string key = $"{text}|{s.Adaptive}|{r.SnapOn}|{r.FinerThanVisible}";+ if (key == _shown) return;+ _shown = key;++ _value.Text = text;+ if (_caption is not null) _caption.Text = s.Adaptive ? "AUTO GRID" : "GRID";+ _value.TextDecorations = r.SnapOn ? null : TextDecorations.Strikethrough;+ _value.Foreground = !r.SnapOn ? NotaPalette.TextDisabled+ : r.FinerThanVisible ? NotaPalette.TextSecondary+ : NotaPalette.TextPrimary;+ string tip = !r.SnapOn ? "Snap off — items move freely (⌘4)"+ : r.FinerThanVisible ? $"{r.Snap.Label} — finer than the visible grid · zoom in to see it"+ : s.Adaptive ? $"Snap grid · Auto follows the zoom ({s.Density})"+ : $"Snap grid · fixed {r.Snap.Label}";+ ToolTip.SetTip(_button, MenuKit.Keys($"{tip}\n{Shortcuts} · hold ⌥ to drag freely"));+ }++ private void OpenMenu()+ {+ var s = Grids.Get(_kind);+ var f = new MenuFlyout();+ void Item(string header, bool on, Func<GridSetting, GridSetting> apply, KeyGesture? gesture = null)+ {+ var mi = new MenuItem { Header = header, InputGesture = gesture };+ if (on) mi.Icon = new Glyph(GlyphKind.Dot, 6) { Foreground = NotaPalette.AccentBright };+ mi.Click += (_, _) => Grids.Set(_kind, apply(Grids.Get(_kind)));+ f.Items.Add(mi);+ }++ foreach (var d in new[] { GridDensity.Narrow, GridDensity.Medium, GridDensity.Wide })+ Item($"Auto · {d}", s.Adaptive && s.Density == d, g => SnapGrid.PickAdaptive(g, d));+ f.Items.Add(new Separator());+ for (int i = 0; i < GridStep.Count; i++)+ {+ int idx = i;+ Item(GridStep.Of(i, s.Triplets).Label, !s.Adaptive && s.FixedIndex == i, g => SnapGrid.PickFixed(g, idx));+ }+ f.Items.Add(new Separator());+ Item("Triplets", s.Triplets, SnapGrid.ToggleTriplets, MenuKit.Cmd(Key.D3));+ Item("Snap to grid", s.SnapOn, SnapGrid.ToggleSnap, MenuKit.Cmd(Key.D4));+ f.ShowAt(_button);+ }+}diff --git a/src/managed/Nota.Application/Editing/SnapGrid.cs b/src/managed/Nota.Application/Editing/SnapGrid.csnew file mode 100644index 00000000..5ea54389--- /dev/null+++ b/src/managed/Nota.Application/Editing/SnapGrid.cs@@ -0,0 +1,201 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The snap grid shared by the arrangement and the piano roll (specs/003-adaptive-snap-grid).+// One rule turns an editor's grid setting and its zoom into the step to snap to and the step+// to draw, and one position rule serves both snapping and line drawing — so every drawn line+// is a snap point and every snap point is drawn ("what you see is what you snap to").+// Grid positions restart at every bar, so bar lines stay snap points in odd meters (3/4 with+// a 1/2 step: 0 2 | 3 5 | 6 …). Pure and UI-free: the smoke test drives it directly.++using System;+using System.Collections.Generic;+using System.Text.Json.Serialization;++namespace Nota.Application.Editing;++/// <summary>How dense the adaptive grid is: the minimum spacing between its finest lines.</summary>+public enum GridDensity { Narrow, Medium, Wide }++/// <summary>One rung of the ladder: 0 = 1/32 … 4 = 1/2 (note values; a beat is a quarter+/// note), 5 = 1 bar, 6 = 2 bars, 7 = 4 bars. Triplet steps are 2/3 of their straight value;+/// bar steps have no triplet form.</summary>+public readonly record struct GridStep(int Index, bool Triplet)+{+ public const int Count = 8, FirstBar = 5;+ private static readonly string[] Names = { "1/32", "1/16", "1/8", "1/4", "1/2", "1 bar", "2 bars", "4 bars" };++ /// <summary>A step with the index clamped to the ladder and the triplet flag dropped on bar steps.</summary>+ public static GridStep Of(int index, bool triplet)+ {+ int i = Math.Clamp(index, 0, Count - 1);+ return new GridStep(i, triplet && i < FirstBar);+ }++ public GridStep Normalize() => Of(Index, Triplet);+ [JsonIgnore] public bool IsBar => Normalize().Index >= FirstBar;++ /// <summary>Length in beats; bar steps follow the time signature.</summary>+ public double Beats(int beatsPerBar)+ {+ var s = Normalize();+ if (s.Index >= FirstBar) return SnapGrid.BarBeats(beatsPerBar) * (1 << (s.Index - FirstBar));+ double straight = 0.125 * (1 << s.Index);+ return s.Triplet ? straight * 2.0 / 3.0 : straight;+ }++ [JsonIgnore]+ public string Label+ {+ get+ {+ var s = Normalize();+ return s.Triplet ? Names[s.Index] + "T" : Names[s.Index];+ }+ }+}++/// <summary>One editor's grid setting (persisted app-wide in Settings, never in a project).+/// <see cref="Density"/> is remembered while Fixed and <see cref="FixedIndex"/> while Adaptive,+/// so ⌘5 goes back to where the user was.</summary>+public sealed record GridSetting+{+ public bool Adaptive { get; init; } = true;+ public GridDensity Density { get; init; } = GridDensity.Medium;+ public int FixedIndex { get; init; } = 3;+ public bool Triplets { get; init; }+ public bool SnapOn { get; init; } = true;++ public static GridSetting DefaultArrangement { get; } = new() { FixedIndex = 3 }; // 1/4+ public static GridSetting DefaultPianoRoll { get; } = new() { FixedIndex = 1 }; // 1/16+}++/// <summary>A setting resolved at a zoom: <see cref="Snap"/> is the step in effect,+/// <see cref="Draw"/> the finest drawn step (equal to Snap except for a Fixed step too fine to+/// draw, which <see cref="FinerThanVisible"/> flags).</summary>+public readonly record struct ResolvedGrid(GridStep Snap, GridStep Draw, bool FinerThanVisible, bool SnapOn);++public static class SnapGrid+{+ private const double Eps = 1e-6;++ /// <summary>Minimum spacing between the finest lines, in px (research R2). Each notch+ /// doubles, so ⌘1 / ⌘2 in Auto move the step one rung.</summary>+ public static double Threshold(GridDensity d) => d switch+ {+ GridDensity.Narrow => 8,+ GridDensity.Wide => 32,+ _ => 16,+ };++ internal static double BarBeats(int beatsPerBar) => beatsPerBar > 0 ? beatsPerBar : 4;++ // A sub-bar step as long as the bar or longer only lands on bar lines; adaptive skips it.+ private static bool Usable(GridStep s, int beatsPerBar)+ => s.IsBar || s.Beats(beatsPerBar) < BarBeats(beatsPerBar) - Eps;++ // The finest step from `from` up whose lines are at least `px` apart (clamped to 4 bars).+ private static GridStep FinestFrom(int from, bool triplet, double pixelsPerBeat, int beatsPerBar, double px)+ {+ for (int i = from; i < GridStep.Count; i++)+ {+ var s = GridStep.Of(i, triplet);+ if (!Usable(s, beatsPerBar)) continue;+ if (s.Beats(beatsPerBar) * pixelsPerBeat >= px) return s;+ }+ return GridStep.Of(GridStep.Count - 1, false);+ }++ /// <summary>The step to snap to and the step to draw for <paramref name="s"/> at a zoom.</summary>+ public static ResolvedGrid Resolve(GridSetting s, double pixelsPerBeat, int beatsPerBar)+ {+ if (!(pixelsPerBeat > 0))+ {+ var q = GridStep.Of(3, s.Triplets);+ return new ResolvedGrid(q, q, false, s.SnapOn);+ }+ if (s.Adaptive)+ {+ var a = FinestFrom(0, s.Triplets, pixelsPerBeat, beatsPerBar, Threshold(s.Density));+ return new ResolvedGrid(a, a, false, s.SnapOn);+ }+ var snap = GridStep.Of(s.FixedIndex, s.Triplets);+ var draw = snap.Beats(beatsPerBar) * pixelsPerBeat >= Threshold(GridDensity.Medium)+ ? snap+ : FinestFrom(snap.Index, s.Triplets, pixelsPerBeat, beatsPerBar, Threshold(GridDensity.Medium));+ return new ResolvedGrid(snap, draw, draw.Index > snap.Index, s.SnapOn);+ }++ /// <summary>The grid position nearest <paramref name="beat"/> (never negative). Sub-bar+ /// steps restart at every bar; bar steps are multiples of their length from beat 0.</summary>+ public static double SnapBeat(double beat, double stepBeats, int beatsPerBar)+ {+ if (!(stepBeats > 0)) return Math.Max(0, beat);+ double bar = BarBeats(beatsPerBar);+ if (stepBeats >= bar - Eps) return Math.Max(0, Math.Round(beat / stepBeats) * stepBeats);+ double barStart = Math.Floor(beat / bar) * bar;+ double rel = beat - barStart;+ int last = LastIndexInBar(stepBeats, bar);+ double a = Math.Clamp(Math.Round(rel / stepBeats), 0, last) * stepBeats;+ double best = Math.Abs(bar - rel) < Math.Abs(a - rel) ? bar : a;+ return Math.Max(0, barStart + best);+ }++ /// <summary>The grid positions in [from, to], ascending — the same set+ /// <see cref="SnapBeat"/> snaps to, for drawing.</summary>+ public static IEnumerable<double> GridLines(double from, double to, double stepBeats, int beatsPerBar)+ {+ if (!(stepBeats > 0) || to < from) yield break;+ from = Math.Max(0, from);+ double bar = BarBeats(beatsPerBar);+ if (stepBeats >= bar - Eps)+ {+ for (double k = Math.Ceiling(from / stepBeats - Eps); k * stepBeats <= to + Eps; k++)+ yield return k * stepBeats;+ yield break;+ }+ int last = LastIndexInBar(stepBeats, bar);+ for (double b = Math.Floor(from / bar); b * bar <= to + Eps; b++)+ for (int n = 0; n <= last; n++)+ {+ double p = b * bar + n * stepBeats;+ if (p > to + Eps) yield break;+ if (p >= from - Eps) yield return p;+ }+ }++ // The highest n with n·step still inside the bar (the next bar start is n = 0 of the next bar).+ private static int LastIndexInBar(double stepBeats, double bar)+ => Math.Max(0, (int)Math.Ceiling((bar - Eps) / stepBeats) - 1);++ /// <summary>The snap control's text: "Auto · 1/8" in Adaptive mode, "1/8" when Fixed.</summary>+ public static string Label(GridSetting s, ResolvedGrid r) => s.Adaptive ? "Auto · " + r.Snap.Label : r.Snap.Label;++ // ---- transitions (⌘1–⌘5 and the menu) ------------------------------------------------++ /// <summary>⌘1: a fixed step one rung finer; in Auto, the density one notch finer.</summary>+ public static GridSetting Narrower(GridSetting s) => s.Adaptive+ ? s with { Density = s.Density switch { GridDensity.Wide => GridDensity.Medium, _ => GridDensity.Narrow } }+ : s with { FixedIndex = Math.Max(0, Math.Clamp(s.FixedIndex, 0, GridStep.Count - 1) - 1) };++ /// <summary>⌘2: a fixed step one rung coarser; in Auto, the density one notch coarser.</summary>+ public static GridSetting Wider(GridSetting s) => s.Adaptive+ ? s with { Density = s.Density switch { GridDensity.Narrow => GridDensity.Medium, _ => GridDensity.Wide } }+ : s with { FixedIndex = Math.Min(GridStep.Count - 1, Math.Clamp(s.FixedIndex, 0, GridStep.Count - 1) + 1) };++ /// <summary>⌘3.</summary>+ public static GridSetting ToggleTriplets(GridSetting s) => s with { Triplets = !s.Triplets };++ /// <summary>⌘4.</summary>+ public static GridSetting ToggleSnap(GridSetting s) => s with { SnapOn = !s.SnapOn };++ /// <summary>⌘5: Auto ↔ Fixed, each side keeping what it had.</summary>+ public static GridSetting ToggleAdaptive(GridSetting s) => s with { Adaptive = !s.Adaptive };++ /// <summary>Menu "Auto · Narrow/Medium/Wide": picking a value means snapping to it.</summary>+ public static GridSetting PickAdaptive(GridSetting s, GridDensity d) => s with { Adaptive = true, Density = d, SnapOn = true };++ /// <summary>Menu fixed step.</summary>+ public static GridSetting PickFixed(GridSetting s, int index)+ => s with { Adaptive = false, FixedIndex = Math.Clamp(index, 0, GridStep.Count - 1), SnapOn = true };+}diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.csindex 1f544787..27626568 100644--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs@@ -92,6 +92,13 @@ 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"),+ // ---- Grid (the arrangement or the piano roll — whichever was used last) -----------+ C("grid.narrower", "Narrow Grid", "Grid", "⌘1", "finer smaller snap"),+ C("grid.wider", "Widen Grid", "Grid", "⌘2", "coarser larger snap"),+ C("grid.triplets", "Toggle Triplet Grid", "Grid", "⌘3", "triplet 1/8T swing"),+ C("grid.snap", "Toggle Snap to Grid", "Grid", "⌘4", "magnet free"),+ C("grid.adaptive", "Toggle Adaptive Grid", "Grid", "⌘5", "auto zoom fixed"),+// ---- Settings ---------------------------------------------------------------------C("prefs.open", "Settings", "Settings", "⌘,", "preferences options"),C("prefs.audio", "Settings: Audio", "Settings", "", "preferences device driver sample rate buffer"),diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.csindex 668391b4..e8207f34 100644--- a/src/managed/Nota.Application/Settings.cs+++ b/src/managed/Nota.Application/Settings.cs@@ -61,6 +61,17 @@ public sealed class Settings/// up/down live-shifts this)</summary>public int GamepadOctave { get; set; }+ // --- snap grid (specs/003-adaptive-snap-grid) ------------------------------+ // App-wide, one per editor, never written to project files: opening a project+ // doesn't change how the user likes to snap.+ /// <summary>The arrangement's grid: Auto · Medium, snap on by default.</summary>+ public Nota.Application.Editing.GridSetting ArrangementGrid { get; set; } = Nota.Application.Editing.GridSetting.DefaultArrangement;+ /// <summary>The piano roll's grid, independent of the arrangement's.</summary>+ public Nota.Application.Editing.GridSetting PianoRollGrid { get; set; } = Nota.Application.Editing.GridSetting.DefaultPianoRoll;+ /// <summary>The piano roll's Quantize (and clip tools') step — its own value, so the+ /// result never depends on the zoom. 1/16 by default.</summary>+ public Nota.Application.Editing.GridStep QuantizeStep { get; set; } = Nota.Application.Editing.GridStep.Of(1, false);+// --- command palette (⌘⇧P) ----------------------------------------------/// <summary>How often and when each palette / browser item was last applied, by palette/// id — frecency for the ranking (CP-15).</summary>diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 06fcb254..8dfcbd16 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -215,6 +215,14 @@ if (args.Length >= 1 && args[0] == "--tap")Console.WriteLine(failures == 0 ? "TAP PASSED" : $"TAP FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Snap grid alone: `--grid`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--grid")+{+ Console.WriteLine("-- snap grid --");+ foreach (var (ok, label) in SnapGridTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "GRID PASSED" : $"GRID FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// What Nota Mosaic makes of a real library: `--mosaic-dump <file.sfz | folder>`.if (args.Length >= 2 && args[0] == "--mosaic-dump"){@@ -14513,6 +14521,9 @@ foreach (var (ok, label) in MosaicTests.Run()) Check(ok, label);Console.WriteLine("-- tap tempo --");foreach (var (ok, label) in TapTempoTests.Run()) Check(ok, label);+Console.WriteLine("-- snap grid --");+foreach (var (ok, label) in SnapGridTests.Run()) Check(ok, label);+// --- command palette: descriptors, golden queries, context table, undo, speed ---Console.WriteLine("-- command palette --");foreach (var (ok, label) in PaletteTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/SnapGridTests.cs b/tests/Nota.SmokeTest/SnapGridTests.csnew file mode 100644index 00000000..8b6a84c1--- /dev/null+++ b/tests/Nota.SmokeTest/SnapGridTests.cs@@ -0,0 +1,147 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Snap grid (specs/003-adaptive-snap-grid): the step ladder, adaptive resolution from the+// zoom, bar-anchored snapping and line enumeration (what you see is what you snap to),+// the ⌘1–⌘5 transitions, triplets, labels, and the app-wide settings round trip.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --grid`.++using System.Text.Json;+using Nota.Application;+using Nota.Application.Editing;++namespace Nota.SmokeTest;++internal static class SnapGridTests+{+ private static bool Near(double a, double b) => Math.Abs(a - b) < 1e-9;++ private static ResolvedGrid At(GridSetting s, double ppb, int bpb = 4) => SnapGrid.Resolve(s, ppb, bpb);++ // Every enumerated line snaps to itself, and every snapped beat is an enumerated line.+ private static bool LinesAgree(double step, int bpb, double from, double to)+ {+ var lines = SnapGrid.GridLines(from, to, step, bpb).ToList();+ if (lines.Count == 0) return false;+ foreach (var l in lines)+ if (!Near(SnapGrid.SnapBeat(l, step, bpb), l)) return false;+ var set = lines.Select(l => Math.Round(l, 6)).ToHashSet();+ for (double b = from; b <= to; b += 0.0371)+ {+ double s = SnapGrid.SnapBeat(b, step, bpb);+ if (s < from - 1e-6 || s > to + 1e-6) continue; // nearest line lies outside the window+ if (!set.Contains(Math.Round(s, 6))) return false;+ }+ return true;+ }++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ // ---- ladder ---------------------------------------------------------------------+ double[] want4 = { 0.125, 0.25, 0.5, 1, 2, 4, 8, 16 };+ yield return (Enumerable.Range(0, 8).All(i => Near(GridStep.Of(i, false).Beats(4), want4[i])),+ "the straight ladder in 4/4 is 1/32 … 1/2, 1, 2, 4 bars");+ yield return (Near(GridStep.Of(5, false).Beats(3), 3) && Near(GridStep.Of(6, false).Beats(3), 6) && Near(GridStep.Of(7, false).Beats(3), 12),+ "bar steps follow the time signature (3/4: 3, 6, 12 beats)");+ yield return (GridStep.Of(42, false).Index == 7 && GridStep.Of(-3, false).Index == 0, "the step index is clamped to 0..7");+ string[] labels = { "1/32", "1/16", "1/8", "1/4", "1/2", "1 bar", "2 bars", "4 bars" };+ yield return (Enumerable.Range(0, 8).All(i => GridStep.Of(i, false).Label == labels[i]), "straight labels read 1/32 … 4 bars");++ // ---- adaptive resolution --------------------------------------------------------+ var def = GridSetting.DefaultArrangement;+ var r = At(def, 28);+ yield return (r.Snap.Index == 3 && r.Draw == r.Snap && r.SnapOn, $"defaults at 28 px/beat resolve to 1/4 (got {r.Snap.Label})");+ yield return (SnapGrid.Label(def, r) == "Auto · 1/4", $"the adaptive label reads \"Auto · 1/4\" (got \"{SnapGrid.Label(def, r)}\")");+ int n = At(def with { Density = GridDensity.Narrow }, 60).Snap.Index;+ int m = At(def with { Density = GridDensity.Medium }, 60).Snap.Index;+ int w = At(def with { Density = GridDensity.Wide }, 60).Snap.Index;+ yield return (n < m && m < w, $"Narrow < Medium < Wide at the same zoom ({n} {m} {w})");+ yield return (At(def with { Density = GridDensity.Narrow }, 240).Snap.Index == 0, "zoomed far in, adaptive stops at 1/32");+ yield return (At(def with { Density = GridDensity.Wide }, 0.5).Snap.Index == 7, "zoomed far out, adaptive stops at 4 bars");+ yield return (At(def, 4).Snap.Index == 5, "the arrangement's widest zoom (4 px/beat) resolves to 1 bar");+ bool finer = true;+ for (double ppb = 2; ppb < 300; ppb *= 1.17)+ if (At(def, ppb * 1.17).Snap.Index > At(def, ppb).Snap.Index) finer = false;+ yield return (finer, "zooming in never makes the adaptive step coarser");++ // ---- snapping and lines ---------------------------------------------------------+ yield return (Near(SnapGrid.SnapBeat(1.3, 0.5, 4), 1.5) && Near(SnapGrid.SnapBeat(1.2, 0.5, 4), 1.0), "SnapBeat picks the nearest position");+ yield return (Near(SnapGrid.SnapBeat(-0.4, 1, 4), 0), "SnapBeat never goes below zero");+ yield return (Near(SnapGrid.SnapBeat(13, 16, 4), 16) && Near(SnapGrid.SnapBeat(7, 16, 4), 0), "4-bar steps snap to multiples of 4 bars");+ bool agree = true;+ foreach (int bpb in new[] { 4, 3, 7 })+ for (int i = 0; i < 8; i++)+ foreach (bool t in new[] { false, true })+ if (!LinesAgree(GridStep.Of(i, t).Beats(bpb), bpb, 0, 40)) agree = false;+ yield return (agree, "lines and snapping agree for every step, straight and triplet, in 4/4, 3/4 and 7/4 (SC-001)");+ var bars34 = SnapGrid.GridLines(0, 12, 2, 3).ToList();+ yield return (new[] { 0.0, 2, 3, 5, 6, 8, 9, 11, 12 }.All(b => bars34.Any(l => Near(l, b))) && bars34.Count == 9,+ "3/4 with 1/2: lines restart at every bar (0 2 | 3 5 | 6 8 | …)");+ yield return (Near(SnapGrid.SnapBeat(2.8, 2, 3), 3), "3/4 with 1/2: the bar line is a snap point (2.8 → 3)");++ // ---- fixed mode, finer than drawn -----------------------------------------------+ var f32 = def with { Adaptive = false, FixedIndex = 0 };+ var far = At(f32, 4);+ yield return (far.Snap.Index == 0 && far.Draw.Index > 0 && far.FinerThanVisible, $"fixed 1/32 at 4 px/beat draws coarser lines ({far.Draw.Label}) and is marked");+ var near = At(f32, 240);+ yield return (near.Draw == near.Snap && !near.FinerThanVisible, "fixed 1/32 at 240 px/beat draws its own lines, unmarked");+ var f8 = def with { Adaptive = false, FixedIndex = 2 };+ yield return (At(f8, 4).Snap.Index == 2 && At(f8, 200).Snap.Index == 2 && SnapGrid.Label(f8, At(f8, 50)) == "1/8",+ "a fixed step ignores the zoom and reads \"1/8\"");++ // ---- transitions (⌘1 ⌘2 ⌘4 ⌘5, menu picks) ------------------------------------+ var fx = def with { Adaptive = false, FixedIndex = 2 };+ yield return (SnapGrid.Narrower(fx).FixedIndex == 1 && SnapGrid.Wider(fx).FixedIndex == 3, "⌘1 / ⌘2 halve / double a fixed step");+ yield return (SnapGrid.Narrower(fx with { FixedIndex = 0 }).FixedIndex == 0 && SnapGrid.Wider(fx with { FixedIndex = 7 }).FixedIndex == 7,+ "⌘1 / ⌘2 stop at 1/32 and 4 bars");+ yield return (SnapGrid.Narrower(def with { Density = GridDensity.Wide }).Density == GridDensity.Medium+ && SnapGrid.Narrower(def with { Density = GridDensity.Narrow }).Density == GridDensity.Narrow+ && SnapGrid.Wider(def).Density == GridDensity.Wide+ && SnapGrid.Wider(def with { Density = GridDensity.Wide }).Density == GridDensity.Wide,+ "in Auto, ⌘1 / ⌘2 move the density one notch and stop at the ends");+ var mixed = def with { Density = GridDensity.Wide, FixedIndex = 1 };+ var toFixed = SnapGrid.ToggleAdaptive(mixed);+ var back = SnapGrid.ToggleAdaptive(toFixed);+ yield return (!toFixed.Adaptive && toFixed.FixedIndex == 1 && back.Adaptive && back.Density == GridDensity.Wide,+ "⌘5 twice restores both the density and the fixed step");+ var off = SnapGrid.ToggleSnap(def);+ yield return (!off.SnapOn && off with { SnapOn = true } == def && SnapGrid.ToggleSnap(off) == def, "⌘4 flips only snap on/off");+ yield return (!At(off, 28).SnapOn, "snap off is carried into the resolved grid");+ yield return (SnapGrid.Narrower(off).SnapOn == false, "⌘1 leaves snap off as it is");+ yield return (SnapGrid.PickFixed(off, 4) is { Adaptive: false, FixedIndex: 4, SnapOn: true }+ && SnapGrid.PickAdaptive(off with { Adaptive = false }, GridDensity.Narrow) is { Adaptive: true, Density: GridDensity.Narrow, SnapOn: true },+ "picking a value from the menu turns snap back on");++ // ---- triplets -------------------------------------------------------------------+ yield return (Near(GridStep.Of(2, true).Beats(4), 1.0 / 3) && Near(GridStep.Of(3, true).Beats(4), 2.0 / 3) && Near(GridStep.Of(4, true).Beats(4), 4.0 / 3),+ "triplet steps are 2/3 of straight ones (1/8T = 1/3 beat)");+ yield return (Near(GridStep.Of(5, true).Beats(4), 4) && !GridStep.Of(6, true).Triplet && GridStep.Of(5, true).Label == "1 bar", "bar steps ignore triplets");+ yield return (GridStep.Of(2, true).Label == "1/8T", "triplet labels add T (1/8T)");+ var trip = def with { Triplets = true };+ var rt = At(trip, 60);+ yield return (rt.Snap.Triplet && SnapGrid.Label(trip, rt) == $"Auto · {rt.Snap.Label}" && rt.Snap.Label.EndsWith('T'),+ $"adaptive with triplets resolves to a triplet step ({rt.Snap.Label})");+ yield return (At(trip, 240).Snap.Triplet && At(trip, 4).Snap.Index >= 5, "adaptive triplets move through the triplet family, then to bars");+ var tt = SnapGrid.ToggleTriplets(fx);+ yield return (tt.Triplets && tt with { Triplets = false } == fx && SnapGrid.ToggleTriplets(tt) == fx, "⌘3 flips only triplets");+ var t34 = SnapGrid.GridLines(0, 6, 4.0 / 3, 3).ToList();+ yield return (t34.Any(l => Near(l, 3)) && t34.Any(l => Near(l, 6)), "3/4 with 1/2T keeps every bar start a line");++ // ---- settings (app-wide, FR-016 / FR-017) ---------------------------------------+ var fresh = JsonSerializer.Deserialize<Settings>("{}")!;+ yield return (fresh.ArrangementGrid == GridSetting.DefaultArrangement && fresh.PianoRollGrid == GridSetting.DefaultPianoRoll+ && fresh.QuantizeStep == GridStep.Of(1, false) && fresh.ArrangementGrid.Adaptive && fresh.ArrangementGrid.SnapOn,+ "settings without grid fields load Auto · Medium, snap on, Quantize 1/16");+ var s = new Settings+ {+ ArrangementGrid = def with { Adaptive = false, FixedIndex = 6 },+ PianoRollGrid = GridSetting.DefaultPianoRoll with { Triplets = true, Density = GridDensity.Narrow },+ QuantizeStep = GridStep.Of(2, true),+ };+ var rs = JsonSerializer.Deserialize<Settings>(JsonSerializer.Serialize(s))!;+ yield return (rs.ArrangementGrid == s.ArrangementGrid && rs.PianoRollGrid == s.PianoRollGrid && rs.QuantizeStep == s.QuantizeStep,+ "a settings round trip keeps both editors' grids and the Quantize step separate");+ var wild = JsonSerializer.Deserialize<Settings>("{\"ArrangementGrid\":{\"FixedIndex\":42,\"Adaptive\":false}}")!;+ yield return (At(wild.ArrangementGrid, 28).Snap.Index == 7 && wild.ArrangementGrid.SnapOn, "an out-of-range stored step is clamped, missing fields keep defaults");+ }+}