Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) Clip editor batch: playhead from the editors, arrangement rulers, warp tempo, live warp drag (#280)

Egor Khindikaynen994d0fb62333
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e9d7c77d..00bd0eb6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,19 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Move the playhead from the clip editors** (nota-daw/nota#278): click or drag the audio
+ clip editor's ruler to place the playhead, snapped to the grid on a warped clip (hold ⌥ to
+ place it freely). In both clip editors the playhead line itself can be grabbed and dragged.
+ A Session slot plays on its own loop clock, so its editors don't seek and say why.
+- **Rulers read in time** (nota-daw/nota#275): click the transport's position read-out to
+ switch it to time, and the arrangement ruler and both clip editor rulers switch with it.
+- **A clip's warp tempo, next to the Warp switch** (nota-daw/nota#248): the audio clip
+ editor's **Tempo** field shows the tempo the audio was recorded at. Drag it or double-click
+ to type a value; **÷2** and **×2** fix a half- or double-time detection in one click.
+ Hand-placed warp markers keep their timing, and on an unwarped clip a tempo turns Warp on.
+- **See the warp while you drag a marker** (nota-daw/nota#140): the waveform stretches and
+ squeezes live as a warp marker moves, and the clip is re-warped once when you let go. Esc
+ during the drag puts it back.
- **Plug-in windows open when you add a plug-in** (nota-daw/nota#250): adding a VST3 / AU
instrument or effect from the browser, by drag and drop or from the palette opens its
editor right away. Loading a project, undo, paste and the AI tools never do. Turn it off in
@@ -84,6 +97,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
**Check now** button. Nothing downloads until you click Update.
### Changed
+- **The clip editor ruler shows where the clip sits** (nota-daw/nota#275): with one MIDI or
+ audio clip open, the ruler reads the clip's arrangement position — a clip at bar 9 starts
+ at 9, not 1 — as a multi-clip selection already did. Unwarped audio clips read in bars too.
- **Detail panel tabs fit the track** (nota-daw/nota#247, nota-daw/nota#246): the **Pattern**
tab shows only on a track with a Drum Rack instead of sitting greyed out everywhere else,
and the panel can't be resized while **Devices** is shown, because the cards don't grow.
@@ -120,6 +136,11 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
`scripts/perf-gate.sh develop` (Linux).
### Fixed
+- **The audio clip editor shows the playhead while stopped** (nota-daw/nota#277): whenever
+ the song position is inside the clip, as the piano roll does.
+- **⌘1–⌘5 change a grid you can see** (nota-daw/nota#114): after a click in the audio clip
+ editor while its view follows no grid (ADSR, or an unwarped clip), the grid shortcuts act
+ on the arrangement instead of silently changing the clip editor's.
- **Context menus are never cut off at the sides**: a menu whose longest item had no shortcut
(the track menu of a live-frozen track, with *Flatten (remove source)*) could open a little
too narrow, clipping every row on both sides. Every menu and submenu now opens at its full
diff --git a/FEATURES.md b/FEATURES.md
index 4abd120c..1cd17811 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -71,7 +71,8 @@ JUCE module; the engine core is JUCE-free.
unsaved; Return saves (right in the dialog, then quits), Escape cancels.
- **Project key** (KEY cell in the transport bar, saved with the project): loops dropped on
the arrangement can be transposed to it.
-- **Transport**: play / stop / record, playhead position.
+- **Transport**: play / stop / record, playhead position. Click the position read-out to
+ switch it between bars and time; the arrangement and clip editor rulers follow it.
- **Stop returns to the launch point** (a seek sets the start anchor).
- **Pause** (⇧Space) — the playhead stays where it stopped and Play carries on from there.
- **Follow** — the arrangement follows the cursor (playhead stays centred); scrolling away
@@ -149,7 +150,9 @@ track count and closes with Escape.
roll's header chip open a menu with every option, as does the audio clip editor's header
(trim brackets, warp markers and envelope points snap); ⌘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.
+ on the editor used last (the arrangement while the audio clip editor shows ADSR or an
+ unwarped clip, which follow no grid). Hold ⌥ to drag freely; clip edges still attract a
+ dragged clip.
- **Session View** — a clip grid (tracks × scenes) with an inspector that the toolbar's
**Inspector** key (the sidebar icon) shows or hides (remembered); on a narrow window the least-used
toolbar controls fold into a **⋯** menu. Named, coloured clips with note / waveform
@@ -242,7 +245,10 @@ track count and closes with Escape.
- **Playable keys**: click a key to hear it, ⇧-drag to glide, ⌘-click to select every note
of that pitch; a vertical drag on the keys zooms the rows.
- Click the roll's ruler to put the playhead there, or drag along it to scrub (snapped to
- the grid); the roll shows the playhead while stopped too, where playback will start.
+ the grid, ⌥ free); the playhead line itself drags too, on the ruler or over empty grid.
+ The roll shows the playhead while stopped, where playback will start, and its ruler
+ reads the clip's arrangement position (a clip at bar 9 starts at 9). A Session slot
+ plays on its own loop clock, so its editor counts from the slot's start and doesn't seek.
- Drag a note's left edge to move its start (the end stays put); stacked notes keep
separate velocity stems (grab a stem by its cap, ⇧-click to add it to the selection).
- Notes replace the same-pitch notes they land on instead of stacking: moved, stretched,
@@ -445,7 +451,15 @@ track count and closes with Escape.
editors' snap grid. Warping runs in the background (the track shows "Processing…" and a
re-warped clip plays its previous version until the new one is ready), so long files
don't stall the app. The clip editor redraws the visible waveform at screen resolution,
- down to single samples, and its ruler thins or adds bars, beats and 16ths with the zoom.
+ down to single samples, and its ruler — in the clip's arrangement position, bars or time,
+ warped or not — thins or adds bars, beats and 16ths with the zoom. Click or drag the ruler,
+ or drag the playhead line, to move the playhead (snapped on a warped clip, ⌥ free); the
+ playhead shows while stopped too.
+ - **Tempo** next to the Warp switch: the tempo the audio was recorded at — drag it or type
+ it; **÷2** / **×2** fix a half- or double-time detection. Warp markers keep their relative
+ timing; on an unwarped clip a tempo turns Warp on. One undo step each.
+ - Dragging a warp marker (or a segment's BPM chip) stretches the waveform live; the clip is
+ re-warped once on release, and Esc during the drag puts it back.
- **Changing the sample rate** does not break third-party plugins or warped clips — the
caches are rebuilt once when the rate changes.
diff --git a/specs/036-clip-editor-batch/checklists/requirements.md b/specs/036-clip-editor-batch/checklists/requirements.md
new file mode 100644
index 00000000..45353ac8
--- /dev/null
+++ b/specs/036-clip-editor-batch/checklists/requirements.md
@@ -0,0 +1,39 @@
+# Specification Quality Checklist: Clip editor batch
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-22
+**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
+
+- Implementation facts are confined to the Nota Context section, which the project's
+ template requires (it drives plan and tasks); requirements and success criteria stay
+ behavioural.
+- Three clarifications resolved with the user on 2026-10-22 (session-slot seeking off,
+ arrangement ruler follows the time display, unwarped tempo edit turns Warp on); recorded
+ under Clarifications in spec.md. All items pass.
diff --git a/specs/036-clip-editor-batch/contracts/clip-editor-ui.md b/specs/036-clip-editor-batch/contracts/clip-editor-ui.md
new file mode 100644
index 00000000..ee6b495f
--- /dev/null
+++ b/specs/036-clip-editor-batch/contracts/clip-editor-ui.md
@@ -0,0 +1,67 @@
+# UI contract: clip editor gestures, keys and controls
+
+The user-facing contract this batch adds or changes. Preferences → Shortcuts (nota-shortcuts)
+and the user docs (nota-docs) are updated from this list.
+
+## Playhead
+
+| Where | Gesture | Result |
+|---|---|---|
+| Audio clip editor ruler (arrangement clip) | click | transport → arrangement position under the pointer, snapped (warped clips, Snap on) |
+| same | drag | scrub, snapped |
+| same | Alt + click / drag | free (no snap) |
+| Audio clip editor, playhead line (ruler, marker strip, wave), ±4 px | drag | scrub like the ruler; cursor ↔ |
+| Piano roll ruler | click / drag / Alt | unchanged (#50) |
+| Piano roll ruler, playhead line ±4 px | drag | scrub |
+| Piano roll note grid, playhead line ±3 px | drag ≥ 3 px | scrub; a click without movement is a normal grid click |
+| Either editor, Session-slot clip | ruler / line | no seek; cursor 🚫; tooltip "A Session slot plays on its own loop clock — launch it to play from the start" |
+
+Playhead visibility: audio editor shows it whenever the song position is inside the clip's
+played region (stopped or playing); Session slots follow the slot clock as today.
+
+## Rulers
+
+| Ruler | Bars mode | Time mode |
+|---|---|---|
+| Arrangement | unchanged | `m:ss` … by zoom |
+| Piano roll, one arrangement clip | arrangement bars (`Origin + local`) | arrangement time |
+| Piano roll, several clips | unchanged (already arrangement) | arrangement time |
+| Audio editor, warped | arrangement bars at the warp's position (before Start bracket = before the clip) | arrangement time |
+| Audio editor, unwarped | arrangement bars | arrangement time |
+| Session-slot clip (any editor) | clip-relative, as today | clip-relative time |
+
+Mode follows a click on the transport position read-out (bars ↔ time), live.
+
+## Keyboard
+
+| Situation | Space / Return | ⌘1–⌘5 (grid) |
+|---|---|---|
+| After a click on a non-text control in the clip editor | transport; the focused control is **not** activated | act on the clip editor grid; if that grid is inert (unwarped audio, ADSR mode) on the arrangement grid; status line names the target |
+| Text field focused | typed into the field | ignored |
+| After Enter / Esc / click-away from a field | transport | as above |
+| During a warp-marker drag | — | Esc cancels the drag |
+
+## Warp section (audio clip editor)
+
+```
+Warp [● on] Complex ▾
+Tempo [ 87.00 BPM ] ÷2 ×2
+[Detect tempo] [To transients]
+```
+
+- **Tempo**: `DragNumber` — vertical drag (0.5 BPM per pixel), double-click → type,
+ Enter / click-away commit, Esc cancel. 20–999 BPM, two decimals.
+- **÷2 / ×2**: one step each; disabled when the result would leave the range or no tempo is
+ known.
+- Tooltip on the label and value: "The tempo the audio was recorded at. Nota stretches it to
+ the project tempo. ×2 / ÷2 fix a half- or double-time detection."
+- Warped clip: value = tempo of the played region; edits scale all markers + trim.
+- Unwarped clip: value = last detected tempo or "—" (dimmed, still editable); an edit turns
+ Warp on at that tempo.
+- Every edit (typed commit, a whole drag, ÷2, ×2) is one undo step.
+
+## Warp-marker drag
+
+While dragging: marker, waveform and the two neighbouring BPM chips follow the pointer.
+Release: one commit, one undo step, the waveform is replaced by the engine's stretch.
+Esc / capture lost: everything returns to the pre-drag state, nothing is committed.
diff --git a/specs/036-clip-editor-batch/data-model.md b/specs/036-clip-editor-batch/data-model.md
new file mode 100644
index 00000000..db887c4f
--- /dev/null
+++ b/specs/036-clip-editor-batch/data-model.md
@@ -0,0 +1,78 @@
+# Data model: Clip editor batch
+
+No persisted data changes: no project-file, preset or settings field is added. The
+entities below are in-memory value types in `src/managed/Nota.App`, pure (no Avalonia, no
+engine) so the smoke test can exercise them as linked source, like `ValueText`.
+
+## ClipTimeMap — editor position ↔ arrangement position
+
+Built by the audio clip editor on every `Reload` from the clip's geometry.
+
+| Field | Meaning |
+|---|---|
+| `StartBeat` | the clip's arrangement start (`NotaClipInfo.start_beat`) |
+| `LengthBeats` | the clip's arrangement length |
+| `Domain` | `WarpBeats` (warped) or `SourceFrames` (unwarped) |
+| `ContentTotal` | `warp_beats` (warped) or the sample's total frames (unwarped) |
+| `PlayStart`, `PlayEnd` | played window in the domain: trim brackets (warped) or `[offset, offset + length]` frames (unwarped) |
+| `Reversed` | the region plays back-to-front |
+| `IsSlot` | a Session-slot clip — no arrangement position |
+
+Operations (all total; NaN-free for `ContentTotal > 0`):
+
+- `PlayFracAtContent(c)` — content frac `c ∈ [0,1]` → played frac; `(c·Total − PlayStart) /
+ (PlayEnd − PlayStart)`, then `1 − f` when reversed. Not clamped (seeks may fall outside).
+- `ContentAtPlayFrac(f)` — the inverse; used to draw the playhead (replaces the inline
+ formula in `Render`).
+- `ArrangementBeatAtContent(c) = StartBeat + PlayFracAtContent(c) × LengthBeats`.
+- `ContentAtArrangementBeat(b)` — the inverse; places ruler ticks at arrangement steps.
+
+Rules: `IsSlot` → the editor uses clip-relative labels and no seeking; the map still serves
+the playhead (the slot position is clip-relative already).
+
+## ClipTempo — the clip's warp tempo
+
+| Input | Meaning |
+|---|---|
+| markers `(src, beat)[]` | warp markers, sorted by `src`, ≥ 2 |
+| `PlayStart`, `PlayEnd` | trim window in warp beats (`PlayEnd = 0` → `warp_beats`) |
+| `SampleRate` | source sample rate |
+
+- `SrcAt(beat)` — piecewise-linear source frame at a warp beat (extrapolates past the ends
+ with the end segments' slope).
+- `Bpm = (PlayEnd − PlayStart) × SampleRate × 60 / (SrcAt(PlayEnd) − SrcAt(PlayStart))`.
+- `Scale(newBpm)` → `(markers', PlayStart', PlayEnd')` with every beat × `k = newBpm / Bpm`;
+ `PlayEnd = 0` stays 0.
+- Valid range 20–999 BPM; `Half()` / `Double()` return null if the result leaves it.
+
+Unwarped clip: `Bpm` is the last detected tempo or null ("—"). With null, typing still sets a
+tempo; ×2 / ÷2 are disabled.
+
+## WarpRemap — live marker-drag preview
+
+| Input | Meaning |
+|---|---|
+| `committed` `(src, beat)[]` | markers as the engine laid out the current peaks |
+| `live` `(src, beat)[]` | markers during the drag (same count, same sources) |
+
+- `OldBeatAt(newBeat) = BeatAt(committed, SrcAt(live, newBeat))` — piecewise linear through
+ both lists; monotone because both lists are.
+- Identity when `live == committed` (no visual change before the pointer moves).
+
+State: `Idle` → (press on marker) `Dragging{committed snapshot}` → release ⇒ commit ⇒ `Idle`;
+Esc / capture lost ⇒ restore `live = committed` ⇒ `Idle`.
+
+## RulerLabels — shared ruler text
+
+- Input: arrangement beat, label step (beats or seconds), mode `Bars | Time`, beats per bar,
+ BPM.
+- Bars: `N` on a bar, `N.b` on a beat, `N.b.s` on a 16th (1-based, like the existing
+ labels).
+- Time: seconds = `beat × 60 / BPM`; `m:ss` for steps ≥ 1 s, `m:ss.f`, `m:ss.ff`, `m:ss.fff`
+ as the step shrinks. Negative positions never occur (clamped at 0 before formatting).
+
+## RulerDisplay — the shared mode
+
+A static observable in `Nota.App`: `bool ShowTime`, `event Action Changed`. Set from the
+transport view model's `ShowTimeDisplay`; read by the arrangement ruler, the piano roll
+ruler and the audio editor ruler.
diff --git a/specs/036-clip-editor-batch/plan.md b/specs/036-clip-editor-batch/plan.md
new file mode 100644
index 00000000..ea10e123
--- /dev/null
+++ b/specs/036-clip-editor-batch/plan.md
@@ -0,0 +1,132 @@
+# Implementation Plan: Clip editor batch — playhead, arrangement ruler, keyboard focus, warp tempo
+
+**Branch**: `feat/clip-editor-batch` | **Date**: 2026-10-22 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `specs/036-clip-editor-batch/spec.md`
+
+## Summary
+
+Six clip-editor issues in one UI-only change. A pure `ClipTimeMap` maps the audio editor's
+content axis to arrangement beats; it fixes the hidden stopped playhead (#277), drives
+ruler / playhead-line seeking in both editors (#278, Session slots excluded with a "not
+available" cursor) and relabels the rulers in arrangement position, with a shared
+bars / time mode that follows the transport read-out across the arrangement, piano roll and
+audio rulers (#275). The keyboard fix (#114) starts from a reproduction; the likely causes
+are a focused props-rail button re-activated by Space's KeyUp and grid commands landing on
+an inert clip-editor grid. A Tempo row (`DragNumber` + ÷2 / ×2) under the Warp switch scales
+markers and trim in one undo group, or auto-warps an unwarped clip at the typed tempo via the
+existing `AutoWarpClipAtBpm` (#248). The marker drag previews the stretch by remapping the
+committed peaks through the old and new markers and commits once on release (#140). No
+engine, ABI or file-format change. Details: [research.md](research.md).
+
+## Nota: Read Before Planning
+
+- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Studio) and the `nota-design` skill — the
+ Tempo row, the playhead-grab cursor, the "not available" state, ruler time labels.
+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).
+- AR-9 (`Transport` is the only source of musical time): seeks go through `Engine.Seek`;
+ the UI only converts positions for display.
+
+## Technical Context
+
+**Language/Version**: C# / .NET 10 (managed app only)
+
+**Primary Dependencies**: Avalonia 12 (existing); no new dependency
+
+**Storage**: N/A — no project, preset or settings change; the bars/time mode stays the
+transport view model's existing in-memory flag
+
+**Audio-Thread Impact**: None. Seeks use the existing `Engine.Seek`. Warp edits use the
+existing marker / trim / auto-warp entry points through `WarpEdit` (deferred background
+stretch). The live marker preview is display-only and sends nothing to the engine until
+release.
+
+**Testing**: `scripts/build.sh` (smoke test + design checks). New pure types (`ClipTimeMap`,
+`ClipTempo`, `WarpRemap`, `RulerLabels`) linked as source into `tests/Nota.SmokeTest`
+(`--clipeditor` section), like `ValueText`. UI flows: headless Avalonia harness and the
+real app per [quickstart.md](quickstart.md).
+
+**Target Platform**: macOS, Windows, Linux (desktop)
+
+**Project Type**: desktop app
+
+**Performance Goals**: live warp preview redraws at the UI's normal rate on a 5-minute clip
+(SC-004): O(columns × log markers) per frame, no allocation per frame beyond what `Render`
+does today
+
+**Constraints**: grid lines and snapping unchanged (FR-011); note entry in the piano roll
+must not be stolen by the playhead grab (narrow zone, click falls through)
+
+**Scale/Scope**: ~8 files in `src/managed/Nota.App` (AudioClipEditorView, PianoRollView,
+ArrangementView.Controls, MainWindow.Detail / .Input / .axaml.cs / .Commands, ClipEditorKit)
+plus 4 new small pure files and a smoke-test section
+
+## Constitution Check
+
+*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
+
+| Principle | Status |
+|---|---|
+| I. Real-time audio safety | Pass — no audio-thread code; preview is UI-only |
+| II. Boundary discipline | Pass — existing C ABI entry points only (`seek`, warp markers / trim, `auto_warp_bpm`, undo group) |
+| III. Licensing hygiene | Pass — new files get the SPDX header; no dependency |
+| IV. Verification gate | Pass — `scripts/build.sh`; new smoke-test section for the pure math; no engine behaviour change |
+| V. One logical change per PR | **Justified exception** — see Complexity Tracking |
+| VI. Docs in sync | Planned — CHANGELOG `[Unreleased]`, nota-features, nota-docs (clip editor + warping pages), nota-shortcuts (playhead drag, ruler click in the audio editor) |
+| VII. Spec first | Pass — spec, clarifications, this plan; tasks next |
+| VIII. Rules not weakened | Pass |
+
+Post-design re-check (after research / data-model / contracts): unchanged — all gates pass,
+the one exception stays as justified.
+
+## Project Structure
+
+### Documentation (this feature)
+
+```text
+specs/036-clip-editor-batch/
+├── plan.md # this file
+├── research.md # R1–R7
+├── data-model.md # ClipTimeMap, ClipTempo, WarpRemap, RulerLabels, RulerDisplay
+├── quickstart.md # build, smoke section, in-app checks, screenshots
+├── contracts/
+│ └── clip-editor-ui.md
+├── checklists/
+│ └── requirements.md
+└── tasks.md # /speckit-tasks
+```
+
+### Source Code (repository root)
+
+```text
+src/managed/Nota.App/
+├── ClipEditor/ # NEW folder for the pure helpers
+│ ├── ClipTimeMap.cs # NEW — content ↔ arrangement mapping (R1)
+│ ├── ClipTempo.cs # NEW — played-region tempo, scale, ÷2/×2 (R5)
+│ ├── WarpRemap.cs # NEW — old↔new marker remap for the live preview (R6)
+│ └── RulerLabels.cs # NEW — bars/time labels + RulerDisplay mode (R3)
+├── AudioClipEditorView.cs # playhead gate, Seek, ruler + line gestures, labels,
+│ # Tempo row, live preview, CancelGesture
+├── PianoRollView.cs # ruler labels (Origin + b, time), playhead-line grab,
+│ # slot "not available" state
+├── ArrangementView.Controls.cs # ruler time mode
+├── ClipEditorKit.cs # pointer-only buttons not focusable (R4, if confirmed)
+├── MainWindow.Detail.cs # audio editor Seek wiring (arrangement clips only)
+├── MainWindow.Input.cs # Space KeyUp swallow; Esc → editor CancelGesture (R4, R6)
+├── MainWindow.Commands.cs # grid target falls back when the clip grid is inert (R4)
+└── MainWindow.axaml.cs # RulerDisplay ← Transport.ShowTimeDisplay
+
+tests/Nota.SmokeTest/
+├── Nota.SmokeTest.csproj # link the four pure files
+└── ClipEditorTests.cs # NEW — `--clipeditor` section
+```
+
+**Structure Decision**: Managed UI only, in `Nota.App`, which already owns both clip
+editors and the rulers. The pure helpers sit in a new `ClipEditor/` folder so the smoke
+test can link them without Avalonia (precedent: `Controls/ValueText.cs`).
+
+## Complexity Tracking
+
+| Violation | Why Needed | Simpler Alternative Rejected Because |
+|-----------|------------|-------------------------------------|
+| Principle V: six issues in one PR | The user asked for one batch PR; all six change the same two editors and share the new position mapping (#277 / #278 / #275) and the warp code (#248 / #140). Precedent: #272, #273. | Six PRs would land the shared `ClipTimeMap` three times or serialise them; the review cost is lower as one PR with one commit per issue. |
diff --git a/specs/036-clip-editor-batch/quickstart.md b/specs/036-clip-editor-batch/quickstart.md
new file mode 100644
index 00000000..440bf921
--- /dev/null
+++ b/specs/036-clip-editor-batch/quickstart.md
@@ -0,0 +1,79 @@
+# Quickstart: verifying the clip editor batch
+
+## Prerequisites
+
+- Release engine build in `src/native/nota.engine/build` (BUILD.md; `build/` stays Release).
+- A scratch data dir: `export NOTA_DATA_DIR=$(mktemp -d)`.
+- A drum loop with a known tempo (e.g. 120 BPM, 2 bars) and a longer unwarped sample.
+
+## 1. Build and smoke test (the PR gate)
+
+```bash
+scripts/build.sh
+```
+
+Expect green. The pure mapping / tempo / remap / label math runs in its own section:
+
+```bash
+dotnet run --project tests/Nota.SmokeTest -c Release -- --clipeditor
+```
+
+Expect every check `ok`: `ClipTimeMap` round trips (warped, trimmed, reversed, unwarped),
+`ClipTempo` (one segment equals the chip, scaling keeps segment ratios, ×2 / ÷2 range),
+`WarpRemap` (identity when unchanged, monotone, end markers fixed), `RulerLabels` (bars and
+time at each step size) — see [data-model.md](data-model.md).
+
+## 2. Playhead (US1, #277 / #278)
+
+1. Audio clip at 2.1, open it. Stop with the song position at 3.1 → playhead drawn; move to
+ 5.1 → gone.
+2. Click the editor ruler at a hit → transport and arrangement playhead jump there (snapped
+ with Warp + Snap on; free with Alt). Drag → scrubs. Space → plays from there.
+3. Drag the playhead line over the wave → scrubs. In the piano roll: drag the line on the
+ ruler and in the note grid; a click on the line without movement adds a note.
+4. Reverse the clip, trim its Start bracket in → clicks still land where that audio plays.
+5. Open a Session-slot clip in each editor → ruler and line show 🚫 and the tooltip; nothing
+ seeks.
+
+## 3. Rulers (US2, #275)
+
+1. MIDI clip at 9.1 → ruler reads 9, 10 …; two MIDI clips selected → unchanged behaviour.
+2. Warped audio clip at 9.1 → 9 at the Start bracket; trim the bracket in one bar → the
+ bracket reads 9, audio before it 8. Unwarped clip → bars too.
+3. Click the transport read-out → arrangement, piano-roll and audio rulers switch to m:ss;
+ click again → bars. The labels at the clip start match the read-out when the playhead is
+ there.
+
+## 4. Keyboard (US3, #114)
+
+1. Reproduce the report first: open an audio clip with ADSR shown, click the ADSR / props
+ rail buttons, press Space and ⌘1–⌘5. Record what happened before the fix in research.md
+ R4.
+2. After the fix, for each region (props rail, wave, ADSR, envelope, piano-roll grid, MIDI
+ tools) click it, press Space twice and ⌘1 → transport toggles, no button under focus
+ re-activates, the grid changes and the status line names it.
+3. Type into a field (clip name, BPM, ADSR value) → spaces type; Enter → Space plays again.
+4. Repeat 2 with the detail panel floating.
+
+## 5. Warp tempo (US4, #248)
+
+1. Warped 120 BPM loop → Tempo reads 120.00. ÷2 → 60.00, the clip spans half the beats
+ (a higher recorded tempo means more beats, so ×2 doubles the length); undo once → 120.00. ×2 / drag / type 87 → each one undo step.
+2. Clip with several markers → tempo change keeps the chips' ratios.
+3. Unwarped sample → Tempo shows the detected value or "—"; type 100 → Warp switches on at
+ 100 BPM; one undo returns to unwarped.
+
+## 6. Live warp drag (US5, #140)
+
+1. Drag a middle marker slowly → waveform on both sides stretches live, chips update.
+2. Release → one undo step; waveform replaced by the engine's render (no visible jump
+ beyond detail).
+3. Drag again and press Esc → everything returns; nothing in undo.
+4. While playing, drag a marker → no dropouts until release.
+
+## 7. Screenshots for the PR
+
+Headless harness per the UI-verify recipe (docked clip editor at 1440×900, Studio Dark and
+Studio Light): audio editor with the playhead stopped inside the clip, the Tempo row, the
+ruler in bars and in time, the piano roll ruler at bar 9, and a mid-drag warp preview.
+Before / after pairs for #277, #275, #248.
diff --git a/specs/036-clip-editor-batch/research.md b/specs/036-clip-editor-batch/research.md
new file mode 100644
index 00000000..1567eb8c
--- /dev/null
+++ b/specs/036-clip-editor-batch/research.md
@@ -0,0 +1,228 @@
+# Research: Clip editor batch
+
+All findings come from reading the code on `develop` @ 92a0608. Paths are under
+`src/managed/Nota.App/` unless noted.
+
+## R1 — Waveform position ↔ arrangement position (#277, #278, #275)
+
+**Facts.** The audio clip editor draws everything on one normalised content axis
+(`FracToX` / `XToFrac`, mirrored when reversed). Three domains map onto it:
+
+- warped clip — warp beats `[0, TotalBeats]` (the full warp, markers' last beat); the
+ played window is `[_trimStart, _trimEnd]` (`warp_play_start / _end`);
+- unwarped clip — source frames `[0, _srcTotal]`; the played region is
+ `[_srcOff, _srcOff + _srcLen]`;
+- the playhead `_frac` runs over the **played** window, `0` = the clip's first audible
+ moment, and is flipped (`1 − frac`) when reversed (`Render`, the `_frac` block).
+
+`OnPlayhead` computes `frac = (beats − _startBeat) / _lengthBeats`, gated on `playing`. Audio
+clips have no clip loop (`NotaAudioClipInfo` has no loop fields), so the played window maps
+linearly onto `[start, start + length]` in the arrangement.
+
+**Decision.** Introduce one pure mapping, `ClipTimeMap` (data-model.md), built from the clip
+geometry on every `Reload` and handed to the waveform view:
+
+- `PlayFracAt(contentFrac)` — inverse of the existing playhead draw: content frac → played
+ frac (clamped to `[0,1]` only for the playhead, not for seeking), reversed-aware;
+- `ArrangementBeatAt(playFrac) = start + playFrac × length`;
+- and the forward direction for ruler labels: `ArrangementBeatAtContent(contentFrac)`.
+
+Seeking left of a trimmed Start (played frac < 0) gives a beat before the clip start;
+clamp at 0, as the spec's edge case says. The same map labels the ruler (R3) so labels
+and seeks can't disagree.
+
+**#277 fix.** Drop the `playing &&` gate for arrangement clips; keep the session branch.
+
+**Alternatives.** Computing the inverse ad hoc in the pointer handler — rejected: the
+ruler labels need the same transform, and the smoke test can exercise a pure map.
+
+## R2 — Seeking from the clip editors (#278)
+
+**Facts.** The piano roll already seeks: `RulerLane` press / drag → `SnapBeat(XToBeat(x))`
+→ `Seek(local)`; the host (`MainWindow.Detail.cs`, `BuildClipEditor`) maps
+`roll.Origin + local` → `Engine.Seek` + `Timeline.SetPlayhead`. The session-slot roll
+(`MainWindow.Detail.cs` ~L772) sets no `Seek`, so seeking is already off there, with a
+default cursor. The audio editor has no `Seek` hook.
+
+**Decision.**
+
+- Audio editor gets `Action<double>? Seek` (arrangement beat), set by `BuildAudioClipEditor`
+ for arrangement clips only (`SessionClip.SceneOf(clipIndex) < 0`), same body as the roll's
+ (`Engine.Seek`, `Timeline.SetPlayhead`).
+- Ruler press / drag in `WaveCanvas` → snap → `Seek`. Snap in the **warp-beat** domain with
+ `SnapWarp` (the grid already drawn there); Alt = free (`_free`, as for markers). Unwarped
+ clips have no beat grid (#269: "Snap needs Warp"), so seeks there are free — this matches
+ what Snap does elsewhere in that editor.
+- Playhead-line grab: a hit zone of ±4 px around the drawn playhead x, active in the ruler,
+ the marker strip and the wave area of the audio editor and in the ruler + note grid of
+ the piano roll. The zone wins over the content gesture under it (FR-005). Cursor
+ `SizeWestEast` over the zone.
+ - Piano roll: the grid's press handler checks the zone first (`NoteGrid.OnPointerPressed`);
+ while dragging it reuses `RulerLane.SeekAt` logic, so snap / Alt match the ruler.
+ - A note under the playhead line stays editable from outside the ±4 px zone; with the
+ transport stopped the line sits where play starts, which is exactly where users click to
+ add a note at the song position — so in the note grid the grab needs **no modifier but a
+ narrower zone (±3 px) and only when the line is visible**, and a click without movement
+ there falls through to the grid's normal click (adds / selects a note). Drag ≥ 3 px
+ turns it into a scrub.
+- Session-slot clips (both editors): no `Seek`; ruler and line show `StandardCursorType.No`
+ and a tooltip "A Session slot plays on its own loop clock — launch it to play from the
+ start". (Avalonia `ToolTip.Tip` on the ruler control, set when `Seek is null` and the clip
+ is a slot.)
+
+**Alternatives.** Seek within a playing slot — rejected by the user (clarification Q1).
+Modifier-gated line grab in the note grid — rejected: undiscoverable; the narrow zone plus
+the click-falls-through rule keeps note entry safe.
+
+## R3 — Ruler labels in arrangement position and in time (#275)
+
+**Facts.**
+
+- Piano roll `RulerLane.Render` labels `barNo = floor(b/bpb) + 1 + RulerBarOffset`, where
+ `RulerBarOffset` is non-zero only for multi-clip sets (their origin sits on a bar line).
+ `Origin` is the clip's start for a single clip.
+- Audio editor `DrawRuler`: warped → bar.beat labels over warp beats from 0; unwarped →
+ seconds over the source from 0 s.
+- Arrangement `RulerControl` (`ArrangementView.Controls.cs`): bars only.
+- The transport read-out flips on `TransportViewModel.ShowTimeDisplay`; time =
+ `beats × 60 / Bpm` (one global tempo; scene tempos change `Bpm` itself — there is no
+ tempo map).
+
+**Decision.**
+
+- One shared formatter, `RulerLabels` (pure): given an arrangement beat, a step and the mode
+ (bars / time), returns the label — bars `N` / `N.b` / `N.b.s`, time `m:ss`, `m:ss.f` …
+ with as many decimals as the step needs (reuses the shape of the existing
+ `SecondsLabel`). Time steps for tick placement come from the existing seconds step table.
+- Mode source: a static `RulerDisplay` (observable `ShowTime` + `Changed` event) in
+ `Nota.App`, set from `TransportViewModel.ShowTimeDisplay`'s property-changed in
+ `MainWindow`; the three rulers subscribe and `InvalidateVisual`.
+- Piano roll single clip: labels use `Origin + b` (arrangement beat), not `b`. Grid lines
+ and their spacing stay clip-local (FR-011); for a bar-aligned clip (the usual case) the
+ labels read 9, 10 … exactly. A clip starting off a bar labels its ticks with their true
+ position (e.g. 2.3). Session-slot rolls keep `Origin = 0` → unchanged.
+- Audio editor: labels come from `ClipTimeMap.ArrangementBeatAtContent` for warped and
+ unwarped clips alike. For an unwarped clip in bars mode the ticks are placed at
+ arrangement beat steps mapped back to content (the inverse of the same map), so the
+ ruler reads bars too; in time mode, seconds.
+- Time mode places ticks at time steps (arrangement seconds) in all three rulers; the
+ grid itself (lines in the content area) does not change.
+
+**Alternatives.** Re-basing the piano roll grid onto arrangement bars for off-bar clips —
+rejected: changes snapping (FR-011) and the multi-clip `ClipSet` origin logic.
+
+## R4 — Keyboard focus after a click in the clip editor (#114)
+
+**Facts.**
+
+- Space / Return: tunnel handler on the main window (`OnGlobalTransportKey`) — runs before
+ any focused control, skipped only when `e.Source` is a `TextBox` / `NumericUpDown`. The
+ floating detail window forwards via `HandleTransportKeyTunnel`.
+- Grid ⌘1–⌘5: native menu items → `StepGrid` → `GridTarget()`. After a press inside the
+ detail area `_detailWasLastFocused` is true, so the grid commands act on the **clip
+ editor's** grid, by design (status line says "Clip editor grid: …"). On an unwarped
+ audio clip or with the ADSR shown, the clip editor's grid has no visible effect
+ ("Snap needs Warp").
+- `StepGrid` ignores the commands while a `TextBox` has focus.
+- Avalonia `Button` / `ToggleButton` activate on **Space KeyUp**; the tunnel handler only
+ marks the KeyDown handled. The clip editor's props rail is made of focusable buttons
+ (`ClipEditorKit.Button`, `SwitchRow`, dropdown cells): after clicking one, Space starts
+ playback *and* re-clicks that button on release.
+- Hidden text fields already hand focus back (`HideBpm`, `ValueEntry.Close`, #141).
+
+**Decision.** Reproduce first in the running app (macOS, the reporter's setup: an audio
+clip with the ADSR shown, then a MIDI clip), using the env-guarded UI-verify hook.
+Expected fixes, by the hypotheses above:
+
+1. Space KeyUp: extend the tunnel handler to also swallow the matching `KeyUp` of a Space
+ it handled (track `_spaceDown`), so a focused button in the clip editor (or anywhere)
+ is not activated.
+2. Clip editor buttons and switches: `Focusable = false` for pointer-only controls in the
+ props rail (`ClipEditorKit` factories), so a click leaves no focused control behind; keep
+ focus for the text fields.
+3. Grid feedback: when the clip editor is the grid target but its grid is inert (unwarped
+ audio / ADSR mode), apply the command to the arrangement grid instead, and say so on the
+ status line. This makes "grid shortcuts work as after a click in the arrangement"
+ (FR-013) true in exactly the case the reporter hit, without changing the design for MIDI
+ and warped audio clips.
+
+If the reproduction shows another cause, record it here and fix that instead; the
+acceptance scenarios in the spec stay the test.
+
+**Reproduction (2026-10-22, T019).** Headless Avalonia run of the real `MainWindow` with
+input through the headless platform (hit testing, focus, tunnel / bubble): an audio clip at
+bar 3, clicks on the arrangement, the props rail, the **ADSR** tab, the ADSR **Reset**
+button and the wave, each followed by Space down / up twice and `grid.narrower`.
+
+- Space played and stopped after every click; the focused element stayed `(none)` after
+ each one — clip editor buttons and segments take no focus on click, so no control was
+ re-activated by Space's KeyUp. Hypotheses 1 and 2 are **not** reproduced (T020, T021 N/A).
+- After any click in the detail area, `grid.narrower` went to "Clip editor grid: Auto ·
+ 1/32" — in ADSR mode and on an unwarped clip, a grid nothing on screen follows. The
+ reporter's screenshot (attachment on #114) shows exactly this state: an unwarped clip on
+ the ADSR tab, status line "Clip editor grid: Auto · 1/32". Hypothesis 3 is the cause of the
+ "grid shortcuts stop responding" half; fixed by `AudioClipEditorView.GridInert` +
+ `GridTarget()` (T022). After the fix the same run reports "Arrangement grid: …".
+- The Space half could not be reproduced (headless is not the macOS native host). The
+ tunnel handler already runs before any focused control; nothing in the clip editor
+ marks Space handled. Left as is; the quickstart's in-app check (§ 4) covers it on macOS.
+
+## R5 — Clip warp tempo control (#248)
+
+**Facts.** Per-segment BPM = `beatSpan × srcSR × 60 / srcSpan` (`ApplySegmentBpm`, the chip
+drawing). Warp edits go through `WarpEdit` (deferred background stretch). The engine keeps
+the trim window across marker edits (`clampWarpPlay`). `nota_clip_auto_warp_bpm(bpm)`
+enables warp with a given tempo and snaps the length (no detection). The managed engine has
+`BeginUndoGroup` / `EndUndoGroup`.
+
+**Decision.**
+
+- Clip tempo = played region's warp-beat span ÷ its source span, in BPM:
+ `bpm = (pe − ps) × srcSR × 60 / (src(pe) − src(ps))`, `src(·)` interpolated through the
+ markers (data-model `ClipTempo`). For a single segment it equals the segment chip.
+- Set tempo `t` on a warped clip: factor `k = t / bpm`; every marker beat × `k`, trim
+ window × `k` (`play_end = 0` stays 0); commit markers then trim inside one undo group via
+ `WarpEdit`. Relative segment timing is preserved (FR-019).
+- Unwarped clip: no detection on open (it is heavy). Show the last detected value (`ai`
+ has none; the editor's `_detectedBpm` comes from Detect tempo / import) or "—". An edit
+ calls the existing `Engine.AutoWarpClipAtBpm(t)` (wrapper over
+ `nota_clip_auto_warp_bpm`) inside `WarpEdit` — enables warp and conforms the clip in one
+ engine call, one undo step.
+- Control: a `DragNumber` (existing control: drag, double-click → text, Enter / Esc) in a
+ "Tempo" row directly under the Warp switch row, with `÷2` and `×2` icon-less text buttons
+ (`ClipEditorKit.Button` style, compact). Range 20–999 BPM (the chips' range); ×2 / ÷2 that
+ would leave it do nothing. Tooltip: "The tempo the audio was recorded at. Nota stretches
+ it to the project tempo. ×2 / ÷2 fix a half- or double-time detection."
+- A drag edits live without committing (scale markers locally, redraw) and commits once on
+ release — same pattern as the BPM chip scrub.
+
+**Alternatives.** Re-running auto-warp with the new tempo on warped clips — rejected: it
+would throw away hand-placed markers.
+
+## R6 — Live waveform while dragging a warp marker (#140)
+
+**Facts.** The waveform of a warped clip is engine-rendered peaks over the full warp in the
+beat domain (`GetClipWarpFullPeaks`, zoomed slices via `GetClipWarpPeaksRange`), i.e. laid
+out by the markers **as committed**. During a marker drag only `_mk` changes; the peaks stay
+until `MarkersCommitted` → engine → `Reload`.
+
+**Decision.** Display-only re-timing: at drag start snapshot the committed markers
+(`_mkCommitted`). While dragging, draw each pixel column at new beat `b` from the peak at
+old beat `b' = beatOld(srcNew(b))`, both piecewise-linear through the marker lists
+(data-model `WarpRemap`). Overview and zoomed detail peaks are both beat-domain, so the
+same remap applies. Cost: two binary searches per column — negligible at ~2 000 columns.
+BPM chips already derive from `_mk`, so they update live for free.
+
+Release → `Commit()` (unchanged: one engine call, one undo step) → `Reload` swaps in the
+real stretch. Esc during the drag: `MainWindow.HandleKeyDown` asks the visible audio editor
+to `CancelGesture()` before the arrangement's `EscapePressed`; the canvas restores
+`_mk = _mkCommitted` and releases capture. Capture lost → same restore.
+
+**Alternatives.** Asking the engine to re-stretch during the drag — rejected: seconds of
+work per move and AR concerns; the display remap is exact for the peaks' envelope at the
+resolution drawn.
+
+## R7 — Principle V (one logical change per PR)
+
+Six issues in one PR is a deliberate batch on one area (the clip editor), like #272 / #273,
+at the user's request. Recorded under Complexity Tracking in plan.md.
diff --git a/specs/036-clip-editor-batch/spec.md b/specs/036-clip-editor-batch/spec.md
new file mode 100644
index 00000000..00a5fcad
--- /dev/null
+++ b/specs/036-clip-editor-batch/spec.md
@@ -0,0 +1,401 @@
+# Feature Specification: Clip editor batch — playhead, arrangement ruler, keyboard focus, warp tempo
+
+**Feature Branch**: `feat/clip-editor-batch`
+
+**Created**: 2026-10-22
+
+**Status**: Draft (clarified 2026-10-22)
+
+**Input**: User description: "Clip editor batch (one PR) covering GitHub issues #277, #278, #275, #114, #248, #140." In short: the audio clip editor shows the playhead while stopped (#277); both clip editors can move the playhead from the ruler and by dragging the playhead line, mapped to the arrangement, with session slots handled sensibly (#278); the clip editor ruler shows the clip's arrangement position and follows the transport's bars/time display (#275); grid shortcuts and Space keep working after a click in the lower clip editor while text entry still types (#114); the audio clip's warp tempo is a prominent, labelled, typeable/draggable value next to the Warp toggle, with a tooltip and ×2 / ÷2 (#248); dragging a warp marker redraws the waveform live and commits once on release (#140).
+
+## 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
+- [ ] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+Everything lives in `src/managed/Nota.App`. What the code does today:
+
+- **Audio clip editor** (`AudioClipEditorView.cs`): a props rail (Clip / Playback / Warp
+ sections) and a waveform canvas — a 24 px ruler, a 22 px warp-marker strip, then the wave.
+ - `OnPlayhead(beats, playing)` hides the arrangement-clip cursor unless `playing` (#277).
+ For a Session slot it already follows the slot's own loop clock
+ (`SessionSlotPosition`). The piano roll's `SetPlayhead` has no such gate.
+ - The ruler has no pointer handling — the playhead can't be moved from this editor (#278).
+ - A warped clip shows its **full warp** with Start/End trim brackets; the ruler counts warp
+ beats from the warp's own start (bar 1), not the arrangement. An unwarped clip shows the
+ whole source sample with a **seconds** ruler from 0 s (#275).
+ - Each segment between two warp markers carries a BPM chip in the marker strip (drag to
+ scrub, double-click to type). The Warp section has a Warp switch, a mode dropdown,
+ "Detect tempo" / "To transients" buttons and a read-only "Detected … BPM" line. There
+ is no single clip-wide tempo control next to Warp (#248).
+ - Dragging a warp marker moves the marker in the strip, but the waveform is redrawn only
+ after release, when `MarkersCommitted` reaches the engine and the stretched peaks are
+ fetched again (#140). Warp edits already run the stretch in the background
+ (`WarpEdit` + `WarpBuildRequested`).
+- **MIDI clip editor** (`PianoRollView.cs`): `RulerLane` seeks on click and scrubs on drag,
+ snapped (#50); `MainWindow.Detail.cs` maps `roll.Origin + local` to the arrangement. The
+ ruler numbers bars from the clip's own start, except with several clips open
+ (`RulerBarOffset`, `ClipSet.Origin`) (#275). The playhead line itself can't be grabbed.
+- **Time display**: the transport's position read-out flips bars ↔ m:ss.mmm on click
+ (`TransportViewModel.ShowTimeDisplay`). No ruler follows it today — the arrangement ruler
+ is bars only.
+- **Keyboard** (`MainWindow.Input.cs`): Space / Return run in a tunnel-phase handler so a
+ focused control can't steal them; everything else goes through the bubble-phase
+ `HandleKeyDown`. Both skip when the key's source is a `TextBox` / `NumericUpDown`.
+ `ReleaseTextFocusOnOutsidePress` drops text focus on a press outside the field. The
+ reporter of #114 saw grid shortcuts and Space die after a click in the lower clip editor
+ with the ADSR shown; the cause is not confirmed.
+
+No engine change is expected: seeking, warp markers, warp length and the stretch all have
+C ABI entry points already.
+
+**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).
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - See and move the playhead from the clip editors (Priority: P1)
+
+A producer is editing an audio clip and wants to hear it from the second hit. They see
+where the song position is on the waveform, stopped or playing, click the clip editor's
+ruler at that hit, and press Space — playback starts there. In the piano roll they grab
+the playhead line itself and drag it back a beat.
+
+**Why this priority**: Two of the six issues (#277 bug, #278) and the most frequent
+interaction: every listen-and-edit cycle in the clip editor starts by placing the playhead.
+
+**Independent Test**: Open an arrangement audio clip, stop the transport with the song
+position inside the clip, confirm the playhead shows; click the ruler, confirm the
+transport position and the arrangement playhead move to the matching place; repeat with a
+drag on the playhead line in both editors.
+
+**Acceptance Scenarios**:
+
+1. **Given** an arrangement audio clip at 2.1–4.1 is open and the transport is stopped at
+ 3.1, **When** the editor is shown, **Then** the playhead is drawn at the clip's 3.1 point
+ on the waveform; **When** the position moves outside the clip, **Then** the playhead is
+ not drawn.
+2. **Given** that clip, **When** the user clicks the clip editor's ruler, **Then** the
+ transport moves to the arrangement position under the click (snapped when Snap is on,
+ free with Alt held) and the arrangement playhead follows.
+3. **Given** the user presses on the ruler and drags, **When** the pointer moves, **Then**
+ the playhead scrubs continuously; release leaves it at the last position.
+4. **Given** the playhead is visible in the MIDI or the audio clip editor, **When** the
+ user presses on the playhead line and drags, **Then** it moves the transport the same
+ way as a ruler drag, and the cursor over the line shows it can be dragged.
+5. **Given** a reversed audio clip or a warped clip whose Start bracket is trimmed in,
+ **When** the user clicks a point on the waveform's ruler, **Then** the transport lands on
+ the arrangement moment at which that audio plays.
+6. **Given** a clip in a Session slot is open, **When** the user clicks the ruler or drags
+ the playhead, **Then** nothing seeks: the ruler and the playhead line show a "not
+ available" cursor and a tooltip saying a Session slot plays on its own loop clock; the
+ playhead keeps following the slot's position.
+
+---
+
+### User Story 2 - The clip editor ruler reads like the arrangement (Priority: P2)
+
+A producer selects one clip placed at bar 9 and wants to line up what they see in the
+editor with the arrangement. The clip editor's ruler reads 9, 9.2, 10 … — the same
+numbers as the arrangement ruler — and when they flip the transport read-out to time, the
+editor ruler reads in minutes and seconds.
+
+**Why this priority**: #275. Removes a constant mental offset; also makes the seek of
+Story 1 predictable ("click at 9.3" means 9.3).
+
+**Independent Test**: Place a MIDI clip and an audio clip at 9.1; open each; read the
+ruler labels; flip the transport position display to time and read them again.
+
+**Acceptance Scenarios**:
+
+1. **Given** a single MIDI clip at 9.1–11.1, **When** it opens in the editor, **Then** the
+ ruler's first bar reads 9 and the last full bar 10 — the same as a multi-clip selection
+ shows today.
+2. **Given** a warped audio clip at 9.1 whose Start bracket sits at the warp's beat 0,
+ **When** it opens, **Then** the ruler reads 9 at the clip start; with the Start bracket
+ trimmed one bar in, the bracket reads 9 and the audio before it reads 8.
+3. **Given** an unwarped audio clip at 9.1, **When** it opens, **Then** the ruler labels the
+ arrangement moment each part of the sample plays at.
+4. **Given** the transport read-out shows time, **When** either clip editor is open, **Then**
+ its ruler labels read as time (m:ss, with finer units when zoomed in) at the clip's
+ arrangement position; flipping the read-out back returns the labels to bars.
+5. **Given** a session-slot clip, **When** it opens, **Then** the ruler numbers the clip
+ from its own start, as today (a slot has no arrangement position).
+6. **Given** the transport read-out is flipped to time, **When** the arrangement is shown,
+ **Then** the arrangement ruler also labels in time, so it and the clip editor rulers
+ always read in the same unit; flipping back returns both to bars.
+
+---
+
+### User Story 3 - Keyboard shortcuts keep working after clicking in the clip editor (Priority: P2)
+
+A producer clicks the ADSR in the lower clip editor, then presses 1 / 2 (⌘1 / ⌘2) to change
+the grid and Space to play. Both work, exactly as after a click in the arrangement. When
+they click into a text field (a typed value, the BPM field, a clip name), typing goes into
+the field until they press Enter / Esc or click elsewhere.
+
+**Why this priority**: #114, a bug. Losing transport keys feels like the app has frozen.
+
+**Independent Test**: For each region of the lower clip editor (props rail, waveform /
+piano roll, ADSR, envelope, MIDI tools), click it and press the grid shortcuts and Space;
+then click a text field there and type a space and digits.
+
+**Acceptance Scenarios**:
+
+1. **Given** the user has clicked anywhere in the lower clip editor that is not a text
+ field, **When** they press Space, **Then** the transport plays / stops.
+2. **Given** the same, **When** they press the grid shortcuts (⌘1–⌘5 / Ctrl+1–5),
+ **Then** the grid changes as it does after a click in the arrangement.
+3. **Given** a text field in the clip editor has focus, **When** the user types, **Then** the
+ keys reach the field (space included) and no shortcut fires; **When** they press Enter /
+ Esc or click outside, **Then** the field lets go and shortcuts work again.
+4. **Given** a typed-value box (ADSR read-out, BPM field) was opened and dismissed, **When**
+ the user presses Space, **Then** the transport responds — no invisible field keeps the
+ focus.
+
+---
+
+### User Story 4 - Find and set the clip's warp tempo (Priority: P3)
+
+A producer imports a loop whose tempo was detected as 87 BPM; it is really 174. Next to
+the Warp switch they see "Tempo 87.00 BPM", press ×2, and the loop locks to the grid. Another time they type 120 into the field or drag it up and down.
+
+**Why this priority**: #248. The control exists only as per-segment chips in the marker
+strip, which users miss and then believe warping is broken.
+
+**Independent Test**: Open a warped loop; read the tempo value next to Warp; type a value,
+drag it, press ×2 and ÷2; check the clip's played length and the marker chips follow;
+undo each.
+
+**Acceptance Scenarios**:
+
+1. **Given** a warped clip, **When** the audio clip editor is open, **Then** the Warp
+ section shows a labelled tempo value (BPM) next to the Warp switch, with ×2 and ÷2
+ buttons and a tooltip explaining that it is the tempo the audio was recorded at.
+2. **Given** that value, **When** the user types a new tempo and presses Enter, or drags the
+ value up / down, **Then** the clip is re-warped from that tempo and the segment chips and
+ the clip's played length update; Esc cancels a typed edit.
+3. **Given** the user presses ×2 or ÷2, **Then** the tempo doubles / halves in one step.
+4. **Given** any of these edits, **When** the user undoes, **Then** one undo step restores
+ the previous tempo (a drag is one step).
+5. **Given** a clip with several warp markers at different tempos, **When** the editor shows
+ it, **Then** the value shows the tempo of the whole played region and setting it scales
+ every segment by the same factor, keeping their relative timing.
+6. **Given** an unwarped clip, **When** the editor shows it, **Then** the value shows the
+ clip's detected tempo (or "—" if none was found); typing a tempo, dragging it or pressing
+ ×2 / ÷2 turns Warp on and warps the clip from that tempo, all in one undo step.
+
+---
+
+### User Story 5 - See the warp while dragging a marker (Priority: P3)
+
+A producer drags a warp marker to line a snare up with beat 2. While they drag, the
+waveform on both sides of the marker stretches and squeezes, so they can see the transient
+land on the grid line before letting go. On release the clip is re-warped once and one
+undo step is recorded.
+
+**Why this priority**: #140. Precision placement without trial-and-error releases.
+
+**Independent Test**: Drag a marker slowly between two grid lines; watch the waveform
+follow; release; undo once and confirm the marker returns.
+
+**Acceptance Scenarios**:
+
+1. **Given** a warped clip with markers, **When** the user drags a marker, **Then** the
+ waveform between the neighbouring markers redraws on every pointer move to show the
+ new stretch, and the BPM chips of the two touched segments update live.
+2. **Given** the drag, **When** the user releases, **Then** the engine receives the new
+ markers once and one undo step is recorded; the waveform then shows the engine's
+ rendered warp.
+3. **Given** the drag, **When** the user presses Esc before release (or the pointer capture
+ is lost), **Then** the marker and the waveform return to where they were and nothing is
+ committed.
+4. **Given** the drag, **Then** playback is unaffected until release (no audio glitches,
+ no partial re-warp).
+
+### Edge Cases
+
+- Song position exactly on the clip's start or end: the playhead is drawn at the edge
+ (inclusive), as the arrangement does.
+- A looped arrangement clip longer than one cycle: the editor shows one cycle; the playhead
+ is shown during every cycle at its position within the cycle, and a click seeks into the
+ **first** cycle of the clip.
+- A ruler click left of the clip's played region (warped clip, trimmed Start): the
+ transport may land before the clip start — it moves to that arrangement position
+ (clamped at 0).
+- Seeking while recording: behaves as the arrangement ruler does during recording.
+- Seeking while the transport is playing: playback continues from the new position.
+- Clip moved in the arrangement while its editor is open: ruler labels and seek mapping
+ follow the new position on the next refresh.
+- Tempo changes in the song (if the project has a tempo map): the time labels and the
+ seconds mapping use the same tempo the transport read-out uses.
+- Warp tempo outside a sane range: typed / dragged values clamp to the same BPM range the
+ segment chips accept; ×2 / ÷2 that would leave the range does nothing.
+- Warp marker dragged onto or past a neighbour: clamped as today; the live preview never
+ shows a negative-length segment.
+- Very long clips (minutes) while dragging a marker: the live redraw stays smooth (see
+ SC-004).
+
+### Clarifications
+
+#### Session 2026-10-22
+
+- Q: Session-slot clips — seek within the slot or disable seeking? → A: Disable seeking,
+ with a "not available" cursor and tooltip; the playhead still follows the slot.
+- Q: Should the arrangement ruler follow the time display too? → A: Yes, both the
+ arrangement ruler and the clip editor rulers switch together.
+- Q: Unwarped clip's tempo value? → A: Show the detected tempo; an edit turns Warp on and
+ warps from that tempo, one undo step.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+**Playhead (#277, #278)**
+
+- **FR-001**: The audio clip editor MUST draw the playhead at the current song position
+ whenever that position lies inside an arrangement clip's played region, whether the
+ transport is playing or stopped.
+- **FR-002**: A left-click on the audio clip editor's ruler MUST move the transport to the
+ arrangement position under the pointer; a press-and-drag MUST scrub it continuously.
+- **FR-003**: Ruler seeks MUST snap to the editor's grid when Snap is on and be free while
+ Alt is held, in both clip editors.
+- **FR-004**: In both clip editors the playhead line MUST be grabbable (a few pixels either
+ side, in the ruler and over the content) and dragging it MUST seek like a ruler drag,
+ with a resize/drag cursor on hover.
+- **FR-005**: Grabbing the playhead line MUST take precedence over the content gesture
+ under it only within the grab zone; outside it, note / marker / envelope editing works
+ as today.
+- **FR-006**: Editor positions MUST map to the arrangement taking the clip's start, the
+ played region (trim / Start bracket), reversal and the clip loop into account.
+- **FR-007**: For a clip in a Session slot, ruler clicks and playhead drags MUST NOT seek;
+ the editor MUST show a "not available" cursor and a tooltip explaining why, and keep
+ showing the slot's playhead.
+
+**Ruler (#275)**
+
+- **FR-008**: For a single arrangement MIDI clip and for an arrangement audio clip, the
+ clip editor ruler MUST label positions with the arrangement position they play at.
+- **FR-009**: When the transport's position read-out shows time, the clip editor rulers
+ MUST label positions as time; when it shows bars, as bars. Flipping the read-out MUST
+ update open editors at once.
+- **FR-010**: Session-slot clips MUST keep clip-relative labels.
+- **FR-011**: Snap and grid behaviour MUST NOT change because the labels changed — grid
+ lines stay where they are today.
+- **FR-012**: The arrangement ruler MUST also follow the transport's time display, so all
+ rulers read in the same unit at any moment.
+
+**Keyboard focus (#114)**
+
+- **FR-013**: After a pointer press anywhere in the lower clip editor that is not a text
+ field, Space, Return and the grid shortcuts MUST work as they do after a press in the
+ arrangement.
+- **FR-014**: While a text field has focus, keys MUST go to the field and no shortcut may
+ fire, except the command-palette chord that already works everywhere.
+- **FR-015**: Dismissing a typed-value box (Enter, Esc, click-away) MUST release keyboard
+ focus so shortcuts work on the next key press.
+- **FR-016**: The same MUST hold when the clip editor is in the floating detail window.
+
+**Warp tempo (#248)**
+
+- **FR-017**: The audio clip editor's Warp section MUST show a labelled tempo value (BPM)
+ next to the Warp switch for warped clips, with ×2 and ÷2 buttons and a tooltip.
+- **FR-018**: The tempo value MUST be editable by typing (Enter commits, Esc cancels,
+ click-away commits) and by vertical drag, with fine drag on the usual modifier.
+- **FR-019**: Setting the tempo MUST re-time the clip so that its played region plays at the
+ project tempo as if recorded at the given tempo, scaling every warp segment by the same
+ factor.
+- **FR-020**: Each tempo edit (typed commit, whole drag, ×2, ÷2) MUST be one undo step.
+- **FR-021**: For an unwarped clip the value MUST show the detected tempo (or "—"); an edit
+ of it MUST turn Warp on and warp from the new tempo as one undo step.
+- **FR-022**: The existing per-segment BPM chips and "Detect tempo" / "To transients" MUST
+ keep working and stay consistent with the new value.
+
+**Live warp drag (#140)**
+
+- **FR-023**: While a warp marker is being dragged, the waveform MUST redraw on each pointer
+ move showing the audio re-timed by the marker's new position, and the neighbouring BPM
+ chips MUST show the live tempos.
+- **FR-024**: The engine MUST receive the new markers once, on release; one undo step MUST
+ be recorded per drag.
+- **FR-025**: Esc during the drag, or a lost pointer capture, MUST restore the markers and
+ waveform without committing.
+- **FR-026**: The live preview MUST NOT touch audio playback.
+
+**General**
+
+- **FR-027**: All new controls, cursors and highlights MUST follow the Studio design
+ language (DESIGN.md) in every colour theme.
+- **FR-028**: New pointer gestures and any shortcut changes MUST be reflected in Preferences
+ → Shortcuts.
+
+### Key Entities
+
+- **Clip editor ↔ arrangement mapping**: for an open clip, the relation between an editor
+ position (piano-roll beat; warp beat or source time on the waveform) and the arrangement
+ position it plays at. Derived from the clip's start, played region, reversal and loop.
+- **Clip warp tempo**: the tempo the clip's played audio is treated as recorded at — the
+ played region's source length versus its warp length. Edits scale all warp markers'
+ beat positions.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: In both clip editors, placing the playhead at a chosen hit takes one click
+ (or one drag), with no trip to the arrangement — verified on MIDI, warped audio,
+ unwarped audio and reversed audio clips.
+- **SC-002**: A ruler click lands the transport within one snap step (Snap on) or within
+ 2 px of the click (Alt) of the clicked label, on all four clip kinds above.
+- **SC-003**: For a clip placed at any bar N, the editor ruler's label at the clip start
+ reads N (bars) or the arrangement time (time display), matching the transport read-out
+ at that moment to the displayed precision.
+- **SC-004**: While dragging a warp marker on a 5-minute clip, the waveform keeps up with the
+ pointer without visible lag (at least the UI's normal redraw rate), and audio playback
+ shows no dropouts.
+- **SC-005**: After a click in any region of the lower clip editor that is not a text
+ field, 10 of 10 tries of Space and of a grid shortcut take effect.
+- **SC-006**: The warp tempo can be found and changed from the Warp section in under 10
+ seconds by someone who has not seen it before; ×2 / ÷2 fixes a half/double-time
+ detection in one click.
+- **SC-007**: Every edit added by this batch is undone by exactly one undo step.
+
+## Assumptions
+
+- One PR covers all six issues; each user story can still be verified on its own.
+- "Snap" in the clip editors is the shared clip-editor grid (the piano roll's), as it is
+ for markers and trim brackets today; Alt for free placement matches the existing
+ gestures there.
+- The time display uses the same tempo source and format family as the transport
+ read-out; the ruler picks m:ss / s / ms steps by zoom, like the existing seconds ruler.
+- A multi-clip MIDI selection keeps its current ruler behaviour (already arrangement-based)
+ and also gains the time display.
+- The clip's warp tempo for a multi-segment clip is the average over the played region
+ (source length ÷ warp length), as Ableton's Seg. BPM does for a single segment.
+- The tempo value is shown in the Warp section of the props rail; showing it on the clip in
+ the arrangement / session (an idea in #248) is out of scope.
+- The live warp preview is a display-only approximation (the existing peaks re-timed
+ segment by segment); the engine's real stretch replaces it on release.
+- #276 (two-column inspector) is out of scope; the new tempo row must fit the current
+ single-column rail.
+- No C ABI or engine change is needed; if planning finds one, it goes through
+ `nota_engine.h` and the smoke test is extended.
+
+## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*
+
+- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)
+- [x] No new dependency — 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; the live warp preview never reaches the engine before release
+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`
+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest` — no engine change planned
+- [x] 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)
+- [x] UI change → follows `DESIGN.md` (Studio design language)
diff --git a/specs/036-clip-editor-batch/tasks.md b/specs/036-clip-editor-batch/tasks.md
new file mode 100644
index 00000000..3d7738ad
--- /dev/null
+++ b/specs/036-clip-editor-batch/tasks.md
@@ -0,0 +1,376 @@
+---
+
+description: "Task list for the clip editor batch (#277, #278, #275, #114, #248, #140)"
+---
+
+# Tasks: Clip editor batch — playhead, arrangement ruler, keyboard focus, warp tempo
+
+**Input**: Design documents from `specs/036-clip-editor-batch/`
+
+**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),
+[data-model.md](data-model.md), [contracts/clip-editor-ui.md](contracts/clip-editor-ui.md),
+[quickstart.md](quickstart.md)
+
+**Tests**: The plan adds smoke-test checks for the four pure helpers (`--clipeditor`
+section, linked as source like `ValueText`). UI flows are verified by the quickstart, not
+by automated tests.
+
+**Organization**: Grouped by user story; each story can be implemented and checked on its
+own. Story → issue: US1 #277 + #278, US2 #275, US3 #114, US4 #248, US5 #140.
+
+All paths are repo-relative. `App/` below means `src/managed/Nota.App/`.
+
+## Format: `[ID] [P?] [Story] Description`
+
+- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
+- **[Story]**: US1–US5 from spec.md
+
+---
+
+## Phase 1: Setup (Shared Infrastructure)
+
+- [X] T001 Create folder `src/managed/Nota.App/ClipEditor/` for the pure helpers, and link
+ its files into the smoke test: add `<Compile Include="..\..\src\managed\Nota.App\ClipEditor\*.cs" LinkBase="ClipEditor" />`
+ next to the `ValueText.cs` link in `tests/Nota.SmokeTest/Nota.SmokeTest.csproj`. Helpers
+ must not reference Avalonia or the engine.
+- [X] T002 Add `tests/Nota.SmokeTest/ClipEditorTests.cs` (SPDX header, `static
+ IEnumerable<(bool ok, string label)> Run()` like `ValueEntryTests`) and wire a
+ `--clipeditor` section in `tests/Nota.SmokeTest/Program.cs` beside `--valueentry`
+ ("-- clip editor --", "CLIP EDITOR PASSED/FAILED"), and add it to the full run.
+
+---
+
+## Phase 2: Foundational (Blocking Prerequisites)
+
+**Purpose**: The position mapping and ruler labels used by US1 and US2.
+
+- [X] T003 [P] Implement `ClipTimeMap` in `src/managed/Nota.App/ClipEditor/ClipTimeMap.cs` per
+ [data-model.md § ClipTimeMap](data-model.md#cliptimemap--editor-position--arrangement-position):
+ fields `StartBeat, LengthBeats, Domain (WarpBeats|SourceFrames), ContentTotal, PlayStart,
+ PlayEnd, Reversed, IsSlot`; `PlayFracAtContent(c)` = `(c·Total − PlayStart) / (PlayEnd −
+ PlayStart)` then `1 − f` when reversed, **not clamped**; `ContentAtPlayFrac(f)` (inverse);
+ `ArrangementBeatAtContent(c) = StartBeat + PlayFracAtContent(c) × LengthBeats`;
+ `ContentAtArrangementBeat(b)` (inverse). Total and NaN-free for `ContentTotal > 0`;
+ degenerate windows (PlayEnd ≤ PlayStart) return 0.
+- [X] T004 [P] Implement `RulerLabels` + `RulerDisplay` in
+ `src/managed/Nota.App/ClipEditor/RulerLabels.cs` per [data-model.md § RulerLabels](data-model.md#rulerlabels--shared-ruler-text):
+ `Bars(beat, stepBeats, beatsPerBar)` → `N` / `N.b` / `N.b.s` (1-based, same output as
+ `PianoRollView` / `AudioClipEditorView.BeatLabel` today); `Time(beat, stepSeconds, bpm)` →
+ `m:ss` for steps ≥ 1 s, then `m:ss.f`, `m:ss.ff`, `m:ss.fff`; clamp negative positions to
+ 0; `TimeSteps` table (reuse the seconds steps from `AudioClipEditorView.DrawRuler`);
+ `static class RulerDisplay { bool ShowTime; event Action? Changed; void Set(bool) }`
+ (raises only on change). Use `NotaNum.Culture`-free formatting (pass a culture in) so it
+ links without the app.
+- [X] T005 Add `ClipTimeMap` and `RulerLabels` checks to `tests/Nota.SmokeTest/ClipEditorTests.cs`:
+ warped untrimmed / trimmed Start / reversed / unwarped round trips (`ContentAtPlayFrac ∘
+ PlayFracAtContent = id`), a clip at beat 32 reads 32 at its played start, seeking left of
+ a trimmed Start gives a beat < StartBeat; labels for bars at 16th / beat / bar steps and
+ time at 1 s / 0.1 s / 0.01 s / 0.001 s steps. (depends on T002–T004)
+- [X] T006 Wire `RulerDisplay` to the transport: in `src/managed/Nota.App/MainWindow.axaml.cs`
+ subscribe to `vm.Transport.PropertyChanged` for `ShowTimeDisplay` and call
+ `RulerDisplay.Set(...)`; set the initial value on DataContext.
+
+**Checkpoint**: `dotnet run --project tests/Nota.SmokeTest -c Release -- --clipeditor` green.
+
+---
+
+## Phase 3: User Story 1 — See and move the playhead from the clip editors (P1) 🎯 MVP
+
+**Goal**: #277 + #278 — playhead visible while stopped; ruler click / drag and playhead-line
+drag seek in both editors; Session slots show "not available".
+
+**Independent Test**: quickstart § 2.
+
+- [X] T007 [US1] In `src/managed/Nota.App/AudioClipEditorView.cs` build a `ClipTimeMap` in
+ `Reload()` from `ci` / `ai` (warped: `WarpBeats`, trim `warp_play_start/_end` with
+ `play_end = 0 → warp_beats`; unwarped: source frames, `source_offset_frames`,
+ `length_frames`; `Reversed`; `IsSlot = SessionClip.SceneOf(ClipIndex) >= 0`) and pass it to
+ the waveform canvas (`_wave.SetTimeMap(map)`); replace the inline playhead x formula in
+ `Render` (the `_frac` block) with `ContentAtPlayFrac` — the drawing must not change.
+- [X] T008 [US1] #277: in `AudioClipEditorView.OnPlayhead` drop the `playing &&` gate for
+ arrangement clips (inclusive at start and end); keep the session-slot branch as is.
+- [X] T009 [US1] Add `public Action<double>? Seek` (arrangement beat) to
+ `AudioClipEditorView`, forwarded to the canvas; in `src/managed/Nota.App/MainWindow.Detail.cs`
+ `BuildAudioClipEditor` set it only when `!slot`: `Engine.Seek(Math.Max(0, beat));
+ Timeline.SetPlayhead(...)` — same body as the piano roll's `Seek`.
+- [X] T010 [US1] Ruler seek in the waveform canvas (`AudioClipEditorView.cs`, nested canvas
+ class): press in `y < RulerH` with the left button → capture, seek at x; move → scrub;
+ release / capture lost → end. Position: x → content frac → `ArrangementBeatAtContent`;
+ snap in the warp-beat domain with `SnapWarp` when warped (Alt = `_free`), unwarped seeks
+ free; skip when the arrangement beat is unchanged; give immediate feedback via
+ `SetPlayhead`. Hand cursor over the ruler when `Seek` is set.
+- [X] T011 [US1] Playhead-line grab in the waveform canvas: hit zone ±4 px around the
+ drawn playhead x in ruler, marker strip and wave; checked **first** in
+ `OnPointerPressed` (before ADSR / envelope / marker / bracket gestures) only inside the
+ zone; drag scrubs like T010; `SizeWestEast` cursor in the zone (update the hover cursor
+ logic in `OnPointerMoved`).
+- [X] T012 [US1] Piano roll playhead-line grab in `src/managed/Nota.App/PianoRollView.cs`:
+ in `RulerLane` a press within ±4 px of `_playheadBeat` scrubs (same `SeekAt`); in
+ `NoteGrid.OnPointerPressed` a press within ±3 px of the visible playhead becomes a
+ *pending* scrub — once the pointer moves ≥ 3 px it scrubs via the ruler's snap / Alt
+ logic, a release without movement runs the grid's normal click (add / select note);
+ `SizeWestEast` cursor in the zone. Only when `Seek` is set and the line is on screen.
+- [X] T013 [US1] Session-slot "not available" state in both editors: when the clip is a
+ slot (`Seek is null` and slot), ruler and playhead-line zone show
+ `StandardCursorType.No` and `ToolTip.Tip` = "A Session slot plays on its own loop clock —
+ launch it to play from the start" (`AudioClipEditorView.cs` canvas ruler,
+ `PianoRollView.cs` `RulerLane`; the slot roll is built in `MainWindow.Detail.cs` ~L772 —
+ pass an `IsSessionSlot` flag there).
+- [X] T014 [US1] Verify US1 by quickstart § 2 (headless harness or app): stopped playhead,
+ ruler click / drag / Alt, line drag in both editors, reversed + trimmed clip, Session
+ slot cursor + tooltip, and a click on the line in the note grid still adds a note.
+
+**Checkpoint**: MVP — the playhead is fully usable from both editors.
+
+---
+
+## Phase 4: User Story 2 — The clip editor ruler reads like the arrangement (P2)
+
+**Goal**: #275 — arrangement-position labels; bars / time follow the transport read-out on
+all three rulers.
+
+**Independent Test**: quickstart § 3.
+
+- [X] T015 [P] [US2] Piano roll ruler in `src/managed/Nota.App/PianoRollView.cs`
+ `RulerLane.Render`: label each tick with `RulerLabels.Bars(Origin + b, …)` for
+ arrangement clips (single and multi; remove `RulerBarOffset` once equivalent), keep
+ `Origin = 0` behaviour for Session slots; tick positions and grid lines unchanged
+ (FR-011). In time mode place labelled ticks at `RulerLabels.TimeSteps` converted to
+ beats (`sec × Bpm / 60`), labels via `RulerLabels.Time`. Subscribe to
+ `RulerDisplay.Changed` → `InvalidateVisual` (unsubscribe on detach). BPM comes from the
+ engine the roll already has or a `Func<double> Bpm` set by the host.
+- [X] T016 [P] [US2] Audio editor ruler in `src/managed/Nota.App/AudioClipEditorView.cs`
+ `DrawRuler`: bars mode — ticks at arrangement-beat steps mapped back with
+ `ContentAtArrangementBeat`, labels `RulerLabels.Bars(arrBeat)`, for warped **and**
+ unwarped clips (unwarped no longer shows source seconds); before the Start bracket the
+ labels continue backwards (stop at arrangement beat 0). Time mode — the same with time
+ steps. Session slots: clip-relative labels as today (warp beats from 0 / seconds from 0).
+ Keep the existing label-thinning by width. Subscribe to `RulerDisplay.Changed`.
+- [X] T017 [P] [US2] Arrangement ruler time mode in
+ `src/managed/Nota.App/ArrangementView.Controls.cs` `RulerControl` render: when
+ `RulerDisplay.ShowTime`, ticks at time steps (chosen by pixel width like the bars) and
+ `RulerLabels.Time` labels; loop brace, markers and gestures unchanged; subscribe to
+ `RulerDisplay.Changed`.
+- [X] T018 [US2] Verify US2 by quickstart § 3: MIDI clip at 9.1 reads 9; warped clip with
+ trimmed Start reads 9 at the bracket and 8 before it; unwarped clip in bars; flip the
+ read-out → all three rulers in m:ss and back; label at clip start matches the read-out.
+
+---
+
+## Phase 5: User Story 3 — Keyboard shortcuts keep working after clicking in the clip editor (P2)
+
+**Goal**: #114.
+
+**Independent Test**: quickstart § 4.
+
+- [X] T019 [US3] Reproduce #114 before changing code (quickstart § 4.1): audio clip with
+ ADSR shown, then a MIDI clip; click props-rail buttons, the ADSR, the wave / grid; press
+ Space and ⌘1–⌘5; log the focused element (`FocusManager.GetFocusedElement()`), whether the
+ focused control re-activates on Space, and the grid target from `GridTarget()`. Record
+ the observed cause(s) in `specs/036-clip-editor-batch/research.md` § R4 ("Reproduction").
+- [X] T020 **N/A — T019: no control takes focus on click, Space is never re-activated (research R4).** [US3] Space KeyUp (R4 fix 1, if confirmed): in
+ `src/managed/Nota.App/MainWindow.Input.cs` remember that the tunnel handler ran Space
+ (`_spaceHandled`) and add a tunnel `KeyUpEvent` handler (registered next to the KeyDown
+ one in `MainWindow.axaml.cs` and forwarded from the floating detail window like
+ `HandleTransportKeyTunnel`) that marks the matching Space KeyUp handled, so a focused
+ Button / ToggleButton is not clicked. Text fields stay exempt.
+- [X] T021 **N/A — T019: clip editor buttons and segments already take no focus on click (research R4).** [P] [US3] Pointer-only props-rail controls not focusable (R4 fix 2, if
+ confirmed): in `src/managed/Nota.App/ClipEditorKit.cs` set `Focusable = false` on the
+ buttons, switches and dropdown cells the factories build (`Button`, `SwitchRow`,
+ `Dropdown`, segment cells), and on any equivalent built directly in
+ `AudioClipEditorView.cs` / `ClipEditorView.cs`; text fields keep focus.
+- [X] T022 [US3] Inert clip grid fallback (R4 fix 3, if confirmed): in
+ `src/managed/Nota.App/MainWindow.Commands.cs` `GridTarget()` return
+ `EditorKind.Arrangement` when the clip editor target is the audio editor and its grid is
+ inert (unwarped clip, or ADSR mode) — expose `bool GridInert` on `AudioClipEditorView`;
+ the status line already names the target.
+- [X] T023 **N/A — T019 found no other cause in the clip editor (research R4).** [US3] Any other cause found in T019: fix at its source and note it in research
+ R4; if T019 refutes a fix in T020–T022, mark that task N/A with the reason instead of
+ doing it.
+- [X] T024 [US3] Verify US3 by quickstart § 4.2–4.4 (docked and floating): each region,
+ Space twice + ⌘1, no button re-activates, typing in fields still types, Enter / Esc
+ release focus.
+
+---
+
+## Phase 6: User Story 4 — Find and set the clip's warp tempo (P3)
+
+**Goal**: #248.
+
+**Independent Test**: quickstart § 5.
+
+- [X] T025 [P] [US4] Implement `ClipTempo` in `src/managed/Nota.App/ClipEditor/ClipTempo.cs`
+ per [data-model.md § ClipTempo](data-model.md#cliptempo--the-clips-warp-tempo): `SrcAt(beat)`
+ piecewise linear through markers sorted by `src` (≥ 2), extrapolating with the end
+ segments' slope; `Bpm = (PlayEnd − PlayStart) × SampleRate × 60 / (SrcAt(PlayEnd) −
+ SrcAt(PlayStart))` with `PlayEnd = 0 → last marker beat`; `Scale(newBpm)` → markers with
+ every beat × `k = newBpm / Bpm`, `PlayStart × k`, `PlayEnd × k` (`PlayEnd = 0` stays 0);
+ "Valid range 20–999 BPM; `Half()` / `Double()` return null if the result leaves it".
+- [X] T026 [US4] `ClipTempo` checks in `tests/Nota.SmokeTest/ClipEditorTests.cs`: one segment
+ equals the segment-chip formula; scaling keeps segment beat ratios; trim scales; ×2 / ÷2
+ range limits; `PlayEnd = 0` handling. (depends on T025)
+- [X] T027 [US4] Tempo row in `src/managed/Nota.App/AudioClipEditorView.cs` Warp section,
+ directly under the Warp switch row (per [contract § Warp section](contracts/clip-editor-ui.md#warp-section-audio-clip-editor)):
+ label "Tempo", a `DragNumber` (20–999, two decimals, "BPM" unit, fine drag on the usual
+ modifier, double-click / click → type, Enter / click-away commit, Esc cancel), and
+ compact `÷2` / `×2` buttons (`ClipEditorKit.Button` style, non-focusable); tooltip on
+ label and value: "The tempo the audio was recorded at. Nota stretches it to the project
+ tempo. ×2 / ÷2 fix a half- or double-time detection." Follow DESIGN.md / nota-design;
+ must fit the current single-column rail.
+- [X] T028 [US4] Warped-clip edits: on commit compute `ClipTempo.Scale(t)` from the current
+ markers / trim / `_srcSR` and apply inside `Engine.BeginUndoGroup()` … `EndUndoGroup()`
+ via `WarpEdit`: `SetClipWarpMarkers` then `SetClipWarpTrim` (skip trim when unchanged);
+ then `Reload()`. A drag scales the canvas markers locally (live redraw, no engine) and
+ commits once on release; ÷2 / ×2 commit once each; disable them when `Half()` /
+ `Double()` is null.
+- [X] T029 [US4] Unwarped-clip edits: show `_detectedBpm` (or "—", dimmed but editable;
+ ÷2 / ×2 disabled when "—"); a commit calls `Engine.AutoWarpClipAtBpm(TrackId, ClipIndex,
+ t)` inside `WarpEdit` (one engine call = one undo step), updates `_detectedBpm` /
+ `_warpEnabled`, then `Reload()`.
+- [X] T030 [US4] Keep the value in sync: refresh it in `Reload()`, after Detect tempo / To
+ transients, after a segment-chip edit and after a marker drag; segment chips keep working
+ (FR-022).
+- [X] T031 [US4] Verify US4 by quickstart § 5: 120 BPM loop reads 120.00; ÷2, ×2, drag,
+ type — each one undo step; multi-marker ratios kept; unwarped → Warp on at the typed
+ tempo, one undo back.
+
+---
+
+## Phase 7: User Story 5 — See the warp while dragging a marker (P3)
+
+**Goal**: #140.
+
+**Independent Test**: quickstart § 6.
+
+- [X] T032 [P] [US5] Implement `WarpRemap` in `src/managed/Nota.App/ClipEditor/WarpRemap.cs`
+ per [data-model.md § WarpRemap](data-model.md#warpremap--live-marker-drag-preview):
+ `OldBeatAt(newBeat) = BeatAt(committed, SrcAt(live, newBeat))`, piecewise linear, using
+ `ClipTempo.SrcAt`-style interpolation; identity when `live == committed`; no allocation
+ per call (arrays passed in, binary search).
+- [X] T033 [US5] `WarpRemap` checks in `tests/Nota.SmokeTest/ClipEditorTests.cs`: identity,
+ monotone over a dragged middle marker, end markers fixed, last-marker drag. (depends on
+ T032)
+- [X] T034 [US5] Live preview in the waveform canvas (`AudioClipEditorView.cs`): on a
+ marker press snapshot the committed markers into reusable arrays; while dragging, draw
+ the overview and the zoomed detail peaks column by column at new beat `b` from the peak at
+ `WarpRemap.OldBeatAt(b)` (both are beat-domain); BPM chips already follow `_mk`. Release
+ → existing `Commit()` (one engine call, one undo step) → `Reload()` swaps in the engine
+ render. No engine call during the drag (FR-026).
+- [X] T035 [US5] Cancel: add `public bool CancelGesture()` on `AudioClipEditorView` (restores
+ `_mk` from the snapshot, releases capture, redraws, returns true if a drag was active);
+ call it first for `Key.Escape` in `src/managed/Nota.App/MainWindow.Input.cs`
+ `HandleKeyDown` (before `Timeline.EscapePressed`), also reached from the floating detail
+ window; capture lost → same restore.
+- [X] T036 [US5] Verify US5 by quickstart § 6, including a 5-minute clip (SC-004: no lag, no
+ dropouts while playing) and Esc leaving nothing in undo.
+
+---
+
+## Phase 8: Polish & Cross-Cutting Concerns
+
+- [X] T037 Design pass with the `nota-design` skill on all new UI (Tempo row, cursors, slot
+ tooltip, time labels) in Studio Dark / Studio Light / Ember Graphite / Ember Paper; the
+ design checks in the smoke test stay green.
+- [X] T038 [P] Preferences → Shortcuts via the `nota-shortcuts` skill: audio-editor ruler
+ click / drag, Alt free seek, playhead-line drag (both editors), Esc cancels a warp-marker
+ drag, Space no longer activates a focused control.
+- [X] T039 [P] User docs via the `nota-docs` skill (EN + RU): clip editor page (playhead,
+ ruler in arrangement position, bars / time), warping page (Tempo field, ÷2 / ×2, live
+ marker drag), arrangement ruler time mode; re-shoot affected screenshots.
+- [X] T040 [P] FEATURES.md via the `nota-features` skill.
+- [X] T041 `CHANGELOG.md` `[Unreleased]`: Fixed — #277, #114; Added / Changed — #278, #275,
+ #248, #140 (one line each, user-facing wording, issue links).
+- [X] T042 Screenshots for the PR (quickstart § 7): before / after for #277, #275, #248 and a
+ mid-drag #140 frame, via the headless harness.
+- [X] T043 Run the full quickstart once more end to end.
+
+### Nota closing tasks *(PR gates)*
+
+- [X] T044 Run `scripts/build.sh` until native + managed + smoke test are green (includes
+ `--clipeditor`).
+- [X] T045 AGPL-3.0-only SPDX two-line header on every new source file
+ (`ClipEditor/*.cs`, `tests/Nota.SmokeTest/ClipEditorTests.cs`).
+- [X] T046 New dependency: N/A (none).
+- [X] T047 CHANGELOG entry: see T041.
+- [X] T048 FEATURES.md / docs / shortcuts: see T038–T040.
+- [X] T049 Engine behaviour change: N/A (UI-only; existing ABI entry points).
+- [ ] T050 Run `/speckit-converge` and reach **Converged** before the PR.
+
+---
+
+## Dependencies & Execution Order
+
+### Phase Dependencies
+
+- **Setup (T001–T002)** → **Foundational (T003–T006)** → user stories.
+- **US1** needs T003 (map) and T006 is not needed. **US2** needs T003, T004, T006.
+- **US3** needs nothing from Phase 2 (can start right after Setup).
+- **US4** and **US5** need only their own pure helper (T025 / T032) and Setup.
+- **Polish** after the stories it documents.
+
+### User Story Dependencies
+
+- US1 → US2 share `AudioClipEditorView`'s canvas: do US1's canvas tasks (T007, T010, T011)
+ before T016 to avoid conflicting edits.
+- US4 and US5 both edit the Warp code in `AudioClipEditorView.cs`: sequence T027–T030
+ before T034–T035.
+- US3 is independent of the others.
+
+### Within Each User Story
+
+- Pure helper → its smoke checks → UI wiring → verification task.
+
+### Parallel Opportunities
+
+- T003 ∥ T004 (different new files); T025 ∥ T032 ∥ T003 (pure helpers, different files).
+- In US2: T015 (PianoRollView) ∥ T017 (ArrangementView.Controls) ∥ T016 (after US1 canvas work).
+- In US3: T021 (ClipEditorKit) ∥ T020 (MainWindow.Input).
+- Polish: T038 ∥ T039 ∥ T040.
+
+---
+
+## Parallel Example: Foundational + pure helpers
+
+```bash
+Task: "Implement ClipTimeMap in src/managed/Nota.App/ClipEditor/ClipTimeMap.cs"
+Task: "Implement RulerLabels + RulerDisplay in src/managed/Nota.App/ClipEditor/RulerLabels.cs"
+Task: "Implement ClipTempo in src/managed/Nota.App/ClipEditor/ClipTempo.cs"
+Task: "Implement WarpRemap in src/managed/Nota.App/ClipEditor/WarpRemap.cs"
+```
+
+## Parallel Example: User Story 2
+
+```bash
+Task: "Piano roll ruler labels + time mode in src/managed/Nota.App/PianoRollView.cs"
+Task: "Arrangement ruler time mode in src/managed/Nota.App/ArrangementView.Controls.cs"
+```
+
+---
+
+## Implementation Strategy
+
+### MVP First (User Story 1)
+
+1. Setup + Foundational (T001–T006).
+2. US1 (T007–T014) → validate by quickstart § 2. The two most-felt issues (#277, #278) are
+ fixed here.
+
+### Incremental Delivery
+
+1. US1 → US2 (rulers build on the same map) → US3 (keyboard) → US4 (tempo) → US5 (live
+ drag), each validated by its quickstart section.
+2. Suggested commit split for the user's review (the user commits): one commit per issue,
+ in the order #277, #278, #275, #114, #248, #140, plus one for docs.
+
+---
+
+## Notes
+
+- [P] = different files, no dependency on unfinished tasks.
+- The user makes the commits; leave changes uncommitted for review.
+- If T019 shows #114 has a cause outside the clip editor, keep the fix scoped and record it.
+
+## Phase 9: Convergence
+
+- [ ] T051 Add fine drag to the audio clip editor's **Tempo** field — holding the usual fine-drag modifier (⇧ / ⌘, as on `Knob` / `SliderTrack`) drags it in smaller BPM steps — in `src/managed/Nota.App/Controls/DragNumber.cs` (opt-in, so the transport BPM field is unchanged unless chosen) and `src/managed/Nota.App/AudioClipEditorView.cs`; restore the fine-drag note in `contracts/clip-editor-ui.md` § Warp section per FR-018 (partial)
+- [ ] T052 Review and justify (or narrow to marker drags) the live warp preview and Esc cancel that also cover the segment BPM-chip scrub and the Tempo-field drag in `src/managed/Nota.App/AudioClipEditorView.cs` (`Remapped`, `CancelGesture`), beyond the warp-marker drag FR-023 / FR-025 call for; if kept, record it in research.md R6 and the contract per FR-023 (unrequested)
diff --git a/src/managed/Nota.App/ArrangementView.Controls.cs b/src/managed/Nota.App/ArrangementView.Controls.cs
index 7762fbc5..d9f8da52 100644
--- a/src/managed/Nota.App/ArrangementView.Controls.cs
+++ b/src/managed/Nota.App/ArrangementView.Controls.cs
@@ -165,6 +165,15 @@ public sealed partial class ArrangementView
}
}
+ // Time display (#275): with the transport read-out on time, the ruler reads time too.
+ double bpm = _o._engine?.Bpm ?? 0;
+ if (RulerDisplay.ShowTime && bpm > 0) RenderTime(ctx, w, h, bpm);
+ else RenderBars(ctx, w, h);
+ RenderPlayheadAndReadout(ctx, w, h);
+ }
+
+ private void RenderBars(DrawingContext ctx, double w, double h)
+ {
// Bar numbers in mono 7. The almanac labels every 4 bars at its base scale
// (16px a bar); zoomed in far enough that a single bar has room, every bar is named.
int firstBar = (int)Math.Floor(_o._scrollBeats / _o._beatsPerBar);
@@ -182,7 +191,49 @@ public sealed partial class ArrangementView
FlowDirection.LeftToRight, NotaFonts.Mono, NotaType.Axis, RulerText);
ctx.DrawText(ft, new Point(x + 3, 3));
}
+ }
+
+ // Ticks at whole time steps wide enough for their label, read m:ss[.f] like the transport.
+ private void RenderTime(DrawingContext ctx, double w, double h, double bpm)
+ {
+ double pxPerSec = _o._pixelsPerBeat * bpm / 60.0;
+ double charW = _charW > 0 ? _charW
+ : _charW = new FormattedText("0000000000", CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
+ NotaFonts.Mono, NotaType.Axis, RulerText).Width / 10;
+ double stepS = RulerLabels.TimeSteps[^1];
+ foreach (var st in RulerLabels.TimeSteps)
+ {
+ int chars = st >= 1 ? 5 : st >= 0.1 ? 7 : st >= 0.01 ? 8 : 9;
+ if (st * pxPerSec >= chars * charW + 14) { stepS = st; break; }
+ }
+ double t0 = RulerLabels.Seconds(_o._scrollBeats, bpm);
+ for (long k = Math.Max(0, (long)Math.Floor(t0 / stepS)); ; k++)
+ {
+ double t = k * stepS;
+ double x = _o.BeatToX(RulerLabels.BeatsAt(t, bpm));
+ if (x > w) break;
+ if (x < 0) continue;
+ ctx.DrawLine(BarPen, new Point(x, h - 7), new Point(x, h));
+ var ft = new FormattedText(RulerLabels.Time(t, stepS, NotaNum.Culture), CultureInfo.InvariantCulture,
+ FlowDirection.LeftToRight, NotaFonts.Mono, NotaType.Axis, RulerText);
+ ctx.DrawText(ft, new Point(x + 3, 3));
+ }
+ }
+ private double _charW;
+ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
+ {
+ base.OnAttachedToVisualTree(e);
+ RulerDisplay.Changed += InvalidateVisual;
+ }
+ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
+ {
+ base.OnDetachedFromVisualTree(e);
+ RulerDisplay.Changed -= InvalidateVisual;
+ }
+
+ private void RenderPlayheadAndReadout(DrawingContext ctx, double w, double h)
+ {
// Playhead flag: a 7×5 brass triangle at the top of the ruler.
double px = _o.BeatToX(_o._playheadBeats);
if (px >= -5 && px <= w + 5)
diff --git a/src/managed/Nota.App/AudioClipEditorView.cs b/src/managed/Nota.App/AudioClipEditorView.cs
index 13c38d72..335940c3 100644
--- a/src/managed/Nota.App/AudioClipEditorView.cs
+++ b/src/managed/Nota.App/AudioClipEditorView.cs
@@ -58,6 +58,15 @@ public sealed class AudioClipEditorView : UserControl
private bool _warpEnabled;
private int _warpMode = 3; // Complex
private double _detectedBpm;
+ // The clip's warp tempo (#248): what the played region reads as recorded at (0 = unknown),
+ // and the markers / trim it was read from, scaled when a new tempo is set.
+ private double _clipBpm;
+ private double[] _mkSrc = Array.Empty<double>(), _mkBeat = Array.Empty<double>();
+ private double _playStart, _playEnd;
+ private DragNumber _tempo = null!;
+ private TextBlock _tempoUnknown = null!;
+ private Button _tempoHalf = null!, _tempoDouble = null!;
+ private bool _tempoGesture;
private long _srcFrames; // the whole sample's frames (unwarped detail peaks)
private bool _envMode;
private int _envTarget; // 0 = Volume (0..1), 1 = Pan (-1..1)
@@ -146,7 +155,7 @@ public sealed class AudioClipEditorView : UserControl
var transients = ClipEditorKit.Button("To transients", TransientWarp);
ToolTip.SetTip(transients, "Pin a marker on every hit so drums lock to the grid");
var warp = Section(SectionTitle("Warp", _markerCount), 8,
- warpRow, Pair(detect, transients), Card(KeyValue("Detected", _detectedText)));
+ warpRow, TempoRow(), Pair(detect, transients), Card(KeyValue("Detected", _detectedText)));
// ADSR — the clip's amplitude shape (the ADSR tab swaps the inspector to it). Times
// run on a square-law slider over the clip length, so short attacks stay fine-grained.
@@ -222,6 +231,14 @@ public sealed class AudioClipEditorView : UserControl
/// <summary>The snap grid of the axis the wave draws (for the status line of ⌘1–⌘5).</summary>
internal ResolvedGrid SnapGridState => _wave.DrawnGrid;
+ /// <summary>Nothing here follows the grid right now: ADSR handles don't snap, and an unwarped
+ /// clip in Sample mode has no beat grid (#269). ⌘1–⌘5 then act on the arrangement (#114).</summary>
+ internal bool GridInert => _mode == 2 || (_mode == 0 && !_warpEnabled);
+
+ /// <summary>Moves the transport to an arrangement beat: a click or drag on the ruler or the
+ /// playhead line (#278). Left null for a Session slot, which plays on its own loop clock.</summary>
+ public Action<double>? Seek { get => _wave.Seek; set => _wave.Seek = value; }
+
private readonly TextBox _bpmBox;
private readonly Canvas _overlay;
private readonly ScrollBar _hScroll;
@@ -335,6 +352,8 @@ public sealed class AudioClipEditorView : UserControl
var ms = new double[128]; var mb = new double[128];
markers = Math.Min(_engine.GetClipWarpMarkers(TrackId, ClipIndex, ms, mb), 128);
_wave.SetMarkers(ms, mb, markers);
+ _mkSrc = ms[..markers]; _mkBeat = mb[..markers];
+ _playStart = gi.WarpPlayStart; _playEnd = gi.WarpPlayEnd;
_wave.SetSourceRegion(0, 0, 0); // source-frame brackets off (warped)
_wave.SetWarpTrim(gi.WarpPlayStart, gi.WarpPlayEnd, gi.WarpBeats);
}
@@ -344,6 +363,7 @@ public sealed class AudioClipEditorView : UserControl
int n = _engine.GetClipSourcePeaks(TrackId, ClipIndex, peaks, 1024);
_wave.SetPeaks(peaks, n);
_wave.SetMarkers(Array.Empty<double>(), Array.Empty<double>(), 0);
+ _mkSrc = _mkBeat = Array.Empty<double>();
if (haveSample)
{
double len = gi.LengthFrames > 0 ? gi.LengthFrames : srcFrames - gi.SourceOffsetFrames;
@@ -352,6 +372,11 @@ public sealed class AudioClipEditorView : UserControl
else _wave.SetSourceRegion(0, 0, 0);
}
_markerCount.Text = _warpEnabled ? $"{markers} {(markers == 1 ? "marker" : "markers")}" : "off";
+ _clipBpm = _warpEnabled ? ClipTempo.Bpm(_mkSrc, _mkBeat, _playStart, _playEnd, srcSR) : 0;
+ SyncTempo();
+
+ // Where the played region sits in the arrangement (playhead, ruler seeks and labels).
+ _wave.SetPlacement(_startBeat, _lengthBeats, SessionClip.SceneOf(ClipIndex) >= 0);
// Clip envelope: clip-local domain = warpBeats when warped, else clip length.
LoadEnvelope();
@@ -359,8 +384,8 @@ public sealed class AudioClipEditorView : UserControl
SyncWaveScroll();
}
- // Called from the UI tick: show a playback cursor when the transport is inside
- // this clip, else hide it.
+ // Called from the UI tick: show the playhead whenever the song position is inside this
+ // clip — stopped too, where play will start, as the piano roll does (#277).
public void OnPlayhead(double beats, bool playing)
{
double frac;
@@ -372,11 +397,126 @@ public sealed class AudioClipEditorView : UserControl
frac = pos >= 0 && _lengthBeats > 0 && pos <= _lengthBeats ? pos / _lengthBeats : -1;
}
else
- frac = (playing && _lengthBeats > 0 && beats >= _startBeat && beats <= _startBeat + _lengthBeats)
+ frac = (_lengthBeats > 0 && beats >= _startBeat && beats <= _startBeat + _lengthBeats)
? (beats - _startBeat) / _lengthBeats : -1;
_wave.SetPlayhead(frac);
}
+ // ---- warp tempo (#248) -----------------------------------------------------
+ private const string TempoTip = "The tempo the audio was recorded at. Nota stretches it to the project tempo. ×2 / ÷2 fix a half- or double-time detection.";
+
+ // "Tempo [ 87.00 BPM ] ÷2 ×2" under the Warp switch: drag the value, double-click to type.
+ private Control TempoRow()
+ {
+ var label = new TextBlock
+ {
+ Text = "Tempo", Width = 44, FontSize = 9, FontWeight = FontWeight.Medium,
+ Foreground = NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Center,
+ };
+ _tempo = new DragNumber(120, ClipTempo.MinBpm, ClipTempo.MaxBpm, 0.5, "0.00", fontSize: NotaType.Body)
+ { VerticalAlignment = VerticalAlignment.Center };
+ _tempo.GestureBegin += () => _tempoGesture = true;
+ _tempo.ValueChanged += PreviewTempo;
+ _tempo.GestureEnd += () => { _tempoGesture = false; SetTempo(_tempo.Value); };
+ // No tempo known yet (an unwarped clip never detected): "—"; a click types one.
+ _tempoUnknown = new TextBlock
+ {
+ Text = "—", FontSize = NotaType.Body, Foreground = NotaPalette.TextDisabled, Background = Brushes.Transparent,
+ HorizontalAlignment = HorizontalAlignment.Stretch, TextAlignment = TextAlignment.Center,
+ VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.Ibeam),
+ };
+ _tempoUnknown.PointerPressed += (_, e) =>
+ {
+ _tempoUnknown.IsVisible = false;
+ _tempo.IsVisible = true;
+ _tempo.Value = _engine.Bpm;
+ _tempo.BeginEdit();
+ e.Handled = true;
+ };
+ var unit = Meta("BPM");
+ unit.VerticalAlignment = VerticalAlignment.Center;
+ var inner = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 4 };
+ inner.Children.Add(new Panel { Children = { _tempo, _tempoUnknown } });
+ Grid.SetColumn(unit, 1); inner.Children.Add(unit);
+ var field = Field(inner, 6);
+ _tempoHalf = ClipEditorKit.Button("÷2", () => StepTempo(ClipTempo.Half));
+ _tempoDouble = ClipEditorKit.Button("×2", () => StepTempo(ClipTempo.Double));
+ foreach (var b in new[] { _tempoHalf, _tempoDouble }) { b.Padding = new Thickness(0); b.Width = 30; }
+ ToolTip.SetTip(label, TempoTip); ToolTip.SetTip(field, TempoTip);
+ ToolTip.SetTip(_tempoHalf, "Half the tempo — the clip spans half as many beats");
+ ToolTip.SetTip(_tempoDouble, "Double the tempo — the clip spans twice as many beats");
+ var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 6 };
+ row.Children.Add(label);
+ Grid.SetColumn(field, 1); row.Children.Add(field);
+ Grid.SetColumn(_tempoHalf, 2); row.Children.Add(_tempoHalf);
+ Grid.SetColumn(_tempoDouble, 3); row.Children.Add(_tempoDouble);
+ return row;
+ }
+
+ /// <summary>Esc: drop a warp-marker or segment-tempo drag in progress, nothing committed (#140).
+ /// True when there was one to drop.</summary>
+ public bool CancelGesture() => _wave.CancelGesture();
+
+ private double KnownTempo => _warpEnabled ? _clipBpm : _detectedBpm;
+
+ private void SyncTempo()
+ {
+ if (_tempoGesture) return; // don't yank the value out from under a drag
+ double bpm = KnownTempo;
+ bool known = bpm > 0;
+ _tempo.IsVisible = known;
+ _tempoUnknown.IsVisible = !known;
+ if (known) _tempo.Value = bpm;
+ _tempoHalf.IsEnabled = known && ClipTempo.Half(bpm) is not null;
+ _tempoDouble.IsEnabled = known && ClipTempo.Double(bpm) is not null;
+ }
+
+ // While the value drags, a warped clip re-times on screen only; the engine hears it on release.
+ private void PreviewTempo(double bpm)
+ {
+ if (!_tempoGesture || !_warpEnabled || _clipBpm <= 0 || _mkBeat.Length < 2) return;
+ var (beats, _, _) = ClipTempo.Scale(_mkBeat, _playStart, _playEnd, _clipBpm, bpm);
+ _wave.PreviewMarkerBeats(beats);
+ }
+
+ private void StepTempo(Func<double, double?> step)
+ {
+ if (step(KnownTempo) is { } bpm) SetTempo(bpm);
+ }
+
+ // One undo step: a warped clip scales its markers and trim window by one factor (hand-placed
+ // markers keep their timing); an unwarped clip turns Warp on at that tempo.
+ private void SetTempo(double bpm)
+ {
+ bpm = ClipTempo.Clamp(bpm);
+ if (_warpEnabled && _clipBpm > 0 && _mkBeat.Length >= 2)
+ {
+ if (Math.Abs(bpm - _clipBpm) < 0.005) { _wave.PreviewMarkerBeats(_mkBeat); return; }
+ var (beats, ps, pe) = ClipTempo.Scale(_mkBeat, _playStart, _playEnd, _clipBpm, bpm);
+ var src = _mkSrc;
+ _engine.BeginUndoGroup();
+ try
+ {
+ WarpEdit(() =>
+ {
+ _engine.SetClipWarpMarkers(TrackId, ClipIndex, src, beats);
+ _engine.SetClipWarpTrim(TrackId, ClipIndex, ps, pe > 0 ? pe : beats[^1]);
+ });
+ }
+ finally { _engine.EndUndoGroup(); }
+ }
+ else if (!_warpEnabled)
+ {
+ double used = 0;
+ WarpEdit(() => used = _engine.AutoWarpClipAtBpm(TrackId, ClipIndex, bpm));
+ if (used > 0) _detectedBpm = used;
+ ShowDetected();
+ }
+ else return;
+ Reload();
+ _onChanged();
+ }
+
/// <summary>Set by the host: runs the engine's background warp build after a warp edit.</summary>
public Action? WarpBuildRequested;
@@ -578,6 +718,31 @@ public sealed class AudioClipEditorView : UserControl
private readonly System.Collections.Generic.List<(double src, double beat)> _mk = new();
private int _drag = -1;
private int _hoverMk = -1; // marker under the cursor (hover highlight)
+
+ // Arrangement placement of the played region (#277 / #278 / #275): the playhead, ruler
+ // seeks and ruler labels all go through Map, so they can't disagree.
+ private double _placeStart, _placeLen = 4;
+ private bool _slot;
+ public Action<double>? Seek;
+ private bool _seekDrag; // a ruler / playhead-line scrub in progress
+ private double _lastSeek = double.NaN;
+ private const double PlayheadGrabPx = 4;
+ private const string SlotSeekTip = "A Session slot plays on its own loop clock — launch it to play from the start";
+ public void SetPlacement(double startBeat, double lengthBeats, bool isSlot)
+ {
+ _placeStart = startBeat; _placeLen = Math.Max(1e-6, lengthBeats); _slot = isSlot;
+ InvalidateVisual();
+ }
+ private ClipTimeMap Map
+ => _srcMode && _srcTotal > 0
+ ? new ClipTimeMap(_placeStart, _placeLen, ClipContentDomain.SourceFrames, _srcTotal, _srcOff, _srcOff + _srcLen, _reversed, _slot)
+ : _trimMode && _trimTotal > 0
+ ? new ClipTimeMap(_placeStart, _placeLen, ClipContentDomain.WarpBeats, TotalBeats, _trimStart, _trimEnd, _reversed, _slot)
+ : new ClipTimeMap(_placeStart, _placeLen, ClipContentDomain.WarpBeats, 1, 0, 1, _reversed, _slot);
+ private double PlayheadX(double w) => FracToX(Map.ContentAtPlayFrac(_frac), w);
+ private bool PlayheadShown => _frac >= 0 && _frac <= 1;
+ private bool OnPlayheadLine(double x, double w) => PlayheadShown && Math.Abs(x - PlayheadX(w)) <= PlayheadGrabPx;
+
private double _srcSR; // source sample rate (for per-marker BPM)
private const double HandlePx = 7;
@@ -618,11 +783,13 @@ public sealed class AudioClipEditorView : UserControl
{
base.OnAttachedToVisualTree(e);
EditorGrids.Shared.Changed += OnGrid;
+ RulerDisplay.Changed += InvalidateVisual;
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
EditorGrids.Shared.Changed -= OnGrid;
+ RulerDisplay.Changed -= InvalidateVisual;
}
private const double MinSrcFrames = 256;
private static readonly Cursor ArrowCur = new(StandardCursorType.Arrow);
@@ -662,6 +829,7 @@ public sealed class AudioClipEditorView : UserControl
private double _adsrAnchorBeat, _adsrAnchorLevel;
private Point _adsrPress;
private static readonly Cursor HandCur = new(StandardCursorType.Hand);
+ private static readonly Cursor NoCur = new(StandardCursorType.No);
/// <summary>Raised when an ADSR handle drag ends (or a handle is reset) with the new shape.</summary>
public Action<ClipAdsr>? AdsrCommitted;
@@ -831,11 +999,52 @@ public sealed class AudioClipEditorView : UserControl
{
_mk.Clear();
for (int i = 0; i < count; i++) _mk.Add((src[i], beat[i]));
+ // The layout the engine drew the peaks under; live edits are drawn relative to it.
+ _cSrc = src[..count]; _cBeat = beat[..count];
+ if (_lBeat.Length != count) _lBeat = new double[count];
if (_selMk >= _mk.Count) _selMk = -1;
InvalidateVisual();
}
public void SetGain(double g) { if (Math.Abs(g - _gain) < 1e-4) return; _gain = g; InvalidateVisual(); }
+ // Live warp preview (#140): while markers move (a marker drag, a segment-tempo scrub, the
+ // Tempo field) the peaks the engine laid out under the committed markers are re-timed on
+ // screen through WarpRemap; the engine only hears the result on release.
+ private double[] _cSrc = Array.Empty<double>(), _cBeat = Array.Empty<double>(), _lBeat = Array.Empty<double>();
+ private IPointer? _gesturePointer;
+ private bool Remapped
+ {
+ get
+ {
+ if (_mk.Count < 2 || _mk.Count != _cBeat.Length) return false;
+ for (int i = 0; i < _mk.Count; i++) if (_mk[i].beat != _cBeat[i]) return true;
+ return false;
+ }
+ }
+ /// <summary>Show markers at these beats (same sources) without committing — a live preview.</summary>
+ public void PreviewMarkerBeats(double[] beats)
+ {
+ if (beats.Length != _mk.Count) return;
+ for (int i = 0; i < beats.Length; i++) _mk[i] = (_mk[i].src, beats[i]);
+ InvalidateVisual();
+ }
+ /// <summary>Drop a marker drag or segment-tempo scrub: back to the committed markers.</summary>
+ public bool CancelGesture()
+ {
+ if (_drag < 0 && _bpmScrubSeg < 0) return false;
+ RestoreCommitted();
+ return true;
+ }
+ private void RestoreCommitted()
+ {
+ _drag = -1; _bpmScrubSeg = -1; _bpmScrubMoved = false;
+ if (_mk.Count == _cBeat.Length)
+ for (int i = 0; i < _mk.Count; i++) _mk[i] = (_cSrc[i], _cBeat[i]);
+ var p = _gesturePointer; _gesturePointer = null;
+ p?.Capture(null);
+ InvalidateVisual();
+ }
+
// Markers map in the BEAT domain, matching the warped waveform drawn across
// the full clip length. Dragging changes a marker's beat (its source stays).
private double TotalBeats => _mk.Count > 1 ? Math.Max(1e-6, _mk[^1].beat) : 1;
@@ -854,6 +1063,20 @@ public sealed class AudioClipEditorView : UserControl
double W = Bounds.Width, H = Bounds.Height;
_free = (e.KeyModifiers & KeyModifiers.Alt) != 0;
+ // The ruler, and the playhead line wherever it runs, move the transport (#278) —
+ // ahead of every other gesture, but only inside the ruler / the line's grab zone.
+ var pt = e.GetCurrentPoint(this);
+ if (Seek is not null && pt.Properties.IsLeftButtonPressed && e.ClickCount == 1
+ && (pt.Position.Y < RulerH || OnPlayheadLine(pt.Position.X, W)))
+ {
+ _seekDrag = true;
+ _lastSeek = double.NaN;
+ e.Pointer.Capture(this);
+ SeekAt(pt.Position.X, W);
+ e.Handled = true;
+ return;
+ }
+
// ADSR mode takes over the pointer: grab a handle (double-click resets its stage).
if (_adsrMode)
{
@@ -893,6 +1116,7 @@ public sealed class AudioClipEditorView : UserControl
{
_bpmScrubSeg = b.seg; _bpmScrubStartY = pp.Y; _bpmScrubStartBpm = b.bpm; _bpmScrubMoved = false;
e.Pointer.Capture(this);
+ _gesturePointer = e.Pointer;
}
e.Handled = true;
return;
@@ -965,7 +1189,7 @@ public sealed class AudioClipEditorView : UserControl
}
int h = HitMarker(x, w);
if (h != _selMk) { _selMk = h; InvalidateVisual(); } // a click picks a marker (or clears the pick)
- if (h > 0 && h < _mk.Count - 1) { _drag = h; e.Pointer.Capture(this); e.Handled = true; }
+ if (h > 0 && h < _mk.Count - 1) { _drag = h; e.Pointer.Capture(this); _gesturePointer = e.Pointer; e.Handled = true; }
}
// Wheel scrolls the clip horizontally; ⌘/Ctrl+wheel zooms toward the cursor.
@@ -996,6 +1220,8 @@ public sealed class AudioClipEditorView : UserControl
protected override void OnPointerMoved(PointerEventArgs e)
{
_free = (e.KeyModifiers & KeyModifiers.Alt) != 0; // live, so Alt can toggle mid-drag
+ if (_seekDrag) { SeekAt(e.GetPosition(this).X, Bounds.Width); return; }
+ if (!Dragging && UpdateSeekHover(e.GetPosition(this), Bounds.Width)) return;
if (_adsrDrag != AdsrHandle.None)
{
var p = e.GetPosition(this);
@@ -1097,6 +1323,7 @@ public sealed class AudioClipEditorView : UserControl
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
+ if (_seekDrag) { _seekDrag = false; e.Pointer.Capture(null); return; }
if (_adsrDrag != AdsrHandle.None)
{
_adsrDrag = AdsrHandle.None;
@@ -1107,7 +1334,7 @@ public sealed class AudioClipEditorView : UserControl
}
if (_bpmScrubSeg >= 0) // push the scrubbed warp (one undo step) — only if it was dragged
{
- _bpmScrubSeg = -1; e.Pointer.Capture(null);
+ _bpmScrubSeg = -1; _gesturePointer = null; e.Pointer.Capture(null);
if (_bpmScrubMoved) Commit();
_bpmScrubMoved = false;
InvalidateVisual();
@@ -1127,7 +1354,7 @@ public sealed class AudioClipEditorView : UserControl
return;
}
if (_drag < 0) return;
- _drag = -1; e.Pointer.Capture(null); Commit();
+ _drag = -1; _gesturePointer = null; e.Pointer.Capture(null); Commit();
}
protected override void OnPointerExited(PointerEventArgs e)
@@ -1146,6 +1373,8 @@ public sealed class AudioClipEditorView : UserControl
{
StandardCursorType.SizeWestEast => ResizeCur,
StandardCursorType.SizeNorthSouth => ScrubCur,
+ StandardCursorType.Hand => HandCur,
+ StandardCursorType.No => NoCur,
_ => ArrowCur,
};
}
@@ -1183,6 +1412,51 @@ public sealed class AudioClipEditorView : UserControl
SetCursorKind(overHandle ? StandardCursorType.SizeWestEast : StandardCursorType.Arrow);
}
+ private bool Dragging => _drag >= 0 || _srcDrag >= 0 || _trimDrag >= 0 || _envDrag >= 0 || _envBend is not null
+ || _bpmScrubSeg >= 0 || _adsrDrag != AdsrHandle.None;
+
+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
+ {
+ _seekDrag = false;
+ // Capture taken away mid-drag (window deactivated, a popup): nothing half-committed.
+ if (_drag >= 0 || _bpmScrubSeg >= 0) { _gesturePointer = null; RestoreCommitted(); }
+ base.OnPointerCaptureLost(e);
+ }
+
+ // Ruler / playhead-line hover: a hand over the ruler, ↔ on the line; a Session slot
+ // can't be seeked from here, so it says why. True when it took the cursor.
+ private bool UpdateSeekHover(Point p, double w)
+ {
+ bool ruler = p.Y < RulerH, line = OnPlayheadLine(p.X, w);
+ object? tip = null;
+ bool took = true;
+ if (Seek is not null && line) SetCursorKind(StandardCursorType.SizeWestEast);
+ else if (Seek is not null && ruler) SetCursorKind(StandardCursorType.Hand);
+ else if (_slot && (ruler || line)) { SetCursorKind(StandardCursorType.No); tip = SlotSeekTip; }
+ else
+ {
+ took = false;
+ if (_curKind is StandardCursorType.Hand or StandardCursorType.No) SetCursorKind(StandardCursorType.Arrow);
+ }
+ if (!Equals(ToolTip.GetTip(this), tip)) ToolTip.SetTip(this, tip);
+ return took;
+ }
+
+ // Seek to the arrangement moment the audio under x plays at; snapped to the drawn warp
+ // grid on a warped clip (Alt: free), free on an unwarped one, which has no beat grid.
+ private void SeekAt(double x, double w)
+ {
+ double c = XToFrac(x, w);
+ if (_trimMode && _mk.Count > 1) c = SnapWarp(c * TotalBeats) / TotalBeats;
+ var map = Map;
+ double beat = Math.Max(0, map.ArrangementBeatAtContent(c));
+ if (beat == _lastSeek) return;
+ _lastSeek = beat;
+ Seek?.Invoke(beat);
+ double pf = (beat - _placeStart) / _placeLen; // immediate feedback; the transport tick follows
+ SetPlayhead(pf >= 0 && pf <= 1 ? pf : -1);
+ }
+
private void AddMarker(double beat)
{
for (int i = 0; i + 1 < _mk.Count; i++)
@@ -1263,6 +1537,7 @@ public sealed class AudioClipEditorView : UserControl
double amp = wh / 2 - 6;
double span = f1 - f0;
if (span <= 0) return;
+ if (Remapped) { DrawPeaksRemapped(ctx, peaks, count, f0, f1, w, mid, amp, adsrF, adsrFit, shaped); return; }
double bwRaw = span * _zoom * w / count;
double bw = Math.Max(1, bwRaw);
var (c0, c1) = VisibleContent(w);
@@ -1287,6 +1562,34 @@ public sealed class AudioClipEditorView : UserControl
}
}
+ // The peaks re-timed to the live markers: each bucket's committed beat span is carried to
+ // where the live markers put that audio, so the wave stretches with the drag.
+ private void DrawPeaksRemapped(DrawingContext ctx, float[] peaks, int count, double f0, double f1, double w,
+ double mid, double amp, AdsrFrame adsrF, ClipAdsr adsrFit, bool shaped)
+ {
+ for (int i = 0; i < _mk.Count; i++) _lBeat[i] = _mk[i].beat;
+ double oldTotal = _cBeat[^1], span = f1 - f0;
+ double XAtBucket(int i)
+ => BeatToX(WarpRemap.NewBeatAt(_cSrc, _cBeat, _lBeat, (f0 + span * i / count) * oldTotal), w);
+ double xa = XAtBucket(0);
+ for (int i = 0; i < count; i++)
+ {
+ double xb = XAtBucket(i + 1);
+ double lo = Math.Min(xa, xb), bw = Math.Max(1, Math.Abs(xb - xa));
+ xa = xb;
+ if (lo + bw < 0 || lo > w) continue;
+ double g = _gain;
+ if (shaped)
+ {
+ double bt = adsrF.Beat(lo + bw / 2);
+ if (bt >= 0 && bt <= _adsrLen) g *= adsrFit.GainAt(bt, _adsrLen);
+ }
+ float mn = (float)Math.Clamp(peaks[i * 2] * g, -1.0, 1.0);
+ float mx = (float)Math.Clamp(peaks[i * 2 + 1] * g, -1.0, 1.0);
+ ctx.FillRectangle(_wave, new Rect(lo, mid - mx * amp, bw, Math.Max(1, (mx - mn) * amp)));
+ }
+ }
+
// ---- ruler / grid density ----------------------------------------------
private const double TickMinPx = 6; // closest two ruler ticks may sit
private const double LabelPadPx = 12; // gap after a ruler label
@@ -1451,7 +1754,10 @@ public sealed class AudioClipEditorView : UserControl
double x = BeatToX(_mk[_selMk].beat, w);
if (x >= -6 && x <= w + 6)
{
- var ft = new FormattedText(Position(_mk[_selMk].beat), NotaNum.Culture, FlowDirection.LeftToRight, GridFace, 9, ChipInkHot);
+ // In the ruler's terms: where the marker plays in the arrangement (a slot: its own).
+ var map = Map;
+ double at = !_slot && map.Valid ? Math.Max(0, map.ArrangementBeatAtContent(_mk[_selMk].beat / TotalBeats)) : _mk[_selMk].beat;
+ var ft = new FormattedText(Position(at), NotaNum.Culture, FlowDirection.LeftToRight, GridFace, 9, ChipInkHot);
double cw = ft.Width + 12;
double lx = x + 9 + cw > w ? x - 9 - cw : x + 9;
var chip = new Rect(lx, RulerH + 3, cw, 16);
@@ -1544,19 +1850,87 @@ public sealed class AudioClipEditorView : UserControl
{
// _frac runs over the PLAYED window, so on a reversed clip it walks the region
// from its end back to its start (which the mirror then draws left-to-right).
- double pf = _reversed ? 1 - _frac : _frac;
- double x = (_srcMode && _srcTotal > 0) ? SrcToX(_srcOff + pf * _srcLen, w)
- : (_trimMode && _trimTotal > 0) ? BeatToX(_trimStart + pf * (_trimEnd - _trimStart), w)
- : FracToX(pf, w);
+ double x = PlayheadX(w);
ctx.DrawLine(PlayheadPen, new Point(x, 0), new Point(x, h));
}
}
- // Ruler: bar.beat over the warp's beats, or seconds over the source when unwarped.
+ // Local ruler (a Session slot): bar.beat over the warp's beats, or seconds over the source when unwarped.
// Bars in Ink 2, beats in Ink 6, mono 9 on the baseline right of each tick.
+ // Ruler (#275): an arrangement clip reads where each point plays in the arrangement — bars,
+ // or time while the transport read-out shows time — warped or not. A Session slot has no
+ // arrangement position and keeps its own: warp bars from 1, or source seconds.
private void DrawRuler(DrawingContext ctx, double w)
{
using var clip = ctx.PushClip(new Rect(0, 0, w, RulerH)); // a label half off-screen stays inside
+ var map = Map;
+ bool hasAxis = _mk.Count > 1 || (_srcMode && _srcTotal > 0);
+ if (!_slot && map.Valid && hasAxis) DrawArrangementRuler(ctx, w, map);
+ else DrawLocalRuler(ctx, w);
+ }
+
+ private void DrawArrangementRuler(DrawingContext ctx, double w, ClipTimeMap map)
+ {
+ double cw = MonoCharW;
+ var (c0, c1) = VisibleContent(w);
+ double a0 = map.ArrangementBeatAtContent(c0), a1 = map.ArrangementBeatAtContent(c1);
+ double lo = Math.Max(0, Math.Min(a0, a1)), hi = Math.Max(a0, a1);
+ double beatsAll = Math.Abs(map.ArrangementBeatAtContent(1) - map.ArrangementBeatAtContent(0));
+ double ppb = _zoom * w / Math.Max(1e-9, beatsAll); // arrangement beats are linear in x
+ double XAt(double beat) => FracToX(map.ContentAtArrangementBeat(beat), w);
+ void Label(string text, double x, bool strong)
+ {
+ var ft = new FormattedText(text, NotaNum.Culture, FlowDirection.LeftToRight, GridFace, 9, strong ? RulerBar : RulerBeat);
+ ctx.DrawText(ft, new Point(x + 4, RulerH - 5 - ft.Height));
+ }
+
+ if (RulerDisplay.ShowTime && _bpm > 0)
+ {
+ double pxPerSec = ppb * _bpm / 60.0;
+ double stepS = RulerLabels.TimeSteps[^1];
+ foreach (var st in RulerLabels.TimeSteps)
+ {
+ int chars = st >= 1 ? 5 : st >= 0.1 ? 7 : st >= 0.01 ? 8 : 9;
+ if (st * pxPerSec >= chars * cw + LabelPadPx + 4) { stepS = st; break; }
+ }
+ double t0 = RulerLabels.Seconds(lo, _bpm), t1 = RulerLabels.Seconds(hi, _bpm);
+ for (long k = Math.Max(0, (long)Math.Floor(t0 / stepS) - 1); k * stepS <= t1 + stepS; k++)
+ {
+ double t = k * stepS, x = XAt(RulerLabels.BeatsAt(t, _bpm));
+ if (x < -200 || x > w + 0.5) continue;
+ ctx.DrawLine(GridBeatPen, new Point(x + 0.5, 0), new Point(x + 0.5, RulerH));
+ Label(RulerLabels.Time(t, stepS, NotaNum.Culture), x, true);
+ }
+ return;
+ }
+
+ // Labels at the smallest step wide enough for its own label text (bars thin to every
+ // 2nd/4th/8th… on a long clip); unlabelled ticks at a finer step.
+ int barDigits = ((int)Math.Floor(hi / BeatsPerBar) + 1).ToString(NotaNum.Culture).Length;
+ double labelStep = BeatSteps[^1];
+ foreach (var st in BeatSteps)
+ {
+ if (st < 0.25 || st == 2) continue; // labels: 16ths, half-beats, beats, then bars
+ int chars = st >= BeatsPerBar ? barDigits : st >= 1 ? barDigits + 2 : barDigits + 4;
+ if (st * ppb >= chars * cw + LabelPadPx + 4) { labelStep = st; break; }
+ }
+ double tickStep = Math.Min(labelStep, BeatStep(ppb, TickMinPx));
+ for (double b = Math.Max(0, Math.Floor(lo / tickStep) * tickStep - labelStep); b <= hi + tickStep; b += tickStep)
+ {
+ double x = XAt(b);
+ if (x < -200 || x > w + 0.5) continue;
+ bool labelled = IsMultiple(b, labelStep);
+ bool bar = IsMultiple(b, BeatsPerBar);
+ if (labelled)
+ ctx.DrawLine(bar ? GridBarPen : GridBeatPen, new Point(x + 0.5, 0), new Point(x + 0.5, RulerH));
+ else
+ ctx.DrawLine(GridBeatPen, new Point(x + 0.5, RulerH - 6), new Point(x + 0.5, RulerH));
+ if (labelled) Label(RulerLabels.Bars(b, labelStep, BeatsPerBar, NotaNum.Culture), x, bar);
+ }
+ }
+
+ private void DrawLocalRuler(DrawingContext ctx, double w)
+ {
double cw = MonoCharW;
if (_mk.Count > 1)
{
@@ -1620,7 +1994,7 @@ public sealed class AudioClipEditorView : UserControl
return t.ToString(fmt, NotaNum.Culture) + " s";
}
- // bar.beat.16th of a warp beat (1-based) for the selected marker's chip.
+ // bar.beat.16th of a beat (1-based) for the selected marker's chip.
private static string Position(double beat)
{
int bar = (int)Math.Floor(beat / BeatsPerBar) + 1;
diff --git a/src/managed/Nota.App/ClipEditor/ClipTempo.cs b/src/managed/Nota.App/ClipEditor/ClipTempo.cs
new file mode 100644
index 00000000..ebd06689
--- /dev/null
+++ b/src/managed/Nota.App/ClipEditor/ClipTempo.cs
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// An audio clip's warp tempo (#248, specs/036-clip-editor-batch): the tempo its played region is
+// treated as recorded at — the region's warp-beat span against the source frames it covers. For
+// one warp segment that is the segment's BPM chip. Setting a tempo scales every marker's beat
+// (and the trim window) by one factor, so hand-placed markers keep their relative timing.
+// Free of Avalonia and the engine so the smoke test can link it.
+
+using System;
+
+namespace Nota.App;
+
+internal static class ClipTempo
+{
+ public const double MinBpm = 20, MaxBpm = 999;
+
+ /// <summary>Source frame at a warp beat, piecewise linear through markers sorted by source;
+ /// past either end it extends the end segment's slope.</summary>
+ public static double SrcAt(ReadOnlySpan<double> src, ReadOnlySpan<double> beat, double b)
+ {
+ int n = Math.Min(src.Length, beat.Length);
+ if (n < 2) return n == 1 ? src[0] : 0;
+ int i = Segment(beat, n, b);
+ double db = beat[i + 1] - beat[i];
+ return db <= 0 ? src[i] : src[i] + (src[i + 1] - src[i]) * (b - beat[i]) / db;
+ }
+
+ /// <summary>Warp beat at a source frame (the inverse of <see cref="SrcAt"/>).</summary>
+ public static double BeatAt(ReadOnlySpan<double> src, ReadOnlySpan<double> beat, double s)
+ {
+ int n = Math.Min(src.Length, beat.Length);
+ if (n < 2) return n == 1 ? beat[0] : 0;
+ int i = Segment(src, n, s);
+ double ds = src[i + 1] - src[i];
+ return ds <= 0 ? beat[i] : beat[i] + (beat[i + 1] - beat[i]) * (s - src[i]) / ds;
+ }
+
+ // Index i of the segment [xs[i], xs[i+1]] holding x (clamped to the first / last segment).
+ private static int Segment(ReadOnlySpan<double> xs, int n, double x)
+ {
+ int lo = 0, hi = n - 2;
+ while (lo < hi)
+ {
+ int mid = (lo + hi + 1) >> 1;
+ if (xs[mid] <= x) lo = mid; else hi = mid - 1;
+ }
+ return lo;
+ }
+
+ /// <summary>Tempo of the played window [playStart, playEnd] (playEnd 0 = to the last marker),
+ /// or 0 when it can't be told.</summary>
+ public static double Bpm(ReadOnlySpan<double> src, ReadOnlySpan<double> beat, double playStart, double playEnd, double sampleRate)
+ {
+ int n = Math.Min(src.Length, beat.Length);
+ if (n < 2 || sampleRate <= 0) return 0;
+ double pe = playEnd > 0 ? playEnd : beat[n - 1];
+ double frames = SrcAt(src, beat, pe) - SrcAt(src, beat, playStart);
+ return frames > 0 && pe > playStart ? (pe - playStart) * sampleRate * 60.0 / frames : 0;
+ }
+
+ /// <summary>Scale every marker beat and the trim window so the clip reads at
+ /// <paramref name="newBpm"/>. playEnd 0 stays 0 ("to the end").</summary>
+ public static (double[] beats, double playStart, double playEnd) Scale(
+ ReadOnlySpan<double> beat, double playStart, double playEnd, double oldBpm, double newBpm)
+ {
+ double k = oldBpm > 0 && newBpm > 0 ? newBpm / oldBpm : 1;
+ var nb = new double[beat.Length];
+ for (int i = 0; i < beat.Length; i++) nb[i] = beat[i] * k;
+ return (nb, playStart * k, playEnd > 0 ? playEnd * k : 0);
+ }
+
+ public static bool InRange(double bpm) => bpm >= MinBpm - 1e-9 && bpm <= MaxBpm + 1e-9;
+ public static double? Half(double bpm) => bpm > 0 && InRange(bpm / 2) ? bpm / 2 : null;
+ public static double? Double(double bpm) => bpm > 0 && InRange(bpm * 2) ? bpm * 2 : null;
+ public static double Clamp(double bpm) => Math.Clamp(bpm, MinBpm, MaxBpm);
+}
diff --git a/src/managed/Nota.App/ClipEditor/ClipTimeMap.cs b/src/managed/Nota.App/ClipEditor/ClipTimeMap.cs
new file mode 100644
index 00000000..03f3ad60
--- /dev/null
+++ b/src/managed/Nota.App/ClipEditor/ClipTimeMap.cs
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Where a point of the audio clip editor plays in the arrangement (specs/036-clip-editor-batch).
+// The editor draws the clip on one content axis — the full warp in beats, or the whole sample in
+// frames when unwarped — of which only the played window [PlayStart, PlayEnd] sounds, mapped
+// linearly onto [StartBeat, StartBeat + LengthBeats] (back to front when reversed). The playhead,
+// the ruler labels and ruler seeks all go through this one map so they can't disagree. Free of
+// Avalonia and the engine so the smoke test can link it.
+
+namespace Nota.App;
+
+internal enum ClipContentDomain { WarpBeats, SourceFrames }
+
+internal readonly record struct ClipTimeMap(
+ double StartBeat,
+ double LengthBeats,
+ ClipContentDomain Domain,
+ double ContentTotal,
+ double PlayStart,
+ double PlayEnd,
+ bool Reversed,
+ bool IsSlot)
+{
+ private double Window => PlayEnd - PlayStart;
+ public bool Valid => ContentTotal > 0 && Window > 0;
+
+ /// <summary>Content frac (0..1 over the whole axis) → played frac (0 = the first audible
+ /// moment). Not clamped: points outside the played window give fracs outside 0..1.</summary>
+ public double PlayFracAtContent(double contentFrac)
+ {
+ if (!Valid) return 0;
+ double f = (contentFrac * ContentTotal - PlayStart) / Window;
+ return Reversed ? 1 - f : f;
+ }
+
+ /// <summary>Played frac → content frac (the inverse of <see cref="PlayFracAtContent"/>).</summary>
+ public double ContentAtPlayFrac(double playFrac)
+ {
+ if (!Valid) return 0;
+ double f = Reversed ? 1 - playFrac : playFrac;
+ return (PlayStart + f * Window) / ContentTotal;
+ }
+
+ public double ArrangementBeatAtContent(double contentFrac)
+ => StartBeat + PlayFracAtContent(contentFrac) * LengthBeats;
+
+ public double ContentAtArrangementBeat(double beat)
+ => LengthBeats > 0 ? ContentAtPlayFrac((beat - StartBeat) / LengthBeats) : 0;
+}
diff --git a/src/managed/Nota.App/ClipEditor/RulerLabels.cs b/src/managed/Nota.App/ClipEditor/RulerLabels.cs
new file mode 100644
index 00000000..2f134fe7
--- /dev/null
+++ b/src/managed/Nota.App/ClipEditor/RulerLabels.cs
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Ruler text shared by the arrangement and both clip editors (specs/036-clip-editor-batch): a
+// position reads in bars (9, 9.2, 9.2.3) or, while the transport read-out shows time, in time
+// (0:16, 0:16.5 …), so every ruler on screen speaks the same unit as the read-out. Free of
+// Avalonia so the smoke test can link it.
+
+using System;
+using System.Globalization;
+
+namespace Nota.App;
+
+internal static class RulerLabels
+{
+ /// <summary>Time steps (seconds) the rulers choose from, finest first.</summary>
+ public static readonly double[] TimeSteps =
+ { 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1200, 1800, 3600 };
+
+ /// <summary>1-based bar.beat.16th of a beat position: "9" on a bar, "9.2" on a beat, else
+ /// "9.2.3". <paramref name="stepBeats"/> is the label step (a 16th step shows 16ths).</summary>
+ public static string Bars(double beat, double stepBeats, int beatsPerBar, IFormatProvider fmt)
+ {
+ beat = Math.Max(0, beat);
+ int bpb = Math.Max(1, beatsPerBar);
+ int bar = (int)Math.Floor(beat / bpb + 1e-9) + 1;
+ double inBar = Math.Max(0, beat - (bar - 1) * bpb);
+ int bt = (int)Math.Floor(inBar + 1e-9) + 1;
+ double sub = inBar - (bt - 1);
+ if (Math.Abs(inBar) < 1e-6 || Math.Abs(inBar - bpb) < 1e-6) return bar.ToString(fmt);
+ if (sub < 1e-6 || stepBeats >= 1) return string.Format(fmt, "{0}.{1}", bar, bt);
+ int six = (int)Math.Floor(sub * 4 + 1e-6) + 1;
+ return string.Format(fmt, "{0}.{1}.{2}", bar, bt, six);
+ }
+
+ /// <summary>Seconds of a beat position at a fixed tempo, as the transport read-out counts.</summary>
+ public static double Seconds(double beat, double bpm) => bpm > 0 ? Math.Max(0, beat) * 60.0 / bpm : 0;
+ public static double BeatsAt(double seconds, double bpm) => seconds * bpm / 60.0;
+
+ /// <summary>m:ss for steps of a second or more, then m:ss.f / .ff / .fff as the step shrinks.</summary>
+ public static string Time(double seconds, double stepSeconds, IFormatProvider fmt)
+ {
+ seconds = Math.Max(0, seconds);
+ int dec = stepSeconds >= 1 - 1e-9 ? 0 : stepSeconds >= 0.1 - 1e-9 ? 1 : stepSeconds >= 0.01 - 1e-9 ? 2 : 3;
+ double scale = Math.Pow(10, dec);
+ long units = (long)Math.Round(seconds * scale, MidpointRounding.AwayFromZero); // round once, then split, so 59.9999 → 1:00
+ long whole = units / (long)scale;
+ long m = whole / 60, s = whole % 60;
+ if (dec == 0) return string.Format(fmt, "{0}:{1:00}", m, s);
+ long frac = units % (long)scale;
+ return string.Format(fmt, "{0}:{1:00}.{2}", m, s, frac.ToString(new string('0', dec), CultureInfo.InvariantCulture));
+ }
+}
+
+/// <summary>Whether the rulers read in time (true) or bars, following the transport read-out.</summary>
+internal static class RulerDisplay
+{
+ public static bool ShowTime { get; private set; }
+ public static event Action? Changed;
+
+ public static void Set(bool showTime)
+ {
+ if (showTime == ShowTime) return;
+ ShowTime = showTime;
+ Changed?.Invoke();
+ }
+}
diff --git a/src/managed/Nota.App/ClipEditor/WarpRemap.cs b/src/managed/Nota.App/ClipEditor/WarpRemap.cs
new file mode 100644
index 00000000..9e7a898c
--- /dev/null
+++ b/src/managed/Nota.App/ClipEditor/WarpRemap.cs
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Live warp-marker drag preview (#140, specs/036-clip-editor-batch). The waveform's peaks were
+// laid out by the engine under the committed markers; while a marker moves, the audio at a new
+// beat is the source frame the live markers put there, which sat at some old beat under the
+// committed ones. Drawing each column from that old beat shows the stretch before the engine has
+// rendered it. Display only — nothing reaches the engine until release.
+
+using System;
+
+namespace Nota.App;
+
+internal static class WarpRemap
+{
+ /// <summary>The committed-layout beat whose audio the live layout puts at <paramref name="newBeat"/>.
+ /// Both marker lists hold the same sources in the same order.</summary>
+ public static double OldBeatAt(
+ ReadOnlySpan<double> src, ReadOnlySpan<double> committedBeat, ReadOnlySpan<double> liveBeat, double newBeat)
+ => ClipTempo.BeatAt(src, committedBeat, ClipTempo.SrcAt(src, liveBeat, newBeat));
+
+ /// <summary>Where the live layout puts the audio that sat at <paramref name="oldBeat"/> under the
+ /// committed one (the inverse of <see cref="OldBeatAt"/>) — used to move each drawn bucket.</summary>
+ public static double NewBeatAt(
+ ReadOnlySpan<double> src, ReadOnlySpan<double> committedBeat, ReadOnlySpan<double> liveBeat, double oldBeat)
+ => ClipTempo.BeatAt(src, liveBeat, ClipTempo.SrcAt(src, committedBeat, oldBeat));
+}
diff --git a/src/managed/Nota.App/Controls/DragNumber.cs b/src/managed/Nota.App/Controls/DragNumber.cs
index 86ed254f..c3b5083b 100644
--- a/src/managed/Nota.App/Controls/DragNumber.cs
+++ b/src/managed/Nota.App/Controls/DragNumber.cs
@@ -107,6 +107,9 @@ public sealed class DragNumber : UserControl
base.OnPointerCaptureLost(e);
}
+ /// <summary>Open the type-in box, as a double-click does.</summary>
+ public void BeginEdit() { if (!_editing) BeginEditor(); }
+
private void BeginEditor()
{
_editing = true;
diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.cs
index 4d984fed..7b089a87 100644
--- a/src/managed/Nota.App/MainWindow.Commands.cs
+++ b/src/managed/Nota.App/MainWindow.Commands.cs
@@ -196,11 +196,12 @@ public partial class MainWindow
// The grid shortcuts act on the clip editor (piano roll or audio — they share one setting)
// when the detail area (docked or floating) was used last and one is open in it; otherwise
- // on the arrangement.
+ // on the arrangement. An audio editor whose current view follows no grid (ADSR, or an
+ // unwarped clip) passes them on to the arrangement, where the change can be seen (#114).
private EditorKind GridTarget()
{
bool clipOpen = (_editorRoll is { } roll && _clipEditor is not null && roll.IsEffectivelyVisible)
- || _audioEditor is { IsEffectivelyVisible: true };
+ || _audioEditor is { IsEffectivelyVisible: true, GridInert: false };
bool detailLast = _detailWasLastFocused || _detailWindow?.IsActive == true;
return clipOpen && detailLast ? EditorKind.PianoRoll : EditorKind.Arrangement;
}
@@ -218,7 +219,7 @@ public partial class MainWindow
var grids = EditorGrids.Shared;
grids.Set(kind, step(grids.Get(kind)));
var r = kind == EditorKind.Arrangement ? Timeline.SnapGridState
- : _audioEditor is { IsEffectivelyVisible: true } audio ? audio.SnapGridState
+ : _audioEditor is { IsEffectivelyVisible: true, GridInert: false } audio ? audio.SnapGridState
: _editorRoll?.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 ? "Clip editor" : "Arrangement")} grid: {label}";
diff --git a/src/managed/Nota.App/MainWindow.Detail.cs b/src/managed/Nota.App/MainWindow.Detail.cs
index 97adcab2..71e7378d 100644
--- a/src/managed/Nota.App/MainWindow.Detail.cs
+++ b/src/managed/Nota.App/MainWindow.Detail.cs
@@ -437,6 +437,13 @@ public partial class MainWindow
_audioEditor = new AudioClipEditorView(Engine, trackId, clipIndex,
TrackBrush(trackId), slot ? () => _session?.Refresh() : () => Timeline.Refresh());
_audioEditor.WarpBuildRequested = () => _ = PollWarpBuildAsync();
+ // The ruler and the playhead line move the transport (#278); a slot plays on its own clock.
+ if (!slot)
+ _audioEditor.Seek = beat =>
+ {
+ Engine.Seek(Math.Max(0, beat));
+ Timeline.SetPlayhead(Math.Max(0, beat));
+ };
_audioEditorTrackId = trackId;
_audioEditorClipIndex = clipIndex;
}
@@ -519,6 +526,7 @@ public partial class MainWindow
AuditionOn = (pitch, vel) => AuditionNoteOn(roll.AuditionTrackId > 0 ? roll.AuditionTrackId : _editorTrackId, pitch, vel),
AuditionOff = pitch => Engine.TrackNoteOff(roll.AuditionTrackId > 0 ? roll.AuditionTrackId : _editorTrackId, pitch),
ClipNameOf = (t, c) => Engine.GetClipName(t, c) is { Length: > 0 } n ? n : $"Track {t} clip",
+ Bpm = () => Engine.Bpm, // the ruler's time display (#275)
// The ruler moves the transport (#50): editor beat → arrangement beat.
Seek = local =>
{
@@ -785,6 +793,8 @@ public partial class MainWindow
CreateExpression = pts => Engine.CreateNoteExpression(pts),
AuditionOn = (pitch, vel) => AuditionNoteOn(trackId, pitch, vel),
AuditionOff = pitch => Engine.TrackNoteOff(trackId, pitch),
+ IsSessionSlot = true, // no Seek: the slot plays on its own loop clock
+ Bpm = () => Engine.Bpm,
};
double slotLen = Engine.SessionSlotLength(trackId, scene);
roll.SetTrackColor(TrackBrush(trackId));
diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.cs
index 652ab0df..8f7637da 100644
--- a/src/managed/Nota.App/MainWindow.Input.cs
+++ b/src/managed/Nota.App/MainWindow.Input.cs
@@ -157,6 +157,12 @@ public partial class MainWindow
// menu usually handles them first; de-duped against auto-repeat via _heldKeys.
// Esc: cancel an in-progress arrangement gesture, else clear the selection (req 1.2.6/2.11).
+ // Esc mid-drag of a warp marker / segment tempo in the audio clip editor drops it (#140).
+ if (!mod && e.Key == Key.Escape && _audioEditor is { IsEffectivelyVisible: true } audioEd && audioEd.CancelGesture())
+ {
+ e.Handled = true;
+ return;
+ }
if (!mod && e.Key == Key.Escape && Timeline.EscapePressed())
{
e.Handled = true;
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 7f756c10..d462e2b8 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -276,7 +276,10 @@ public partial class MainWindow : Window
else if (e.PropertyName == nameof(vm.Transport.TimeSigNumerator)) tsNum.Value = vm.Transport.TimeSigNumerator;
else if (e.PropertyName == nameof(vm.Transport.TimeSigDenominator)) tsDen.Value = vm.Transport.TimeSigDenominator;
else if (e.PropertyName == nameof(vm.Transport.KeyCode)) ShowProjectKey();
+ // Every ruler reads in the read-out's unit, bars or time (#275).
+ else if (e.PropertyName == nameof(vm.Transport.ShowTimeDisplay)) RulerDisplay.Set(vm.Transport.ShowTimeDisplay);
};
+ RulerDisplay.Set(vm.Transport.ShowTimeDisplay);
var cpuGreen = (IBrush?)NotaPalette.Success;
var cpuAmber = (IBrush?)NotaPalette.Warning;
diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.cs
index 4178d0fc..799f2ddf 100644
--- a/src/managed/Nota.App/PianoRollView.cs
+++ b/src/managed/Nota.App/PianoRollView.cs
@@ -42,6 +42,8 @@ public sealed partial class PianoRollView : UserControl
/// <summary>Moves the transport to a clip-local beat (#50): a click or drag on the ruler.
/// Null (a session slot, which runs its own clock) leaves the ruler inert.</summary>
public Action<double>? Seek { get; set; }
+ /// <summary>The roll edits a Session slot: its ruler says why it can't move the transport.</summary>
+ public bool IsSessionSlot { get; set; }
/// <summary>Starts / ends a note on the clip's own track (note audition, #46; the playable
/// keys, #47): pitch and velocity 0..1. Null leaves the roll silent. Set by the host.</summary>
public Action<int, float>? AuditionOn { get; set; }
@@ -1420,7 +1422,8 @@ public sealed partial class PianoRollView : UserControl
// Ruler label at beat b: "bar.beat", plus a 1/16 index when mid-beat (e.g. 3.2.3).
internal string GridLabel(double b)
{
- int bar = (int)Math.Floor(b / _beatsPerBar) + 1 + RulerBarOffset;
+ b += RulerOrigin;
+ 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);
@@ -1428,9 +1431,31 @@ public sealed partial class PianoRollView : UserControl
return $"{bar}.{beat}.{(int)Math.Round(frac * 4) + 1}";
}
- // Ruler bar numbers: the clip's own bars for one clip, the arrangement's when several are
- // open (their origin sits on a bar line, see ClipSet).
- private int RulerBarOffset => _set.IsMulti ? (int)Math.Round(_set.Origin / Math.Max(1, _beatsPerBar)) : 0;
+ // The ruler reads arrangement positions (#275): editor beat 0 is the open clips' origin —
+ // the clip's start for one clip, a bar line for several (see ClipSet). A Session slot has
+ // no arrangement position, so it counts from its own start.
+ private double RulerOrigin => IsSessionSlot ? 0 : _set.Origin;
+ /// <summary>The project tempo, for the ruler's time display. Set by the host.</summary>
+ public Func<double>? Bpm { get; set; }
+
+ // The playhead line can be grabbed and dragged like the ruler (#278).
+ private bool OnPlayheadLine(double x, double px)
+ => Seek is not null && _playheadBeat >= 0 && Math.Abs(x - BeatToX(_playheadBeat)) <= px;
+
+ // A ruler click or drag, or a playhead-line drag: seek to the (snapped; Alt free) beat.
+ private void SeekAtX(double x, bool free)
+ {
+ double raw = XToBeat(x);
+ double b = Math.Clamp(free ? raw : SnapBeat(raw), 0, _lengthBeats);
+ if (Math.Abs(b - _playheadBeat) < 1e-9) return;
+ Seek?.Invoke(b);
+ SetPlayhead(b, true); // immediate feedback; the transport tick keeps it in sync
+ }
+
+ private const string SlotSeekTip = "A Session slot plays on its own loop clock — launch it to play from the start";
+ private static readonly Cursor HandCursorShared = new(StandardCursorType.Hand);
+ private static readonly Cursor LineCursor = new(StandardCursorType.SizeWestEast);
+ private static readonly Cursor NoCursor = new(StandardCursorType.No);
// ---- ruler -----------------------------------------------------------
private sealed class RulerLane : Control
@@ -1444,7 +1469,15 @@ public sealed partial class PianoRollView : UserControl
protected override void OnPointerEntered(PointerEventArgs e)
{
base.OnPointerEntered(e);
- Cursor = _o.Seek is null ? Cursor.Default : new Cursor(StandardCursorType.Hand);
+ UpdateCursor(e.GetPosition(this).X);
+ }
+ // A hand over the ruler, ↔ on the playhead line; a Session slot can't seek, and says why.
+ private void UpdateCursor(double x)
+ {
+ Cursor = _o.Seek is not null ? (_o.OnPlayheadLine(x, PlayheadGrabPx) ? LineCursor : HandCursorShared)
+ : _o.IsSessionSlot ? NoCursor : Cursor.Default;
+ object? tip = _o.Seek is null && _o.IsSessionSlot ? SlotSeekTip : null;
+ if (!Equals(ToolTip.GetTip(this), tip)) ToolTip.SetTip(this, tip);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
@@ -1452,13 +1485,14 @@ public sealed partial class PianoRollView : UserControl
if (_o.Seek is null || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
_scrub = true;
e.Pointer.Capture(this);
- SeekAt(e.GetPosition(this).X);
+ SeekAt(e);
e.Handled = true;
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
- if (_scrub) SeekAt(e.GetPosition(this).X);
+ if (_scrub) SeekAt(e);
+ else UpdateCursor(e.GetPosition(this).X);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
@@ -1472,13 +1506,48 @@ public sealed partial class PianoRollView : UserControl
_scrub = false;
base.OnPointerCaptureLost(e);
}
- private void SeekAt(double x)
+ // Time display (#275): ticks at whole time steps of the arrangement, wide enough for
+ // their own label, read as m:ss[.fff] like the transport.
+ private void RenderTime(DrawingContext ctx, double h, double ppb, double viewEnd, double origin, double bpm)
+ {
+ double pxPerSec = ppb * bpm / 60.0;
+ double charW = _charW > 0 ? _charW
+ : _charW = new FormattedText("0000000000", NotaNum.Culture, FlowDirection.LeftToRight, Mono, 9, LabelText).Width / 10;
+ double stepS = RulerLabels.TimeSteps[^1];
+ foreach (var st in RulerLabels.TimeSteps)
+ {
+ int chars = st >= 1 ? 5 : st >= 0.1 ? 7 : st >= 0.01 ? 8 : 9;
+ if (st * pxPerSec >= chars * charW + 16) { stepS = st; break; }
+ }
+ double t0 = RulerLabels.Seconds(origin + _o.ScrollBeats, bpm), t1 = RulerLabels.Seconds(origin + viewEnd, bpm);
+ for (long k = (long)Math.Floor(t0 / stepS); k * stepS <= t1 + 1e-9; k++)
+ {
+ double t = k * stepS;
+ double b = RulerLabels.BeatsAt(t, bpm) - origin;
+ if (b < -1e-9) continue;
+ double x = _o.BeatToX(b);
+ ctx.DrawLine(BeatPen, new Point(x + 0.5, 0), new Point(x + 0.5, h));
+ if (b >= _o._lengthBeats - 1e-9) continue;
+ var ft = new FormattedText(RulerLabels.Time(t, stepS, NotaNum.Culture), NotaNum.Culture, FlowDirection.LeftToRight, Mono, 9, LabelText);
+ ctx.DrawText(ft, new Point(x + 4, h - 5 - ft.Height));
+ }
+ }
+ private double _charW;
+
+ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
+ {
+ base.OnAttachedToVisualTree(e);
+ RulerDisplay.Changed += InvalidateVisual;
+ }
+ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
- double b = Math.Clamp(_o.SnapBeat(_o.XToBeat(x)), 0, _o._lengthBeats);
- if (Math.Abs(b - _o._playheadBeat) < 1e-9) return;
- _o.Seek?.Invoke(b);
- _o.SetPlayhead(b, true); // immediate feedback; the transport tick keeps it in sync
+ base.OnDetachedFromVisualTree(e);
+ RulerDisplay.Changed -= InvalidateVisual;
}
+
+ private const double PlayheadGrabPx = 4;
+ private void SeekAt(PointerEventArgs e)
+ => _o.SeekAtX(e.GetPosition(this).X, (e.KeyModifiers & KeyModifiers.Alt) != 0);
// Beats only: a bar reads "3" in Ink 2, a beat "3.2" in Ink 5, set on the baseline in
// mono 9 just right of its tick. The loop is a 3px brass strip along the top.
public override void Render(DrawingContext ctx)
@@ -1495,22 +1564,28 @@ public sealed partial class PianoRollView : UserControl
double loopStart = Math.Max(0, _o.BeatToX(cs));
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 : _o._beatsPerBar;
- double startB = Math.Max(0, Math.Floor(_o.ScrollBeats / step) * step);
- for (int k = 0; ; k++)
+ double origin = _o.RulerOrigin;
+ double bpm = _o.Bpm?.Invoke() ?? 0;
+ if (RulerDisplay.ShowTime && bpm > 0) RenderTime(ctx, h, ppb, viewEnd, origin, bpm);
+ else
{
- double b = startB + k * step;
- if (b > viewEnd + 1e-9) break;
- double x = _o.BeatToX(b);
- 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 / bpb) + 1 + _o.RulerBarOffset, 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));
+ // Label every beat while there is room for "12.4", else bars only. Ticks stay on
+ // the editor's own grid; the labels read where each sits in the arrangement.
+ 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);
+ 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;
+ string label = RulerLabels.Bars(origin + b, step, bpb, NotaNum.Culture);
+ 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));
+ }
}
_o.DrawOutsideClip(ctx, w, h);
if (_o._playheadBeat >= 0)
@@ -1664,7 +1739,11 @@ public sealed partial class PianoRollView : UserControl
private sealed class NoteGrid : Control
{
private readonly PianoRollView _o;
- private enum Mode { None, Move, Resize, ResizeLeft, Marquee }
+ // PlayheadPending: pressed on the playhead line over empty space — a drag scrubs the
+ // transport (Scrub), a click without movement stays an ordinary empty-space click.
+ private enum Mode { None, Move, Resize, ResizeLeft, Marquee, PlayheadPending, Scrub }
+ private double _pressX;
+ private const double PlayheadGrabPx = 3, ScrubSlop = 3;
private Mode _drag = Mode.None;
/// <summary>A note move / resize / box selection is in progress.</summary>
internal bool Dragging => _drag != Mode.None;
@@ -1962,6 +2041,17 @@ public sealed partial class PianoRollView : UserControl
return;
}
+ // The playhead line over empty space can be dragged to scrub (#278); notes under it
+ // stay editable, and a plain click there is still an empty-space click.
+ if (hit < 0 && !shift && _o.OnPlayheadLine(p.X, PlayheadGrabPx))
+ {
+ _drag = Mode.PlayheadPending;
+ _pressX = p.X;
+ e.Pointer.Capture(this);
+ e.Handled = true;
+ return;
+ }
+
if (hit >= 0)
{
if (shift) // toggle membership, no drag
@@ -2013,6 +2103,9 @@ public sealed partial class PianoRollView : UserControl
var p = e.GetPosition(this);
_free = (e.KeyModifiers & KeyModifiers.Alt) != 0; // live, so Alt can toggle mid-drag
if (_drag == Mode.None) { UpdateHover(p); return; }
+ if (_drag == Mode.PlayheadPending && Math.Abs(p.X - _pressX) >= ScrubSlop) _drag = Mode.Scrub;
+ if (_drag == Mode.Scrub) _o.SeekAtX(p.X, _free);
+ if (_drag is Mode.PlayheadPending or Mode.Scrub) return;
_lastGrid = p;
DragUpdate(p);
EvaluateAutoScroll(p);
@@ -2118,7 +2211,8 @@ public sealed partial class PianoRollView : UserControl
private void UpdateHover(Point p)
{
int hit = HitTest(p, out int edge);
- int kind = hit < 0 ? 0 : edge != 0 ? 1 : 2; // 0 arrow, 1 resize edge, 2 move body
+ // 0 arrow, 1 resize edge (also the draggable playhead line), 2 move body
+ int kind = hit < 0 ? (_o.OnPlayheadLine(p.X, PlayheadGrabPx) ? 1 : 0) : edge != 0 ? 1 : 2;
if (kind != _cursorKind) { _cursorKind = kind; Cursor = kind == 1 ? ResizeCursor : kind == 2 ? MoveCursor : ArrowCursor; }
int hn = kind == 1 ? hit : -1; // the bright trim-edge affordance shows only on the edge
bool left = edge < 0;
@@ -2129,6 +2223,7 @@ public sealed partial class PianoRollView : UserControl
protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
{
_o.StopAudition();
+ if (_drag is Mode.PlayheadPending or Mode.Scrub) _drag = Mode.None;
base.OnPointerCaptureLost(e);
}
@@ -2147,6 +2242,12 @@ public sealed partial class PianoRollView : UserControl
var was = _drag;
_drag = Mode.None;
e.Pointer.Capture(null);
+ if (was is Mode.PlayheadPending or Mode.Scrub)
+ {
+ // A click without movement on the line: what an empty-space click does — clear the selection.
+ if (was == Mode.PlayheadPending && _o._selection.Count > 0) { _o._selection.Clear(); _o.Invalidate(); _o.Changed?.Invoke(); }
+ return;
+ }
_orig.Clear();
if ((was == Mode.Resize || was == Mode.ResizeLeft) && _dragMoved) _o.Remember(_primary);
if (was != Mode.Marquee && _dragMoved)
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index a568c3bc..b5f1f7be 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -1155,6 +1155,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("Right-click ruler", "Loop on / off · loop the selection · clear the loop region"),
("P", "Show playhead · scroll the Arrangement to it without moving it · picks up a paused Follow"),
("⌘⇧R", "Loop recording: Overdub (every pass adds) / Replace (keep the latest pass)"),
+ ("Click the position read-out", "Switch it between bars and time · every ruler follows"),
}),
("Arrangement & editing", new[]
{
@@ -1183,6 +1184,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("⌘4", "Snap to grid on / off"),
("⌘5", "Switch between the adaptive (Auto) and a fixed grid"),
("⌥ while dragging", "Move freely, ignoring the grid"),
+ ("Audio clip editor on ADSR or an unwarped clip", "⌘1–⌘5 act on the Arrangement · that view follows no grid"),
}),
("Tracks (after a click in the track headers)", new[]
{
@@ -1221,7 +1223,8 @@ public sealed partial class PreferencesWindow : NotaWindow
("Delete", "Delete the selected notes"),
("Double-click empty grid", "Add a note with the length and velocity of the last note touched · on a note, delete it"),
("Drag note edge", "Change the note's start or end"),
- ("Click · drag the ruler", "Move the playhead there · drag to scrub, snapped to the grid"),
+ ("Click · drag the ruler", "Move the playhead there · drag to scrub, snapped to the grid · ⌥ off the grid"),
+ ("Drag the playhead line", "Scrub the playhead · on the ruler or over empty grid"),
("Drag velocity stem", "Set velocity · selected notes move together · ⇧ adds a note"),
("Drag in the Bend / Pres / Slide lane", "Draw the selected note's MPE curve · ⌥ draws a straight line · drag a point to move it"),
("Double-click in an MPE lane", "Add a point · on a point, delete it · right-click to clear the curve"),
@@ -1232,6 +1235,15 @@ public sealed partial class PreferencesWindow : NotaWindow
("⌥ + pinch", "Zoom rows (trackpad)"),
("⇧F", "Fit to notes"),
}),
+ ("Audio clip editor", new[]
+ {
+ ("Click · drag the ruler", "Move the playhead there · drag to scrub · snapped to the grid on a warped clip, ⌥ off it"),
+ ("Drag the playhead line", "Scrub the playhead"),
+ ("Double-click the wave", "Add a warp marker · on a marker, delete it"),
+ ("Drag a warp marker", "Align the audio to the grid · the wave stretches as you drag"),
+ ("Esc", "While dragging a warp marker or a segment tempo: put it back"),
+ ("Drag · double-click Tempo", "Set the tempo the clip was recorded at · ÷2 / ×2 halve or double it"),
+ }),
("Play notes (computer keyboard)", new[]
{
("A S D F G H J K", "White keys, from C4"),
diff --git a/tests/Nota.SmokeTest/ClipEditorTests.cs b/tests/Nota.SmokeTest/ClipEditorTests.cs
new file mode 100644
index 00000000..51afa40d
--- /dev/null
+++ b/tests/Nota.SmokeTest/ClipEditorTests.cs
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Clip editor math (specs/036-clip-editor-batch): the audio editor's content ↔ arrangement map
+// (playhead, ruler seeks and labels), the shared ruler labels, a clip's warp tempo and the live
+// warp-drag remap. Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --clipeditor`.
+
+using System.Globalization;
+using Nota.App;
+
+namespace Nota.SmokeTest;
+
+internal static class ClipEditorTests
+{
+ private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
+ private static bool Near(double a, double b, double eps = 1e-9) => Math.Abs(a - b) <= eps;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ // ---- ClipTimeMap ------------------------------------------------------------
+ // Warped clip at beat 32, 8 beats long, full warp 8 beats, untrimmed.
+ var warped = new ClipTimeMap(32, 8, ClipContentDomain.WarpBeats, 8, 0, 8, false, false);
+ yield return (Near(warped.ArrangementBeatAtContent(0), 32), "map: warped clip start reads its arrangement beat");
+ yield return (Near(warped.ArrangementBeatAtContent(0.5), 36), "map: warped clip middle");
+ // Start bracket trimmed one bar in (4 of 12 warp beats); the clip plays 8 beats from 32.
+ var trimmed = new ClipTimeMap(32, 8, ClipContentDomain.WarpBeats, 12, 4, 12, false, false);
+ yield return (Near(trimmed.ArrangementBeatAtContent(4.0 / 12), 32), "map: trimmed Start bracket reads the clip start");
+ yield return (Near(trimmed.ArrangementBeatAtContent(0), 28), "map: audio before the Start bracket reads before the clip");
+ yield return (trimmed.PlayFracAtContent(0) < 0, "map: left of the played window is not clamped");
+ // Reversed: the content's end plays first.
+ var rev = new ClipTimeMap(0, 4, ClipContentDomain.WarpBeats, 4, 0, 4, true, false);
+ yield return (Near(rev.ArrangementBeatAtContent(1), 0) && Near(rev.ArrangementBeatAtContent(0), 4), "map: reversed clip plays its end first");
+ // Unwarped: 96 000 frames, region 24 000..72 000, plays 4 beats at 16.
+ var unwarped = new ClipTimeMap(16, 4, ClipContentDomain.SourceFrames, 96000, 24000, 72000, false, false);
+ yield return (Near(unwarped.ArrangementBeatAtContent(0.25), 16) && Near(unwarped.ArrangementBeatAtContent(0.75), 20), "map: unwarped region maps onto the clip");
+ bool roundTrip = true;
+ foreach (var m in new[] { warped, trimmed, rev, unwarped })
+ for (double c = 0; c <= 1.0001; c += 0.125)
+ {
+ roundTrip &= Near(m.ContentAtPlayFrac(m.PlayFracAtContent(c)), c, 1e-9);
+ roundTrip &= Near(m.ContentAtArrangementBeat(m.ArrangementBeatAtContent(c)), c, 1e-9);
+ }
+ yield return (roundTrip, "map: content ↔ played frac ↔ arrangement beat round-trips");
+ var empty = new ClipTimeMap(0, 4, ClipContentDomain.WarpBeats, 0, 0, 0, false, false);
+ yield return (empty.PlayFracAtContent(0.5) == 0 && !double.IsNaN(empty.ContentAtPlayFrac(0.5)), "map: an empty clip stays NaN-free");
+
+ // ---- RulerLabels --------------------------------------------------------------
+ yield return (RulerLabels.Bars(32, 4, 4, Inv) == "9", "labels: bar 9");
+ yield return (RulerLabels.Bars(33, 1, 4, Inv) == "9.2", "labels: beat 9.2");
+ yield return (RulerLabels.Bars(33.5, 0.25, 4, Inv) == "9.2.3", "labels: 16th 9.2.3");
+ yield return (RulerLabels.Bars(33.5, 1, 4, Inv) == "9.2", "labels: a beat step shows no 16ths");
+ yield return (RulerLabels.Bars(-2, 1, 4, Inv) == "1", "labels: negative positions clamp to 1");
+ yield return (RulerLabels.Time(16, 1, Inv) == "0:16", "labels: time m:ss");
+ yield return (RulerLabels.Time(75.5, 0.5, Inv) == "1:15.5", "labels: time tenths");
+ yield return (RulerLabels.Time(1.25, 0.01, Inv) == "0:01.25", "labels: time hundredths");
+ yield return (RulerLabels.Time(0.0625, 0.001, Inv) == "0:00.063", "labels: time milliseconds");
+ yield return (RulerLabels.Time(59.9996, 0.001, Inv) == "1:00.000", "labels: rounding carries into the minute");
+ yield return (Near(RulerLabels.Seconds(32, 120), 16) && Near(RulerLabels.BeatsAt(16, 120), 32), "labels: beats ↔ seconds at the tempo");
+
+ // ---- ClipTempo ----------------------------------------------------------------
+ const double sr = 48000;
+ // One segment: 2 bars (8 beats) over 4 s of audio = 120 BPM; same formula as the segment chip.
+ double[] src1 = { 0, 192000 }, beat1 = { 0, 8 };
+ double chip = (beat1[1] - beat1[0]) * sr * 60.0 / (src1[1] - src1[0]);
+ double t1 = ClipTempo.Bpm(src1, beat1, 0, 0, sr);
+ yield return (Near(t1, 120, 1e-9) && Near(t1, chip, 1e-9), "tempo: one segment equals its chip");
+ // Three segments at different tempos; scaling keeps their ratios.
+ double[] src3 = { 0, 48000, 120000, 192000 }, beat3 = { 0, 2, 5, 8 };
+ double t3 = ClipTempo.Bpm(src3, beat3, 0, 0, sr);
+ var (sb, ps, pe) = ClipTempo.Scale(beat3, 0, 0, t3, t3 * 2);
+ bool ratios = true;
+ for (int i = 1; i < beat3.Length; i++) ratios &= Near(sb[i] / beat3[i], 2, 1e-12);
+ yield return (ratios && ps == 0 && pe == 0, "tempo: scaling keeps segment ratios; play end 0 stays 0");
+ yield return (Near(ClipTempo.Bpm(src3, sb, 0, 0, sr), t3 * 2, 1e-9), "tempo: the scaled clip reads the new tempo");
+ // Trimmed window: only the played part counts, and the window scales with the beats.
+ double tTrim = ClipTempo.Bpm(src3, beat3, 2, 5, sr);
+ double seg2 = 3 * sr * 60.0 / 72000;
+ yield return (Near(tTrim, seg2, 1e-9), "tempo: a trimmed window reads its own tempo");
+ var (_, ps2, pe2) = ClipTempo.Scale(beat3, 2, 5, tTrim, tTrim / 2);
+ yield return (Near(ps2, 1) && Near(pe2, 2.5), "tempo: the trim window scales");
+ yield return (ClipTempo.Half(30) == null && ClipTempo.Double(600) == null, "tempo: ÷2 / ×2 stay in 20–999 BPM");
+ yield return (ClipTempo.Half(87) == 43.5 && ClipTempo.Double(87) == 174, "tempo: ÷2 / ×2 in range");
+ yield return (ClipTempo.Bpm(new double[] { 0 }, new double[] { 0 }, 0, 0, sr) == 0, "tempo: under two markers reads 0");
+
+ // ---- WarpRemap ----------------------------------------------------------------
+ double[] live = { 0, 2, 5, 8 };
+ bool identity = true;
+ for (double b = 0; b <= 8; b += 0.25) identity &= Near(WarpRemap.OldBeatAt(src3, beat3, live, b), b, 1e-9);
+ yield return (identity, "remap: unchanged markers are the identity");
+ double[] moved = { 0, 3, 5, 8 }; // the second marker dragged a beat later
+ bool mono = true, ends = true;
+ double prev = -1;
+ for (double b = 0; b <= 8; b += 0.125) { double o = WarpRemap.OldBeatAt(src3, beat3, moved, b); mono &= o > prev; prev = o; }
+ ends &= Near(WarpRemap.OldBeatAt(src3, beat3, moved, 0), 0) && Near(WarpRemap.OldBeatAt(src3, beat3, moved, 8), 8);
+ yield return (mono, "remap: monotone over a dragged middle marker");
+ yield return (ends, "remap: fixed end markers stay put");
+ yield return (Near(WarpRemap.OldBeatAt(src3, beat3, moved, 3), 2, 1e-9), "remap: the dragged marker shows the audio it carries");
+ bool inverse = true;
+ for (double b = 0; b <= 8; b += 0.25) inverse &= Near(WarpRemap.NewBeatAt(src3, beat3, moved, WarpRemap.OldBeatAt(src3, beat3, moved, b)), b, 1e-9);
+ yield return (inverse, "remap: NewBeatAt inverts OldBeatAt");
+ double[] stretched = { 0, 2, 5, 10 }; // the last marker dragged out
+ yield return (Near(WarpRemap.OldBeatAt(src3, beat3, stretched, 10), 8, 1e-9) && Near(WarpRemap.OldBeatAt(src3, beat3, stretched, 7.5), 6.5, 1e-9),
+ "remap: dragging the last marker stretches the last segment");
+ }
+}
diff --git a/tests/Nota.SmokeTest/Nota.SmokeTest.csproj b/tests/Nota.SmokeTest/Nota.SmokeTest.csproj
index e1bfab6e..a1b22fe5 100644
--- a/tests/Nota.SmokeTest/Nota.SmokeTest.csproj
+++ b/tests/Nota.SmokeTest/Nota.SmokeTest.csproj
@@ -47,6 +47,8 @@
<Compile Include="..\..\src\managed\Nota.App\Changelog.cs" Link="Changelog.cs" />
<!-- Typed value entry's parser / read-out search (no Avalonia inside). -->
<Compile Include="..\..\src\managed\Nota.App\Controls\ValueText.cs" Link="ValueText.cs" />
+ <!-- Clip editor position / tempo / ruler math (specs/036; no Avalonia inside). -->
+ <Compile Include="..\..\src\managed\Nota.App\ClipEditor\*.cs" LinkBase="ClipEditor" />
</ItemGroup>
</Project>
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 030d76b8..13c6f8b5 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -297,6 +297,14 @@ if (args.Length >= 1 && args[0] == "--valueentry")
Console.WriteLine(failures == 0 ? "VALUE ENTRY PASSED" : $"VALUE ENTRY FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Clip editor math alone: `--clipeditor`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--clipeditor")
+{
+ Console.WriteLine("-- clip editor --");
+ foreach (var (ok, label) in ClipEditorTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "CLIP EDITOR PASSED" : $"CLIP EDITOR FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Snap grid alone: `--grid`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--grid")
{
@@ -14959,6 +14967,10 @@ foreach (var (ok, label) in ReleaseNotesTests.Run()) Check(ok, label);
Console.WriteLine("-- typed value entry --");
foreach (var (ok, label) in ValueEntryTests.Run()) Check(ok, label);
+// --- app: clip editor position / tempo / ruler math (specs/036) ---
+Console.WriteLine("-- clip editor --");
+foreach (var (ok, label) in ClipEditorTests.Run()) Check(ok, label);
+
// --- project: content-addressed bundle (samples / plugin states named by hash) ---
Console.WriteLine("-- project: content-addressed bundle --");
foreach (var (ok, label) in BundleContentTests.Run()) Check(ok, label);