Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Redesign of session view
Egor Khindikaynend30fbed0bce7
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 00000000..9c618ba7--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,75 @@+name: Bug report+description: Something doesn't work, sounds wrong, or crashes.+labels: [bug]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for taking the time to report this — every report gets read.+ Can't get Nota to open at all? See [First launch](https://github.com/nota-daw/nota#first-launch) first.+ - type: textarea+ id: what+ attributes:+ label: What happened?+ description: What you saw or heard, and what you expected instead.+ placeholder: When I drag a VST3 onto a MIDI track, the device card stays empty and nothing plays.+ validations:+ required: true+ - type: textarea+ id: steps+ attributes:+ label: Steps to reproduce+ description: The shorter the better. Attaching a small `.nota` project that shows the problem helps a lot.+ placeholder: |+ 1. New project+ 2. Add a MIDI track+ 3. Drag Surge XT from the browser onto it+ 4. ...+ validations:+ required: true+ - type: input+ id: version+ attributes:+ label: Nota version+ description: Nota → About Nota (or the file name you downloaded).+ placeholder: 0.43.1+ validations:+ required: true+ - type: dropdown+ id: os+ attributes:+ label: Operating system+ options:+ - macOS — Apple Silicon+ - macOS — Intel+ - Windows — x64+ - Windows — ARM+ - Linux — x86_64+ - Linux — ARM+ validations:+ required: true+ - type: input+ id: os-version+ attributes:+ label: OS version+ placeholder: macOS 15.3 / Windows 11 24H2 / Ubuntu 24.04+ - type: input+ id: audio+ attributes:+ label: Audio interface and plugins involved (if any)+ placeholder: Focusrite Scarlett 2i2 · Surge XT 1.3.4 (VST3)+ - type: textarea+ id: logs+ attributes:+ label: Log+ description: |+ If Nota crashed or misbehaved, attach today's log file from:+ - **macOS:** `~/Library/Application Support/Nota/logs/`+ - **Windows:** `%APPDATA%\Nota\logs\`+ - **Linux:** `~/.config/nota/logs/`+ placeholder: Drag the file here, or paste the last lines.+ - type: textarea+ id: extra+ attributes:+ label: Anything else?+ description: Screenshots, screen recordings, audio examples.diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 00000000..67ce61db--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,8 @@+blank_issues_enabled: true+contact_links:+ - name: Nota won't open on macOS / Windows+ url: https://github.com/nota-daw/nota#first-launch+ about: Nota isn't signed with a paid certificate yet — here's how to open it the first time.+ - name: Add a plugin to the one-click Downloads list+ url: https://github.com/nota-daw/nota-plugins-registry+ about: Plugin requests and additions go to the plugin registry.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 00000000..be14c5a1--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,39 @@+name: Feature request+description: An idea for something Nota should do, or do better.+labels: [enhancement]+body:+ - type: textarea+ id: problem+ attributes:+ label: What are you trying to do?+ description: Describe the music-making situation, not the solution yet — it helps find the best fix.+ placeholder: I record vocals in several takes and want to pick the best parts of each without cutting clips by hand.+ validations:+ required: true+ - type: textarea+ id: idea+ attributes:+ label: What would help?+ description: How you imagine it working. Mentioning how another DAW does it is welcome.+ validations:+ required: true+ - type: dropdown+ id: area+ attributes:+ label: Area+ options:+ - Arrangement / Session / editing+ - Piano roll / MIDI+ - Audio / recording / warp+ - Built-in instruments and effects+ - Plugins (VST3 / AU)+ - Mixer / routing / automation+ - Browser / samples / presets+ - Export+ - Nota Remote (phone)+ - Other+ - type: textarea+ id: extra+ attributes:+ label: Anything else?+ description: Sketches, screenshots, links.diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4f70aaa5..4bd0a5d5 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -216,6 +216,21 @@ jobs:if [ ! -s RELEASE_NOTES.md ]; thenecho "See CHANGELOG.md for details." > RELEASE_NOTES.mdfi+ cat >> RELEASE_NOTES.md <<'EOF'++ ---++ ### Install++ | System | File |+ |---|---|+ | macOS, Apple Silicon | `Nota-*-arm64.dmg` |+ | macOS, Intel | `Nota-*-x86_64.dmg` |+ | Windows | `Nota-Setup-*-x64.exe` (`-arm64` for Windows on ARM) |+ | Linux | `Nota-*-x86_64.AppImage` (`-aarch64` for ARM) |++ **First launch:** Nota isn't signed with a paid certificate yet. On **macOS**, if it says Apple could not verify Nota, open **System Settings → Privacy & Security** and click **Open Anyway** — [step-by-step guide](https://github.com/nota-daw/nota#opening-nota-on-macos). On **Windows**, click **More info → Run anyway** in SmartScreen.+ EOFecho "----- release notes -----"; cat RELEASE_NOTES.md- name: Download all build artifactsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 98632c6d..8dd5b864 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,8 +36,27 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.the players' names. **USB works too:** a phone on a cable (USB tethering on Android,Internet Sharing on the Mac) gets an instant, radio-free link — Nota notices the cable,puts its address in the QR and marks the phone "USB" in the list.+- **Session View, rebuilt for real work.** Columns carry the track's name and colour; clips+ have a name, a colour, a note or waveform preview and a length in bars, and their progress+ pie runs on the clip's own clock. Clicking a cell selects it, its triangle launches it, and+ an inspector on the right edits the selected clip, scene or empty slot. Clips get launch+ modes (Trigger, Gate, Toggle, Repeat), their own launch quantize, legato, one-shot (loop+ off), velocity amount and **follow actions** A/B with chances and a time (Next, Again,+ Previous, First, Last, Any, Other, Stop, Jump), with a global **Follow** switch. Scenes have+ names, colours, a tempo and time signature that apply as they launch, and can follow on to+ the next scene after a number of bars. Edit the grid from the keyboard (arrows, Return, ⌘C /+ ⌘X / ⌘V, ⌘D, ⌘I, F2, Delete) or by dragging clips between slots (⌥ copies) and scenes up and+ down the rail; insert, duplicate, capture and move scenes without stopping what plays.+ **Session Rec** records into the armed track at the selected scene — open-ended takes are cut+ to whole bars, or set a **Fixed** length of 1–8 bars. Group tracks show as one launchable+ column that folds its tracks away; returns and the master close the row; the mixer under the+ grid has I/O, Sends and Mixer sections to show or hide. An empty slot's stop button can be+ removed so a scene keeps that track playing, and the **ARR** badge hands one track back to the+ Arrangement. All of it is saved with the project and reachable over MCP.### Changed+- **Import audio** moved to ⌘⇧I — ⌘I now inserts a scene in the Session view. Launch+ quantize lives in the Session toolbar instead of the transport bar.- **A cleaner main window.** The project's name now leads the transport bar. In thearrangement, tracks inside a group step their colour stripe in under it, so nesting readsat a glance; the Overview strip is slimmer and calmer (a thin line per track, a neutraldiff --git a/DESIGN.md b/DESIGN.mdindex 8117821c..344060ee 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -399,7 +399,7 @@ filterable knob grid (and the sidechain source when it has a bus). Rhythm movedsignature, grid · the switches (metronome, follow, snap, automation) — then, pinned right,MIDI, CPU and master. Buttons are 28, Play 40; Play is raised at rest and solid brass onlywhile the transport runs. There is no add-track button — tracks come from the browser.- Launch quantize appears only in Session. Transport buttons are not focusable, so+ Launch quantize lives in the Session toolbar, not here. Transport buttons are not focusable, soSpace / R / L / Return always reach the window.- **Body** — the browser on the left and the canvas float as panels on `Gutter` with 12 pxgaps; the canvas is always sunken relative to panels. The splitter is a transparent grabdiff --git a/FEATURES.md b/FEATURES.mdindex 30dddc87..201ca090 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -97,9 +97,15 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).and the name prints only at the head of each run so a repeated pattern reads as oneblock. View ▸ Clip names cycles every clip / first of a run / none; a clip named byhand always shows its name.-- **Session View** — a clip grid (tracks × scenes): launch and stop a clip, launch a whole- scene, launch quantization, recording into a clip slot (MIDI or audio), loop clips with- a configurable length, and moving material between Session and Arrangement.+- **Session View** — a clip grid (tracks × scenes) with an inspector: named, coloured clips+ with note / waveform previews and a progress pie on the clip's own clock; selection apart+ from launching, keyboard editing (arrows, Return, ⌘C/X/V, ⌘D, ⌘I, F2, Delete) and drag+ between slots; launch modes (Trigger / Gate / Toggle / Repeat), per-clip quantize, legato,+ one-shot, velocity amount and follow actions with a global switch; scenes with names,+ colours, tempo / signature and scene follow, inserted, duplicated, captured and reordered+ without stopping playback; Session Rec with fixed length; group columns that fold;+ returns + master; I/O · Sends · Mixer sections; removable stop buttons; per-track+ Back to Arrangement; and moving material between Session and Arrangement.- **Modular View** — a signal-graph editor for the track's chain, on its own island: MIDI FX → instrument →effects shown as nodes you can expand, bypass, duplicate, delete and reorder right on thecanvas (node positions are saved with the project), plus a **Global view** that shows@@ -865,9 +871,12 @@ Coverage:and split.- **Automation**: create a lane, read and write points.- **MIDI effects** and engine status.-- **Session**: the clip launcher (grid snapshot, create a MIDI or audio slot, read and- write slot notes, loop length, launch and stop a slot or scene, launch quantization,- slot recording, slot ↔ arrangement).+- **Session**: the clip launcher (grid snapshot with clip and scene properties, create, copy,+ move and clear slots, read and write slot notes, loop length, clip name / colour / launch+ mode / quantize / legato / loop / follow actions, scene name / colour / tempo / signature /+ follow, insert / duplicate / capture / move / delete scenes, stop buttons, launch and+ release a slot, launch and stop a scene, launch quantization, the follow switch, slot and+ scene recording with a fixed length, back to arrangement, slot ↔ arrangement).- **Racks** (Instrument/Drum): chain snapshot, add and remove a chain and change itsinstrument, parameters, mix (gain/pan/mute/solo), key and velocity zones, trigger note,8 macros and their mappings, rack volume and glide; for the Drum Rack, per-paddiff --git a/README.md b/README.mdindex 3b861a9b..9cf21eca 100644--- a/README.md+++ b/README.md@@ -109,22 +109,55 @@ Download the file for your system from theNota isn't signed with a paid Apple or Microsoft certificate yet, so the system asks you toconfirm the first time:-- **macOS** — open the `.dmg` and drag Nota to Applications. If macOS says it "can't verify"- Nota, open **System Settings → Privacy & Security**, scroll down and click- **Open Anyway**. (Or, in Terminal: `xattr -dr com.apple.quarantine /Applications/Nota.app`.)+- **macOS** — see [Opening Nota on macOS](#opening-nota-on-macos) below.- **Windows** — if SmartScreen shows "Windows protected your PC", click **More info →Run anyway**.- **Linux** — make the AppImage executable (`chmod +x Nota-*.AppImage`, or Properties →Permissions in your file manager) and run it.+### Opening Nota on macOS++1. Open the downloaded `.dmg` and drag **Nota** into **Applications**.+2. Open Nota from Applications. The first time, macOS stops it with+ *"Nota" Not Opened — Apple could not verify "Nota" is free of malware…*+ (older macOS: *"Nota" can't be opened because Apple cannot check it for malicious+ software*). Click **Done** — not *Move to Trash*.+3. Open **System Settings → Privacy & Security** and scroll down to **Security**. You'll see+ *"Nota" was blocked to protect your Mac*. Click **Open Anyway**, confirm with your+ password or Touch ID, then click **Open Anyway** once more.++That's it — from now on Nota opens like any other app.++<details>+<summary>Still won't open, or macOS says Nota "is damaged"?</summary>++That message is the same check with scarier wording — the download isn't actually broken.+Open **Terminal** (Applications → Utilities) and run:++```bash+xattr -dr com.apple.quarantine /Applications/Nota.app+```++This removes the "downloaded from the internet" mark from Nota only. Then open Nota+normally.++On **macOS 13–14** there's also a shortcut for step 3: in Finder, **right-click** (or+Control-click) Nota in Applications → **Open** → **Open**.+</details>++Why the extra step? Signing an app so macOS trusts it right away needs a paid Apple+developer certificate, which Nota doesn't have yet. Nota is open source and built in public by+GitHub Actions from the code in this repository.+Nota checks for updates itself and shows what's new after each update.## StatusNota is young and moving fast — new releases come out every week or so (see the[changelog](CHANGELOG.md)). It's already used to make real music, but expect rough edges.-Found a bug or missing something? [Open an issue](https://github.com/nota-daw/nota/issues) —-every report gets read.+Found a bug or missing something? [Open an issue](https://github.com/nota-daw/nota/issues/new/choose) —+every report gets read. Want to help with code? Start with a+[good first issue](https://github.com/nota-daw/nota/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22).## For plugin developersdiff --git a/src/managed/Nota.App/Controls/DragNumber.cs b/src/managed/Nota.App/Controls/DragNumber.csindex 7a9ff7db..1b41e42f 100644--- a/src/managed/Nota.App/Controls/DragNumber.cs+++ b/src/managed/Nota.App/Controls/DragNumber.cs@@ -26,6 +26,9 @@ public sealed class DragNumber : UserControlprivate double _startY, _startValue;public event Action<double>? ValueChanged;+ /// <summary>A drag starts / ends — callers bracket an undo group or automation write.</summary>+ public event Action? GestureBegin;+ public event Action? GestureEnd;public DragNumber(double value, double min, double max, double step, string format = "0", double fontSize = 12){@@ -67,6 +70,7 @@ public sealed class DragNumber : UserControl_startY = e.GetPosition(this).Y;_startValue = _value;e.Pointer.Capture(this);+ GestureBegin?.Invoke();e.Handled = true;}@@ -81,6 +85,7 @@ public sealed class DragNumber : UserControlprotected override void OnPointerReleased(PointerReleasedEventArgs e){+ if (_drag) GestureEnd?.Invoke();_drag = false;e.Pointer.Capture(null);}diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.csindex d5138a69..1703c35e 100644--- a/src/managed/Nota.App/MainWindow.Input.cs+++ b/src/managed/Nota.App/MainWindow.Input.cs@@ -50,11 +50,17 @@ public partial class MainWindow}else if (e.Key == Key.Return){- _vm.Transport.StopCommand.Execute(null); // stop; second press returns to 1.1+ // In the Session grid Return launches the selected slot or scene (design 1a);+ // everywhere else it stops (second press returns to 1.1).+ if (SessionFocused) _session!.LaunchSelection();+ else _vm.Transport.StopCommand.Execute(null);e.Handled = true;}}+ // The Session grid has the keyboard: its arrows / Return / ⌘C… act on its selection.+ private bool SessionFocused => _session is { IsVisible: true, IsKeyboardFocusWithin: true };+// Route a floating detail window's key presses through the same handling. Undo/redo are// handled explicitly here because their native-menu accelerators only target the main// window (on macOS AppKit usually consumes them first, so this is a cross-platformdiff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.csindex b931c288..07f59c21 100644--- a/src/managed/Nota.App/MainWindow.Menu.cs+++ b/src/managed/Nota.App/MainWindow.Menu.cs@@ -66,10 +66,18 @@ public partial class MainWindow}private void OnMenuImport(object? sender, EventArgs e) => _ = DoImportAsync();+ private void OnMenuInsertScene(object? sender, EventArgs e)+ {+ if (_vm is null || _session is null) return;+ if (!_session.IsVisible) { _vm.StatusText = "Scenes live in the Session view."; return; }+ _session.InsertSceneAtSelection();+ }private void OnMenuExport(object? sender, EventArgs e) => _ = DoExportAsync();private void OnMenuDuplicate(object? sender, EventArgs e){if (_vm is null) return;+ // The Session grid duplicates its selected clip or scene.+ if (SessionFocused && _session!.DuplicateSelection()) return;// While the piano roll has focus, Cmd+D duplicates the selected notes; otherwise// it duplicates the selected arrangement clip.if (_editorRoll is { GridFocused: true } roll && roll.DuplicateSelection())@@ -123,6 +131,7 @@ public partial class MainWindowprivate void OnMenuCopy(object? sender, EventArgs e){if (_vm is null) return;+ if (SessionFocused && _session!.CopySelection()) return;if (_trackHeadersFocused && Timeline.CopySelectedTracks()) { _vm.StatusText = "Copied track(s)"; return; }if (ActiveRoll() is { } roll && roll.CopySelection()) { _vm.StatusText = "Copied notes"; return; }if (Timeline.CopySelectedClip()) _vm.StatusText = "Copied clip";@@ -130,6 +139,7 @@ public partial class MainWindowprivate void OnMenuCut(object? sender, EventArgs e){if (_vm is null) return;+ if (SessionFocused && _session!.CutSelection()) return;if (_trackHeadersFocused && Timeline.CutSelectedTracks()) { _vm.StatusText = "Cut track(s)"; return; }if (ActiveRoll() is { } roll && roll.CutSelection()) { _vm.StatusText = "Cut notes"; return; }if (Timeline.CutSelectedClip()) { _session?.Refresh(); _vm.StatusText = "Cut clip"; }@@ -137,6 +147,7 @@ public partial class MainWindowprivate void OnMenuPaste(object? sender, EventArgs e){if (_vm is null) return;+ if (SessionFocused && _session!.PasteSelection()) return;if (_trackHeadersFocused && Timeline.PasteTracks()) { _vm.StatusText = "Pasted track(s)"; return; }if (ActiveRoll() is { } roll && roll.PasteClipboard()) { _vm.StatusText = "Pasted notes"; return; }if (Timeline.PasteClipboard()) { _session?.Refresh(); _vm.StatusText = "Pasted clip"; }@@ -144,6 +155,7 @@ public partial class MainWindowprivate void OnMenuDeleteSel(object? sender, EventArgs e){if (_vm is null) return;+ if (SessionFocused && _session!.DeleteSelection()) return;if (_trackHeadersFocused && Timeline.DeleteSelectedTracks()) { _vm.StatusText = "Deleted track(s)"; return; }if (ActiveRoll() is { } roll && roll.DeleteSelection()) { _vm.StatusText = "Deleted notes"; return; }if (Timeline.DeleteSelectedClips()) { _session?.Refresh(); _vm.StatusText = "Deleted clip(s)"; }diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axamlindex 57ccdd27..3bf05430 100644--- a/src/managed/Nota.App/MainWindow.axaml+++ b/src/managed/Nota.App/MainWindow.axaml@@ -27,7 +27,7 @@<NativeMenuItem Header="Save As…" Click="OnMenuSaveAs" Gesture="Shift+Cmd+S"/><NativeMenuItem Header="Save Version with Note…" Click="OnMenuSaveVersion" Gesture="Alt+Cmd+S"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Import audio…" Click="OnMenuImport" Gesture="Cmd+I"/>+ <NativeMenuItem Header="Import audio…" Click="OnMenuImport" Gesture="Shift+Cmd+I"/><NativeMenuItem Header="Export audio…" Click="OnMenuExport" Gesture="Shift+Cmd+E"/><NativeMenuItemSeparator/><NativeMenuItem Header="Settings…" Click="OnPreferences" Gesture="Ctrl+,"/>@@ -41,6 +41,7 @@<NativeMenuItem Header="Redo" Click="OnMenuRedo" Gesture="Shift+Cmd+Z"/><NativeMenuItemSeparator/><NativeMenuItem Header="Duplicate clip" Click="OnMenuDuplicate" Gesture="Cmd+D"/>+ <NativeMenuItem Header="Insert scene" Click="OnMenuInsertScene" Gesture="Cmd+I"/><NativeMenuItem Header="Split at playhead" Click="OnMenuSplit" Gesture="Cmd+E"/><NativeMenuItem Header="Consolidate" Click="OnMenuConsolidate" Gesture="Cmd+J"/><NativeMenuItemSeparator/>@@ -217,15 +218,6 @@<TextBlock Classes="CellLabel" Text="GRID" HorizontalAlignment="Center"/></StackPanel></Button>- <!-- Launch quantize — a Session concept, so it only appears there -->- <Button x:Name="LaunchQChip" Classes="cell" Click="OnCycleLaunchQ" IsVisible="False"- ToolTip.Tip="Set when Session slots and scenes launch">- <StackPanel Spacing="2">- <TextBlock x:Name="LaunchQLabel" Classes="Mono" Text="1 Bar" FontSize="14" LineHeight="16"- MinWidth="44" TextAlignment="Center" HorizontalAlignment="Center" Foreground="{DynamicResource Brush.TextPrimary}"/>- <TextBlock Classes="CellLabel" Text="LAUNCH" HorizontalAlignment="Center"/>- </StackPanel>- </Button></StackPanel><!-- Switches. Each draws the thing it does, so the row carries no prose: adiff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 66ea77cc..c3a60177 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -251,6 +251,7 @@ public partial class MainWindow : WindowTimeline.RefreshAutomationLive(); // show writes live (M9-C)SyncReenableAutomation(); // "a control is overriding its lane"if (_session?.IsVisible == true) _session.UpdateStates(); // live launch/queue/play+ SyncSceneTempo(); // a launched scene set tempo / signatureif (_mixer?.IsVisible == true) _mixer.UpdateMeters(); // Mixer tab stripsif (_modular?.IsVisible == true) _modular.Tick(vm.Engine.IsPlaying); // graph knobs follow automation + edge pulseif (DetailBody.Content is MixerView mx && mx.IsEffectivelyVisible) mx.UpdateMeters(); // 1f strips@@ -318,10 +319,19 @@ public partial class MainWindow : WindowTimeline.ClipGeometryChanged += OnClipGeometryChanged; // clip trimmed/moved → follow it in the open editorTimeline.StatusMessage += msg => { if (_vm is not null) _vm.StatusText = msg; }; // automation-follow hints etc.- _session = new SessionView(vm.Engine) { IsVisible = false };+ _session = new SessionView(vm.Engine)+ {+ IsVisible = false,+ GetMasterVolume = () => (float)vm.Transport.MasterVolume,+ SetMasterVolume = v => vm.Transport.MasterVolume = v,+ GetTempo = () => ((double)vm.Transport.Bpm, vm.Transport.TimeSigNumerator, vm.Transport.TimeSigDenominator),+ };_session.SlotEditRequested += OpenSessionClipEditor;_session.ItemDropped += OnSessionDrop; // browser drag & drop (M7-5)_session.ArrangementChanged += () => Timeline.Refresh(); // M5-6+ _session.Status += msg => vm.StatusText = msg;+ // Selecting a slot selects its track everywhere: devices below, arrangement header.+ _session.SlotSelected += (trackId, _) => Timeline.Select(trackId, -1);Timeline.SessionChanged += () => _session?.Refresh(); // M5-6MainContent.Children.Add(_session);@@ -395,6 +405,7 @@ public partial class MainWindow : Window{Timeline.Refresh();if (_deviceChain is { } dc && dc.TrackId > 0) dc.Refresh();+ if (_session?.IsVisible == true) _session.Refresh(); // session tools edit slots + scenes};_ = App.Services.GetRequiredService<McpService>().ApplyAsync();@@ -515,7 +526,6 @@ public partial class MainWindow : WindowSessionBtn.IsChecked = session;ModularBtn.IsChecked = modular;PlayBtn.Classes.Set("session", session); // play button turns green in Session (1c)- LaunchQChip.IsVisible = session; // launch quantize only applies to Session launchesif (session) _session.Refresh();if (modular){@@ -557,19 +567,13 @@ public partial class MainWindow : WindowSnapLabel.Text = label;}- // Session launch-quantize steps (beats, label). 0 = launch immediately (no quantize).- private static readonly (double beats, string label)[] LaunchQSteps =- {- (0.0, "None"), (0.25, "1/16"), (0.5, "1/8"), (1.0, "1/4"), (2.0, "1/2"),- (4.0, "1 Bar"), (8.0, "2 Bars"), (16.0, "4 Bars"),- };- private int _launchQIndex = 5; // 1 Bar — matches the engine default (launchQuant_ = 4)- private void OnCycleLaunchQ(object? sender, RoutedEventArgs e)+ // A launched scene may carry its own tempo / signature; the engine applies it on the+ // scene's start boundary and the transport follows here.+ private void SyncSceneTempo(){- _launchQIndex = (_launchQIndex + 1) % LaunchQSteps.Length;- var (beats, label) = LaunchQSteps[_launchQIndex];- Engine.SetLaunchQuant(beats);- LaunchQLabel.Text = label;+ if (_vm is null || !Engine.TakeSceneTempoChange(out double bpm, out int num, out int den)) return;+ if (bpm > 0) _vm.Transport.Bpm = (decimal)Math.Round(bpm, 2);+ if (num > 0 && den > 0) { _vm.Transport.TimeSigNumerator = num; _vm.Transport.TimeSigDenominator = den; }}// Snap a dragged denominator to the nearest musical power of two (1/2/4/8/16).diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex d54957f7..ee64b21a 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -950,12 +950,12 @@ public sealed partial class PreferencesWindow : NotaWindow("⌘N ⌘O", "New project / open a project"),("⌘S ⌘⇧S", "Save (records a version) / save as"),("⌥⌘S", "Save a version with a note"),- ("⌘I ⌘⇧E", "Import audio / export audio"),+ ("⌘⇧I ⌘⇧E", "Import audio / export audio"),}),("TRANSPORT", new[]{("Space", "Play / Stop"),- ("Return", "Stop (again → back to the start)"),+ ("Return", "Stop (again → back to the start) · in the Session grid it launches the selection"),("⌘R", "Record"),("⌘M", "Metronome"),("⌘L", "Loop on / off · loop the selected clips or time range"),@@ -984,6 +984,20 @@ public sealed partial class PreferencesWindow : NotaWindow("⌘D", "Duplicate the selected tracks"),("Delete", "Delete the selected tracks · a group goes with its tracks"),}),+ ("SESSION (AFTER A CLICK IN THE GRID)", new[]+ {+ ("← → ↑ ↓", "Move the selection between slots and scenes"),+ ("Return", "Launch the selected clip or scene"),+ ("⌘C ⌘X ⌘V", "Copy / cut / paste a clip · a cut clip moves when pasted"),+ ("⌘D", "Duplicate a clip into the slot below · a scene below itself"),+ ("⌘I", "Insert a scene below the selection"),+ ("F2", "Rename the selected clip or scene"),+ ("Delete", "Delete the selected clip or scene"),+ ("Drag clip", "Move it to another slot · ⌥ copies"),+ ("Drag scene", "Reorder scenes"),+ ("Double-click slot", "Edit the clip · an empty MIDI slot gets a new clip"),+ ("Double-click header", "Rename the track"),+ }),("PIANO ROLL", new[]{("← →", "Move notes by the grid"),diff --git a/src/managed/Nota.App/SessionView.Grid.cs b/src/managed/Nota.App/SessionView.Grid.csnew file mode 100644index 00000000..755d34d0--- /dev/null+++ b/src/managed/Nota.App/SessionView.Grid.cs@@ -0,0 +1,872 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Session view — the grid: the scene rail, column headers, and the custom-drawn cells+// (clip slot, group slot, scene). Cells paint straight from engine state at the UI clock;+// only previews (notes / peaks), names and colours are cached per Refresh.++using System;+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;++namespace Nota.App;++public sealed partial class SessionView+{+ private const double TopRowH = 24; // launch triangle + name + length+ private const double StopRowH = 24;+ private const double SpacerH = 22;++ private readonly HashSet<int> _armed = new();+ private int _recTrack, _recScene = -1;+ private double _recElapsed;++ // Clip drag between slots: the cell the pointer is over while a clip is dragged.+ private (int TrackId, int Scene)? _dragTarget;++ private void ReadRecordTarget()+ {+ if (_engine.TryGetSessionRecordTarget(out int t, out int s, out double el)) { _recTrack = t; _recScene = s; _recElapsed = el; }+ else { _recTrack = 0; _recScene = -1; _recElapsed = 0; }+ }++ // ---- scene rail ---------------------------------------------------------------++ private void AddSceneRail()+ {+ _headerRow.Children.Add(new Border+ {+ Width = SceneRailW, Height = HeaderH, Padding = new Thickness(10, 0),+ Child = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center,+ Children =+ {+ Text("SCENES", 9, NotaPalette.TextTertiary, FontWeight.Bold),+ Mono(_sceneCount.ToString(CultureInfo.CurrentCulture), 9, NotaPalette.TextDisabled),+ },+ },+ });++ var mid = new StackPanel { Width = SceneRailW, Spacing = Gap };+ for (int s = 0; s < _sceneCount; s++)+ {+ var cell = new SceneCell(this, s);+ _sceneCells.Add(cell);+ mid.Children.Add(cell);+ }+ _cellsRow.Children.Add(mid);++ var addScene = new Button { Content = "+ Scene", Classes = { "ghost" }, Height = SpacerH, FontSize = 10, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Center, Padding = new Thickness(0) };+ ToolTip.SetTip(addScene, "Add a scene at the end");+ addScene.Click += (_, _) => { int s = _engine.InsertScene(_engine.SceneCount); Refresh(); if (s >= 0) Select(new Selection(SelKind.Scene, 0, s)); };++ var stopAll = new Button+ {+ Height = StopRowH, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Center, Padding = new Thickness(0),+ Content = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 7,+ Children = { new Glyph(GlyphKind.Stop, 7), new TextBlock { Text = "Stop All Clips", FontSize = 10, FontWeight = FontWeight.SemiBold } },+ },+ };+ ToolTip.SetTip(stopAll, "Stop every session clip");+ stopAll.Click += (_, _) => { _engine.StopAllSession(); UpdateStates(); };++ var foot = new StackPanel { Width = SceneRailW, Spacing = Gap, Children = { addScene, stopAll } };+ foot.Children.Add(MixerRailLabels());+ _footerRow.Children.Add(foot);+ }++ // ---- columns ------------------------------------------------------------------++ private void AddColumn(Column c)+ {+ c.Header = new ColumnHeader(this, c);+ _headerRow.Children.Add(c.Header);++ var mid = new StackPanel { Width = c.Width, Spacing = Gap };+ for (int s = 0; s < _sceneCount; s++)+ {+ Control cell = c.Kind switch+ {+ ColKind.Track => new SlotCell(this, c, s),+ ColKind.Group => new GroupCell(this, c, s),+ _ => new BlankCell(c.Width),+ };+ c.Cells.Add(cell);+ mid.Children.Add(cell);+ }+ _cellsRow.Children.Add(mid);++ var foot = new StackPanel { Width = c.Width, Spacing = Gap };+ foot.Children.Add(new Border { Height = SpacerH });+ if (c.Kind is ColKind.Track or ColKind.Group)+ {+ var stop = new Button { Height = StopRowH, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Center, Padding = new Thickness(0), Content = new Glyph(GlyphKind.Stop, 7) };+ ToolTip.SetTip(stop, c.Kind == ColKind.Group ? "Stop every track in this group" : "Stop this track");+ stop.Click += (_, _) => { StopColumn(c); UpdateStates(); };+ foot.Children.Add(stop);+ }+ else foot.Children.Add(new Border { Height = StopRowH });+ c.Mixer = BuildMixer(c);+ foot.Children.Add(c.Mixer.Root);+ _footerRow.Children.Add(foot);+ }++ // ---- small builders -----------------------------------------------------------++ private static TextBlock Text(string text, double size, IBrush ink, FontWeight? weight = null)+ => new() { Text = text, FontSize = size, Foreground = ink, FontWeight = weight ?? FontWeight.Normal, VerticalAlignment = VerticalAlignment.Center };++ private static TextBlock Mono(string text, double size, IBrush ink)+ {+ var t = new TextBlock { Text = text, FontSize = size, Foreground = ink, VerticalAlignment = VerticalAlignment.Center };+ t.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ return t;+ }++ private static FormattedText Ft(string text, Typeface face, double size, IBrush ink, double maxWidth = double.PositiveInfinity)+ {+ var ft = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, face, size, ink);+ if (!double.IsInfinity(maxWidth)) { ft.MaxTextWidth = Math.Max(1, maxWidth); ft.MaxLineCount = 1; ft.Trimming = TextTrimming.CharacterEllipsis; }+ return ft;+ }++ private static readonly IPen SelPen = new Pen(NotaPalette.Accent, 1);+ private static readonly IPen PlayheadPen = new Pen(NotaPalette.TextPrimary, 1);++ // The almanac's play triangle, drawn in a w×h box centred on c.+ private static void DrawTriangle(DrawingContext ctx, Point c, double w, double h, IBrush fill)+ {+ var g = new StreamGeometry();+ using (var gc = g.Open())+ {+ gc.BeginFigure(new Point(c.X - w / 2, c.Y - h / 2), true);+ gc.LineTo(new Point(c.X + w / 2, c.Y));+ gc.LineTo(new Point(c.X - w / 2, c.Y + h / 2));+ gc.EndFigure(true);+ }+ ctx.DrawGeometry(fill, null, g);+ }++ // Progress pie: a dim disc with the played fraction filled clockwise from 12 o'clock.+ private static void DrawPie(DrawingContext ctx, Point c, double r, double frac)+ {+ ctx.DrawEllipse(NotaPalette.Wash(NotaPalette.Success, 0x33), null, c, r, r);+ frac = Math.Clamp(frac, 0, 1);+ if (frac <= 0.001) return;+ if (frac >= 0.999) { ctx.DrawEllipse(NotaPalette.Success, null, c, r, r); return; }+ double a = frac * Math.PI * 2;+ var end = new Point(c.X + r * Math.Sin(a), c.Y - r * Math.Cos(a));+ var g = new StreamGeometry();+ using (var gc = g.Open())+ {+ gc.BeginFigure(c, true);+ gc.LineTo(new Point(c.X, c.Y - r));+ gc.ArcTo(end, new Size(r, r), 0, frac > 0.5, SweepDirection.Clockwise);+ gc.EndFigure(true);+ }+ ctx.DrawGeometry(NotaPalette.Success, null, g);+ }++ private static void DrawSelection(DrawingContext ctx, Rect r)+ => ctx.DrawRectangle(null, SelPen, new Rect(r.X - 1.5, r.Y - 1.5, r.Width + 3, r.Height + 3).Normalize(), NotaRadius.TileValue - 1, NotaRadius.TileValue - 1);++ private static void FillCell(DrawingContext ctx, Rect r, IBrush bg, IBrush? border)+ {+ ctx.DrawRectangle(bg, border is null ? null : new Pen(border, 1), r.Deflate(0.5), NotaRadius.BadgeValue, NotaRadius.BadgeValue);+ }++ /// <summary>The track slot under a point in this view's coordinates (clip drag target).</summary>+ private (Column Col, int Scene)? SlotAt(Point p)+ {+ foreach (var c in LaunchCols)+ for (int s = 0; s < c.Cells.Count; s++)+ if (this.TranslatePoint(p, c.Cells[s]) is { } q && new Rect(c.Cells[s].Bounds.Size).Contains(q)) return (c, s);+ return null;+ }++ private void PromptText(Control anchor, string current, Action<string> commit)+ {+ var box = new TextBox { Text = current, Width = 180, FontSize = 12, Classes = { "field" } };+ var flyout = new Flyout { Content = box, Placement = Avalonia.Controls.PlacementMode.Pointer };+ box.KeyDown += (_, ke) =>+ {+ if (ke.Key == Key.Enter) { commit((box.Text ?? "").Trim()); flyout.Hide(); ke.Handled = true; }+ else if (ke.Key == Key.Escape) { flyout.Hide(); ke.Handled = true; }+ };+ flyout.ShowAt(anchor);+ Avalonia.Threading.Dispatcher.UIThread.Post(() => { box.SelectAll(); box.Focus(); }, Avalonia.Threading.DispatcherPriority.Input);+ }++ // ---- column header -------------------------------------------------------------++ private sealed class ColumnHeader : Border+ {+ private readonly SessionView _o;+ private readonly Column _c;+ private readonly Border? _arr;++ public ColumnHeader(SessionView o, Column c)+ {+ _o = o; _c = c;+ Width = c.Width; Height = HeaderH;+ CornerRadius = NotaRadius.Badge;+ BorderThickness = new Thickness(1);+ ClipToBounds = true;++ var stripe = new Border { Height = 3, VerticalAlignment = VerticalAlignment.Top, Background = c.Kind == ColKind.Master ? NotaPalette.Accent : c.Brush };+ var name = new TextBlock+ {+ Text = c.Name, FontSize = 12, FontWeight = FontWeight.SemiBold, TextTrimming = TextTrimming.CharacterEllipsis,+ Foreground = c.Kind == ColKind.Return ? NotaPalette.TextSecondary : NotaPalette.TextPrimary, VerticalAlignment = VerticalAlignment.Center,+ };+ var top = new DockPanel { LastChildFill = true };+ if (c.Kind == ColKind.Group)+ {+ bool folded = o._collapsed.Contains(c.TrackId);+ var chevron = new Border+ {+ Width = 14, Height = 14, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new Glyph(folded ? GlyphKind.ChevronRight : GlyphKind.ChevronDown, 8) { Foreground = NotaPalette.TextSecondary },+ Margin = new Thickness(0, 0, 4, 0),+ };+ ToolTip.SetTip(chevron, folded ? "Show the group's tracks" : "Fold the group into one column");+ chevron.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ if (!o._collapsed.Add(c.TrackId)) o._collapsed.Remove(c.TrackId);+ o.Refresh();+ };+ DockPanel.SetDock(chevron, Dock.Left);+ top.Children.Add(chevron);+ }+ if (c.Kind == ColKind.Track)+ {+ var arrText = new TextBlock { Text = "ARR", FontSize = 8, FontWeight = FontWeight.Medium, Foreground = NotaPalette.Accent };+ arrText.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ _arr = new Border+ {+ BorderBrush = NotaPalette.AccentDim, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Clip,+ Padding = new Thickness(3, 0), Margin = new Thickness(4, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center,+ Cursor = new Cursor(StandardCursorType.Hand), Child = arrText, IsVisible = false,+ };+ ToolTip.SetTip(_arr, "Back to Arrangement for this track");+ _arr.PointerPressed += (_, e) => { e.Handled = true; o._engine.TrackBackToArrangement(c.TrackId); o.UpdateStates(); };+ DockPanel.SetDock(_arr, Dock.Right);+ top.Children.Add(_arr);+ }+ top.Children.Add(name);++ var kind = new TextBlock { Text = c.KindLabel, FontSize = 8, FontWeight = FontWeight.Medium, Foreground = NotaPalette.TextDisabled, TextTrimming = TextTrimming.CharacterEllipsis };+ kind.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ var stack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 3, 8, 0), Children = { top, kind } };+ Child = new Panel { Children = { stripe, stack } };++ if (c.Kind is ColKind.Track or ColKind.Group)+ PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2)+ {+ o.PromptText(this, o._engine.GetTrackName(c.TrackId), t =>+ {+ o._engine.SetTrackName(c.TrackId, t);+ o.Refresh();+ o.ArrangementChanged?.Invoke(); // the arrangement header shows the same name+ });+ return;+ }+ o.Select(new Selection(SelKind.Slot, c.TrackId, o._sel.Scene));+ };+ Sync();+ }++ public void Sync()+ {+ bool sel = _o._sel.Kind == SelKind.Slot && _o._sel.TrackId == _c.TrackId && _c.Kind is ColKind.Track or ColKind.Group;+ Background = sel ? NotaPalette.SelHeaderBg : _c.Kind is ColKind.Return or ColKind.Master ? NotaPalette.Panel : NotaPalette.SurfaceCard;+ BorderBrush = sel ? NotaPalette.AccentDim : Brushes.Transparent;+ if (_arr is not null) _arr.IsVisible = _o._engine.SessionPlayingSlot(_c.TrackId) >= 0;+ }+ }++ // ---- cells ----------------------------------------------------------------------++ /// <summary>A cell polled at the UI clock: repaints itself only when its look changed.</summary>+ private interface ILiveCell { void Tick(); }++ private sealed class BlankCell : Control+ {+ public BlankCell(double w) { Width = w; Height = CellH; }+ public override void Render(DrawingContext ctx) => FillCell(ctx, new Rect(Bounds.Size), NotaPalette.SurfaceDeep, null);+ }++ /// <summary>A track's clip slot: empty (stop / record affordance), a clip, or a take+ /// being recorded.</summary>+ private sealed class SlotCell : Control, ILiveCell+ {+ private readonly SessionView _o;+ private readonly Column _c;+ private readonly int _scene;+ private readonly bool _filled;+ private readonly string _name = "";+ private readonly string _len = "";+ private readonly double _lenBeats;+ private readonly SolidColorBrush _brush;+ private readonly bool _stopButton;+ private readonly List<(double Start, double Len, int Pitch)> _notes = new();+ private int _minPitch, _maxPitch;+ private readonly float[]? _peaks;+ private int _peakCount;+ private bool _dropHover, _hoverLaunch, _hoverCentre;+ private Point _pressAt;+ private bool _pressed, _dragging, _launched;++ public SlotCell(SessionView o, Column c, int scene)+ {+ _o = o; _c = c; _scene = scene;+ Width = c.Width; Height = CellH;+ var eng = o._engine;+ _filled = eng.SessionSlotState(c.TrackId, scene) != 0;+ _brush = _filled ? o.ClipBrush(c, scene) : c.Brush;+ _stopButton = eng.GetSessionSlotStopButton(c.TrackId, scene);+ if (_filled)+ {+ _name = o.ClipName(c, scene);+ _lenBeats = eng.SessionSlotLength(c.TrackId, scene);+ _len = FormatLength(_lenBeats);+ if (c.IsInstrument)+ {+ foreach (var n in eng.GetSessionNotes(c.TrackId, scene))+ _notes.Add((n.StartBeat, n.LengthBeats, n.Pitch));+ if (_notes.Count > 0) { _minPitch = _notes.Min(n => n.Pitch); _maxPitch = _notes.Max(n => n.Pitch); }+ }+ else+ {+ _peaks = new float[44 * 2];+ _peakCount = eng.GetSessionSlotPeaks(c.TrackId, scene, _peaks, 44);+ }+ }++ DragDrop.SetAllowDrop(this, true);+ DragDrop.AddDragOverHandler(this, (_, e) => e.DragEffects = BrowserView.IsAcceptableDrag(e) ? DragDropEffects.Copy : DragDropEffects.None);+ DragDrop.AddDragEnterHandler(this, (_, e) => { if (BrowserView.IsAcceptableDrag(e)) { _dropHover = true; InvalidateVisual(); } });+ DragDrop.AddDragLeaveHandler(this, (_, _) => { _dropHover = false; InvalidateVisual(); });+ DragDrop.AddDropHandler(this, (_, e) =>+ {+ _dropHover = false; InvalidateVisual();+ var items = BrowserView.DroppedItems(e);+ if (items.Count > 0) { _o.RaiseDrop(items[0], c.TrackId, scene, c.IsInstrument); e.Handled = true; }+ });+ }++ private static readonly Rect LaunchZone = new(3, 3, 18, 18);+ private Rect CentreZone => new(Bounds.Width / 2 - 8, Bounds.Height / 2 - 8, 16, 16);+ private bool Recording => _o._recTrack == _c.TrackId && _o._recScene == _scene;+ private int _lastState = -1;+ private bool _lastArmed, _lastDrag;++ public void Tick()+ {+ int st = Recording ? 4 : _o._engine.SessionSlotState(_c.TrackId, _scene);+ bool armed = _o._armed.Contains(_c.TrackId);+ bool drag = _o._dragTarget == (_c.TrackId, _scene);+ bool animating = st is 2 or 3 or 4; // blink, progress, elapsed+ if (st == _lastState && armed == _lastArmed && drag == _lastDrag && !animating) return;+ _lastState = st; _lastArmed = armed; _lastDrag = drag;+ InvalidateVisual();+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ var p = e.GetPosition(this);+ bool hl = LaunchZone.Contains(p), hc = CentreZone.Contains(p);+ if (hl != _hoverLaunch || hc != _hoverCentre) { _hoverLaunch = hl; _hoverCentre = hc; InvalidateVisual(); }+ Cursor = (_filled || Recording) && hl || !_filled && hc ? new Cursor(StandardCursorType.Hand) : Cursor.Default;++ if (_pressed && _filled && !_dragging && Math.Abs(p.X - _pressAt.X) + Math.Abs(p.Y - _pressAt.Y) > 5) _dragging = true;+ if (_dragging)+ {+ Cursor = new Cursor(StandardCursorType.DragMove);+ var hit = _o.SlotAt(e.GetPosition(_o));+ var t = hit is { } h && (h.Col.TrackId, h.Scene) != (_c.TrackId, _scene) ? (h.Col.TrackId, h.Scene) : ((int, int)?)null;+ if (t != _o._dragTarget) { _o._dragTarget = t; _o.UpdateStates(); }+ }+ }++ protected override void OnPointerExited(PointerEventArgs e)+ {+ if (_hoverLaunch || _hoverCentre) { _hoverLaunch = _hoverCentre = false; InvalidateVisual(); }+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ var pt = e.GetCurrentPoint(this);+ var p = pt.Position;+ if (pt.Properties.IsRightButtonPressed)+ {+ _o.Select(new Selection(SelKind.Slot, _c.TrackId, _scene));+ _o.ShowSlotMenu(this, _c, _scene);+ e.Handled = true;+ return;+ }+ if (!pt.Properties.IsLeftButtonPressed) return;+ e.Handled = true;++ if (Recording && LaunchZone.Contains(p)) { _o._engine.StopSessionRecord(); _o.Refresh(); return; }+ if (_filled && LaunchZone.Contains(p))+ {+ _o._engine.LaunchSlotVelocity(_c.TrackId, _scene, 1f);+ _launched = true;+ e.Pointer.Capture(this); // a Gate / Repeat clip stops when the button lets go+ _o.UpdateStates();+ return;+ }+ if (!_filled && !Recording && CentreZone.Contains(p))+ {+ if (_o._armed.Contains(_c.TrackId)) { _o._engine.RecordSessionSlot(_c.TrackId, _scene); _o.Refresh(); }+ else if (_stopButton) { _o._engine.StopSlot(_c.TrackId); _o.UpdateStates(); }+ return;+ }++ _o.Select(new Selection(SelKind.Slot, _c.TrackId, _scene));+ if (e.ClickCount == 2)+ {+ if (_filled) _o.SlotEditRequested?.Invoke(_c.TrackId, _scene);+ else if (_c.IsInstrument) { _o.InsertMidiClip(_c.TrackId, _scene); _o.SlotEditRequested?.Invoke(_c.TrackId, _scene); }+ return;+ }+ _pressed = true; _pressAt = p;+ e.Pointer.Capture(this);+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ if (_launched) { _launched = false; _o._engine.ReleaseSlot(_c.TrackId, _scene); }+ bool wasDragging = _dragging;+ _pressed = _dragging = false;+ e.Pointer.Capture(null);+ if (wasDragging && _o._dragTarget is { } t)+ {+ bool copy = (e.KeyModifiers & KeyModifiers.Alt) != 0; // Alt+drag copies+ _o._dragTarget = null;+ if (_o.MoveOrCopySlot(_c.TrackId, _scene, t.TrackId, t.Scene, move: !copy))+ {+ _o.Select(new Selection(SelKind.Slot, t.TrackId, t.Scene));+ _o.Say(copy ? "Copied clip" : "Moved clip");+ }+ else _o.Say("Drop a MIDI clip on a MIDI track, audio on audio.");+ return;+ }+ if (_o._dragTarget is not null) { _o._dragTarget = null; _o.UpdateStates(); }+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ var eng = _o._engine;+ bool selected = _o._sel.Kind == SelKind.Slot && _o._sel.TrackId == _c.TrackId && _o._sel.Scene == _scene;+ bool dropTarget = _dropHover || _o._dragTarget == (_c.TrackId, _scene);++ if (Recording) { RenderRecording(ctx, r); if (selected) DrawSelection(ctx, r); return; }++ if (!_filled)+ {+ FillCell(ctx, r, NotaPalette.SurfaceCard, dropTarget ? NotaPalette.Accent : null);+ var c = r.Center;+ if (_o._armed.Contains(_c.TrackId))+ ctx.DrawEllipse(null, new Pen(_hoverCentre ? NotaPalette.Record : NotaPalette.TextMuted, 1.5), c, 3.25, 3.25);+ else if (_stopButton)+ ctx.DrawRectangle(_hoverCentre ? NotaPalette.TextSecondary : NotaPalette.BorderStrong, null, new Rect(c.X - 3, c.Y - 3, 6, 6), 1, 1);+ if (selected) DrawSelection(ctx, r);+ return;+ }++ int state = eng.SessionSlotState(_c.TrackId, _scene);+ bool playing = state == 3, queued = state == 2;+ bool leaving = playing && QueuedElsewhere(); // another slot on this track is about to take over+ double pos = playing ? eng.SessionSlotPosition(_c.TrackId) : 0;+ double frac = playing && _lenBeats > 0 ? pos / _lenBeats : 0;++ IBrush bg = NotaPalette.Wash(_brush, playing ? (byte)0x40 : (byte)0x24);+ IBrush border = dropTarget ? NotaPalette.Accent+ : playing ? NotaPalette.Success+ : queued ? (_o._blinkOn ? NotaPalette.Warning : NotaPalette.Wash(NotaPalette.Warning, 0x66))+ : NotaPalette.Wash(_brush, 0x55);+ FillCell(ctx, r, bg, border);++ // Launch: a triangle (queued blinks between full and dim Caution), or the+ // progress pie while the clip plays.+ var lc = LaunchZone.Center;+ bool blinkDim = (queued || leaving) && !_o._blinkOn;+ if (_hoverLaunch) ctx.DrawRectangle(NotaPalette.Wash(NotaPalette.TextPrimary, 0x14), null, LaunchZone, NotaRadius.ClipValue, NotaRadius.ClipValue);+ if (playing && !leaving) DrawPie(ctx, lc, 5.5, frac);+ else+ {+ IBrush tri = queued ? (blinkDim ? NotaPalette.Wash(NotaPalette.Warning, 0x66) : NotaPalette.Warning)+ : playing ? (blinkDim ? NotaPalette.Wash(NotaPalette.Success, 0x66) : NotaPalette.Success)+ : _hoverLaunch ? NotaPalette.TextPrimary : NotaPalette.TextSecondary;+ DrawTriangle(ctx, lc, 8, 9, tri);+ }++ var lenFt = Ft(_len, NotaFonts.Mono, 9, playing ? NotaPalette.TextStrong : NotaPalette.TextMuted);+ double lenX = r.Width - 6 - lenFt.Width;+ ctx.DrawText(lenFt, new Point(lenX, (TopRowH - lenFt.Height) / 2));+ var nameFt = Ft(_name, NotaFonts.SansMedium, 11, NotaPalette.TextPrimary, lenX - 27 - 4);+ ctx.DrawText(nameFt, new Point(27, (TopRowH - nameFt.Height) / 2));++ var area = new Rect(7, 25, r.Width - 14, r.Height - 31);+ DrawPreview(ctx, area);+ if (playing)+ {+ double x = area.X + Math.Clamp(frac, 0, 1) * area.Width;+ ctx.DrawLine(PlayheadPen, new Point(Math.Round(x) + 0.5, area.Y - 2), new Point(Math.Round(x) + 0.5, area.Bottom + 2));+ }+ if (selected) DrawSelection(ctx, r);+ }++ private bool QueuedElsewhere()+ {+ for (int s = 0; s < _o._sceneCount; s++)+ if (s != _scene && _o._engine.SessionSlotState(_c.TrackId, s) == 2) return true;+ return false;+ }++ private void DrawPreview(DrawingContext ctx, Rect area)+ {+ if (_c.IsInstrument)+ {+ if (_notes.Count == 0 || _lenBeats <= 0) return;+ int range = Math.Max(1, _maxPitch - _minPitch);+ foreach (var n in _notes)+ {+ if (n.Start >= _lenBeats) continue;+ double x = area.X + n.Start / _lenBeats * area.Width;+ double w = Math.Max(1.5, Math.Min(n.Len, _lenBeats - n.Start) / _lenBeats * area.Width);+ double y = area.Y + (_maxPitch - n.Pitch) / (double)range * (area.Height - 3);+ ctx.DrawRectangle(_brush, null, new Rect(x, y, w, 3), 1, 1);+ }+ return;+ }+ DrawPeaks(ctx, area, _peaks, _peakCount, _brush);+ }++ private void RenderRecording(DrawingContext ctx, Rect r)+ {+ bool waiting = _o._recElapsed <= 0;+ FillCell(ctx, r, NotaPalette.Wash(NotaPalette.Record, 0x33), NotaPalette.Record);+ var lc = LaunchZone.Center;+ ctx.DrawEllipse(waiting && !_o._blinkOn ? NotaPalette.Wash(NotaPalette.Record, 0x66) : NotaPalette.Record, null, lc, 4.5, 4.5);+ var lenFt = Ft(FormatDuration(_o._recElapsed), NotaFonts.Mono, 9, NotaPalette.DangerBright);+ double lenX = r.Width - 6 - lenFt.Width;+ ctx.DrawText(lenFt, new Point(lenX, (TopRowH - lenFt.Height) / 2));+ var nameFt = Ft(waiting ? "Rec in…" : "Recording", NotaFonts.SansMedium, 11, NotaPalette.TextHeading, lenX - 31);+ ctx.DrawText(nameFt, new Point(27, (TopRowH - nameFt.Height) / 2));+ if (!_c.IsInstrument)+ {+ var buf = new float[44 * 2];+ int n = _o._engine.AudioRecordPeaks(buf, 44);+ DrawPeaks(ctx, new Rect(7, 25, r.Width - 14, r.Height - 31), buf, n, NotaPalette.DangerBright);+ }+ }+ }++ // Waveform preview: one bar per peak bucket, centred, scaled to the loudest bucket.+ private static void DrawPeaks(DrawingContext ctx, Rect area, float[]? peaks, int count, IBrush ink)+ {+ if (peaks is null || count <= 0) return;+ float max = 1e-6f;+ for (int i = 0; i < count; i++) max = Math.Max(max, Math.Max(Math.Abs(peaks[i * 2]), Math.Abs(peaks[i * 2 + 1])));+ double step = area.Width / count, bw = Math.Max(1, step * 0.62);+ for (int i = 0; i < count; i++)+ {+ double a = Math.Max(Math.Abs(peaks[i * 2]), Math.Abs(peaks[i * 2 + 1])) / max;+ double h = Math.Max(1, a * area.Height);+ ctx.DrawRectangle(ink, null, new Rect(area.X + i * step, area.Y + (area.Height - h) / 2, bw, h), 0.5, 0.5);+ }+ }++ /// <summary>A group's slot: launches every child slot in the scene; shows how many+ /// children hold a clip there and one bar per child.</summary>+ private sealed class GroupCell : Control, ILiveCell+ {+ private readonly SessionView _o;+ private readonly Column _g;+ private readonly int _scene;+ private readonly List<(int Id, bool Has, SolidColorBrush Brush)> _kids = new();+ private bool _hoverLaunch;++ public GroupCell(SessionView o, Column g, int scene)+ {+ _o = o; _g = g; _scene = scene;+ Width = g.Width; Height = CellH;+ foreach (int id in g.Children)+ _kids.Add((id, o._engine.SessionSlotState(id, scene) != 0, ArrangementView.TrackBrush(ArrangementView.EffectiveColorIndex(o._engine, id))));+ }++ private static readonly Rect LaunchZone = new(3, 3, 18, 18);+ private bool Any => _kids.Any(k => k.Has);+ private int _lastSig = -1;++ public void Tick()+ {+ int sig = 0;+ foreach (var k in _kids) sig = sig * 5 + (k.Has ? _o._engine.SessionSlotState(k.Id, _scene) : 0);+ if (sig == _lastSig) return;+ _lastSig = sig;+ InvalidateVisual();+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ bool h = Any && LaunchZone.Contains(e.GetPosition(this));+ if (h != _hoverLaunch) { _hoverLaunch = h; Cursor = h ? new Cursor(StandardCursorType.Hand) : Cursor.Default; InvalidateVisual(); }+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ var pt = e.GetCurrentPoint(this);+ if (!pt.Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ var p = pt.Position;+ if (Any && LaunchZone.Contains(p)) { _o.LaunchGroup(_g, _scene); _o.UpdateStates(); return; }+ if (!Any && new Rect(Bounds.Width / 2 - 8, Bounds.Height / 2 - 8, 16, 16).Contains(p)) { _o.StopColumn(_g); _o.UpdateStates(); return; }+ _o.Select(new Selection(SelKind.Slot, _g.TrackId, _scene));+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ bool selected = _o._sel.Kind == SelKind.Slot && _o._sel.TrackId == _g.TrackId && _o._sel.Scene == _scene;+ if (!Any)+ {+ FillCell(ctx, r, NotaPalette.SurfaceCard, null);+ ctx.DrawRectangle(NotaPalette.BorderStrong, null, new Rect(r.Center.X - 3, r.Center.Y - 3, 6, 6), 1, 1);+ if (selected) DrawSelection(ctx, r);+ return;+ }+ var eng = _o._engine;+ bool playingAny = _kids.Any(k => k.Has && eng.SessionSlotState(k.Id, _scene) == 3);+ FillCell(ctx, r, NotaPalette.Wash(_g.Brush, playingAny ? (byte)0x2E : (byte)0x17), playingAny ? NotaPalette.Wash(NotaPalette.Success, 0x80) : null);+ DrawTriangle(ctx, LaunchZone.Center, 8, 9, playingAny ? NotaPalette.Success : _hoverLaunch ? NotaPalette.TextPrimary : NotaPalette.TextSecondary);+ var label = Ft($"{_kids.Count(k => k.Has)} of {_kids.Count}", NotaFonts.Sans, 10, NotaPalette.TextSecondary);+ ctx.DrawText(label, new Point(27, (TopRowH - label.Height) / 2));++ double y = r.Height - 7 - 3;+ for (int i = _kids.Count - 1; i >= 0 && y > TopRowH; i--, y -= 6)+ {+ var k = _kids[i];+ IBrush ink = !k.Has ? NotaPalette.BorderDefault : eng.SessionSlotState(k.Id, _scene) == 3 ? NotaPalette.Success : k.Brush;+ ctx.DrawRectangle(ink, null, new Rect(7, y, r.Width - 14, 3), 1, 1);+ }+ if (selected) DrawSelection(ctx, r);+ }+ }++ /// <summary>A scene row in the rail: launch box, colour, name, index, tempo / signature.</summary>+ private int? _sceneDragTarget;++ private int SceneAt(Point p)+ {+ for (int s = 0; s < _sceneCells.Count; s++)+ if (this.TranslatePoint(p, _sceneCells[s]) is { } q && q.Y >= -Gap && q.Y < _sceneCells[s].Bounds.Height) return s;+ return p.Y < 0 ? 0 : _sceneCells.Count - 1;+ }++ private sealed class SceneCell : Control+ {+ private readonly SessionView _o;+ private readonly int _scene;+ private readonly string _name;+ private readonly bool _named;+ private readonly IBrush _color;+ private readonly string _badge;+ private bool _hoverLaunch;++ public SceneCell(SessionView o, int scene)+ {+ _o = o; _scene = scene;+ Width = SceneRailW; Height = CellH;+ string n = o._engine.GetSceneName(scene);+ _named = n.Length > 0;+ _name = _named ? n : $"Scene {scene + 1}";+ o._engine.TryGetSceneProps(scene, out var p);+ _color = p.Color >= 0 ? ArrangementView.TrackBrush(p.Color) : NotaPalette.BorderStrong;+ var parts = new List<string>();+ if (p.Tempo > 0) parts.Add(NotaNum.Str(p.Tempo, "0.##"));+ if (p.SigNum > 0 && p.SigDen > 0) parts.Add($"{p.SigNum}/{p.SigDen}");+ _badge = string.Join(" · ", parts);+ }++ private static readonly Rect LaunchBox = new(8, (CellH - 22) / 2, 22, 22);+ private int _lastSig = -1;+ private bool _pressed, _dragging;+ private Point _pressAt;++ public void Tick()+ {+ int sig = 0;+ bool queued = false;+ foreach (var c in _o.LaunchCols)+ {+ int st = _o._engine.SessionSlotState(c.TrackId, _scene);+ if (st == 2) queued = true;+ sig = unchecked(sig * 7 + st);+ }+ if (_o._sceneDragTarget == _scene) sig ^= 0x5A5A;+ if (sig == _lastSig && !queued) return;+ _lastSig = sig;+ InvalidateVisual();+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ var p = e.GetPosition(this);+ bool h = LaunchBox.Contains(p);+ if (h != _hoverLaunch) { _hoverLaunch = h; Cursor = h ? new Cursor(StandardCursorType.Hand) : Cursor.Default; InvalidateVisual(); }+ // Drag a scene up or down the rail to reorder it.+ if (_pressed && !_dragging && Math.Abs(p.Y - _pressAt.Y) > 5) _dragging = true;+ if (_dragging)+ {+ Cursor = new Cursor(StandardCursorType.SizeNorthSouth);+ int t = _o.SceneAt(e.GetPosition(_o));+ int? target = t == _scene ? null : t;+ if (target != _o._sceneDragTarget) { _o._sceneDragTarget = target; _o.InvalidateAll(); }+ }+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ bool wasDragging = _dragging;+ _pressed = _dragging = false;+ e.Pointer.Capture(null);+ if (_o._sceneDragTarget is { } to && wasDragging)+ {+ _o._sceneDragTarget = null;+ if (_o._engine.MoveScene(_scene, to)) { _o.Refresh(); _o.Select(new Selection(SelKind.Scene, 0, to)); _o.Say("Moved scene"); }+ return;+ }+ if (_o._sceneDragTarget is not null) { _o._sceneDragTarget = null; _o.InvalidateAll(); }+ }++ protected override void OnPointerExited(PointerEventArgs e) { if (_hoverLaunch) { _hoverLaunch = false; InvalidateVisual(); } }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ var pt = e.GetCurrentPoint(this);+ if (pt.Properties.IsRightButtonPressed)+ {+ _o.Select(new Selection(SelKind.Scene, 0, _scene));+ _o.ShowSceneMenu(this, _scene);+ e.Handled = true;+ return;+ }+ if (!pt.Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ if (LaunchBox.Contains(pt.Position)) { _o.LaunchSceneRow(_scene); _o.UpdateStates(); return; }+ _o.Select(new Selection(SelKind.Scene, 0, _scene));+ if (e.ClickCount == 2) { _o.PromptText(this, _named ? _name : "", t => { _o._engine.SetSceneName(_scene, t); _o.RefreshScene(_scene); }); return; }+ _pressed = true; _pressAt = pt.Position;+ e.Pointer.Capture(this);+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ var eng = _o._engine;+ bool playing = false, all = true, queued = false, any = false;+ foreach (var c in _o.LaunchCols)+ {+ int st = eng.SessionSlotState(c.TrackId, _scene);+ if (st == 0) continue;+ any = true;+ if (st == 3) playing = true; else all = false;+ if (st == 2) queued = true;+ }+ bool selected = _o._sel.Kind == SelKind.Scene && _o._sel.Scene == _scene;+ bool rowSel = _o._sel.Kind == SelKind.Slot && _o._sel.Scene == _scene;+ IBrush? edge = _o._sceneDragTarget == _scene ? NotaPalette.Accent : any && playing && all ? NotaPalette.Wash(NotaPalette.Success, 0x66) : null;+ FillCell(ctx, r, rowSel ? NotaPalette.SurfaceRaised : NotaPalette.SurfaceCard, edge);++ ctx.DrawRectangle(_hoverLaunch ? NotaPalette.SurfaceHover : NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), LaunchBox.Deflate(0.5), NotaRadius.BadgeValue, NotaRadius.BadgeValue);+ IBrush tri = queued ? (_o._blinkOn ? NotaPalette.Warning : NotaPalette.Wash(NotaPalette.Warning, 0x66)) : playing ? NotaPalette.Success : NotaPalette.TextSecondary;+ DrawTriangle(ctx, LaunchBox.Center, 8, 9, tri);++ double x = LaunchBox.Right + 8;+ ctx.DrawRectangle(_color, null, new Rect(x, r.Height / 2 - 3, 6, 6), 1, 1);+ x += 14;+ double right = r.Width - 8;+ if (_badge.Length > 0)+ {+ var b = Ft(_badge, NotaFonts.Mono, 9, NotaPalette.TextSecondary);+ var box = new Rect(right - b.Width - 8, r.Height / 2 - 8, b.Width + 8, 16);+ ctx.DrawRectangle(null, new Pen(NotaPalette.BorderDefault, 1), box.Deflate(0.5), NotaRadius.BadgeValue, NotaRadius.BadgeValue);+ ctx.DrawText(b, new Point(box.X + 4, box.Y + (16 - b.Height) / 2));+ right = box.X - 6;+ }+ var idx = Ft((_scene + 1).ToString("00", CultureInfo.CurrentCulture), NotaFonts.Mono, 9, NotaPalette.TextDisabled);+ var name = Ft(_name, NotaFonts.SansSemiBold, 12, _named ? NotaPalette.TextPrimary : NotaPalette.TextTertiary, Math.Max(10, right - x - idx.Width - 6));+ ctx.DrawText(name, new Point(x, (r.Height - name.Height) / 2));+ ctx.DrawText(idx, new Point(x + name.Width + 6, (r.Height - name.Height) / 2 + (name.Baseline - idx.Baseline)));+ if (selected) DrawSelection(ctx, r);+ }+ }++ // ---- context menus -------------------------------------------------------------------++ private void ShowSlotMenu(Control anchor, Column c, int scene)+ {+ bool filled = SlotFilled(c.TrackId, scene);+ var f = new MenuFlyout();+ if (filled)+ {+ f.Items.Add(MenuKit.Item("Launch", GlyphKind.Play, () => _engine.LaunchSlot(c.TrackId, scene)));+ f.Items.Add(MenuKit.Item("Edit", GlyphKind.Edit, () => SlotEditRequested?.Invoke(c.TrackId, scene)));+ f.Items.Add(MenuKit.Item("Rename…", GlyphKind.Edit, () => RenameSelection(), new KeyGesture(Key.F2)));+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Item("Copy", GlyphKind.Copy, () => CopySelection(), MenuKit.CopyKey));+ f.Items.Add(MenuKit.Item("Cut", GlyphKind.Cut, () => CutSelection(), MenuKit.CutKey));+ }+ f.Items.Add(MenuKit.Item("Paste", GlyphKind.Paste, () => PasteSelection(), MenuKit.PasteKey, _clip is not null));+ if (filled)+ {+ f.Items.Add(MenuKit.Item("Duplicate", GlyphKind.Duplicate, () => DuplicateSelection(), MenuKit.DuplicateKey));+ f.Items.Add(MenuKit.Item("Copy to arrangement (at playhead)", GlyphKind.Arrow, () => ToArrangement(c.TrackId, scene)));+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Item("Delete", GlyphKind.Trash, () => DeleteSelection(), MenuKit.DeleteKey));+ }+ else+ {+ f.Items.Add(new Separator());+ if (c.IsInstrument) f.Items.Add(MenuKit.Item("Insert MIDI clip", GlyphKind.Plus, () => InsertMidiClip(c.TrackId, scene)));+ f.Items.Add(MenuKit.Item("Record here", GlyphKind.Record, () => { _engine.RecordSessionSlot(c.TrackId, scene); Refresh(); }));+ bool stop = _engine.GetSessionSlotStopButton(c.TrackId, scene);+ f.Items.Add(MenuKit.Item(stop ? "Remove stop button" : "Add stop button", GlyphKind.Stop, () => { _engine.SetSessionSlotStopButton(c.TrackId, scene, !stop); RefreshSlot(c.TrackId, scene); }));+ }+ f.ShowAt(anchor, showAtPointer: true);+ }++ private void ShowSceneMenu(Control anchor, int scene)+ {+ var f = new MenuFlyout();+ f.Items.Add(MenuKit.Item("Launch scene", GlyphKind.Play, () => LaunchSceneRow(scene)));+ f.Items.Add(MenuKit.Item("Stop scene", GlyphKind.Stop, () => _engine.StopScene(scene)));+ f.Items.Add(MenuKit.Item("Rename…", GlyphKind.Edit, () => RenameSelection(), new KeyGesture(Key.F2)));+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Item("Insert scene below", GlyphKind.Plus, () => InsertSceneAtSelection(), MenuKit.Cmd(Key.I)));+ f.Items.Add(MenuKit.Item("Duplicate scene", GlyphKind.Duplicate, () => DuplicateSelection(), MenuKit.DuplicateKey));+ f.Items.Add(MenuKit.Item("Capture playing clips below", GlyphKind.Copy, CaptureScene));+ f.Items.Add(new Separator());+ f.Items.Add(MenuKit.Item("Delete scene", GlyphKind.Trash, () => DeleteSelection(), MenuKit.DeleteKey, _sceneCount > 1));+ f.ShowAt(anchor, showAtPointer: true);+ }+}diff --git a/src/managed/Nota.App/SessionView.Inspector.cs b/src/managed/Nota.App/SessionView.Inspector.csnew file mode 100644index 00000000..f7548e3e--- /dev/null+++ b/src/managed/Nota.App/SessionView.Inspector.cs@@ -0,0 +1,487 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Session view — the inspector: properties of the selected clip (length, loop, launch mode,+// quantize, legato, velocity, follow actions, colour), scene (tempo, signature, follow,+// colour) or empty slot (stop button). Every edit goes straight to the engine, so it is one+// undo step and shows on the grid at once.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;++namespace Nota.App;++public sealed partial class SessionView+{+ private static readonly string[] ModeLabels = { "Trigger", "Gate", "Toggle", "Repeat" };+ private static readonly (SessionFollowAction Action, string Label)[] FollowActions =+ {+ (SessionFollowAction.None, "None"), (SessionFollowAction.Next, "Next"), (SessionFollowAction.Again, "Again"),+ (SessionFollowAction.Previous, "Previous"), (SessionFollowAction.First, "First"), (SessionFollowAction.Last, "Last"),+ (SessionFollowAction.Any, "Any"), (SessionFollowAction.Other, "Other"), (SessionFollowAction.Stop, "Stop"),+ (SessionFollowAction.Jump, "Jump"),+ };+ private static readonly (double Beats, string Label)[] LengthSteps =+ {+ (1, "1 beat"), (2, "2 beats"), (4, "1 bar"), (8, "2 bars"), (16, "4 bars"), (32, "8 bars"), (64, "16 bars"),+ };+ private static readonly (double Beats, string Label)[] FollowTimes =+ {+ (0, "One pass"), (1, "1 beat"), (2, "2 beats"), (4, "1 bar"), (8, "2 bars"), (16, "4 bars"), (32, "8 bars"), (64, "16 bars"),+ };+ private static readonly (int Num, int Den)[] Signatures = { (0, 0), (2, 4), (3, 4), (4, 4), (5, 4), (6, 8), (7, 8), (12, 8) };++ private InspectorPreview? _inspPreview;++ private void RebuildInspector()+ {+ _inspPreview = null;+ var stack = new StackPanel { Spacing = 18, Margin = new Thickness(16) };+ if (_sel.Kind == SelKind.Scene) BuildSceneInspector(stack, _sel.Scene);+ else if (ColumnFor(_sel.TrackId) is { } c)+ {+ if (c.Kind == ColKind.Group) BuildGroupInspector(stack, c, _sel.Scene);+ else if (SlotFilled(c.TrackId, _sel.Scene) && !(_recTrack == c.TrackId && _recScene == _sel.Scene)) BuildClipInspector(stack, c, _sel.Scene);+ else BuildEmptyInspector(stack, c, _sel.Scene);+ }++ var hint = new TextBlock+ {+ Text = "Click selects · the triangle launches · Enter launches the selection\n←↑↓→ move · ⌘C ⌘V ⌘D · ⌫ delete · ⌘I insert scene",+ FontSize = 9, LineHeight = 15, Foreground = NotaPalette.TextDisabled, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(16),+ };+ hint.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ var dock = new DockPanel();+ DockPanel.SetDock(hint, Dock.Bottom);+ dock.Children.Add(hint);+ dock.Children.Add(new ScrollViewer { Content = stack, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled });+ _inspectorHost.Child = dock;+ }++ private void UpdateInspectorLive() => _inspPreview?.InvalidateVisual();++ // ---- pieces -------------------------------------------------------------------------++ private static Control Title(IBrush color, string title, string sub)+ {+ var head = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 8,+ Children =+ {+ new Border { Width = 10, Height = 10, CornerRadius = NotaRadius.Clip, Background = color, VerticalAlignment = VerticalAlignment.Center },+ new TextBlock { Text = title, FontSize = 15, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary, TextTrimming = TextTrimming.CharacterEllipsis, MaxWidth = InspectorW - 60 },+ },+ };+ var s = Mono(sub, 10, NotaPalette.TextTertiary);+ s.TextTrimming = TextTrimming.CharacterEllipsis;+ return new StackPanel { Spacing = 4, Children = { head, s } };+ }++ private static TextBlock SectionHead(string text) => new()+ {+ Text = text, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = NotaPalette.TextMuted,+ };++ // A labelled value well (LENGTH, LOOP, START…): a click opens its choices when it has any.+ private static Control Field(string label, string value, IBrush ink, Action<Control>? click)+ {+ var text = Mono(value, 11, ink);+ Control well;+ if (click is null)+ {+ well = new Border+ {+ Height = NotaSize.Shell, Padding = new Thickness(8, 0), CornerRadius = NotaRadius.Badge,+ Background = NotaPalette.BgSunken, BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(1), Child = text,+ };+ }+ else+ {+ var b = new Button+ {+ Height = NotaSize.Shell, Padding = new Thickness(8, 0), HorizontalAlignment = HorizontalAlignment.Stretch,+ HorizontalContentAlignment = HorizontalAlignment.Left, Background = NotaPalette.BgSunken, Content = text,+ };+ b.Click += (_, _) => click(b);+ well = b;+ }+ return new StackPanel+ {+ Spacing = 4,+ Children = { new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = NotaPalette.TextTertiary }, well },+ };+ }++ private static Grid TwoUp(params Control[] items)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 10, RowSpacing = 10 };+ for (int i = 0; i < items.Length; i++)+ {+ if (i % 2 == 0) g.RowDefinitions.Add(new RowDefinition(GridLength.Auto));+ Grid.SetColumn(items[i], i % 2);+ Grid.SetRow(items[i], i / 2);+ g.Children.Add(items[i]);+ }+ return g;+ }++ // A label on the left and a small value chip on the right (Quantize, Legato…).+ private static Control Row(string label, Control right)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 22 };+ g.Children.Add(new TextBlock { Text = label, FontSize = 11, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center });+ Grid.SetColumn(right, 1);+ right.VerticalAlignment = VerticalAlignment.Center;+ g.Children.Add(right);+ return g;+ }++ private static Button Chip(string value, bool lit, Action<Button> click)+ {+ var b = new Button { Classes = { "chip" }, Height = 22, Padding = new Thickness(8, 0), MinWidth = 0, Content = Mono(value, 10, lit ? NotaPalette.TextOnAccent : NotaPalette.TextPrimary) };+ b.Classes.Set("lit", lit);+ b.Click += (_, _) => click(b);+ return b;+ }++ private static void Pick<T>(Control anchor, IEnumerable<(T Value, string Label)> items, Func<T, bool> isCurrent, Action<T> choose)+ {+ var f = new MenuFlyout();+ foreach (var (v, label) in items)+ {+ var value = v;+ var mi = new MenuItem { Header = label, ToggleType = MenuItemToggleType.Radio, IsChecked = isCurrent(value) };+ mi.Click += (_, _) => choose(value);+ f.Items.Add(mi);+ }+ f.ShowAt(anchor);+ }++ private static Control Actions(params (string Label, string Key, Action Click)[] actions)+ {+ var wrap = new WrapPanel { Orientation = Orientation.Horizontal };+ foreach (var (label, key, click) in actions)+ {+ var content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { new TextBlock { Text = label, FontSize = 11, FontWeight = FontWeight.Medium } } };+ if (key.Length > 0) content.Children.Add(Mono(key, 9, NotaPalette.TextDisabled));+ var b = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(0, 0, 6, 6), Content = content };+ b.Click += (_, _) => click();+ wrap.Children.Add(b);+ }+ return wrap;+ }++ // Colour swatches: the track palette's bases in two shades. Clicking the current one+ // again goes back to the inherited colour (the track's, or none for a scene).+ private static Control Swatches(int current, Action<int> pick)+ {+ int bases = ArrangementView.PaletteBases;+ var grid = new UniformGrid { Columns = bases };+ for (int shade = 0; shade < 2; shade++)+ for (int b = 0; b < bases; b++)+ {+ int idx = b * ArrangementView.PaletteShades + shade;+ bool on = idx == current;+ var sw = new Border+ {+ Height = 22, Margin = new Thickness(3), CornerRadius = NotaRadius.Badge, Background = ArrangementView.TrackBrush(idx),+ BorderBrush = on ? NotaPalette.TextPrimary : Brushes.Transparent, BorderThickness = new Thickness(on ? 1.5 : 0),+ Cursor = new Cursor(StandardCursorType.Hand),+ };+ ToolTip.SetTip(sw, on ? "Click again to use the default colour" : null);+ sw.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(sw).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ pick(on ? -1 : idx);+ };+ grid.Children.Add(sw);+ }+ return new StackPanel { Spacing = 7, Children = { SectionHead("COLOR"), grid } };+ }++ // ---- clip ---------------------------------------------------------------------------++ private void BuildClipInspector(StackPanel s, Column c, int scene)+ {+ if (!_engine.TryGetSessionClipProps(c.TrackId, scene, out var p)) return;+ int id = c.TrackId;+ void Set(Func<NotaSessionClipProps, NotaSessionClipProps> edit)+ {+ if (!_engine.TryGetSessionClipProps(id, scene, out var cur)) return;+ _engine.SetSessionClipProps(id, scene, edit(cur));+ RefreshSlot(id, scene);+ }+ var brush = ClipBrush(c, scene);+ double len = _engine.SessionSlotLength(id, scene);+ string kind = c.IsInstrument ? "MIDI" : "AUDIO";+ s.Children.Add(Title(brush, ClipName(c, scene), $"{c.Name.ToUpperInvariant()} · {SceneName(scene).ToUpperInvariant()} · {kind}"));++ _inspPreview = new InspectorPreview(this, c, scene, brush);+ s.Children.Add(new Border+ {+ Height = 68, CornerRadius = NotaRadius.Control, Background = NotaPalette.Wash(brush, 0x1F),+ BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(1), ClipToBounds = true, Child = _inspPreview,+ });++ bool loop = p.Loop != 0;+ s.Children.Add(TwoUp(+ Field("LENGTH", FormatLength(len), NotaPalette.TextPrimary, a => Pick(a, LengthSteps, b => Math.Abs(b - len) < 1e-6,+ b => { _engine.SetSessionSlotLength(id, scene, b); RefreshSlot(id, scene); })),+ Field("LOOP", loop ? "On" : "Off · one-shot", loop ? NotaPalette.TextPrimary : NotaPalette.Warning, _ => Set(x => { x.Loop = loop ? 0 : 1; return x; })),+ Field("START", "1.1.1", NotaPalette.TextSecondary, null),+ Field("LOOP END", FormatPosition(len), NotaPalette.TextSecondary, null)));++ var launch = new StackPanel { Spacing = 10 };+ launch.Children.Add(SectionHead("LAUNCH"));+ var modes = Segmented(ModeLabels, Math.Clamp(p.LaunchMode, 0, 3), i => Set(x => { x.LaunchMode = i; return x; }));+ ToolTip.SetTip(modes, "Trigger starts · Gate plays while held · Toggle starts and stops · Repeat retriggers while held");+ launch.Children.Add(modes);+ string quant = p.QuantBeats < 0 ? "Global" : QuantLabel(p.QuantBeats);+ var quantItems = new List<(double, string)> { (-1.0, "Global") };+ foreach (var q in QuantSteps) quantItems.Add(q);+ launch.Children.Add(Row("Quantize", Chip(quant, false, a => Pick(a, quantItems, q => Math.Abs(q - p.QuantBeats) < 1e-6,+ q => Set(x => { x.QuantBeats = q; return x; })))));+ launch.Children.Add(Row("Legato", Chip(p.Legato != 0 ? "On" : "Off", p.Legato != 0, _ => Set(x => { x.Legato = x.Legato != 0 ? 0 : 1; return x; }))));+ var vel = new DragNumber(p.VelocityAmount * 100, 0, 100, 0.5, "0", 10) { Width = 44, Height = 22 };+ OneUndoStep(vel);+ vel.ValueChanged += v => { if (_engine.TryGetSessionClipProps(id, scene, out var cur)) { cur.VelocityAmount = (float)(v / 100); _engine.SetSessionClipProps(id, scene, cur); } };+ ToolTip.SetTip(vel, "Velocity amount: how far the launch velocity scales the clip · drag");+ launch.Children.Add(Row("Velocity %", new Border { CornerRadius = NotaRadius.Badge, BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(1), Child = vel }));+ s.Children.Add(launch);++ // Follow actions.+ bool follow = _engine.SessionFollow;+ var fa = new StackPanel { Spacing = 10 };+ var faHead = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ faHead.Children.Add(SectionHead("FOLLOW ACTION"));+ if (!follow) { var off = Mono("OFF GLOBALLY", 9, NotaPalette.TextTertiary); Grid.SetColumn(off, 1); faHead.Children.Add(off); }+ fa.Children.Add(faHead);+ string ActionLabel(int a) => Array.Find(FollowActions, x => (int)x.Action == a).Label ?? "None";+ Control ActionRow(string slot, int action, Action<int> setAction, Control chance)+ {+ var label = Mono(slot, 10, NotaPalette.TextTertiary);+ label.Width = 14;+ var pick = new Button+ {+ Height = 24, Padding = new Thickness(8, 0), HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch,+ Background = NotaPalette.BgSunken,+ Content = new DockPanel+ {+ Children = { new Glyph(GlyphKind.ChevronDown, 7) { Foreground = NotaPalette.TextDisabled, [DockPanel.DockProperty] = Dock.Right }, new TextBlock { Text = ActionLabel(action), FontSize = 11, Foreground = NotaPalette.TextPrimary } },+ },+ };+ pick.Click += (_, _) => Pick(pick, Array.ConvertAll(FollowActions, x => ((int)x.Action, x.Label)), a => a == action, setAction);+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 8, Height = 24 };+ g.Children.Add(label);+ Grid.SetColumn(pick, 1); g.Children.Add(pick);+ chance.Width = 40;+ Grid.SetColumn(chance, 2); g.Children.Add(chance);+ return g;+ }+ int total = Math.Max(1, p.ChanceA + p.ChanceB);+ int pctA = (int)Math.Round(p.ChanceA * 100.0 / total);+ var chanceA = new DragNumber(pctA, 0, 100, 0.5, "0", 10) { Height = 24 };+ OneUndoStep(chanceA);+ var chanceB = Mono($"{100 - pctA}", 10, NotaPalette.TextSecondary);+ chanceB.TextAlignment = TextAlignment.Center;+ chanceA.ValueChanged += v =>+ {+ int a = (int)Math.Round(v);+ chanceB.Text = $"{100 - a}";+ if (_engine.TryGetSessionClipProps(id, scene, out var cur)) { cur.ChanceA = a; cur.ChanceB = 100 - a; _engine.SetSessionClipProps(id, scene, cur); }+ };+ ToolTip.SetTip(chanceA, "Chance of A in percent · B gets the rest · drag");+ fa.Children.Add(ActionRow("A", p.FollowA, a => Set(x => { x.FollowA = a; return x; }), chanceA));+ fa.Children.Add(ActionRow("B", p.FollowB, a => Set(x => { x.FollowB = a; return x; }), chanceB));+ if (p.FollowA == (int)SessionFollowAction.Jump || p.FollowB == (int)SessionFollowAction.Jump)+ {+ var scenes = new List<(int, string)>();+ for (int i = 0; i < _sceneCount; i++) scenes.Add((i, SceneName(i)));+ fa.Children.Add(Row("Jump to", Chip(SceneName(Math.Clamp(p.JumpScene, 0, Math.Max(0, _sceneCount - 1))), false,+ a => Pick(a, scenes, i => i == p.JumpScene, i => Set(x => { x.JumpScene = i; return x; })))));+ }+ double after = p.FollowBeats > 0 ? p.FollowBeats : len;+ fa.Children.Add(Row("After", Chip(FormatDuration(after), false, a => Pick(a, FollowTimes, b => Math.Abs(b - p.FollowBeats) < 1e-6,+ b => Set(x => { x.FollowBeats = b; return x; })))));+ s.Children.Add(fa);+ if (!follow) Inactive.Set(fa, true, interactive: true);++ s.Children.Add(Swatches(p.Color, idx => Set(x => { x.Color = idx; return x; })));+ s.Children.Add(Actions(+ ("Duplicate", "⌘D", () => DuplicateSelection()),+ ("Rename", "F2", () => RenameSelection()),+ ("To Arrangement", "", () => ToArrangement(id, scene)),+ ("Edit", "", () => SlotEditRequested?.Invoke(id, scene)),+ ("Delete", "⌫", () => DeleteSelection())));+ }++ // A drag on a number is one undo step, however many values it passes through.+ private void OneUndoStep(DragNumber dn)+ {+ dn.GestureBegin += _engine.BeginUndoGroup;+ dn.GestureEnd += _engine.EndUndoGroup;+ }++ private static string QuantLabel(double beats)+ {+ foreach (var (b, label) in QuantSteps) if (Math.Abs(b - beats) < 1e-6) return label;+ return NotaNum.Str(beats, "0.##") + " beats";+ }++ // ---- scene --------------------------------------------------------------------------++ private void BuildSceneInspector(StackPanel s, int scene)+ {+ _engine.TryGetSceneProps(scene, out var p);+ void Set(Func<NotaSceneProps, NotaSceneProps> edit)+ {+ if (!_engine.TryGetSceneProps(scene, out var cur)) return;+ _engine.SetSceneProps(scene, edit(cur));+ RefreshScene(scene);+ }+ int clips = 0;+ foreach (var c in LaunchCols) if (SlotFilled(c.TrackId, scene)) clips++;+ var color = p.Color >= 0 ? ArrangementView.TrackBrush(p.Color) : NotaPalette.BorderStrong;+ s.Children.Add(Title(color, SceneName(scene), $"SCENE {scene + 1:00} · {clips} {(clips == 1 ? "clip" : "clips")}"));++ Control tempo;+ if (p.Tempo > 0)+ {+ var dn = new DragNumber(p.Tempo, 20, 999, 0.25, "0.00", 11) { Height = NotaSize.Shell - 2 };+ OneUndoStep(dn);+ dn.ValueChanged += v => { if (_engine.TryGetSceneProps(scene, out var cur)) { cur.Tempo = v; _engine.SetSceneProps(scene, cur); } };+ var clear = new Button { Classes = { "ghost" }, Width = 22, Height = 22, Padding = new Thickness(0), Content = new Glyph(GlyphKind.Close, 8), HorizontalContentAlignment = HorizontalAlignment.Center };+ ToolTip.SetTip(clear, "Launch without a tempo change");+ clear.Click += (_, _) => Set(x => { x.Tempo = 0; return x; });+ var row = new DockPanel { Children = { clear, dn } };+ DockPanel.SetDock(clear, Dock.Right);+ tempo = new StackPanel+ {+ Spacing = 4,+ Children =+ {+ new TextBlock { Text = "TEMPO", FontSize = 9, FontWeight = FontWeight.Bold, Foreground = NotaPalette.TextTertiary },+ new Border { Height = NotaSize.Shell, CornerRadius = NotaRadius.Badge, Background = NotaPalette.BgSunken, BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(1), Child = row },+ },+ };+ ToolTip.SetTip(tempo, "Tempo set when the scene launches · drag to change");+ }+ else+ tempo = Field("TEMPO", "—", NotaPalette.TextDisabled, _ =>+ Set(x => { x.Tempo = GetTempo?.Invoke().Bpm ?? 120; return x; }));+ string sig = p.SigNum > 0 && p.SigDen > 0 ? $"{p.SigNum}/{p.SigDen}" : "—";+ var sigField = Field("SIGNATURE", sig, p.SigNum > 0 ? NotaPalette.TextPrimary : NotaPalette.TextDisabled, a =>+ Pick(a, Array.ConvertAll(Signatures, x => ((x.Num, x.Den), x.Num == 0 ? "None" : $"{x.Num}/{x.Den}")),+ v => v.Num == p.SigNum && v.Den == p.SigDen, v => Set(x => { x.SigNum = v.Num; x.SigDen = v.Den; return x; })));+ s.Children.Add(TwoUp(tempo, sigField));++ var rows = new StackPanel { Spacing = 8 };+ string follow = p.Follow != 0 ? $"Next · {FormatLength(p.FollowBeats)}" : "Off";+ var followItems = new List<(double, string)> { (0, "Off") };+ foreach (double bars in new[] { 1.0, 2, 4, 8, 16, 32 }) followItems.Add((bars * 4, $"Next after {FormatLength(bars * 4)}"));+ rows.Children.Add(Row("Follow action", Chip(follow, p.Follow != 0, a => Pick(a, followItems,+ b => p.Follow == 0 ? b == 0 : Math.Abs(b - p.FollowBeats) < 1e-6,+ b => Set(x => { x.Follow = b > 0 ? 1 : 0; if (b > 0) x.FollowBeats = b; return x; })))));+ rows.Children.Add(Row("Select next scene on launch", Chip(_selectNextOnLaunch ? "On" : "Off", _selectNextOnLaunch, _ => { _selectNextOnLaunch = !_selectNextOnLaunch; RebuildInspector(); })));+ s.Children.Add(rows);++ s.Children.Add(Swatches(p.Color, idx => Set(x => { x.Color = idx; return x; })));+ s.Children.Add(Actions(+ ("Launch", "", () => LaunchSceneRow(scene)),+ ("Insert below", "⌘I", () => InsertSceneAtSelection()),+ ("Duplicate", "⌘D", () => DuplicateSelection()),+ ("Rename", "F2", () => RenameSelection()),+ ("Delete", "⌫", () => DeleteSelection())));+ }++ // ---- empty slot + group slot ------------------------------------------------------------++ private void BuildEmptyInspector(StackPanel s, Column c, int scene)+ {+ bool rec = _recTrack == c.TrackId && _recScene == scene;+ s.Children.Add(Title(NotaPalette.BorderStrong, rec ? "Recording" : "Empty slot", $"{c.Name.ToUpperInvariant()} · {SceneName(scene).ToUpperInvariant()}"));+ bool stop = _engine.GetSessionSlotStopButton(c.TrackId, scene);+ var rows = new StackPanel { Spacing = 8 };+ rows.Children.Add(Row("Stop button", Chip(stop ? "On" : "Removed", false, _ => { _engine.SetSessionSlotStopButton(c.TrackId, scene, !stop); RefreshSlot(c.TrackId, scene); })));+ rows.Children.Add(new TextBlock+ {+ Text = stop ? $"Launching this scene stops {c.Name}." : $"Launching this scene keeps {c.Name} playing.",+ FontSize = 11, LineHeight = 16, Foreground = NotaPalette.TextTertiary, TextWrapping = TextWrapping.Wrap,+ });+ s.Children.Add(rows);+ var actions = new List<(string, string, Action)>();+ if (c.IsInstrument) actions.Add(("Insert MIDI clip", "", () => InsertMidiClip(c.TrackId, scene)));+ actions.Add(rec ? ("Stop recording", "", () => { _engine.StopSessionRecord(); Refresh(); })+ : ("Record here", "", () => { _engine.RecordSessionSlot(c.TrackId, scene); Refresh(); }));+ if (_clip is not null) actions.Add(("Paste", "⌘V", () => PasteSelection()));+ s.Children.Add(Actions(actions.ToArray()));+ }++ private void BuildGroupInspector(StackPanel s, Column g, int scene)+ {+ s.Children.Add(Title(g.Brush, $"{g.Name} · {SceneName(scene)}", $"GROUP SLOT · {g.Children.Count} TRACKS"));+ s.Children.Add(new TextBlock+ {+ Text = "Launches every track's slot in this scene. The stop button stops them all.",+ FontSize = 11, LineHeight = 16, Foreground = NotaPalette.TextTertiary, TextWrapping = TextWrapping.Wrap,+ });+ s.Children.Add(Actions(("Launch group slot", "↵", () => LaunchGroup(g, scene)), ("Stop group", "", () => StopColumn(g))));+ }++ /// <summary>The selected clip's notes / waveform with a live playhead.</summary>+ private sealed class InspectorPreview : Control+ {+ private readonly SessionView _o;+ private readonly Column _c;+ private readonly int _scene;+ private readonly IBrush _brush;+ private readonly NotaNote[] _notes = Array.Empty<NotaNote>();+ private readonly float[] _peaks = new float[96 * 2];+ private readonly int _peakCount;+ private readonly double _len;++ public InspectorPreview(SessionView o, Column c, int scene, IBrush brush)+ {+ _o = o; _c = c; _scene = scene; _brush = brush;+ _len = o._engine.SessionSlotLength(c.TrackId, scene);+ if (c.IsInstrument) _notes = o._engine.GetSessionNotes(c.TrackId, scene);+ else _peakCount = o._engine.GetSessionSlotPeaks(c.TrackId, scene, _peaks, 96);+ }++ public override void Render(DrawingContext ctx)+ {+ var area = new Rect(10, 10, Math.Max(0, Bounds.Width - 20), Math.Max(0, Bounds.Height - 20));+ if (_len <= 0) return;+ if (_c.IsInstrument && _notes.Length > 0)+ {+ int lo = int.MaxValue, hi = int.MinValue;+ foreach (var n in _notes) { lo = Math.Min(lo, n.Pitch); hi = Math.Max(hi, n.Pitch); }+ int range = Math.Max(1, hi - lo);+ foreach (var n in _notes)+ {+ if (n.StartBeat >= _len) continue;+ double x = area.X + n.StartBeat / _len * area.Width;+ double w = Math.Max(2, Math.Min(n.LengthBeats, _len - n.StartBeat) / _len * area.Width);+ double y = area.Y + (hi - n.Pitch) / (double)range * (area.Height - 5);+ ctx.DrawRectangle(_brush, null, new Rect(x, y, w, 5), 1, 1);+ }+ }+ else if (!_c.IsInstrument) DrawPeaks(ctx, area, _peaks, _peakCount, _brush);++ if (_o._engine.SessionSlotState(_c.TrackId, _scene) == 3)+ {+ double x = area.X + Math.Clamp(_o._engine.SessionSlotPosition(_c.TrackId) / _len, 0, 1) * area.Width;+ ctx.DrawLine(PlayheadPen, new Point(Math.Round(x) + 0.5, area.Y - 4), new Point(Math.Round(x) + 0.5, area.Bottom + 4));+ }+ }+ }+}diff --git a/src/managed/Nota.App/SessionView.Mixer.cs b/src/managed/Nota.App/SessionView.Mixer.csnew file mode 100644index 00000000..49d52c1f--- /dev/null+++ b/src/managed/Nota.App/SessionView.Mixer.cs@@ -0,0 +1,328 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Session view — the mixer under each column, in three sections the toolbar shows or hides:+// I/O (input, monitor, output), Sends (one row per return bus) and Mixer (pan, volume,+// meter, mute / solo / arm). The scene rail carries the row labels.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using Nota.Presentation;++namespace Nota.App;++public sealed partial class SessionView+{+ private const double IoRowH = 22;+ private const double FaderRowH = 18;+ private const double MeterRowH = 6;+ private const double ButtonRowH = 22;+ private const double SectionTop = 6;++ /// <summary>Master fader plumbing (the master level lives on the transport view-model).</summary>+ public Func<float>? GetMasterVolume { get; set; }+ public Action<float>? SetMasterVolume { get; set; }++ private sealed class MixerParts+ {+ public required Control Root { get; init; }+ public required Action UpdateMeter { get; init; }+ }++ private int ReturnRows => Math.Min(_engine.ReturnTrackCount, 4);++ private List<(int Id, string Name)> Returns()+ {+ var list = new List<(int, string)>();+ for (int i = 0; i < _engine.TrackCount; i++)+ if (_engine.TryGetTrackInfo(i, out var ti) && ti.IsReturn) list.Add((ti.Id, TrackNames.Of(_engine, ti)));+ return list;+ }++ private Control MixerRailLabels()+ {+ var stack = new StackPanel { Spacing = Gap };+ TextBlock Label(string text) => new()+ {+ Text = text, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = NotaPalette.TextDisabled,+ Margin = new Thickness(10, 0), VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,+ };+ Border Row(double h, string text) => new() { Height = h, Child = Label(text) };+ if (_showIO)+ stack.Children.Add(Section(Row(IoRowH, "INPUT"), Row(IoRowH, "MONITOR"), Row(IoRowH, "OUTPUT")));+ if (_showSends && ReturnRows > 0)+ {+ var rows = Returns().Take(ReturnRows).Select((r, i) => (Control)Row(FaderRowH, $"SEND {(char)('A' + i)} · {r.Name.ToUpperInvariant()}")).ToArray();+ stack.Children.Add(Section(rows));+ }+ if (_showMixer)+ stack.Children.Add(Section(Row(FaderRowH, "PAN"), Row(FaderRowH, "VOLUME"), new Border { Height = MeterRowH }, new Border { Height = ButtonRowH }));+ return stack;+ }++ private static StackPanel Section(params Control[] rows)+ {+ var s = new StackPanel { Spacing = Gap, Margin = new Thickness(0, SectionTop, 0, 0) };+ foreach (var r in rows) s.Children.Add(r);+ return s;+ }++ private MixerParts BuildMixer(Column c)+ {+ var root = new StackPanel { Spacing = Gap };+ bool hasTrack = c.Kind != ColKind.Master;+ NotaTrackInfo ti = default;+ if (hasTrack)+ for (int i = 0; i < _engine.TrackCount; i++)+ if (_engine.TryGetTrackInfo(i, out var t) && t.Id == c.TrackId) { ti = t; break; }+ if (c.Kind == ColKind.Track && ti.Armed != 0) _armed.Add(c.TrackId); else _armed.Remove(c.TrackId);++ if (_showIO) root.Children.Add(Section(InputRow(c), MonitorRow(c), OutputRow(c)));++ if (_showSends && ReturnRows > 0)+ {+ var rows = new List<Control>();+ for (int b = 0; b < ReturnRows; b++)+ {+ if (c.Kind is ColKind.Track or ColKind.Group)+ {+ int bus = b, id = c.TrackId;+ var f = new MiniFader(_engine.GetTrackSend(id, bus), 1.0) { Default = 0 };+ var read = ReadoutText();+ void Show() => read.Text = f.Value <= 0.005 ? "–" : NotaNum.Str(f.Value * 100, "0");+ f.ValueChanged += v => { _engine.SetTrackSend(id, bus, (float)v); Show(); };+ Show();+ rows.Add(FaderRow(f, read));+ }+ else rows.Add(new Border { Height = FaderRowH });+ }+ root.Children.Add(Section(rows.ToArray()));+ }++ Action meter = () => { };+ if (_showMixer)+ {+ Control panRow;+ if (hasTrack)+ {+ int id = c.TrackId;+ var pan = new PanBar(ti.Pan) { VerticalAlignment = VerticalAlignment.Center }; // draws its own C / 12L readout+ pan.PanChanged += p => _engine.SetTrackPan(id, (float)p);+ panRow = FaderRow(pan, ReadoutText());+ }+ else panRow = new Border { Height = FaderRowH };++ double vol0 = hasTrack ? ti.Volume : GetMasterVolume?.Invoke() ?? 1f;+ var vol = new MiniFader(vol0, 1.5) { Default = 1.0 };+ var db = ReadoutText();+ void ShowDb() => db.Text = vol.Value <= 1e-4 ? "−∞" : NotaNum.Db(AudioMath.LinToDb(vol.Value), signed: true);+ vol.ValueChanged += v =>+ {+ if (hasTrack) _engine.SetTrackVolume(c.TrackId, (float)v);+ else SetMasterVolume?.Invoke((float)v);+ ShowDb();+ };+ ShowDb();++ var mL = new MeterLine(); var mR = new MeterLine();+ var meters = new StackPanel { Height = MeterRowH, Spacing = 1, Margin = new Thickness(4, 0), VerticalAlignment = VerticalAlignment.Center, Children = { mL, mR } };+ meter = () =>+ {+ NotaMeter m = default;+ if (hasTrack) { if (!_engine.TryGetTrackMeter(c.TrackId, out m)) m = default; }+ else m = _engine.MasterMeter();+ mL.Level = m.PeakL; mR.Level = m.PeakR;+ };++ var btns = new UniformGrid { Rows = 1, Height = ButtonRowH, Margin = new Thickness(4, 0) };+ if (hasTrack)+ {+ int id = c.TrackId;+ btns.Children.Add(MixToggle("M", ti.Muted != 0, false, v => _engine.SetTrackMute(id, v)));+ btns.Children.Add(MixToggle("S", ti.Soloed != 0, false, v => _engine.SetTrackSolo(id, v)));+ if (c.Kind == ColKind.Track)+ btns.Children.Add(MixToggle(null, ti.Armed != 0, true, v =>+ {+ _engine.SetTrackArmed(id, v);+ if (v) _armed.Add(id); else _armed.Remove(id);+ UpdateStates();+ }));+ }+ root.Children.Add(Section(panRow, FaderRow(vol, db), meters, btns));+ }+ return new MixerParts { Root = root, UpdateMeter = meter };+ }++ private static TextBlock ReadoutText()+ {+ var t = new TextBlock { FontSize = 9, Foreground = NotaPalette.TextMuted, Width = 30, TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center };+ t.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ return t;+ }++ private static Control FaderRow(Control fader, TextBlock readout)+ {+ fader.VerticalAlignment = VerticalAlignment.Center;+ var g = new Grid { Height = FaderRowH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(4, 0), ColumnSpacing = 6 };+ g.Children.Add(fader);+ Grid.SetColumn(readout, 1);+ g.Children.Add(readout);+ return g;+ }++ // M / S / record-arm: a 20px chip. Engaged mute is a raised neutral, solo the brass fill,+ // arm the record red with its pale disc (DESIGN.md § Controls).+ private static Control MixToggle(string? label, bool initial, bool arm, Action<bool> set)+ {+ bool on = initial;+ var text = new TextBlock { Text = label ?? "", FontSize = 10, FontWeight = FontWeight.SemiBold, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var disc = new Glyph(GlyphKind.Record, 7);+ var b = new Border+ {+ Height = 20, Margin = new Thickness(1.5, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1),+ BorderBrush = NotaPalette.BorderDefault, Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),+ Child = arm ? disc : text,+ };+ void Paint()+ {+ if (arm)+ {+ b.Background = on ? NotaPalette.Record : NotaPalette.SurfaceCard;+ b.BorderBrush = on ? NotaPalette.Record : NotaPalette.BorderDefault;+ disc.Foreground = on ? NotaPalette.RecordInk : NotaPalette.TextDisabled;+ return;+ }+ bool solo = label == "S";+ b.Background = on ? (solo ? NotaPalette.Accent : NotaPalette.BorderStrong) : NotaPalette.SurfaceCard;+ text.Foreground = on ? (solo ? NotaPalette.TextOnAccent : NotaPalette.TextPrimary) : NotaPalette.TextMuted;+ }+ ToolTip.SetTip(b, arm ? "Arm for recording" : label == "M" ? "Mute" : "Solo");+ b.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ on = !on; set(on); Paint();+ };+ Paint();+ return b;+ }++ // ---- I/O rows --------------------------------------------------------------------++ private Control InputRow(Column c)+ {+ if (c.Kind != ColKind.Track) return new Border { Height = IoRowH };+ var names = new List<(int Id, string Name, bool Instrument)>();+ for (int i = 0; i < _engine.TrackCount; i++)+ if (_engine.TryGetTrackInfo(i, out var t) && t.Id != c.TrackId && !t.IsGroup)+ names.Add((t.Id, TrackNames.Of(_engine, t), t.IsInstrument));++ var items = new List<(int Value, string Label)>();+ int cur;+ if (c.IsInstrument)+ {+ items.Add((-1, "All Ins"));+ foreach (var n in names.Where(n => n.Instrument)) items.Add((n.Id, n.Name));+ cur = _engine.GetTrackMidiSource(c.TrackId);+ }+ else+ {+ items.Add((0, "Ext In"));+ items.Add((-1, "Master"));+ foreach (var n in names) items.Add((n.Id, n.Name));+ cur = _engine.GetTrackRecordInput(c.TrackId);+ }+ var cb = new ComboBox { Height = IoRowH, FontSize = 10, Padding = new Thickness(6, 0), HorizontalAlignment = HorizontalAlignment.Stretch, Margin = new Thickness(4, 0) };+ foreach (var it in items) cb.Items.Add(new ComboBoxItem { Content = it.Label, FontSize = 10 });+ int sel = items.FindIndex(it => it.Value == cur);+ cb.SelectedIndex = sel >= 0 ? sel : 0;+ int id = c.TrackId;+ bool inst = c.IsInstrument;+ cb.SelectionChanged += (_, _) =>+ {+ if (cb.SelectedIndex < 0) return;+ int v = items[cb.SelectedIndex].Value;+ if (inst) _engine.SetTrackMidiSource(id, v); else _engine.SetTrackRecordInput(id, v);+ };+ ToolTip.SetTip(cb, inst ? "MIDI input: every input, or another instrument track" : "Record input");+ return cb;+ }++ private Control MonitorRow(Column c)+ {+ if (c.Kind != ColKind.Track || !c.IsAudio) return new Border { Height = IoRowH };+ int id = c.TrackId;+ bool on = _engine.GetTrackMonitor(id);+ var seg = Segmented(new[] { "In", "Auto" }, on ? 0 : 1, i => _engine.SetTrackMonitor(id, i == 0), compact: true);+ seg.Margin = new Thickness(4, 0);+ ToolTip.SetTip(seg, "In: hear the input live through this track · Auto: only while recording");+ return seg;+ }++ private Control OutputRow(Column c)+ {+ string text = c.Kind == ColKind.Master ? "Ext Out 1/2" : "Master";+ if (c.GroupId > 0 && ColumnFor(c.GroupId) is { } g) text = g.Name;+ else if (c.GroupId > 0)+ for (int i = 0; i < _engine.TrackCount; i++)+ if (_engine.TryGetTrackInfo(i, out var t) && t.Id == c.GroupId) { text = TrackNames.Of(_engine, t); break; }+ var b = new Border+ {+ Height = IoRowH, Margin = new Thickness(4, 0), Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Badge,+ Background = NotaPalette.SurfaceCard, BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(1),+ Child = new TextBlock { Text = text, FontSize = 10, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis },+ };+ ToolTip.SetTip(b, "Output — group a track to route it through the group");+ return b;+ }++ /// <summary>A segmented switch (Border.segmented + ToggleButton.seg); exactly one is lit.</summary>+ private static Border Segmented(IReadOnlyList<string> labels, int selected, Action<int> pick, bool compact = false, bool mono = false)+ {+ var row = new UniformGrid { Rows = 1 };+ var buttons = new List<ToggleButton>();+ for (int i = 0; i < labels.Count; i++)+ {+ int idx = i;+ var tb = new ToggleButton+ {+ Content = labels[i], Classes = { "seg" }, IsChecked = i == selected, HorizontalAlignment = HorizontalAlignment.Stretch,+ HorizontalContentAlignment = HorizontalAlignment.Center, Padding = new Thickness(compact ? 4 : 8, 0),+ FontSize = compact ? 9 : 10, Height = compact ? 16 : 20, MinWidth = 0,+ };+ if (mono) tb.BindResource(ToggleButton.FontFamilyProperty, "Font.Mono");+ tb.Click += (_, _) =>+ {+ foreach (var b in buttons) b.IsChecked = ReferenceEquals(b, tb);+ pick(idx);+ };+ buttons.Add(tb);+ row.Children.Add(tb);+ }+ return new Border { Classes = { "segmented" }, Padding = new Thickness(2), Child = row };+ }++ /// <summary>A thin horizontal peak meter line (Signal green), 2px tall.</summary>+ private sealed class MeterLine : Control+ {+ private double _level;+ public MeterLine() { Height = 2; }+ public double Level+ {+ set { double v = Math.Clamp(value, 0, 1); if (Math.Abs(v - _level) < 0.004) return; _level = v; InvalidateVisual(); }+ }+ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width;+ ctx.DrawRectangle(NotaPalette.SurfaceRaised, null, new Rect(0, 0, w, 2), 1, 1);+ if (_level > 0) ctx.DrawRectangle(NotaPalette.Success, null, new Rect(0, 0, w * _level, 2), 1, 1);+ }+ }+}diff --git a/src/managed/Nota.App/SessionView.Toolbar.cs b/src/managed/Nota.App/SessionView.Toolbar.csnew file mode 100644index 00000000..ae9e866b--- /dev/null+++ b/src/managed/Nota.App/SessionView.Toolbar.cs@@ -0,0 +1,203 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Session view — the toolbar: Session Rec with a fixed record length, the launch quantum,+// the global follow-action switch, Capture Scene; on the right the I/O · Sends · Mixer+// section toggles, the position readout, Back to Arrangement and Stop All.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Layout;+using Avalonia.Media;++namespace Nota.App;++public sealed partial class SessionView+{+ // Launch quantum steps (beats, label). 0 = launch at once.+ internal static readonly (double Beats, string Label)[] QuantSteps =+ {+ (0.0, "None"), (0.25, "1/16"), (0.5, "1/8"), (1.0, "1/4"), (2.0, "1/2"),+ (4.0, "1 Bar"), (8.0, "2 Bars"), (16.0, "4 Bars"), (32.0, "8 Bars"),+ };+ private static readonly int[] FixedBars = { 0, 1, 2, 4, 8 };++ private Button? _recBtn;+ private Glyph? _recDot;+ private TextBlock? _recText;+ private TextBlock? _quantLabel;+ private SwitchTrack? _followSwitch;+ private TextBlock? _followText;+ private Border? _fixedSeg;+ private TextBlock? _posText, _tempoText;+ private Button? _backBtn;+ private readonly List<ToggleButton> _sectionToggles = new();++ /// <summary>Tempo and time signature for the toolbar readout.</summary>+ public Func<(double Bpm, int Num, int Den)>? GetTempo { get; set; }++ private Control BuildToolbar()+ {+ _recDot = new Glyph(GlyphKind.Record, 8);+ _recText = new TextBlock { Text = "Session Rec", FontSize = 11, FontWeight = FontWeight.SemiBold };+ _recBtn = new Button+ {+ Height = NotaSize.Shell, Padding = new Thickness(10, 0),+ Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7, Children = { _recDot, _recText } },+ };+ ToolTip.SetTip(_recBtn, "Record into the armed track at the selected scene · click again to keep the take");+ _recBtn.Click += (_, _) => SessionRec();++ var fixedLabel = Caps("FIXED");+ _fixedSeg = new Border();+ var fixedRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { fixedLabel, _fixedSeg } };+ ToolTip.SetTip(fixedRow, "Fixed record length in bars — the take stops by itself");++ _quantLabel = new TextBlock { FontSize = 10, Foreground = NotaPalette.TextPrimary, VerticalAlignment = VerticalAlignment.Center };+ _quantLabel.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ var quant = new Button+ {+ Height = NotaSize.Shell, Padding = new Thickness(9, 0),+ Content = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 8,+ Children = { Caps("QUANT"), _quantLabel, new Glyph(GlyphKind.ChevronDown, 7) { Foreground = NotaPalette.TextDisabled } },+ },+ };+ ToolTip.SetTip(quant, "Launch quantize: when clips and scenes start");+ quant.Click += (_, _) =>+ {+ var f = new MenuFlyout();+ double cur = _engine.LaunchQuant;+ foreach (var (beats, label) in QuantSteps)+ {+ var mi = new MenuItem { Header = label, ToggleType = MenuItemToggleType.Radio, IsChecked = Math.Abs(beats - cur) < 1e-6 };+ mi.Click += (_, _) => { _engine.SetLaunchQuant(beats); SyncToolbar(); };+ f.Items.Add(mi);+ }+ f.ShowAt(quant);+ };++ _followSwitch = new SwitchTrack { VerticalAlignment = VerticalAlignment.Center };+ _followText = new TextBlock { Text = "Follow", FontSize = 11, FontWeight = FontWeight.Medium, VerticalAlignment = VerticalAlignment.Center };+ var follow = new Button+ {+ Height = NotaSize.Shell, Padding = new Thickness(9, 0),+ Content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7, Children = { _followSwitch, _followText } },+ };+ ToolTip.SetTip(follow, "Follow actions on or off for every clip and scene");+ follow.Click += (_, _) => { _engine.SessionFollow = !_engine.SessionFollow; SyncToolbar(); RebuildInspector(); };++ var capture = new Button { Content = "Capture Scene", Height = NotaSize.Shell, Padding = new Thickness(10, 0), FontSize = 11 };+ ToolTip.SetTip(capture, "Copy the clips playing now into a new scene");+ capture.Click += (_, _) => CaptureScene();++ // Section toggles: each shows or hides one mixer section under the grid.+ var sections = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 };+ void Section(string label, Func<bool> get, Action<bool> set)+ {+ var tb = new ToggleButton { Content = label, Classes = { "seg" }, IsChecked = get(), Height = 20, FontSize = 10, Padding = new Thickness(9, 0) };+ tb.Click += (_, _) => { set(tb.IsChecked == true); Refresh(); };+ _sectionToggles.Add(tb);+ sections.Children.Add(tb);+ }+ Section("I/O", () => _showIO, v => _showIO = v);+ Section("Sends", () => _showSends, v => _showSends = v);+ Section("Mixer", () => _showMixer, v => _showMixer = v);+ var sectionsWell = new Border { Classes = { "segmented" }, Padding = new Thickness(2), Child = sections };++ _posText = new TextBlock { FontSize = 12, Foreground = NotaPalette.TextPrimary, MinWidth = 56, VerticalAlignment = VerticalAlignment.Center };+ _posText.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ _tempoText = new TextBlock { FontSize = 10, Foreground = NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Center };+ _tempoText.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");+ var readout = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Margin = new Thickness(8, 0), Children = { _posText, _tempoText } };++ _backBtn = new Button { Content = "Back to Arrangement", Height = NotaSize.Shell, Padding = new Thickness(10, 0), FontSize = 11 };+ ToolTip.SetTip(_backBtn, "Stop session clips and hand every track back to the Arrangement");+ _backBtn.Click += (_, _) => { _engine.BackToArrangement(); UpdateStates(); };++ var stopAll = new Button+ {+ Height = NotaSize.Shell, Padding = new Thickness(10, 0),+ Content = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 7,+ Children = { new Glyph(GlyphKind.Stop, 7), new TextBlock { Text = "Stop All", FontSize = 11, FontWeight = FontWeight.SemiBold } },+ },+ };+ ToolTip.SetTip(stopAll, "Stop every session clip");+ stopAll.Click += (_, _) => { _engine.StopAllSession(); UpdateStates(); };++ var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { _recBtn, fixedRow, quant, follow, capture } };+ var right = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { sectionsWell, readout, _backBtn, stopAll } };+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), Margin = new Thickness(10, 0) };+ grid.Children.Add(left);+ Grid.SetColumn(right, 2); grid.Children.Add(right);+ return new Border+ {+ Height = 44, Background = NotaPalette.BgSunken, BorderBrush = NotaPalette.BorderDefault,+ BorderThickness = new Thickness(0, 0, 0, 1), Child = grid,+ };+ }++ private static TextBlock Caps(string text) => new()+ {+ Text = text, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Center,+ };++ private void SessionRec()+ {+ // A take in progress: keep it (it loops back), whatever the button's scene.+ if (_engine.TryGetSessionRecordTarget(out _, out _, out _)) { _engine.StopSessionRecord(); Refresh(); return; }+ int scene = _sel.Scene;+ int id = _engine.RecordSessionScene(scene);+ if (id == 0) { Say("Arm a track with an empty slot in this scene to record."); return; }+ Refresh();+ }++ /// <summary>Re-reads the engine's session settings into the toolbar (after a load).</summary>+ public void SyncToolbar()+ {+ double q = _engine.LaunchQuant;+ string ql = q > 0 ? NotaNum.Str(q, "0.##") + " beats" : "None";+ foreach (var (beats, label) in QuantSteps) if (Math.Abs(beats - q) < 1e-6) ql = label;+ if (_quantLabel is not null) _quantLabel.Text = ql;++ bool follow = _engine.SessionFollow;+ if (_followSwitch is not null) _followSwitch.IsOn = follow;+ if (_followText is not null) _followText.Foreground = follow ? NotaPalette.TextPrimary : NotaPalette.TextMuted;++ if (_fixedSeg is not null)+ {+ double len = _engine.SessionRecordLength;+ int sel = Array.FindIndex(FixedBars, b => Math.Abs(b * 4 - len) < 1e-6);+ var seg = Segmented(Array.ConvertAll(FixedBars, b => b == 0 ? "Off" : b.ToString(NotaNum.Culture)), sel < 0 ? 0 : sel,+ i => _engine.SessionRecordLength = FixedBars[i] * 4.0, mono: true);+ _fixedSeg.Child = seg;+ }+ for (int i = 0; i < _sectionToggles.Count; i++)+ _sectionToggles[i].IsChecked = i switch { 0 => _showIO, 1 => _showSends, _ => _showMixer };+ }++ private void UpdateToolbar()+ {+ bool rec = _recScene >= 0;+ if (_recBtn is not null)+ {+ if (rec) { _recBtn.Background = NotaPalette.Record; _recBtn.BorderBrush = NotaPalette.Record; }+ else { _recBtn.ClearValue(BackgroundProperty); _recBtn.ClearValue(BorderBrushProperty); }+ _recDot!.Foreground = rec ? NotaPalette.RecordInk : NotaPalette.Record;+ _recText!.Foreground = rec ? NotaPalette.RecordInk : NotaPalette.TextSecondary;+ }+ if (_posText is not null) _posText.Text = FormatPosition(_engine.PositionBeats);+ if (_tempoText is not null && GetTempo?.Invoke() is { } t) _tempoText.Text = $"{NotaNum.Bpm(t.Bpm)} · {t.Num}/{t.Den}";+ if (_backBtn is not null)+ {+ _backBtn.Classes.Set("primary", _sessionActive);+ _backBtn.IsEnabled = _sessionActive;+ }+ }+}diff --git a/src/managed/Nota.App/SessionView.cs b/src/managed/Nota.App/SessionView.csindex c10be41d..0dbe4a52 100644--- a/src/managed/Nota.App/SessionView.cs+++ b/src/managed/Nota.App/SessionView.cs@@ -1,18 +1,23 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Session view (mockup 1c): a clip-launch grid of tracks × scenes. A scene rail-// launches/stops whole rows; each track column is a stack of clip slots over a-// mini-mixer (pan / send A / vol / M-S-arm / meter) so you can jam without-// leaving the grid; a master column launches scenes. Slot colour reflects live-// engine state (empty / filled / queued / playing / recording), polled at the-// UI clock by MainWindow via UpdateStates. See ARCHITECTURE.md § UI.+// Session view (nota-design "Nota Session View", 1a grid + inspector): a clip-launch grid of+// tracks × scenes. Columns take the track's name and colour; a clip shows its name, colour,+// a note / waveform preview and its length in bars, and its progress runs on the slot's own+// clock. Selecting is separate from launching: a click on a cell selects it, a click on its+// triangle launches it. The inspector on the right edits the selected clip, scene or empty+// slot. Groups fold their children into one launchable column; returns and the master close+// the row with mixer-only columns. Live state (queued / playing / recording, meters) is+// polled at the UI clock by MainWindow through UpdateStates. See ARCHITECTURE.md § UI.+//+// Partials: SessionView.Grid.cs (cells, headers, scene rail), SessionView.Mixer.cs (I/O,+// sends, mixer rows), SessionView.Toolbar.cs, SessionView.Inspector.cs.using System;using System.Collections.Generic;+using System.Linq;using Avalonia;using Avalonia.Controls;-using Avalonia.Controls.Shapes;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;@@ -21,62 +26,58 @@ using Nota.Presentation;namespace Nota.App;-public sealed class SessionView : UserControl+public sealed partial class SessionView : UserControl{- private const double SceneRailW = 168;- private const double ColW = 126;- private const double SlotH = 62;- private const double HeaderH = 38;- private const double StopNubH = 24;- private const double Gap = 2;- private const double Radius = NotaRadius.TileValue;-- // Ember Graphite palette (static so cells can repaint without resource lookups).- private static readonly IBrush Lane = NotaPalette.SurfaceInset;- private static readonly IBrush Card = NotaPalette.SurfaceCard;- private static readonly IBrush Raised = NotaPalette.SurfaceRaised;- private static readonly IBrush Sunken = NotaPalette.BgSunken;- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;- private static readonly IBrush BorderStrong = NotaPalette.BorderStrong;- private static readonly IBrush Success = NotaPalette.Success;- private static readonly IBrush Warning = NotaPalette.Warning;- private static readonly IBrush Warning40 = NotaPalette.Wash(NotaPalette.Warning, 0x66); // queued blink dim (HANDOFF §4)- private static readonly IBrush Danger = NotaPalette.Danger;- private static readonly IBrush Record = NotaPalette.Record; // red belongs to recording- private static readonly IBrush Brass = NotaPalette.Accent;- private static readonly IBrush AccentBright = NotaPalette.AccentBright;- private static readonly IBrush TextPrimary = NotaPalette.TextPrimary;- private static readonly IBrush TextSecondary = NotaPalette.TextSecondary;- private static readonly IBrush TextTertiary = NotaPalette.TextTertiary;- private static readonly IBrush TextDisabled = NotaPalette.TextDisabled;- private static readonly IBrush OnAccent = NotaPalette.TextOnAccent;- private static readonly IBrush GreenFill = NotaPalette.Wash(NotaPalette.Success, 0x21);- private static readonly IBrush RedFill = NotaPalette.Wash(NotaPalette.Record, 0x28);- private static readonly IBrush AmberFill = NotaPalette.Wash(NotaPalette.Warning, 0x1F);-- // Track palette — mirrors ArrangementView.TrackBase (Brush.Track1..8 + Return A/B).- private static Color[] TrackBase => NotaPalette.TrackColors;+ // Geometry (design 1a, Normal density).+ private const double SceneRailW = 176;+ private const double TrackColW = 124;+ private const double ReturnColW = 96;+ private const double MasterColW = 104;+ private const double CellH = 58;+ private const double HeaderH = 44;+ private const double Gap = 3;+ private const double GridPad = 10;+ private const double InspectorW = 300;private readonly IAudioEngine _engine;- // Three horizontally-aligned strips (same column widths + spacing) so a column's- // header, slots and mixer line up: headers pin to the top, the slot grid scrolls- // vertically in the middle, mixers + stop nubs pin to the bottom.- private readonly StackPanel _headerRow = new() { Orientation = Orientation.Horizontal, Spacing = Gap, Margin = new Thickness(12, 12, 12, 0) };- private readonly StackPanel _slotsRow = new() { Orientation = Orientation.Horizontal, Spacing = Gap, Margin = new Thickness(12, Gap, 12, Gap) };- private readonly StackPanel _footerRow = new() { Orientation = Orientation.Horizontal, Spacing = Gap, Margin = new Thickness(12, 0, 12, 12) };- private readonly List<SlotCell> _cells = new();- private readonly List<TrackStrip> _strips = new();-- private readonly HashSet<int> _armed = new(); // tracks armed for slot-click recording- private int _blinkFrame; // drives the 2Hz queued blink at the UI clock- private Border? _backToArr; // "Back to Arrangement" — lit while session overrides the timeline-- /// <summary>Raised to edit a filled slot's notes (trackId, scene).</summary>- public event Action<int, int>? SlotEditRequested;- /// <summary>Raised after a slot is copied into the arrangement (M5-6).</summary>- public event Action? ArrangementChanged;+ // Three horizontally aligned strips (same column widths + spacing) so a column's header,+ // cells and mixer line up: headers pin to the top, the cells scroll vertically in the+ // middle, the stop row + mixer pin to the bottom. All three scroll sideways together.+ private readonly StackPanel _headerRow = new() { Orientation = Orientation.Horizontal, Spacing = Gap, Margin = new Thickness(GridPad, GridPad, GridPad, 0) };+ private readonly StackPanel _cellsRow = new() { Orientation = Orientation.Horizontal, Spacing = Gap, Margin = new Thickness(GridPad, Gap, GridPad, 0) };+ private readonly StackPanel _footerRow = new() { Orientation = Orientation.Horizontal, Spacing = Gap, Margin = new Thickness(GridPad, Gap, GridPad, GridPad) };+ private readonly Border _inspectorHost = new() { Width = InspectorW };++ private readonly List<Column> _cols = new();+ private readonly List<SceneCell> _sceneCells = new();+ private int _sceneCount;++ // UI-only state: which group columns are folded, which mixer sections show, and the+ // selection (a slot on a track or group column, or a scene row).+ private readonly HashSet<int> _collapsed = new();+ private bool _showIO, _showSends = true, _showMixer = true;+ private bool _selectNextOnLaunch;+ private Selection _sel = new(SelKind.Slot, 0, 0);+ // Clipboard: a reference to a slot; a cut moves it on paste.+ private (int TrackId, int Scene, bool Cut)? _clip;++ private int _blinkFrame;+ private bool _blinkOn = true;+ private bool _sessionActive;++ internal enum SelKind { Slot, Scene }+ internal readonly record struct Selection(SelKind Kind, int TrackId, int Scene);++ /// <summary>Raised to edit a filled slot's notes / audio (trackId, scene).</summary>+ public event Action<int, int>? SlotEditRequested;+ /// <summary>Raised when the selection lands on a track's slot (trackId, scene).</summary>+ public event Action<int, int>? SlotSelected;+ /// <summary>Raised after a slot is copied into the arrangement (M5-6) or a track is renamed.</summary>+ public event Action? ArrangementChanged;+ /// <summary>A one-line status message for the main window's status bar.</summary>+ public event Action<string>? Status;/// <summary>Raised when a browser item is dropped on a slot (M7-5): item, track id,/// scene, and whether the slot's track is an instrument track.</summary>public event Action<BrowserItem, int, int, bool>? ItemDropped;@@ -86,689 +87,499 @@ public sealed class SessionView : UserControlpublic SessionView(IAudioEngine engine){_engine = engine;+ Focusable = true;+ FocusAdorner = null;- // Middle: only the slot grid scrolls vertically (headers/mixers stay pinned).var vScroll = new ScrollViewer{- Content = _slotsRow,+ Content = _cellsRow,HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,};var inner = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto") };- inner.Children.Add(_headerRow); // row 0 — pinned headers- Grid.SetRow(vScroll, 1); inner.Children.Add(vScroll); // row 1 — scrolling slots- Grid.SetRow(_footerRow, 2); inner.Children.Add(_footerRow); // row 2 — pinned mixers-- // Outer: everything scrolls horizontally together so columns stay aligned.+ inner.Children.Add(_headerRow);+ Grid.SetRow(vScroll, 1); inner.Children.Add(vScroll);+ Grid.SetRow(_footerRow, 2); inner.Children.Add(_footerRow);var hScroll = new ScrollViewer{Content = inner,HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,};+ var gridArea = new Border { Background = NotaPalette.BgSunken, Child = hScroll };- var stack = new DockPanel();- var bar = BuildActionBar();- DockPanel.SetDock(bar, Dock.Top);- stack.Children.Add(bar);- stack.Children.Add(hScroll);- Content = stack;- }+ _inspectorHost.Background = NotaPalette.Panel;+ _inspectorHost.BorderBrush = NotaPalette.BorderDefault;+ _inspectorHost.BorderThickness = new Thickness(1, 0, 0, 0);- // Session toolbar row (mockup 1c): + Scene (no engine support yet → N/A),- // Stop All (live), and a right-aligned follow-actions placeholder (M7+).- private Control BuildActionBar()- {- var addScene = new Border- {- Background = Raised, BorderBrush = BorderStrong, BorderThickness = new Thickness(1),- CornerRadius = new CornerRadius(Radius), Padding = new Thickness(9, 3),- Cursor = new Cursor(StandardCursorType.Hand),- Child = new TextBlock { Text = "+ Scene", FontSize = 11, Foreground = TextSecondary },- };- ToolTip.SetTip(addScene, "Add a scene");- addScene.PointerPressed += (_, _) => { _engine.AddScene(); Refresh(); };- AddHoverPress(addScene);+ var body = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ body.Children.Add(gridArea);+ Grid.SetColumn(_inspectorHost, 1); body.Children.Add(_inspectorHost);- var stopAll = new Border- {- Background = Raised, BorderBrush = BorderStrong, BorderThickness = new Thickness(1),- CornerRadius = new CornerRadius(Radius), Padding = new Thickness(9, 3),- Child = new TextBlock { Text = "Stop All", FontSize = 11, Foreground = TextSecondary },- };- stopAll.PointerPressed += (_, _) => { _engine.StopAllSession(); _engine.StopSessionRecord(); UpdateStates(); };- AddHoverPress(stopAll);+ var root = new DockPanel();+ var bar = BuildToolbar();+ DockPanel.SetDock(bar, Dock.Top);+ root.Children.Add(bar);+ root.Children.Add(body);+ Content = root;- // Lit only while session clips override the Arrangement; click returns every track to- // the timeline ("Back to Arrangement").- var backToArr = new Border- {- Background = Raised, BorderBrush = BorderStrong, BorderThickness = new Thickness(1),- CornerRadius = new CornerRadius(Radius), Padding = new Thickness(9, 3),- IsHitTestVisible = false,- Child = new TextBlock { Text = "Back to Arrangement", FontSize = 11, Foreground = NotaPalette.TextDisabled },- };- ToolTip.SetTip(backToArr, "Stop session clips and return all tracks to the Arrangement");- backToArr.PointerPressed += (_, _) => { _engine.BackToArrangement(); UpdateStates(); };- backToArr.Cursor = new Cursor(StandardCursorType.Hand); // press dim via its own accent highlight- _backToArr = backToArr;+ // A click anywhere in the view takes keyboard focus, so arrows / Enter / ⌘C… reach it.+ AddHandler(PointerPressedEvent, (_, _) => Focus(), Avalonia.Interactivity.RoutingStrategies.Tunnel, handledEventsToo: true);+ }- var follow = new StackPanel- {- Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Right,- Children =- {- new TextBlock { Text = "Follow actions", FontSize = 11, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center },- new NaBadge { Kind = NaBadgeKind.Future },- },- };+ // ---- model ------------------------------------------------------------------++ internal enum ColKind { Track, Group, Return, Master }- var grid = new Grid { Height = 34, ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*"), Margin = new Thickness(12, 8, 12, 0) };- var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { addScene, stopAll, backToArr } };- grid.Children.Add(left);- Grid.SetColumn(follow, 3);- follow.VerticalAlignment = VerticalAlignment.Center;- grid.Children.Add(follow);- return grid;+ private sealed class Column+ {+ public ColKind Kind;+ public int TrackId; // master: 0+ public string Name = "";+ public string KindLabel = "";+ public int ColorIndex;+ public bool IsInstrument;+ public bool IsAudio;+ public int GroupId = -1;+ public List<int> Children = new(); // group: every launchable track below it+ public double Width;+ public ColumnHeader? Header;+ public readonly List<Control> Cells = new();+ public MixerParts? Mixer;+ public SolidColorBrush Brush => ArrangementView.TrackBrush(ColorIndex);}+ private Column? ColumnFor(int trackId) => _cols.FirstOrDefault(c => c.TrackId == trackId && c.Kind is ColKind.Track or ColKind.Group);+ private IEnumerable<Column> LaunchCols => _cols.Where(c => c.Kind == ColKind.Track);+ private List<Column> NavCols => _cols.Where(c => c.Kind is ColKind.Track or ColKind.Group).ToList();+public void Refresh(){_headerRow.Children.Clear();- _slotsRow.Children.Clear();+ _cellsRow.Children.Clear();_footerRow.Children.Clear();- _cells.Clear();- _strips.Clear();- int scenes = _engine.SceneCount;+ _cols.Clear();+ _sceneCells.Clear();+ _sceneCount = _engine.SceneCount;- AddSceneRail(scenes);+ BuildColumns();+ AddSceneRail();+ foreach (var c in _cols) AddColumn(c);+ // Keep the selection on something that still exists.+ if (_sel.Scene >= _sceneCount) _sel = _sel with { Scene = Math.Max(0, _sceneCount - 1) };+ if (_sel.Kind == SelKind.Slot && ColumnFor(_sel.TrackId) is null)+ _sel = NavCols.FirstOrDefault() is { } first ? _sel with { TrackId = first.TrackId } : new Selection(SelKind.Scene, 0, _sel.Scene);++ SyncToolbar();+ UpdateStates();+ RebuildInspector();+ }++ private void BuildColumns()+ {int n = _engine.TrackCount;- int colorCounter = 0;- for (int i = 0; i < n; i++)+ var infos = new List<NotaTrackInfo>();+ for (int i = 0; i < n; i++) if (_engine.TryGetTrackInfo(i, out var ti)) infos.Add(ti);+ var byId = infos.ToDictionary(t => t.Id);++ bool Hidden(NotaTrackInfo t){- if (!_engine.TryGetTrackInfo(i, out var ti) || ti.IsReturn || ti.IsGroup) continue; // groups have no clip slots- AddTrackColumn(ti, scenes, colorCounter++ % TrackBase.Length);+ int g = t.GroupId, guard = 0;+ while (g > 0 && guard++ < 32)+ {+ if (_collapsed.Contains(g)) return true;+ g = byId.TryGetValue(g, out var p) ? p.GroupId : -1;+ }+ return false;}+ bool Under(NotaTrackInfo t, int groupId)+ {+ int g = t.GroupId, guard = 0;+ while (g > 0 && guard++ < 32) { if (g == groupId) return true; g = byId.TryGetValue(g, out var p) ? p.GroupId : -1; }+ return false;+ }+ string Parent(NotaTrackInfo t)+ => t.GroupId > 0 && byId.TryGetValue(t.GroupId, out var g) ? " · " + TrackNames.Of(_engine, g).ToUpperInvariant() : "";- AddMasterColumn(scenes);- UpdateStates();+ foreach (var ti in infos)+ {+ if (ti.IsReturn || Hidden(ti)) continue;+ var col = new Column+ {+ TrackId = ti.Id,+ Name = TrackNames.Of(_engine, ti),+ ColorIndex = ArrangementView.EffectiveColorIndex(_engine, ti.Id),+ GroupId = ti.GroupId,+ Width = TrackColW,+ };+ if (ti.IsGroup)+ {+ col.Kind = ColKind.Group;+ col.Children = infos.Where(c => !c.IsGroup && !c.IsReturn && Under(c, ti.Id)).Select(c => c.Id).ToList();+ col.KindLabel = $"GROUP · {col.Children.Count}{Parent(ti)}";+ }+ else+ {+ col.Kind = ColKind.Track;+ col.IsInstrument = ti.IsInstrument;+ col.IsAudio = ti.Type == 0;+ col.KindLabel = (ti.IsInstrument ? "MIDI" : "AUDIO") + Parent(ti);+ }+ _cols.Add(col);+ }+ int r = 0;+ foreach (var ti in infos.Where(t => t.IsReturn))+ {+ _cols.Add(new Column+ {+ Kind = ColKind.Return, TrackId = ti.Id, Name = TrackNames.Of(_engine, ti), KindLabel = "RETURN",+ ColorIndex = ArrangementView.ReturnColorIndex(r++), Width = ReturnColW,+ });+ }+ _cols.Add(new Column { Kind = ColKind.Master, TrackId = 0, Name = "Master", KindLabel = "OUT 1/2", ColorIndex = -1, Width = MasterColW });}- /// <summary>Re-reads live slot state + meters and recolours (no rebuild).</summary>+ // ---- live state ---------------------------------------------------------------++ /// <summary>Re-reads live slot state, progress and meters and repaints (no rebuild).</summary>public void UpdateStates(){+ ReadRecordTarget();_blinkFrame++;- bool blinkOn = (_blinkFrame / 8) % 2 == 0; // ~2Hz at a 30Hz clock- double pos = _engine.PositionBeats;- bool sessionOverride = false;- foreach (var c in _cells)+ _blinkOn = (_blinkFrame / 8) % 2 == 0; // ~2 Hz at the 30 Hz UI clock+ bool active = false;+ foreach (var c in _cols){- int st = _engine.SessionSlotState(c.TrackId, c.Scene);- if (st >= 2) sessionOverride = true; // queued / playing / recording → session has the track- c.ApplyState(st, blinkOn, pos);+ if (c.Kind != ColKind.Track) continue;+ if (_engine.SessionPlayingSlot(c.TrackId) >= 0) active = true;}- foreach (var s in _strips)- s.UpdateMeter(_engine);+ for (int s = 0; s < _sceneCount && !active; s++)+ foreach (var c in LaunchCols)+ if (_engine.SessionSlotState(c.TrackId, s) >= 2) { active = true; break; }+ _sessionActive = active;- // "Back to Arrangement" lights up (and becomes clickable) only while session overrides.- if (_backToArr is not null)+ // Cells repaint only when their state moved or while they animate (progress, blink).+ foreach (var c in _cols){- _backToArr.IsHitTestVisible = sessionOverride;- _backToArr.BorderBrush = sessionOverride ? Brass : BorderStrong;- ((TextBlock)_backToArr.Child!).Foreground = sessionOverride ? AccentBright : NotaPalette.TextDisabled;+ foreach (var cell in c.Cells) (cell as ILiveCell)?.Tick();+ c.Header?.Sync();+ c.Mixer?.UpdateMeter();}+ foreach (var sc in _sceneCells) sc.Tick();+ UpdateToolbar();+ UpdateInspectorLive();}- // ---- scene rail -------------------------------------------------------+ // ---- selection + commands ------------------------------------------------------ private void AddSceneRail(int scenes)+ private void Select(Selection sel){- _headerRow.Children.Add(new Border- {- Width = SceneRailW, Height = HeaderH,- Child = new TextBlock- {- Text = "SCENES", FontSize = 10, FontWeight = FontWeight.Bold,- Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center,- Margin = new Thickness(8, 0, 0, 0),- },- });+ var prev = _sel;+ _sel = sel;+ InvalidateAll();+ RebuildInspector();+ if (sel.Kind == SelKind.Slot && (prev.Kind != SelKind.Slot || prev.TrackId != sel.TrackId) && ColumnFor(sel.TrackId) is not null)+ SlotSelected?.Invoke(sel.TrackId, sel.Scene);+ }- var mid = new StackPanel { Width = SceneRailW, Spacing = Gap };- for (int s = 0; s < scenes; s++) mid.Children.Add(SceneRow(s));- _slotsRow.Children.Add(mid);+ private void InvalidateAll()+ {+ foreach (var c in _cols) { foreach (var cell in c.Cells) cell.InvalidateVisual(); c.Header?.Sync(); }+ foreach (var sc in _sceneCells) sc.InvalidateVisual();+ }- // No bottom controls on the scene rail — a spacer keeps the columns aligned.- _footerRow.Children.Add(new Border { Width = SceneRailW });+ // Rebuild one slot's cell (after an edit to it) instead of the whole grid, plus the group+ // slots that summarise it.+ private void RefreshSlot(int trackId, int scene)+ {+ if (ColumnFor(trackId) is not { Kind: ColKind.Track } c || scene < 0 || scene >= c.Cells.Count) { Refresh(); return; }+ ReplaceCell(c.Cells, scene, new SlotCell(this, c, scene));+ foreach (var g in _cols)+ if (g.Kind == ColKind.Group && g.Children.Contains(trackId)) ReplaceCell(g.Cells, scene, new GroupCell(this, g, scene));+ RebuildInspector();}- private Control SceneRow(int scene)+ private void RefreshScene(int scene){- var launch = IconButton(GlyphKind.Play, AccentBright, 22, 22, 9);- launch.PointerPressed += (_, _) => { _engine.LaunchScene(scene); UpdateStates(); };- ToolTip.SetTip(launch, $"Launch scene {scene + 1}");+ if (scene < 0 || scene >= _sceneCells.Count) { Refresh(); return; }+ var cell = new SceneCell(this, scene);+ var panel = (Panel)_sceneCells[scene].Parent!;+ panel.Children[panel.Children.IndexOf(_sceneCells[scene])] = cell;+ _sceneCells[scene] = cell;+ RebuildInspector();+ }- var texts = new StackPanel- {- VerticalAlignment = VerticalAlignment.Center,- Children =- {- new TextBlock { Text = $"Scene {scene + 1}", FontSize = 11, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary },- new MonoText($"{scene + 1:00}", 9, TextTertiary),- },- };+ private static void ReplaceCell(List<Control> cells, int index, Control cell)+ {+ var panel = (Panel)cells[index].Parent!;+ panel.Children[panel.Children.IndexOf(cells[index])] = cell;+ cells[index] = cell;+ }- var stop = IconButton(GlyphKind.Stop, TextTertiary, 14, 14, 6);- stop.PointerPressed += (_, _) => { _engine.StopScene(scene); UpdateStates(); };- ToolTip.SetTip(stop, $"Stop scene {scene + 1}");+ private void Say(string text) => Status?.Invoke(text);- var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };- var content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { launch, texts } };- row.Children.Add(content);- Grid.SetColumn(stop, 2);- stop.VerticalAlignment = VerticalAlignment.Center;- row.Children.Add(stop);+ private bool SlotFilled(int trackId, int scene) => _engine.SessionSlotState(trackId, scene) != 0;- var cell = new Border- {- Height = SlotH, Background = Card, BorderBrush = BorderDef,- BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(Radius),- Padding = new Thickness(8, 0), Child = row,- };- // Right-click a scene row → delete that scene (keeps at least one).- cell.PointerPressed += (_, e) =>- {- if (!e.GetCurrentPoint(cell).Properties.IsRightButtonPressed) return;- e.Handled = true;- var flyout = new MenuFlyout();- var del = new MenuItem { Header = $"Delete scene {scene + 1}", IsEnabled = _engine.SceneCount > 1 };- del.Click += (_, _) => { _engine.RemoveScene(scene); Refresh(); };- flyout.Items.Add(del);- flyout.ShowAt(cell, showAtPointer: true);- };- return cell;+ private void LaunchSceneRow(int scene)+ {+ _engine.LaunchScene(scene);+ Select(new Selection(SelKind.Scene, 0, _selectNextOnLaunch ? Math.Min(scene + 1, _sceneCount - 1) : scene));}- // ---- track column ------------------------------------------------------- private void AddTrackColumn(NotaTrackInfo ti, int scenes, int colorIndex)+ private void LaunchGroup(Column g, int scene){- var color = NotaPalette.TrackBrushes[colorIndex];- _headerRow.Children.Add(ColumnHeader((ti.IsInstrument ? "Inst " : "Audio ") + ti.Id, color));-- var mid = new StackPanel { Width = ColW, Spacing = Gap };- for (int s = 0; s < scenes; s++)- {- var slot = new SlotCell(this, ti.Id, s, ti.IsInstrument, color);- _cells.Add(slot);- mid.Children.Add(slot.Border);- }- _slotsRow.Children.Add(mid);+ foreach (int id in g.Children) _engine.LaunchSlot(id, scene);+ }- // Per-track stop nub + mini-mixer, pinned to the bottom.- var stop = new Border- {- Height = StopNubH, Background = Lane, BorderBrush = Raised,- BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(Radius),- Child = new Glyph(GlyphKind.Stop, 7) { Foreground = TextTertiary },- };- ToolTip.SetTip(stop, "Stop this track");- stop.PointerPressed += (_, _) => { _engine.StopSlot(ti.Id); UpdateStates(); };- AddHoverPress(stop);+ private void StopColumn(Column c)+ {+ if (c.Kind == ColKind.Group) foreach (int id in c.Children) _engine.StopSlot(id);+ else _engine.StopSlot(c.TrackId);+ }- _footerRow.Children.Add(new StackPanel { Width = ColW, Spacing = Gap, Children = { stop, BuildMiniMixer(ti, color) } });+ private void InsertMidiClip(int trackId, int scene)+ {+ _engine.AddSessionMidiClip(trackId, scene, 4.0);+ RefreshSlot(trackId, scene);}- private Control ColumnHeader(string name, IBrush topColor)+ /// <summary>Enter: launch the selected slot or scene.</summary>+ public void LaunchSelection(){- var grid = new Grid { RowDefinitions = new RowDefinitions("2,*") };- var spine = new Rectangle { Fill = topColor, Height = 2, Margin = new Thickness(Radius, 0, Radius, 0), VerticalAlignment = VerticalAlignment.Top };- var label = new TextBlock- {- Text = name, FontSize = 11, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary,- VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(7, 0, 7, 0),- TextTrimming = TextTrimming.CharacterEllipsis,- };- grid.Children.Add(spine);- Grid.SetRow(label, 1);- grid.Children.Add(label);- return new Border+ if (_sel.Kind == SelKind.Scene) { LaunchSceneRow(_sel.Scene); return; }+ if (ColumnFor(_sel.TrackId) is { } c){- Width = ColW, Height = HeaderH, Background = Card, BorderBrush = BorderDef,- BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(Radius), Child = grid,- };+ if (c.Kind == ColKind.Group) LaunchGroup(c, _sel.Scene);+ else _engine.LaunchSlot(c.TrackId, _sel.Scene);+ }}- private Control BuildMiniMixer(NotaTrackInfo ti, IBrush color)+ /// <summary>⌘C on the selected slot.</summary>+ public bool CopySelection(){- int id = ti.Id;- var vol = new MiniFader(ti.Volume, 1.5);- vol.ValueChanged += v => _engine.SetTrackVolume(id, (float)v);- var pan = new MiniFader((ti.Pan + 1) / 2, 1.0);- pan.ValueChanged += v => _engine.SetTrackPan(id, (float)(v * 2 - 1));-- var db = new MonoText("", 8, TextTertiary);- void RefreshDb() { double d = AudioMath.LinToDb(Math.Max(1e-4, vol.Value)); db.Text = vol.Value <= 1e-4 ? "−∞" : $"{d:+0.0;−0.0}"; }- vol.ValueChanged += _ => RefreshDb();- RefreshDb();+ if (_sel.Kind != SelKind.Slot || !SlotFilled(_sel.TrackId, _sel.Scene)) return false;+ _clip = (_sel.TrackId, _sel.Scene, false);+ Say("Copied clip");+ return true;+ }- var meter = new MiniMeter { Height = 4 };- var strip = new TrackStrip { TrackId = id, Meter = meter };- _strips.Add(strip);+ /// <summary>⌘X: the clip moves to where it is pasted next.</summary>+ public bool CutSelection()+ {+ if (_sel.Kind != SelKind.Slot || !SlotFilled(_sel.TrackId, _sel.Scene)) return false;+ _clip = (_sel.TrackId, _sel.Scene, true);+ Say("Cut clip — paste to move it");+ return true;+ }- var mute = MixToggle("M", false, ti.Muted != 0, v => _engine.SetTrackMute(id, v));- var solo = MixToggle("S", false, ti.Soloed != 0, v => _engine.SetTrackSolo(id, v));- if (ti.Armed != 0) _armed.Add(id);- var arm = ArmToggle(ti.Armed != 0, v =>- {- _engine.SetTrackArmed(id, v);- if (v) _armed.Add(id); else _armed.Remove(id);- UpdateStates(); // empty audio slots show/hide their record affordance on arm- });-- var btnRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*"), ColumnSpacing = 3 };- btnRow.Children.Add(mute);- Grid.SetColumn(solo, 1); btnRow.Children.Add(solo);- Grid.SetColumn(arm, 2); btnRow.Children.Add(arm);- var meterWrap = new Border { Height = 4, Background = Sunken, CornerRadius = NotaRadius.Clip, ClipToBounds = true, VerticalAlignment = VerticalAlignment.Center, Child = meter };- Grid.SetColumn(meterWrap, 3); meterWrap.Margin = new Thickness(2, 0, 0, 0);- btnRow.Children.Add(meterWrap);-- var body = new StackPanel { Spacing = 6 };- body.Children.Add(FaderRow("PAN", pan, null));- // One send fader per existing return bus (A, B, …) — nothing when there are no returns.- int returns = Math.Min(_engine.ReturnTrackCount, 4);- for (int b = 0; b < returns; b++)+ /// <summary>⌘V onto the selected slot.</summary>+ public bool PasteSelection()+ {+ if (_sel.Kind != SelKind.Slot || _clip is not { } src) return false;+ if (ColumnFor(_sel.TrackId) is not { Kind: ColKind.Track }) return false;+ bool move = src.Cut && (src.TrackId, src.Scene) != (_sel.TrackId, _sel.Scene);+ if (!MoveOrCopySlot(src.TrackId, src.Scene, _sel.TrackId, _sel.Scene, move)){- int bus = b;- var send = new MiniFader(_engine.GetTrackSend(id, bus), 1.0);- send.ValueChanged += v => _engine.SetTrackSend(id, bus, (float)v);- body.Children.Add(FaderRow(((char)('A' + bus)).ToString(), send, null));+ Say("Paste a MIDI clip onto a MIDI track, audio onto audio.");+ return true;}- body.Children.Add(FaderRow("VOLUME", vol, db));- body.Children.Add(btnRow);- return new Border- {- Background = Card, BorderBrush = BorderDef, BorderThickness = new Thickness(1),- CornerRadius = new CornerRadius(Radius), Padding = new Thickness(7), Child = body,- };+ if (move) _clip = (_sel.TrackId, _sel.Scene, false);+ Say(move ? "Moved clip" : "Pasted clip");+ return true;}- private Control FaderRow(string label, MiniFader fader, TextBlock? trailing)+ // Copy a slot onto another (same track kind), and for a move clear the source — one undo+ // step either way. Repaints just the two cells.+ private bool MoveOrCopySlot(int fromTrack, int fromScene, int toTrack, int toScene, bool move){- fader.VerticalAlignment = VerticalAlignment.Center;- var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };- grid.Children.Add(new TextBlock { Text = label, FontSize = 8, Foreground = TextTertiary, Width = 32, VerticalAlignment = VerticalAlignment.Center });- Grid.SetColumn(fader, 1);- grid.Children.Add(fader);- if (trailing is not null)+ _engine.BeginUndoGroup();+ bool ok;+ try{- Grid.SetColumn(trailing, 2);- trailing.VerticalAlignment = VerticalAlignment.Center;- trailing.Margin = new Thickness(4, 0, 0, 0);- grid.Children.Add(trailing);+ ok = _engine.CopySessionSlot(fromTrack, fromScene, toTrack, toScene);+ if (ok && move) _engine.ClearSessionSlot(fromTrack, fromScene);}- return grid;+ finally { _engine.EndUndoGroup(); }+ if (!ok) return false;+ if (move) RefreshSlot(fromTrack, fromScene);+ RefreshSlot(toTrack, toScene);+ return true;}- // Record-arm: neutral with a red disc at rest, solid record red with a pale disc when armed.- private Border ArmToggle(bool initial, Action<bool> set)+ /// <summary>F2: rename the selected clip or scene.</summary>+ public bool RenameSelection(){- bool on = initial;- var disc = new Glyph(GlyphKind.Record, 6);- var b = new Border { Width = 17, Height = 15, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Child = disc };- void Paint()+ if (_sel.Kind == SelKind.Scene){- b.Background = on ? Record : Raised;- b.BorderBrush = on ? Record : BorderStrong;- disc.Foreground = on ? NotaPalette.RecordInk : Record;+ int sc = _sel.Scene;+ PromptText(_sceneCells.Count > sc ? _sceneCells[sc] : this, _engine.GetSceneName(sc), t => { _engine.SetSceneName(sc, t); RefreshScene(sc); });+ return true;}- b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; e.Handled = true; on = !on; set(on); Paint(); };- Paint();- return b;+ if (ColumnFor(_sel.TrackId) is not { Kind: ColKind.Track } c || !SlotFilled(c.TrackId, _sel.Scene)) return false;+ int s = _sel.Scene, id = c.TrackId;+ PromptText(c.Cells[s], _engine.GetSessionClipName(id, s), t => { _engine.SetSessionClipName(id, s, t); RefreshSlot(id, s); });+ return true;}- private Border MixToggle(string label, bool danger, bool initial, Action<bool> set)+ /// <summary>⌘D: a scene duplicates below itself; a clip copies into the empty slot below.</summary>+ public bool DuplicateSelection(){- bool on = initial;- var t = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };- var b = new Border { Width = 17, Height = 15, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Child = t };- void Paint()- {- var accent = danger ? Danger : Brass;- b.Background = on ? accent : Raised;- b.BorderBrush = on ? accent : BorderStrong;- t.Foreground = on ? OnAccent : TextSecondary;+ if (_sel.Kind == SelKind.Scene)+ {+ int s = _engine.DuplicateScene(_sel.Scene);+ if (s < 0) return false;+ Refresh();+ Select(new Selection(SelKind.Scene, 0, s));+ Say("Duplicated scene");+ return true;}- b.PointerPressed += (_, e) => { e.Handled = true; on = !on; set(on); Paint(); };- Paint();- return b;+ int below = _sel.Scene + 1;+ if (!SlotFilled(_sel.TrackId, _sel.Scene)) return false;+ if (below >= _sceneCount || SlotFilled(_sel.TrackId, below)) { Say("The slot below is taken."); return true; }+ MoveOrCopySlot(_sel.TrackId, _sel.Scene, _sel.TrackId, below, move: false);+ Select(_sel with { Scene = below });+ Say("Duplicated clip");+ return true;}- // ---- master column ------------------------------------------------------ private void AddMasterColumn(int scenes)+ /// <summary>⌫: delete the selected clip or scene.</summary>+ public bool DeleteSelection(){- var header = ColumnHeader("Master", Brass);- ((Border)header).Background = Raised;- _headerRow.Children.Add(header);-- var mid = new StackPanel { Width = ColW, Spacing = Gap };- for (int s = 0; s < scenes; s++)+ if (_sel.Kind == SelKind.Scene){- int scene = s;- var launch = new StackPanel- {- Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center,- Children =- {- new Glyph(GlyphKind.Play, 9) { Foreground = AccentBright },- new TextBlock { Text = $"Scene {scene + 1}", FontSize = 10, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center },- },- };- var row = new Border- {- Height = SlotH, Background = Raised, BorderBrush = BorderDef, BorderThickness = new Thickness(1),- CornerRadius = new CornerRadius(Radius), Padding = new Thickness(8, 0), Child = launch,- };- row.PointerPressed += (_, _) => { _engine.LaunchScene(scene); UpdateStates(); };- AddHoverPress(row);- mid.Children.Add(row);+ if (!_engine.RemoveScene(_sel.Scene)) return false;+ Refresh();+ Say("Deleted scene");+ return true;}- _slotsRow.Children.Add(mid);-- var stopAll = new Border- {- Height = StopNubH, Background = Raised, BorderBrush = BorderStrong, BorderThickness = new Thickness(1),- CornerRadius = new CornerRadius(Radius),- Child = new StackPanel- {- Orientation = Orientation.Horizontal, Spacing = 5, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,- Children =- {- new Glyph(GlyphKind.Stop, 7) { Foreground = TextSecondary },- new TextBlock { Text = "Stop All", FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center },- },- },- };- stopAll.PointerPressed += (_, _) => { _engine.StopAllSession(); _engine.StopSessionRecord(); UpdateStates(); };- AddHoverPress(stopAll);- // Pin Stop All to the very bottom so it aligns with the track mixers' base.- _footerRow.Children.Add(new StackPanel { Width = ColW, VerticalAlignment = VerticalAlignment.Bottom, Children = { stopAll } });+ if (!_engine.ClearSessionSlot(_sel.TrackId, _sel.Scene)) return false;+ RefreshSlot(_sel.TrackId, _sel.Scene);+ Say("Deleted clip");+ return true;}- // ---- helpers ------------------------------------------------------------ private static Border IconButton(GlyphKind glyph, IBrush fg, double w, double h, double glyphSize = 9)+ /// <summary>⌘I: insert an empty scene below the selection.</summary>+ public bool InsertSceneAtSelection(){- var b = new Border- {- Width = w, Height = h, Background = Raised, BorderBrush = BorderStrong,- BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(Radius),- Child = new Glyph(glyph, glyphSize) { Foreground = fg },- };- AddHoverPress(b);- return b;+ int s = _engine.InsertScene(Math.Min(_sel.Scene + 1, _sceneCount));+ if (s < 0) return false;+ Refresh();+ Select(new Selection(SelKind.Scene, 0, s));+ Say("Inserted scene");+ return true;}- // Manual hover/press feedback for the hand-built Border "buttons" (these aren't themed- // Buttons, so they'd otherwise be visually inert): brass outline on hover, recess on press.- private static void AddHoverPress(Border b)+ private void CaptureScene(){- var restBorder = b.BorderBrush;- b.Cursor = new Cursor(StandardCursorType.Hand);- b.PointerEntered += (_, _) => { b.BorderBrush = Brass; };- var restBg = b.Background;- b.PointerExited += (_, _) => { b.BorderBrush = restBorder; b.Background = restBg; };- // Pressed goes into the recess (almanac § States) — the ground changes, nothing fades.- b.PointerPressed += (_, _) => { b.Background = NotaPalette.BgSunken; };- b.PointerReleased += (_, _) => { b.Background = restBg; };+ int s = _engine.CaptureScene(Math.Min(_sel.Scene + 1, _sceneCount));+ if (s < 0) return;+ if (string.IsNullOrEmpty(_engine.GetSceneName(s))) _engine.SetSceneName(s, "Captured");+ Refresh();+ Select(new Selection(SelKind.Scene, 0, s));+ Say("Captured the playing clips into a new scene");}- private sealed class MonoText : TextBlock+ private void ToArrangement(int trackId, int scene){- public MonoText(string text, double size, IBrush fg)- {- Text = text; FontSize = size; Foreground = fg;- this.BindResource(FontFamilyProperty, "Font.Mono");- }+ if (_engine.SessionSlotToArrangement(trackId, scene, _engine.PositionBeats) < 0) return;+ ArrangementChanged?.Invoke();+ Say("Copied clip to the arrangement at the playhead");}- // A live mini-mixer strip: keeps a handle to its meter for per-frame updates.- private sealed class TrackStrip+ protected override void OnKeyDown(KeyEventArgs e){- public int TrackId;- public MiniMeter Meter = null!;- public void UpdateMeter(IAudioEngine eng)- => Meter.SetLevel(eng.TryGetTrackMeter(TrackId, out var m) ? m.Peak : 0);+ if (HandleKey(e)) { e.Handled = true; return; }+ base.OnKeyDown(e);}- // A thin horizontal peak meter (green), width-agnostic.- private sealed class MiniMeter : Control+ private bool HandleKey(KeyEventArgs e){- private double _level;- public void SetLevel(double v) { v = Math.Clamp(v, 0, 1); if (Math.Abs(v - _level) < 0.005) return; _level = v; InvalidateVisual(); }- public override void Render(DrawingContext ctx)- {- double w = Bounds.Width, h = Bounds.Height;- if (w <= 0 || _level <= 0) return;- ctx.FillRectangle(Success, new Rect(0, 0, w * _level, h));+ if (e.Source is TextBox) return false;+ bool mod = ArrangementView.IsPrimaryDown(e.KeyModifiers);+ bool other = (e.KeyModifiers & (KeyModifiers.Alt | KeyModifiers.Shift)) != 0;+ var nav = NavCols;+ switch (e.Key)+ {+ case Key.Up or Key.Down or Key.Left or Key.Right when !mod:+ Move(e.Key, nav);+ return true;+ case Key.Back or Key.Delete when !mod:+ DeleteSelection();+ return true;+ case Key.F2 when !mod:+ RenameSelection();+ return true;}+ if (!mod || other) return false;+ return e.Key switch+ {+ Key.C => CopySelection(),+ Key.X => CutSelection(),+ Key.V => PasteSelection(),+ Key.D => DuplicateSelection(),+ Key.I => InsertSceneAtSelection(),+ _ => false,+ };}- // A single clip slot: owns its Border + repaints on state changes.- private sealed class SlotCell+ private void Move(Key key, List<Column> nav){- public int TrackId { get; }- public int Scene { get; }- public Border Border { get; }-- private readonly SessionView _owner;- private readonly bool _instrument;- private readonly IBrush _trackColor;- private readonly IBrush _trackBorder; // track colour @ ~45%- private readonly Glyph _icon;- private readonly TextBlock _label;- private readonly MonoText _badge;- private readonly Rectangle _progress;- private int _state = -2;- private bool _lastBlink;- private bool _lastArmed; // empty audio slots repaint their record affordance on arm changes-- public SlotCell(SessionView owner, int trackId, int scene, bool instrument, ISolidColorBrush trackColor)+ int s = _sel.Scene, last = Math.Max(0, _sceneCount - 1);+ if (_sel.Kind == SelKind.Scene){- _owner = owner;- TrackId = trackId;- Scene = scene;- _instrument = instrument;- _trackColor = trackColor;- _trackBorder = trackColor is SolidColorBrush slot- ? NotaPalette.Wash(slot, 0x73)- : new SolidColorBrush(Color.FromArgb(0x73, trackColor.Color.R, trackColor.Color.G, trackColor.Color.B));-- _icon = new Glyph(GlyphKind.Play, 9);- _label = new TextBlock { FontSize = 10, FontWeight = FontWeight.Medium, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };- _badge = new MonoText("", 8, TextTertiary) { VerticalAlignment = VerticalAlignment.Center };-- var topRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), VerticalAlignment = VerticalAlignment.Top };- var head = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, Children = { _icon, _label } };- topRow.Children.Add(head);- Grid.SetColumn(_badge, 2);- topRow.Children.Add(_badge);-- _progress = new Rectangle { Height = 2, Fill = Success, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom, Width = 0 };-- Border = new Border- {- Width = ColW, Height = SlotH, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(Radius),- Padding = new Thickness(7, 6), ClipToBounds = true,- Child = new Panel { Children = { topRow, _progress } },- };- Border.PointerPressed += OnPressed;-- // Accept both browser rows and external audio files (Finder / other apps) — same- // path the arrangement uses, so a slot fills from either source.- IBrush? savedBorder = null;- DragDrop.SetAllowDrop(Border, true);- DragDrop.AddDragOverHandler(Border, (_, e) =>- e.DragEffects = BrowserView.IsAcceptableDrag(e) ? DragDropEffects.Copy : DragDropEffects.None);- DragDrop.AddDragEnterHandler(Border, (_, e) =>- {- if (!BrowserView.IsAcceptableDrag(e)) return;- savedBorder = Border.BorderBrush; Border.BorderBrush = Brass; // highlight the target- });- DragDrop.AddDragLeaveHandler(Border, (_, _) =>- { if (savedBorder is not null) { Border.BorderBrush = savedBorder; savedBorder = null; } });- DragDrop.AddDropHandler(Border, (_, e) =>- {- if (savedBorder is not null) { Border.BorderBrush = savedBorder; savedBorder = null; }- var items = BrowserView.DroppedItems(e);- if (items.Count > 0)- { _owner.RaiseDrop(items[0], TrackId, Scene, _instrument); e.Handled = true; }- });+ if (key == Key.Up) Select(_sel with { Scene = Math.Max(0, s - 1) });+ else if (key == Key.Down) Select(_sel with { Scene = Math.Min(last, s + 1) });+ else if (key == Key.Right && nav.Count > 0) Select(new Selection(SelKind.Slot, nav[0].TrackId, s));+ return;}+ int i = Math.Max(0, nav.FindIndex(c => c.TrackId == _sel.TrackId));+ if (key == Key.Up) s = Math.Max(0, s - 1);+ if (key == Key.Down) s = Math.Min(last, s + 1);+ if (key == Key.Left) { if (i == 0) { Select(new Selection(SelKind.Scene, 0, s)); return; } i--; }+ if (key == Key.Right) i = Math.Min(nav.Count - 1, i + 1);+ if (nav.Count > 0) Select(new Selection(SelKind.Slot, nav[i].TrackId, s));+ }- private void OnPressed(object? sender, PointerPressedEventArgs e)- {- // Right-click a filled slot (any type) → its context menu (delete, + more for MIDI).- if (_state >= 1 && e.GetCurrentPoint(Border).Properties.IsRightButtonPressed)- { ShowSlotMenu(); return; }+ // ---- shared paint helpers -------------------------------------------------------- // Click a recording slot → stop recording (the take materialises and loops back).- if (_state == 4)- { _owner._engine.StopSessionRecord(); _owner.Refresh(); return; }+ // A clip's colour: its own palette index, else its track's.+ private SolidColorBrush ClipBrush(Column c, int scene)+ => _engine.TryGetSessionClipProps(c.TrackId, scene, out var p) && p.Color >= 0 ? ArrangementView.TrackBrush(p.Color) : c.Brush;- // Armed track: click a slot to record into it (overdub MIDI / capture- // audio input, M5-4). Per-track arm from the mini-mixer.- if (_owner._armed.Contains(TrackId))- { _owner._engine.RecordSessionSlot(TrackId, Scene); _owner.Refresh(); return; }+ private string ClipName(Column c, int scene)+ {+ string n = _engine.GetSessionClipName(c.TrackId, scene);+ return n.Length > 0 ? n : $"{c.Name} {scene + 1}";+ }- bool filled = _state >= 1;- if (filled)- {- // Double-click edits (piano roll for MIDI, audio-slot editor for audio); single- // click launches.- if (e.ClickCount == 2) _owner.SlotEditRequested?.Invoke(TrackId, Scene);- else _owner._engine.LaunchSlot(TrackId, Scene);- _owner.UpdateStates();- }- else if (_instrument)- {- _owner._engine.AddSessionMidiClip(TrackId, Scene, 4.0);- _owner.Refresh();- }- else if (e.GetCurrentPoint(Border).Properties.IsLeftButtonPressed)- {- // Empty audio slot: one-click record — arm the track first if it isn't already.- if (!_owner._armed.Contains(TrackId))- { _owner._engine.SetTrackArmed(TrackId, true); _owner._armed.Add(TrackId); }- _owner._engine.RecordSessionSlot(TrackId, Scene);- _owner.Refresh();- }- }+ private string SceneName(int scene)+ {+ string n = _engine.GetSceneName(scene);+ return n.Length > 0 ? n : $"Scene {scene + 1}";+ }- private void ShowSlotMenu()- {- var flyout = new MenuFlyout();- if (_instrument)- {- var lengths = new MenuItem { Header = "Loop length" };- foreach (double beats in new[] { 1.0, 2.0, 4.0, 8.0, 16.0 })- {- double b = beats;- var item = new MenuItem { Header = $"{b:0.#} beats" };- item.Click += (_, _) => { _owner._engine.SetSessionSlotLength(TrackId, Scene, b); _owner.UpdateStates(); };- lengths.Items.Add(item);- }- flyout.Items.Add(lengths);- var toArr = new MenuItem { Header = "Copy to arrangement (at playhead)" };- toArr.Click += (_, _) =>- {- _owner._engine.SessionSlotToArrangement(TrackId, Scene, _owner._engine.PositionBeats);- _owner.ArrangementChanged?.Invoke();- };- flyout.Items.Add(toArr);- flyout.Items.Add(new Separator());- }- var del = new MenuItem { Header = "Delete clip" };- del.Click += (_, _) => { _owner._engine.ClearSessionSlot(TrackId, Scene); _owner.Refresh(); };- flyout.Items.Add(del);- flyout.ShowAt(Border, showAtPointer: true);- }+ /// <summary>"2 bars", "3 beats", "2.2 bars" — a clip length as the grid shows it.</summary>+ internal static string FormatLength(double beats)+ {+ if (beats <= 0) return "";+ if (Math.Abs(beats % 4) < 1e-6) { int n = (int)Math.Round(beats / 4); return n == 1 ? "1 bar" : $"{n} bars"; }+ if (beats < 4) return NotaNum.Str(beats, "0.##") + (Math.Abs(beats - 1) < 1e-6 ? " beat" : " beats");+ return $"{(int)(beats / 4)}.{NotaNum.Str(beats % 4, "0.##")} bars";+ }- // 0 empty, 1 filled, 2 queued, 3 playing, 4 recording.- public void ApplyState(int state, bool blinkOn, double posBeats)- {- // Loop-length badge (M5-5) + progress bar update every call (live).- double len = state >= 1 ? _owner._engine.SessionSlotLength(TrackId, Scene) : 0;- _badge.Text = len > 0 ? $"{len:0.#}b" : "";+ /// <summary>bars.beats.sixteenths, 1-based, the way positions read in the transport.</summary>+ internal static string FormatPosition(double beats)+ {+ beats = Math.Max(0, beats);+ int bar = (int)(beats / 4) + 1, beat = (int)(beats % 4) + 1, six = (int)(beats % 1 * 4) + 1;+ return $"{bar}.{beat}.{six}";+ }- if (state == 3 && len > 0)- {- double frac = (posBeats % len) / len;- _progress.Width = Math.Clamp(frac, 0, 1) * (ColW - 2);- }- else _progress.Width = 0;-- // An empty audio slot's affordance depends on the track's arm state, so it must- // also repaint when arming toggles (not just on a slot-state change).- bool armed = _owner._armed.Contains(TrackId);- bool armAffordance = state == 0 && !_instrument;-- // Queued cells blink at ~2Hz; repaint on state / blink-phase / arm change.- if (state == _state && (state != 2 || blinkOn == _lastBlink)- && (!armAffordance || armed == _lastArmed)) return;- _state = state;- _lastBlink = blinkOn;- _lastArmed = armed;- ToolTip.SetTip(Border, state == 4 ? "Click to stop recording" : null);-- switch (state)- {- case 4: // recording- Border.Background = RedFill; Border.BorderBrush = Record;- _icon.Kind = GlyphKind.Record; _icon.IsVisible = true; _icon.Foreground = Record;- _label.Text = "rec"; _label.Foreground = Record;- break;- case 3: // playing- Border.Background = GreenFill; Border.BorderBrush = Success;- _icon.Kind = GlyphKind.Play; _icon.IsVisible = true; _icon.Foreground = Success;- _label.Text = "Clip"; _label.Foreground = TextPrimary;- break;- case 2: // queued — border blinks 100%↔40% at ~2Hz (HANDOFF §4)- Border.Background = AmberFill;- Border.BorderBrush = blinkOn ? Warning : Warning40;- _icon.Kind = GlyphKind.Play; _icon.IsVisible = true; _icon.Foreground = Warning;- _label.Text = "Clip"; _label.Foreground = Warning;- break;- case 1: // filled- Border.Background = Raised; Border.BorderBrush = _trackBorder;- _icon.Kind = GlyphKind.Play; _icon.IsVisible = true; _icon.Foreground = _trackColor;- _label.Text = "Clip"; _label.Foreground = TextPrimary;- break;- default: // empty- Border.Background = Lane; Border.BorderBrush = BorderDef;- if (_instrument)- {- // Instrument: "+" to create a MIDI clip.- _icon.IsVisible = false;- _label.Text = "+"; _label.Foreground = TextDisabled;- }- else if (armed)- {- // Armed audio track: a red record dot — click to capture input here.- _icon.Kind = GlyphKind.Record; _icon.IsVisible = true; _icon.Foreground = Record;- _label.Text = "Rec"; _label.Foreground = Record;- }- else- {- // Idle audio slot: a faint hollow ring hints it's a record / drop target.- _icon.Kind = GlyphKind.RecordRing; _icon.IsVisible = true; _icon.Foreground = TextDisabled;- _label.Text = ""; _label.Foreground = TextDisabled;- }- break;- }- }+ /// <summary>A duration as bars.beats.sixteenths (0-based), like a follow time "2.0.0".</summary>+ internal static string FormatDuration(double beats)+ {+ beats = Math.Max(0, beats);+ return $"{(int)(beats / 4)}.{(int)(beats % 4)}.{(int)Math.Round(beats % 1 * 4)}";}}diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 69efabc3..8dda5649 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -143,6 +143,45 @@ public struct NotaSessionAudioSlotpublic float Gain;}+/// <summary>How a session clip reacts to its launch button (Session P0).</summary>+public enum SessionLaunchMode { Trigger = 0, Gate = 1, Toggle = 2, Repeat = 3 }++/// <summary>What a session clip does once it has played its follow time (Session P0).</summary>+public enum SessionFollowAction { None = 0, Stop, Again, Previous, Next, First, Last, Any, Other, Jump }++/// <summary>Session clip (slot) properties. Matches native NotaSessionClipProps (Session P0).+/// Color is a track-palette index (-1 = the track's colour); QuantBeats < 0 = global;+/// ChanceA/B are relative weights 0..100; FollowBeats 0 = one pass.</summary>+[StructLayout(LayoutKind.Sequential)]+public struct NotaSessionClipProps+{+ public int Color;+ public int LaunchMode;+ public double QuantBeats;+ public int Legato;+ public int Loop;+ public float VelocityAmount;+ public int FollowA;+ public int FollowB;+ public int ChanceA;+ public int ChanceB;+ public double FollowBeats;+ public int JumpScene;+}++/// <summary>Scene row properties. Matches native NotaSceneProps (Session P0). Color is a+/// track-palette index (-1 = neutral); Tempo / SigNum+SigDen > 0 apply on launch.</summary>+[StructLayout(LayoutKind.Sequential)]+public struct NotaSceneProps+{+ public int Color;+ public double Tempo;+ public int SigNum;+ public int SigDen;+ public int Follow;+ public double FollowBeats;+}+/// <summary>Post-fader level meter (linear 0..1). Matches native NotaMeter (M6-2).</summary>[StructLayout(LayoutKind.Sequential)]public struct NotaMeterdiff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 6d0d811d..fa31d324 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -105,6 +105,55 @@ public interface IAudioEngine : IDisposablevoid SetSessionNotes(int trackId, int scene, NotaNote[] notes);NotaNote[] GetSessionNotes(int trackId, int scene);+ // --- Session P0: clip + scene properties, scene/slot editing, follow ------+ /// <summary>Properties of a filled slot; false when the slot is empty.</summary>+ bool TryGetSessionClipProps(int trackId, int scene, out NotaSessionClipProps props);+ bool SetSessionClipProps(int trackId, int scene, NotaSessionClipProps props);+ /// <summary>Clip name (empty = unnamed).</summary>+ string GetSessionClipName(int trackId, int scene);+ void SetSessionClipName(int trackId, int scene, string name);+ /// <summary>An empty slot's stop button: true (default) = launching its scene stops the track.</summary>+ bool GetSessionSlotStopButton(int trackId, int scene);+ void SetSessionSlotStopButton(int trackId, int scene, bool on);+ /// <summary>Copies a slot (clip + properties) onto a slot of a same-kind track.</summary>+ bool CopySessionSlot(int srcTrackId, int srcScene, int dstTrackId, int dstScene);+ bool TryGetSceneProps(int scene, out NotaSceneProps props);+ void SetSceneProps(int scene, NotaSceneProps props);+ string GetSceneName(int scene);+ void SetSceneName(int scene, string name);+ /// <summary>Inserts an empty row at <paramref name="at"/>; returns it or -1.</summary>+ int InsertScene(int at);+ /// <summary>Copies a row below itself; returns the new row or -1.</summary>+ int DuplicateScene(int scene);+ /// <summary>Inserts a row at <paramref name="at"/> holding the clips playing now.</summary>+ int CaptureScene(int at);+ /// <summary>Moves a scene row (slots + properties) to another index; players follow.</summary>+ bool MoveScene(int from, int to);+ /// <summary>True once after a launched scene applied its tempo / signature (0 = unchanged),+ /// so the transport can show the new values.</summary>+ bool TakeSceneTempoChange(out double bpm, out int num, out int den);+ /// <summary>Launch with a velocity 0..1, scaled by the clip's velocity amount.</summary>+ void LaunchSlotVelocity(int trackId, int scene, float velocity);+ /// <summary>The launch button was released: stops a Gate / Repeat clip.</summary>+ void ReleaseSlot(int trackId, int scene);+ /// <summary>Hands one track back to the Arrangement (stops its session clip now).</summary>+ void TrackBackToArrangement(int trackId);+ /// <summary>Playing slot of a track, or -1.</summary>+ int SessionPlayingSlot(int trackId);+ /// <summary>Loop-local position of the playing slot, in beats.</summary>+ double SessionSlotPosition(int trackId);+ double LaunchQuant { get; }+ /// <summary>Global follow-action switch.</summary>+ bool SessionFollow { get; set; }+ /// <summary>Fixed session record length in beats (0 = off).</summary>+ double SessionRecordLength { get; set; }+ /// <summary>Session Rec: records into the first armed track with an empty slot in the row; returns that track id or 0.</summary>+ int RecordSessionScene(int scene);+ /// <summary>The in-progress session take, if any.</summary>+ bool TryGetSessionRecordTarget(out int trackId, out int scene, out double elapsedBeats);+ /// <summary>Min/max peak pairs over an audio slot's take; returns the bucket count.</summary>+ int GetSessionSlotPeaks(int trackId, int scene, float[] outMinMax, int maxPoints);+// --- Arrangement geometry (M4) -----------------------------------------bool TryGetTrackInfo(int index, out NotaTrackInfo info);bool TryGetClipInfo(int trackId, int clipIndex, out NotaClipInfo info);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Session.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Session.csindex 083101a1..f109b63a 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Session.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Session.cs@@ -2,6 +2,7 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.using System.Runtime.InteropServices;+using Nota.Application;namespace Nota.Infrastructure;@@ -100,4 +101,92 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_session_add_audio_file", StringMarshalling = StringMarshalling.Utf8)]internal static partial int SessionAddAudioFile(IntPtr engine, int trackId, int scene, string path);++ // --- Session P0 -------------------------------------------------------------+ [LibraryImport(Lib, EntryPoint = "nota_session_get_clip_props")]+ internal static partial int SessionGetClipProps(IntPtr engine, int trackId, int scene, out NotaSessionClipProps props);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_clip_props")]+ internal static partial NotaResult SessionSetClipProps(IntPtr engine, int trackId, int scene, in NotaSessionClipProps props);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_clip_name")]+ internal static partial int SessionGetClipName(IntPtr engine, int trackId, int scene, [Out] byte[] outBuf, int cap);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_clip_name", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial NotaResult SessionSetClipName(IntPtr engine, int trackId, int scene, string name);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_slot_stop_button")]+ internal static partial int SessionGetSlotStopButton(IntPtr engine, int trackId, int scene);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_slot_stop_button")]+ internal static partial NotaResult SessionSetSlotStopButton(IntPtr engine, int trackId, int scene, int on);++ [LibraryImport(Lib, EntryPoint = "nota_session_copy_slot")]+ internal static partial NotaResult SessionCopySlot(IntPtr engine, int srcTrack, int srcScene, int dstTrack, int dstScene);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_scene_props")]+ internal static partial int SessionGetSceneProps(IntPtr engine, int scene, out NotaSceneProps props);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_scene_props")]+ internal static partial NotaResult SessionSetSceneProps(IntPtr engine, int scene, in NotaSceneProps props);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_scene_name")]+ internal static partial int SessionGetSceneName(IntPtr engine, int scene, [Out] byte[] outBuf, int cap);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_scene_name", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial NotaResult SessionSetSceneName(IntPtr engine, int scene, string name);++ [LibraryImport(Lib, EntryPoint = "nota_session_insert_scene")]+ internal static partial int SessionInsertScene(IntPtr engine, int at);++ [LibraryImport(Lib, EntryPoint = "nota_session_duplicate_scene")]+ internal static partial int SessionDuplicateScene(IntPtr engine, int scene);++ [LibraryImport(Lib, EntryPoint = "nota_session_capture_scene")]+ internal static partial int SessionCaptureScene(IntPtr engine, int at);++ [LibraryImport(Lib, EntryPoint = "nota_session_launch_slot_vel")]+ internal static partial NotaResult SessionLaunchSlotVel(IntPtr engine, int trackId, int scene, float velocity);++ [LibraryImport(Lib, EntryPoint = "nota_session_release_slot")]+ internal static partial NotaResult SessionReleaseSlot(IntPtr engine, int trackId, int scene);++ [LibraryImport(Lib, EntryPoint = "nota_session_track_back_to_arrangement")]+ internal static partial NotaResult SessionTrackBackToArrangement(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_session_playing_slot")]+ internal static partial int SessionPlayingSlot(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_session_slot_position")]+ internal static partial double SessionSlotPosition(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_launch_quant")]+ internal static partial double SessionGetLaunchQuant(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_follow")]+ internal static partial NotaResult SessionSetFollow(IntPtr engine, int on);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_follow")]+ internal static partial int SessionGetFollow(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_session_set_record_length")]+ internal static partial NotaResult SessionSetRecordLength(IntPtr engine, double beats);++ [LibraryImport(Lib, EntryPoint = "nota_session_get_record_length")]+ internal static partial double SessionGetRecordLength(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_session_record_scene")]+ internal static partial int SessionRecordScene(IntPtr engine, int scene);++ [LibraryImport(Lib, EntryPoint = "nota_session_record_target")]+ internal static partial int SessionRecordTarget(IntPtr engine, out int trackId, out int scene, out double elapsed);++ [LibraryImport(Lib, EntryPoint = "nota_session_slot_peaks")]+ internal static partial int SessionSlotPeaks(IntPtr engine, int trackId, int scene, [Out] float[] outMinMax, int maxPoints);++ [LibraryImport(Lib, EntryPoint = "nota_session_move_scene")]+ internal static partial NotaResult SessionMoveScene(IntPtr engine, int from, int to);++ [LibraryImport(Lib, EntryPoint = "nota_session_take_scene_tempo")]+ internal static partial int SessionTakeSceneTempo(IntPtr engine, out double bpm, out int num, out int den);}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.csindex f17413f5..d2290e8a 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.cs@@ -1,6 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+using Nota.Application;+namespace Nota.Infrastructure;public sealed partial class NotaEngine@@ -128,4 +130,82 @@ public sealed partial class NotaEngine/// <summary>Drops a whole audio file into a session slot, auto-computing loop length (M7-5).</summary>public bool AddSessionAudioFile(int trackId, int scene, string path){ ThrowIfDisposed(); return NativeMethods.SessionAddAudioFile(_handle, trackId, scene, path) != 0; }++ // --- Session P0 -------------------------------------------------------------++ public bool TryGetSessionClipProps(int trackId, int scene, out NotaSessionClipProps props)+ { ThrowIfDisposed(); return NativeMethods.SessionGetClipProps(_handle, trackId, scene, out props) != 0; }++ public bool SetSessionClipProps(int trackId, int scene, NotaSessionClipProps props)+ { ThrowIfDisposed(); return NativeMethods.SessionSetClipProps(_handle, trackId, scene, in props) == NativeMethods.NotaResult.Ok; }++ public string GetSessionClipName(int trackId, int scene)+ { ThrowIfDisposed(); return ReadNativeString((b, c) => NativeMethods.SessionGetClipName(_handle, trackId, scene, b, c)); }++ public void SetSessionClipName(int trackId, int scene, string name)+ { ThrowIfDisposed(); NativeMethods.SessionSetClipName(_handle, trackId, scene, name ?? ""); }++ public bool GetSessionSlotStopButton(int trackId, int scene)+ { ThrowIfDisposed(); return NativeMethods.SessionGetSlotStopButton(_handle, trackId, scene) != 0; }++ public void SetSessionSlotStopButton(int trackId, int scene, bool on)+ { ThrowIfDisposed(); NativeMethods.SessionSetSlotStopButton(_handle, trackId, scene, on ? 1 : 0); }++ public bool CopySessionSlot(int srcTrackId, int srcScene, int dstTrackId, int dstScene)+ { ThrowIfDisposed(); return NativeMethods.SessionCopySlot(_handle, srcTrackId, srcScene, dstTrackId, dstScene) == NativeMethods.NotaResult.Ok; }++ public bool TryGetSceneProps(int scene, out NotaSceneProps props)+ { ThrowIfDisposed(); return NativeMethods.SessionGetSceneProps(_handle, scene, out props) != 0; }++ public void SetSceneProps(int scene, NotaSceneProps props)+ { ThrowIfDisposed(); NativeMethods.SessionSetSceneProps(_handle, scene, in props); }++ public string GetSceneName(int scene)+ { ThrowIfDisposed(); return ReadNativeString((b, c) => NativeMethods.SessionGetSceneName(_handle, scene, b, c)); }++ public void SetSceneName(int scene, string name)+ { ThrowIfDisposed(); NativeMethods.SessionSetSceneName(_handle, scene, name ?? ""); }++ public int InsertScene(int at) { ThrowIfDisposed(); return NativeMethods.SessionInsertScene(_handle, at); }+ public int DuplicateScene(int scene) { ThrowIfDisposed(); return NativeMethods.SessionDuplicateScene(_handle, scene); }+ public int CaptureScene(int at) { ThrowIfDisposed(); return NativeMethods.SessionCaptureScene(_handle, at); }++ public void LaunchSlotVelocity(int trackId, int scene, float velocity)+ { ThrowIfDisposed(); Check(NativeMethods.SessionLaunchSlotVel(_handle, trackId, scene, velocity)); }++ public void ReleaseSlot(int trackId, int scene)+ { ThrowIfDisposed(); Check(NativeMethods.SessionReleaseSlot(_handle, trackId, scene)); }++ public void TrackBackToArrangement(int trackId)+ { ThrowIfDisposed(); Check(NativeMethods.SessionTrackBackToArrangement(_handle, trackId)); }++ public int SessionPlayingSlot(int trackId) { ThrowIfDisposed(); return NativeMethods.SessionPlayingSlot(_handle, trackId); }+ public double SessionSlotPosition(int trackId) { ThrowIfDisposed(); return NativeMethods.SessionSlotPosition(_handle, trackId); }+ public double LaunchQuant { get { ThrowIfDisposed(); return NativeMethods.SessionGetLaunchQuant(_handle); } }++ public bool SessionFollow+ {+ get { ThrowIfDisposed(); return NativeMethods.SessionGetFollow(_handle) != 0; }+ set { ThrowIfDisposed(); NativeMethods.SessionSetFollow(_handle, value ? 1 : 0); }+ }++ public double SessionRecordLength+ {+ get { ThrowIfDisposed(); return NativeMethods.SessionGetRecordLength(_handle); }+ set { ThrowIfDisposed(); NativeMethods.SessionSetRecordLength(_handle, value); }+ }++ public int RecordSessionScene(int scene) { ThrowIfDisposed(); return NativeMethods.SessionRecordScene(_handle, scene); }++ public bool TryGetSessionRecordTarget(out int trackId, out int scene, out double elapsedBeats)+ { ThrowIfDisposed(); return NativeMethods.SessionRecordTarget(_handle, out trackId, out scene, out elapsedBeats) != 0; }++ public int GetSessionSlotPeaks(int trackId, int scene, float[] outMinMax, int maxPoints)+ { ThrowIfDisposed(); return NativeMethods.SessionSlotPeaks(_handle, trackId, scene, outMinMax, Math.Min(maxPoints, outMinMax.Length / 2)); }++ public bool MoveScene(int from, int to)+ { ThrowIfDisposed(); return NativeMethods.SessionMoveScene(_handle, from, to) == NativeMethods.NotaResult.Ok; }++ public bool TakeSceneTempoChange(out double bpm, out int num, out int den)+ { ThrowIfDisposed(); return NativeMethods.SessionTakeSceneTempo(_handle, out bpm, out num, out den) != 0; }}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex 8c9be15d..4cdddb13 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -24,6 +24,9 @@ public sealed class ProjectDocumentpublic string App { get; set; } = "Nota";public TransportDto Transport { get; set; } = new();public int SceneCount { get; set; } = 8;+ /// <summary>Session view settings + scene rows (names, colours, tempo, follow). Null in+ /// files from before Session P0 = defaults.</summary>+ public SessionDto? Session { get; set; }public List<TrackDto> Tracks { get; set; } = new();/// <summary>Master-volume automation points (graph-level, format v7).</summary>public List<AutomationPointDto> MasterVolumeAutomation { get; set; } = new();@@ -97,6 +100,8 @@ public sealed class TrackDtopublic List<MidiClipDto> MidiClips { get; set; } = new();public List<AudioClipDto> AudioClips { get; set; } = new();public List<SessionSlotDto> SessionSlots { get; set; } = new();+ /// <summary>Empty slots whose stop button was removed (scene launch leaves the track playing).</summary>+ public List<int>? SessionNoStop { get; set; }public List<AutomationLaneDto> Automation { get; set; } = new(); // M9-A4 (format v2)public List<ModulatorDto> Modulators { get; set; } = new(); // CV modulation sources (Phase 3)public List<CvLinkDto> CvLinks { get; set; } = new(); // CV modulation edges (Phase 3)@@ -317,6 +322,30 @@ public sealed class MidiClipDto[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }}+public sealed class SessionDto+{+ public double LaunchQuant { get; set; } = 4.0;+ public bool Follow { get; set; } = true;+ public double RecordLength { get; set; }+ public List<SceneDto> Scenes { get; set; } = new();++ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }+}++public sealed class SceneDto+{+ public int Index { get; set; }+ public string? Name { get; set; }+ public int Color { get; set; } = -1;+ public double Tempo { get; set; }+ public int SigNum { get; set; }+ public int SigDen { get; set; }+ public bool Follow { get; set; }+ public double FollowBeats { get; set; } = 32.0;++ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }+}+public sealed class SessionSlotDto{public int Scene { get; set; }@@ -324,6 +353,20 @@ public sealed class SessionSlotDtopublic NoteDto[] Notes { get; set; } = System.Array.Empty<NoteDto>();/// <summary>Set for audio-track slots (a captured take); Notes is empty then.</summary>public AudioClipDto? Audio { get; set; }+ // Clip properties (Session P0); defaults match a fresh clip.+ public string? Name { get; set; }+ public int Color { get; set; } = -1;+ public int LaunchMode { get; set; }+ public double Quant { get; set; } = -1.0;+ public bool Legato { get; set; }+ public bool Loop { get; set; } = true;+ public float VelocityAmount { get; set; }+ public int FollowA { get; set; }+ public int FollowB { get; set; }+ public int ChanceA { get; set; } = 100;+ public int ChanceB { get; set; }+ public double FollowBeats { get; set; }+ public int JumpScene { get; set; }[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex b9328857..61cb0ab9 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -57,6 +57,7 @@ public sealed class ProjectService{SessionNames = !contentNames,SceneCount = engine.SceneCount,+ Session = CaptureSession(engine),Transport = new TransportDto{Bpm = transport.Bpm,@@ -212,24 +213,26 @@ public sealed class ProjectService// Session slots.for (int s = 0; s < engine.SceneCount; s++){+ if (!engine.GetSessionSlotStopButton(ti.Id, s) && engine.SessionSlotState(ti.Id, s) == 0)+ (t.SessionNoStop ??= new List<int>()).Add(s);// Persist any slot that holds a clip — skip only truly empty ones. (A slot// that's playing/queued/recording is state 2-4, not 1, but still has content;// gating on == 1 dropped it when saving mid-jam.)if (engine.SessionSlotState(ti.Id, s) == 0) continue;if (ti.IsInstrument){- t.SessionSlots.Add(new SessionSlotDto+ t.SessionSlots.Add(WithClipProps(engine, ti.Id, new SessionSlotDto{Scene = s,LengthBeats = engine.SessionSlotLength(ti.Id, s),Notes = ToDtos(engine.GetSessionNotes(ti.Id, s)),- });+ }));}else if (ti.Type == 0 && engine.TryGetSessionAudioSlot(ti.Id, s, out var sa)){string? rel = RegisterSample(doc, engine, sa.SampleId, warnings);if (rel == null) continue;- t.SessionSlots.Add(new SessionSlotDto+ t.SessionSlots.Add(WithClipProps(engine, ti.Id, new SessionSlotDto{Scene = s,LengthBeats = sa.LengthBeats,@@ -240,7 +243,7 @@ public sealed class ProjectServiceLengthFrames = sa.LengthFrames,Gain = sa.Gain,},- });+ }));}}@@ -436,6 +439,7 @@ public sealed class ProjectService// hold more/fewer scenes than the fresh default after add/remove-scene edits).while (engine.SceneCount < doc.SceneCount) engine.AddScene();while (engine.SceneCount > doc.SceneCount && engine.SceneCount > 1) engine.RemoveScene(engine.SceneCount - 1);+ ApplySession(engine, doc.Session);// Doc index -> new live track id, and deferred sidechain wiring (a source may be// a track created later), both resolved after every track exists (Phase B).@@ -649,7 +653,10 @@ public sealed class ProjectServiceengine.AddSessionMidiClip(id, sl.Scene, sl.LengthBeats);if (sl.Notes.Length > 0) engine.SetSessionNotes(id, sl.Scene, ToNotes(sl.Notes));}+ ApplyClipProps(engine, id, sl);}+ if (t.SessionNoStop is { } noStop)+ foreach (int sc in noStop) engine.SetSessionSlotStopButton(id, sc, false);// Automation lanes (M9-A4). Devices are already rebuilt above, so// DeviceParam lanes resolve to the same chain positions; plugin-param@@ -941,4 +948,70 @@ public sealed class ProjectServicefor (int i = 0; i < dtos.Length; i++) arr[i] = dtos[i].ToNote();return arr;}++ // --- Session P0: clip + scene properties ------------------------------------++ private static SessionDto CaptureSession(IAudioEngine engine)+ {+ var dto = new SessionDto+ {+ LaunchQuant = engine.LaunchQuant,+ Follow = engine.SessionFollow,+ RecordLength = engine.SessionRecordLength,+ };+ for (int s = 0; s < engine.SceneCount; s++)+ {+ if (!engine.TryGetSceneProps(s, out var p)) continue;+ string name = engine.GetSceneName(s);+ if (name.Length == 0 && p.Color < 0 && p.Tempo <= 0 && p.SigNum <= 0 && p.Follow == 0) continue;+ dto.Scenes.Add(new SceneDto+ {+ Index = s, Name = name.Length > 0 ? name : null, Color = p.Color, Tempo = p.Tempo,+ SigNum = p.SigNum, SigDen = p.SigDen, Follow = p.Follow != 0, FollowBeats = p.FollowBeats,+ });+ }+ return dto;+ }++ private static void ApplySession(IAudioEngine engine, SessionDto? dto)+ {+ if (dto is null) return;+ engine.SetLaunchQuant(Math.Max(0, dto.LaunchQuant));+ engine.SessionFollow = dto.Follow;+ engine.SessionRecordLength = Math.Max(0, dto.RecordLength);+ foreach (var sc in dto.Scenes)+ {+ if (sc.Index < 0 || sc.Index >= engine.SceneCount) continue;+ if (!string.IsNullOrEmpty(sc.Name)) engine.SetSceneName(sc.Index, sc.Name);+ engine.SetSceneProps(sc.Index, new NotaSceneProps+ {+ Color = sc.Color, Tempo = sc.Tempo, SigNum = sc.SigNum, SigDen = sc.SigDen,+ Follow = sc.Follow ? 1 : 0, FollowBeats = sc.FollowBeats,+ });+ }+ }++ private static SessionSlotDto WithClipProps(IAudioEngine engine, int trackId, SessionSlotDto dto)+ {+ string name = engine.GetSessionClipName(trackId, dto.Scene);+ dto.Name = name.Length > 0 ? name : null;+ if (!engine.TryGetSessionClipProps(trackId, dto.Scene, out var p)) return dto;+ dto.Color = p.Color; dto.LaunchMode = p.LaunchMode; dto.Quant = p.QuantBeats;+ dto.Legato = p.Legato != 0; dto.Loop = p.Loop != 0; dto.VelocityAmount = p.VelocityAmount;+ dto.FollowA = p.FollowA; dto.FollowB = p.FollowB; dto.ChanceA = p.ChanceA; dto.ChanceB = p.ChanceB;+ dto.FollowBeats = p.FollowBeats; dto.JumpScene = p.JumpScene;+ return dto;+ }++ private static void ApplyClipProps(IAudioEngine engine, int trackId, SessionSlotDto sl)+ {+ if (!string.IsNullOrEmpty(sl.Name)) engine.SetSessionClipName(trackId, sl.Scene, sl.Name);+ engine.SetSessionClipProps(trackId, sl.Scene, new NotaSessionClipProps+ {+ Color = sl.Color, LaunchMode = sl.LaunchMode, QuantBeats = sl.Quant,+ Legato = sl.Legato ? 1 : 0, Loop = sl.Loop ? 1 : 0, VelocityAmount = sl.VelocityAmount,+ FollowA = sl.FollowA, FollowB = sl.FollowB, ChanceA = sl.ChanceA, ChanceB = sl.ChanceB,+ FollowBeats = sl.FollowBeats, JumpScene = sl.JumpScene,+ });+ }}diff --git a/src/managed/Nota.Mcp/Tools/SessionTools.cs b/src/managed/Nota.Mcp/Tools/SessionTools.csindex e6e4517e..b34fd621 100644--- a/src/managed/Nota.Mcp/Tools/SessionTools.cs+++ b/src/managed/Nota.Mcp/Tools/SessionTools.cs@@ -2,8 +2,11 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// MCP tools — the Session (clip-launcher) view: a grid of slots (scene × track). A slot holds a-// looping MIDI or audio clip you launch/stop live; launches quantise to the global launch grid.-// Slot state: 0 empty, 1 filled, 2 queued (about to start), 3 playing, 4 recording.+// looping MIDI or audio clip you launch/stop live; launches quantise to the global launch grid+// (or the clip's own quantum). Clips carry a name, colour and launch properties (launch mode,+// legato, loop, follow actions); scenes carry a name, colour, tempo / signature and a scene+// follow action. Slot state: 0 empty, 1 filled, 2 queued (about to start), 3 playing,+// 4 recording.using System.ComponentModel;using ModelContextProtocol.Server;@@ -16,32 +19,75 @@ public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch,: EngineTools(engine, dispatch, refresh){public sealed record Note(int Pitch, double Start, double Length, float Velocity);- public sealed record Slot(int TrackId, int Scene, string State, double LengthBeats);- public sealed record SessionSnapshot(int SceneCount, Slot[] FilledSlots);+ public sealed record FollowAction(string Action, int Chance);+ public sealed record Slot(int TrackId, int Scene, string State, double LengthBeats, string Name, int Color,+ string LaunchMode, double? QuantBeats, bool Legato, bool Loop, float VelocityAmount,+ FollowAction A, FollowAction B, double FollowBeats, int JumpScene);+ public sealed record Scene(int Index, string Name, int Color, double? Tempo, string? Signature, double? FollowNextAfterBeats);+ public sealed record TrackState(int TrackId, int PlayingScene, double PositionBeats);+ public sealed record SlotRef(int TrackId, int Scene);+ public sealed record SessionSnapshot(int SceneCount, double LaunchQuantBeats, bool FollowActions, double RecordLengthBeats,+ Scene[] Scenes, Slot[] FilledSlots, TrackState[] Playing, SlotRef[] NoStopButton);++ private static readonly string[] Modes = { "trigger", "gate", "toggle", "repeat" };+ private static readonly string[] Actions = { "none", "stop", "again", "previous", "next", "first", "last", "any", "other", "jump" };private static string StateName(int s) => s switch { 4 => "recording", 3 => "playing", 2 => "queued", 1 => "filled", _ => "empty" };private static NotaNote ToEngine(Note n) => new(n.Pitch, n.Start, n.Length, Math.Clamp(n.Velocity, 0f, 1f));private static Note FromEngine(NotaNote n) => new(n.Pitch, n.StartBeat, n.LengthBeats, n.Velocity);+ private static int Parse(string? value, string[] names, string what)+ {+ int i = Array.IndexOf(names, (value ?? "").Trim().ToLowerInvariant());+ if (i < 0) throw new ArgumentException($"Unknown {what} \"{value}\" — use one of: {string.Join(", ", names)}.");+ return i;+ }+[McpServerTool(Name = "get_session"), Description(- "Snapshot of the Session (clip-launcher) grid: scene count and every non-empty slot "- + "(track id, scene, state, loop length in beats). Call before launching or filling slots.")]+ "Snapshot of the Session (clip-launcher) grid: scene count + scene names/colours/tempo/signature/follow, "+ + "the launch quantum, the global follow-action switch, the fixed record length, every non-empty slot "+ + "(track id, scene, state, loop length in beats, name, colour, launch mode, quantum, legato, loop, velocity "+ + "amount, follow actions A/B with chances and time), which scene each track is playing (with its position "+ + "in the loop), and empty slots whose stop button was removed. Call before launching or filling slots.")]public Task<SessionSnapshot> GetSession() => Read(() =>{int scenes = E.SceneCount, n = E.TrackCount;var slots = new List<Slot>();+ var playing = new List<TrackState>();+ var noStop = new List<SlotRef>();for (int i = 0; i < n; i++){- if (!E.TryGetTrackInfo(i, out var ti)) continue;+ if (!E.TryGetTrackInfo(i, out var ti) || ti.IsReturn || ti.IsGroup) continue;+ int p = E.SessionPlayingSlot(ti.Id);+ if (p >= 0) playing.Add(new TrackState(ti.Id, p, Math.Round(E.SessionSlotPosition(ti.Id), 3)));for (int s = 0; s < scenes; s++){int st = E.SessionSlotState(ti.Id, s);- if (st != 0) slots.Add(new Slot(ti.Id, s, StateName(st), E.SessionSlotLength(ti.Id, s)));+ if (st == 0)+ {+ if (!E.GetSessionSlotStopButton(ti.Id, s)) noStop.Add(new SlotRef(ti.Id, s));+ continue;+ }+ E.TryGetSessionClipProps(ti.Id, s, out var c);+ slots.Add(new Slot(ti.Id, s, StateName(st), E.SessionSlotLength(ti.Id, s), E.GetSessionClipName(ti.Id, s), c.Color,+ Modes[Math.Clamp(c.LaunchMode, 0, 3)], c.QuantBeats < 0 ? null : c.QuantBeats, c.Legato != 0, c.Loop != 0, c.VelocityAmount,+ new FollowAction(Actions[Math.Clamp(c.FollowA, 0, 9)], c.ChanceA), new FollowAction(Actions[Math.Clamp(c.FollowB, 0, 9)], c.ChanceB),+ c.FollowBeats, c.JumpScene));}}- return new SessionSnapshot(scenes, slots.ToArray());+ var sceneList = new List<Scene>();+ for (int s = 0; s < scenes; s++)+ {+ E.TryGetSceneProps(s, out var p);+ sceneList.Add(new Scene(s, E.GetSceneName(s), p.Color, p.Tempo > 0 ? p.Tempo : null,+ p.SigNum > 0 && p.SigDen > 0 ? $"{p.SigNum}/{p.SigDen}" : null, p.Follow != 0 ? p.FollowBeats : null));+ }+ return new SessionSnapshot(scenes, E.LaunchQuant, E.SessionFollow, E.SessionRecordLength,+ sceneList.ToArray(), slots.ToArray(), playing.ToArray(), noStop.ToArray());});+ // ---- slots -------------------------------------------------------------------------------+[McpServerTool(Name = "add_session_midi_clip"), Description("Create an empty looping MIDI clip in a slot (track × scene) of the given length in beats.")]public Task AddSessionMidiClip(int trackId, int scene, double lengthBeats = 4.0)=> Mutate(() => E.AddSessionMidiClip(trackId, scene, Math.Max(0.25, lengthBeats)));@@ -49,6 +95,24 @@ public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch,[McpServerTool(Name = "add_session_audio_file"), Description("Load an audio file (WAV/FLAC/MP3) into a session slot as a looping clip.")]public Task<bool> AddSessionAudioFile(int trackId, int scene, string path) => Mutate(() => E.AddSessionAudioFile(trackId, scene, path));+ [McpServerTool(Name = "clear_session_slot"), Description("Delete the clip in a session slot (stops it first if it is playing). Returns false if the slot was already empty.")]+ public Task<bool> ClearSessionSlot(int trackId, int scene) => Mutate(() => E.ClearSessionSlot(trackId, scene));++ [McpServerTool(Name = "copy_session_slot"), Description(+ "Copy a slot's clip (notes or audio, name, colour, launch properties) onto another slot, overwriting it. "+ + "Both tracks must be the same kind (MIDI→MIDI, audio→audio). move=true clears the source afterwards. One undo step.")]+ public Task<bool> CopySessionSlot(int srcTrackId, int srcScene, int dstTrackId, int dstScene, bool move = false) => Mutate(() =>+ {+ E.BeginUndoGroup();+ try+ {+ bool ok = E.CopySessionSlot(srcTrackId, srcScene, dstTrackId, dstScene);+ if (ok && move && (srcTrackId, srcScene) != (dstTrackId, dstScene)) E.ClearSessionSlot(srcTrackId, srcScene);+ return ok;+ }+ finally { E.EndUndoGroup(); }+ });+[McpServerTool(Name = "get_session_notes"), Description("Get the notes of a session MIDI slot (pitch, start, length in beats, velocity).")]public Task<Note[]> GetSessionNotes(int trackId, int scene)=> Read(() => Array.ConvertAll(E.GetSessionNotes(trackId, scene), FromEngine));@@ -61,16 +125,113 @@ public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch,public Task SetSessionSlotLength(int trackId, int scene, double lengthBeats)=> Mutate(() => E.SetSessionSlotLength(trackId, scene, Math.Max(0.25, lengthBeats)));+ [McpServerTool(Name = "set_session_clip"), Description(+ "Edit a filled session slot's clip; omit any argument to leave it unchanged. name: the clip name (empty = unnamed). "+ + "color: a track-palette index (base*3+shade, 0..23), -1 = the track's colour. launchMode: trigger | gate (plays while "+ + "held) | toggle (second launch stops) | repeat (retriggers each quantum while held). quantBeats: the clip's own launch "+ + "quantum in beats (0 = immediate), -1 = global. legato: start at the outgoing clip's position. loop: false = one-shot. "+ + "velocityAmount 0..1: how far launch velocity scales the clip. followA/followB: none | stop | again | previous | next | "+ + "first | last | any | other | jump; chanceA/chanceB: relative weights 0..100; followBeats: when the follow action fires "+ + "(0 = after one pass); jumpScene: the target of 'jump'. Follow actions run only while the global switch is on.")]+ public Task SetSessionClip(int trackId, int scene, string? name = null, int? color = null, string? launchMode = null,+ double? quantBeats = null, bool? legato = null, bool? loop = null, float? velocityAmount = null,+ string? followA = null, int? chanceA = null, string? followB = null, int? chanceB = null,+ double? followBeats = null, int? jumpScene = null) => Mutate(() =>+ {+ if (!E.TryGetSessionClipProps(trackId, scene, out var p))+ throw new ArgumentException($"Slot (track {trackId}, scene {scene}) is empty.");+ E.BeginUndoGroup();+ try+ {+ if (name is not null) E.SetSessionClipName(trackId, scene, name);+ if (color is { } c) p.Color = c;+ if (launchMode is not null) p.LaunchMode = Parse(launchMode, Modes, "launch mode");+ if (quantBeats is { } q) p.QuantBeats = q < 0 ? -1 : q;+ if (legato is { } l) p.Legato = l ? 1 : 0;+ if (loop is { } lp) p.Loop = lp ? 1 : 0;+ if (velocityAmount is { } v) p.VelocityAmount = Math.Clamp(v, 0f, 1f);+ if (followA is not null) p.FollowA = Parse(followA, Actions, "follow action");+ if (followB is not null) p.FollowB = Parse(followB, Actions, "follow action");+ if (chanceA is { } ca) p.ChanceA = Math.Clamp(ca, 0, 100);+ if (chanceB is { } cb) p.ChanceB = Math.Clamp(cb, 0, 100);+ if (followBeats is { } fb) p.FollowBeats = Math.Max(0, fb);+ if (jumpScene is { } js) p.JumpScene = Math.Max(0, js);+ E.SetSessionClipProps(trackId, scene, p);+ }+ finally { E.EndUndoGroup(); }+ });++ [McpServerTool(Name = "set_session_slot_stop_button"), Description(+ "An EMPTY slot's stop button. on=true (default): launching that scene stops the track. on=false: the scene leaves "+ + "the track playing — e.g. keep the drums going while scenes change.")]+ public Task SetSessionSlotStopButton(int trackId, int scene, bool on) => Mutate(() => E.SetSessionSlotStopButton(trackId, scene, on));++ // ---- scenes ------------------------------------------------------------------------------++ [McpServerTool(Name = "set_scene"), Description(+ "Edit a scene row; omit any argument to leave it unchanged. name (empty = unnamed). color: a track-palette index, "+ + "-1 = none. tempo: BPM applied when the scene launches (0 = no change). signature: \"3/4\" etc. applied on launch "+ + "(\"\" = no change). followNextAfterBeats: launch the next scene this many beats after this one starts (0 = off).")]+ public Task SetScene(int scene, string? name = null, int? color = null, double? tempo = null, string? signature = null,+ double? followNextAfterBeats = null) => Mutate(() =>+ {+ if (!E.TryGetSceneProps(scene, out var p)) throw new ArgumentException($"No scene {scene}.");+ E.BeginUndoGroup();+ try+ {+ if (name is not null) E.SetSceneName(scene, name);+ if (color is { } c) p.Color = c;+ if (tempo is { } t) p.Tempo = Math.Max(0, t);+ if (signature is not null)+ {+ var parts = signature.Split('/');+ if (signature.Trim().Length == 0) { p.SigNum = 0; p.SigDen = 0; }+ else if (parts.Length == 2 && int.TryParse(parts[0], out int num) && int.TryParse(parts[1], out int den)) { p.SigNum = num; p.SigDen = den; }+ else throw new ArgumentException($"Signature \"{signature}\" should look like 3/4.");+ }+ if (followNextAfterBeats is { } f) { p.Follow = f > 0 ? 1 : 0; if (f > 0) p.FollowBeats = f; }+ E.SetSceneProps(scene, p);+ }+ finally { E.EndUndoGroup(); }+ });++ [McpServerTool(Name = "insert_scene"), Description("Insert an empty scene row at index `at` (later rows shift down; playing clips keep playing). Returns the new row.")]+ public Task<int> InsertScene(int at) => Mutate(() => E.InsertScene(at));++ [McpServerTool(Name = "duplicate_scene"), Description("Copy a scene row (its clips and properties) to a new row just below it. Returns the new row.")]+ public Task<int> DuplicateScene(int scene) => Mutate(() => E.DuplicateScene(scene));++ [McpServerTool(Name = "capture_scene"), Description("Capture and insert scene: a new row at `at` holding the clips playing right now. Returns the new row.")]+ public Task<int> CaptureScene(int at) => Mutate(() => E.CaptureScene(at));++ [McpServerTool(Name = "move_scene"), Description("Move a scene row (its clips on every track and its properties) to another index.")]+ public Task<bool> MoveScene(int from, int to) => Mutate(() => E.MoveScene(from, to));++ [McpServerTool(Name = "delete_scene"), Description("Delete a scene row and its clips (at least one scene always stays).")]+ public Task<bool> DeleteScene(int scene) => Mutate(() => E.RemoveScene(scene));++ // ---- launching ---------------------------------------------------------------------------+[McpServerTool(Name = "set_launch_quant"), Description("Set the global launch quantisation in beats (e.g. 4 = 1 bar, 1 = 1 beat, 0 = off).")]public Task SetLaunchQuant(double beats) => Mutate(() => E.SetLaunchQuant(Math.Max(0, beats)));- [McpServerTool(Name = "launch_slot"), Description("Launch (start) the clip in a slot; obeys the launch quantisation.")]- public Task LaunchSlot(int trackId, int scene) => Mutate(() => E.LaunchSlot(trackId, scene));+ [McpServerTool(Name = "set_session_follow"), Description("Turn follow actions on or off for every clip and scene (the global Follow switch).")]+ public Task SetSessionFollow(bool on) => Mutate(() => E.SessionFollow = on);++ [McpServerTool(Name = "launch_slot"), Description(+ "Launch (start) the clip in a slot; obeys its launch quantum. velocity 0..1 scales the clip by its velocity amount. "+ + "Launching an empty slot stops the track. A gate / repeat clip keeps playing until release_slot.")]+ public Task LaunchSlot(int trackId, int scene, float velocity = 1f) => Mutate(() => E.LaunchSlotVelocity(trackId, scene, Math.Clamp(velocity, 0f, 1f)));++ [McpServerTool(Name = "release_slot"), Description("Release a slot's launch button: stops a gate or repeat clip (no effect on other launch modes).")]+ public Task ReleaseSlot(int trackId, int scene) => Mutate(() => E.ReleaseSlot(trackId, scene));[McpServerTool(Name = "stop_slot"), Description("Stop the currently-playing session clip on a track.")]public Task StopSlot(int trackId) => Mutate(() => E.StopSlot(trackId));- [McpServerTool(Name = "launch_scene"), Description("Launch a whole scene (row) — every filled slot in that scene starts together.")]+ [McpServerTool(Name = "launch_scene"), Description(+ "Launch a whole scene (row) — every filled slot in that scene starts together; tracks with an empty slot stop "+ + "unless that slot's stop button was removed. The scene's tempo / signature apply as it starts.")]public Task LaunchScene(int scene) => Mutate(() => E.LaunchScene(scene));[McpServerTool(Name = "stop_scene"), Description("Stop every session clip in a scene (row).")]@@ -79,17 +240,44 @@ public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch,[McpServerTool(Name = "stop_all_session"), Description("Stop all playing session clips on every track.")]public Task StopAllSession() => Mutate(() => E.StopAllSession());- [McpServerTool(Name = "record_session_slot"), Description("Arm-and-record a new take into a session slot (track must have a record input / be recordable).")]+ [McpServerTool(Name = "back_to_arrangement"), Description(+ "Hand tracks back to the Arrangement. With a trackId: stop just that track's session clip now. Without: stop every "+ + "session clip and re-activate the Arrangement timeline.")]+ public Task BackToArrangement(int? trackId = null) => Mutate(() =>+ {+ if (trackId is { } id) E.TrackBackToArrangement(id);+ else E.BackToArrangement();+ });++ // ---- recording ---------------------------------------------------------------------------++ [McpServerTool(Name = "record_session_slot"), Description(+ "Record a take into a session slot (MIDI: overdub, or a fresh take in an empty slot; audio: capture the track's input). "+ + "A fresh take runs until stop_session_record and is cut to whole bars, or to the fixed record length.")]public Task RecordSessionSlot(int trackId, int scene) => Mutate(() => E.RecordSessionSlot(trackId, scene));+ [McpServerTool(Name = "record_session_scene"), Description(+ "Session Record: record into the first armed track that has an empty slot in this scene. Returns that track id, or 0 "+ + "if no armed track has room.")]+ public Task<int> RecordSessionScene(int scene) => Mutate(() => E.RecordSessionScene(scene));++ [McpServerTool(Name = "set_session_record_length"), Description("Fixed session record length in beats (e.g. 16 = 4 bars; 0 = off): a take stops by itself after it.")]+ public Task SetSessionRecordLength(double beats) => Mutate(() => E.SessionRecordLength = Math.Max(0, beats));+[McpServerTool(Name = "stop_session_record"), Description("Stop the in-progress session slot recording and keep the take.")]public Task StopSessionRecord() => Mutate(() => E.StopSessionRecord());- [McpServerTool(Name = "session_slot_to_arrangement"), Description("Copy a session slot's clip into the arrangement timeline at startBeat. Returns the new clip index.")]+ // ---- transfer ----------------------------------------------------------------------------++ [McpServerTool(Name = "session_slot_to_arrangement"), Description("Copy a session slot's clip (MIDI or audio, with its name) into the arrangement timeline at startBeat. Returns the new clip index.")]public Task<int> SessionSlotToArrangement(int trackId, int scene, double startBeat)=> Mutate(() => E.SessionSlotToArrangement(trackId, scene, Math.Max(0, startBeat)));- [McpServerTool(Name = "arrangement_clip_to_session"), Description("Copy an arrangement clip into a session slot (track × scene).")]- public Task ArrangementClipToSession(int trackId, int clipIndex, int scene)- => Mutate(() => E.ArrangementClipToSession(trackId, clipIndex, scene));+ [McpServerTool(Name = "arrangement_clip_to_session"), Description("Copy an arrangement clip (MIDI or audio, with its name) into a session slot (track × scene).")]+ public Task<bool> ArrangementClipToSession(int trackId, int clipIndex, int scene) => Mutate(() =>+ {+ if (E.TryGetClipInfo(trackId, clipIndex, out var ci) && !ci.IsMidi) return E.ArrangementAudioClipToSession(trackId, clipIndex, scene);+ E.ArrangementClipToSession(trackId, clipIndex, scene);+ return E.SessionSlotState(trackId, scene) != 0;+ });}diff --git a/src/managed/Nota.Remote/RemoteHub.State.cs b/src/managed/Nota.Remote/RemoteHub.State.csindex dc863e41..6ac1ccbf 100644--- a/src/managed/Nota.Remote/RemoteHub.State.cs+++ b/src/managed/Nota.Remote/RemoteHub.State.cs@@ -18,7 +18,6 @@ public sealed partial class RemoteHub{private string? _projectJson; // shared part of the project message, re-read every few ticksprivate List<TrackRow> _tracks = new();- private readonly Dictionary<(int Track, int Scene), double> _slotStart = new(); // session launch beat (progress)internal sealed record TrackRow(int Id, string Name, string Color, string Kind, string Device, int Group, int Index);@@ -268,8 +267,7 @@ public sealed partial class RemoteHubif (_engine.SessionSlotState(trackId, s) != 3) continue;double len = _engine.SessionSlotLength(trackId, s);if (len <= 0) continue;- double start = SlotStart(trackId, s, snap.Pos);- double local = ((snap.Pos - start) % len + len) % len;+ double local = _engine.SessionSlotPosition(trackId); // the slot's own loop clockforeach (var n in _engine.GetSessionNotes(trackId, s))if (local >= n.StartBeat && local < n.StartBeat + n.LengthBeats) set.Add(n.Pitch);}@@ -297,14 +295,6 @@ public sealed partial class RemoteHubreturn null;}- // Where a playing slot started, for its progress line: first seen playing, on the bar.- private double SlotStart(int trackId, int scene, double pos)- {- if (!_slotStart.TryGetValue((trackId, scene), out double s))- _slotStart[(trackId, scene)] = s = Math.Floor(pos / 4) * 4;- return s;- }-// ---- mixer ---------------------------------------------------------------------------private string BuildMixer(IRemoteHost host) => Json(w =>@@ -443,14 +433,9 @@ public sealed partial class RemoteHubfor (int s = 0; s < scenes; s++){int st = _engine.SessionSlotState(r.Id, s);- if (st != 3) _slotStart.Remove((r.Id, s));double len = st == 0 ? 0 : _engine.SessionSlotLength(r.Id, s);- double prog = 0;- if (st == 3 && len > 0)- {- double start = SlotStart(r.Id, s, snap.Pos);- prog = (((snap.Pos - start) % len) + len) % len / len;- }+ // Progress runs on the slot's own loop clock (the engine's), not the song position.+ double prog = st == 3 && len > 0 ? Math.Clamp(_engine.SessionSlotPosition(r.Id) / len, 0, 1) : 0;w.WriteStartArray();w.WriteNumberValue(st);w.WriteNumberValue(Math.Round(len, 2));diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 1470cd65..5b816555 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -132,6 +132,39 @@ typedef struct NotaSessionAudioSlot {float gain;} NotaSessionAudioSlot;+/* Session clip (slot) properties (Session P0). color is a track-palette index, -1 = the+ * track's colour. launch_mode: 0 Trigger, 1 Gate, 2 Toggle, 3 Repeat. quant_beats < 0 uses+ * the global launch quantum. follow_a/b: 0 None, 1 Stop, 2 Again, 3 Previous, 4 Next,+ * 5 First, 6 Last, 7 Any, 8 Other, 9 Jump (to jump_scene); chance_a/b are relative weights+ * 0..100; follow_beats 0 = after one pass. velocity_amount 0..1 scales the clip by the+ * launch velocity. */+typedef struct NotaSessionClipProps {+ int32_t color;+ int32_t launch_mode;+ double quant_beats;+ int32_t legato;+ int32_t loop;+ float velocity_amount;+ int32_t follow_a;+ int32_t follow_b;+ int32_t chance_a;+ int32_t chance_b;+ double follow_beats;+ int32_t jump_scene;+} NotaSessionClipProps;++/* Scene row properties (Session P0). color: track-palette index, -1 = neutral. tempo > 0+ * and sig_num/sig_den > 0 are applied when the scene launches. follow = 1 launches the+ * next scene follow_beats after this one started. */+typedef struct NotaSceneProps {+ int32_t color;+ double tempo;+ int32_t sig_num;+ int32_t sig_den;+ int32_t follow;+ double follow_beats;+} NotaSceneProps;+/* Post-fader level meter reading over the last processed block (M6-2). Linear* amplitude 0..1 (peaks may hit 1.0 after the master clamp). */typedef struct NotaMeter {@@ -772,7 +805,8 @@ NOTA_API int32_t nota_session_add_scene(NotaEngine* engine);NOTA_API NotaResult nota_session_remove_scene(NotaEngine* engine, int32_t scene);/* Overdub-record live MIDI into a slot (M5-4): launches the slot looping and* captures armed input against the slot's loop clock. stop_record ends recording- * (the slot keeps playing). */+ * (the slot keeps playing). An empty slot records a fresh take: it runs until stopped and+ * is cut to whole launch quanta (bars when unquantized), or to the fixed record length. */NOTA_API NotaResult nota_session_record_slot(NotaEngine* engine, int32_t track_id, int32_t scene);NOTA_API NotaResult nota_session_stop_record(NotaEngine* engine);/* Move MIDI between Session and Arrangement (M5-6). slot->arrangement returns the@@ -797,6 +831,57 @@ NOTA_API NotaResult nota_session_set_notes(NotaEngine* engine, int32_t track_id,NOTA_API int32_t nota_session_get_notes(const NotaEngine* engine, int32_t track_id, int32_t scene, NotaNoteData* out, int32_t max_notes);NOTA_API int32_t nota_session_note_count(const NotaEngine* engine, int32_t track_id, int32_t scene);+/* ---- Session P0: clip + scene properties, scene/slot editing, follow -------- */+/* Clip properties of a filled slot (get returns 1 if the slot holds a clip). */+NOTA_API int32_t nota_session_get_clip_props(const NotaEngine* engine, int32_t track_id, int32_t scene, NotaSessionClipProps* out);+NOTA_API NotaResult nota_session_set_clip_props(NotaEngine* engine, int32_t track_id, int32_t scene, const NotaSessionClipProps* props);+/* Clip name (UTF-8). get returns the byte length (0 = unnamed) and copies at most cap-1 bytes. */+NOTA_API int32_t nota_session_get_clip_name(const NotaEngine* engine, int32_t track_id, int32_t scene, char* out, int32_t cap);+NOTA_API NotaResult nota_session_set_clip_name(NotaEngine* engine, int32_t track_id, int32_t scene, const char* name_utf8);+/* An EMPTY slot's stop button: 1 (default) = launching its scene stops the track, 0 = leaves it playing. */+NOTA_API int32_t nota_session_get_slot_stop_button(const NotaEngine* engine, int32_t track_id, int32_t scene);+NOTA_API NotaResult nota_session_set_slot_stop_button(NotaEngine* engine, int32_t track_id, int32_t scene, int32_t on);+/* Copy a slot (clip + properties) onto another slot of a track of the same kind; overwrites. */+NOTA_API NotaResult nota_session_copy_slot(NotaEngine* engine, int32_t src_track, int32_t src_scene, int32_t dst_track, int32_t dst_scene);+/* Scene properties and name. */+NOTA_API int32_t nota_session_get_scene_props(const NotaEngine* engine, int32_t scene, NotaSceneProps* out);+NOTA_API NotaResult nota_session_set_scene_props(NotaEngine* engine, int32_t scene, const NotaSceneProps* props);+NOTA_API int32_t nota_session_get_scene_name(const NotaEngine* engine, int32_t scene, char* out, int32_t cap);+NOTA_API NotaResult nota_session_set_scene_name(NotaEngine* engine, int32_t scene, const char* name_utf8);+/* Insert an empty scene row at `at` (later rows shift down); duplicate a row below itself;+ * capture the currently playing clips into a new row at `at`. Each returns the new row or -1. */+NOTA_API int32_t nota_session_insert_scene(NotaEngine* engine, int32_t at);+NOTA_API int32_t nota_session_duplicate_scene(NotaEngine* engine, int32_t scene);+NOTA_API int32_t nota_session_capture_scene(NotaEngine* engine, int32_t at);+/* Move a scene row (its slots on every track and its properties) to another index. */+NOTA_API NotaResult nota_session_move_scene(NotaEngine* engine, int32_t from, int32_t to);+/* Launch with a velocity 0..1 (scaled by the clip's velocity_amount); launch_slot uses 1. */+NOTA_API NotaResult nota_session_launch_slot_vel(NotaEngine* engine, int32_t track_id, int32_t scene, float velocity);+/* The launch button was released: stops a Gate / Repeat slot. No-op for other modes. */+NOTA_API NotaResult nota_session_release_slot(NotaEngine* engine, int32_t track_id, int32_t scene);+/* Hand one track back to the Arrangement: stops its session clip right away. */+NOTA_API NotaResult nota_session_track_back_to_arrangement(NotaEngine* engine, int32_t track_id);+/* Playing slot of a track (-1 none) and its loop-local position in beats (progress). */+NOTA_API int32_t nota_session_playing_slot(const NotaEngine* engine, int32_t track_id);+NOTA_API double nota_session_slot_position(const NotaEngine* engine, int32_t track_id);+NOTA_API double nota_session_get_launch_quant(const NotaEngine* engine);+/* Global follow-action switch (default on): off = clips and scenes never follow. */+NOTA_API NotaResult nota_session_set_follow(NotaEngine* engine, int32_t on);+NOTA_API int32_t nota_session_get_follow(const NotaEngine* engine);+/* Fixed recording length in beats (0 = off): a session take stops by itself after it. */+NOTA_API NotaResult nota_session_set_record_length(NotaEngine* engine, double beats);+NOTA_API double nota_session_get_record_length(const NotaEngine* engine);+/* Session Rec: record into the first armed track with an empty slot in `scene`.+ * Returns that track id, or 0 if no armed track has room. */+NOTA_API int32_t nota_session_record_scene(NotaEngine* engine, int32_t scene);+/* The in-progress session take: 1 if recording (track, scene, beats recorded so far). */+/* A launched scene applied its tempo / signature (on its start boundary): returns 1 once and+ * the values (bpm 0 or num/den 0 = unchanged), so the UI's transport can follow. */+NOTA_API int32_t nota_session_take_scene_tempo(NotaEngine* engine, double* bpm, int32_t* num, int32_t* den);+/* Min/max peak pairs over an audio slot's take (whole sample); returns the bucket count. */+NOTA_API int32_t nota_session_slot_peaks(const NotaEngine* engine, int32_t track_id, int32_t scene, float* out_min_max, int32_t max_points);+NOTA_API int32_t nota_session_record_target(const NotaEngine* engine, int32_t* track_id, int32_t* scene, double* elapsed_beats);+/* ---- Arrangement geometry (M4) ------------------------------------------- *//* Fills `out` for the track at `index` (0..track_count-1). Returns 1, or 0 if* the index is out of range. */diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cppindex 3e847c45..be938b02 100644--- a/src/native/nota.engine/src/Engine.cpp+++ b/src/native/nota.engine/src/Engine.cpp@@ -399,6 +399,7 @@ void Engine::backToArrangement() {if (authoring_)for (auto& t : authoring_->tracks)if (t->sessionPlayer) t->sessionPlayer->requestStop();+ sceneFollowScene_ = -1;arrangementActive_.store(true, std::memory_order_relaxed);}void Engine::setBpm(double bpm) {@@ -502,6 +503,7 @@ void Engine::publish(std::shared_ptr<Graph> g) {void Engine::republishWithTrackRaw(int32_t trackId, std::shared_ptr<Track> nt) {auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount; // preserve scene count across the swap+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume; // carry master automation (M9 follow-up)g->masterTrack = (trackId == kMasterTrackId) ? nt : authoring_->masterTrack; // master chain edit or carryg->tracks.reserve(authoring_->tracks.size());diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex 78e2455e..2aa7bfdd 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -396,6 +396,36 @@ public:bool setSessionNotes(int32_t trackId, int32_t scene, const NotaNoteData* notes, int32_t count);int32_t getSessionNotes(int32_t trackId, int32_t scene, NotaNoteData* out, int32_t maxNotes) const;int32_t sessionNoteCount(int32_t trackId, int32_t scene) const;+ // Session P0: clip + scene properties, scene/slot editing, follow, fixed-length capture.+ bool sessionClipProps(int32_t trackId, int32_t scene, NotaSessionClipProps* out) const;+ bool setSessionClipProps(int32_t trackId, int32_t scene, const NotaSessionClipProps& p);+ bool sessionClipName(int32_t trackId, int32_t scene, std::string& out) const;+ bool setSessionClipName(int32_t trackId, int32_t scene, const std::string& name);+ bool sessionSlotStopButton(int32_t trackId, int32_t scene) const;+ bool setSessionSlotStopButton(int32_t trackId, int32_t scene, bool on);+ bool copySessionSlot(int32_t srcTrack, int32_t srcScene, int32_t dstTrack, int32_t dstScene);+ bool sceneProps(int32_t scene, NotaSceneProps* out) const;+ bool setSceneProps(int32_t scene, const NotaSceneProps& p);+ bool sceneName(int32_t scene, std::string& out) const;+ bool setSceneName(int32_t scene, const std::string& name);+ int32_t insertScene(int32_t at);+ int32_t duplicateScene(int32_t scene);+ int32_t captureScene(int32_t at);+ bool moveScene(int32_t from, int32_t to);+ void launchSlotVel(int32_t trackId, int32_t scene, float velocity);+ void releaseSlot(int32_t trackId, int32_t scene);+ void trackBackToArrangement(int32_t trackId);+ int32_t sessionPlayingSlot(int32_t trackId) const;+ double sessionSlotPosition(int32_t trackId) const;+ double launchQuant() const { return launchQuant_.load(std::memory_order_relaxed); }+ void setSessionFollow(bool on) { sessionFollow_.store(on, std::memory_order_relaxed); }+ bool sessionFollow() const { return sessionFollow_.load(std::memory_order_relaxed); }+ void setSessionRecordLength(double beats) { sessionRecordLen_ = beats > 0.0 ? beats : 0.0; }+ double sessionRecordLength() const { return sessionRecordLen_; }+ int32_t recordSessionScene(int32_t scene);+ bool sessionRecordTarget(int32_t* trackId, int32_t* scene, double* elapsed) const;+ int32_t sessionSlotPeaks(int32_t trackId, int32_t scene, float* outMinMax, int32_t maxPoints) const;+ bool takeSceneTempoChange(double* bpm, int32_t* num, int32_t* den); // once per applied scene tempo// --- clip editing (M4-2) ---bool moveClip(int32_t trackId, int32_t clipIndex, double newStartBeat);@@ -930,6 +960,12 @@ private:// Hand a MIDI-keyed device its source track's notes for this block (from blockMidi_).void feedMidiKey(Graph* g, Device& d, int32_t srcTrackId);void renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double spb);+ // Session P0 (audio thread): queue a follow action / Repeat retrigger before the launch+ // request applies, and after rendering advance the player + end a one-shot slot.+ void sessionPreApply(Track& t, double blockBeats);+ void sessionPostRender(Track& t, double blockBeats);+ int32_t followTarget(const Track& t, int32_t cur, FollowAction a);+ uint32_t followRng_ = 0x9E3779B9u; // audio-thread RNG for follow-action chance / Any / Otherint applyMidiEffects(Track& t, MidiEv* evs, int n, MidiEv* scratch,int32_t frames, double beatStart, double spb, bool playing);void applyMidiCcRouting(Track& t);@@ -1141,6 +1177,26 @@ private:// Build a fresh graph with a new scene count, cloning tracks so slot vectors resize safely.std::shared_ptr<Graph> rebuildScenes(int32_t newCount,const std::function<void(std::vector<SessionSlot>&)>& mutate);+ // Session P0 helpers (message thread).+ int32_t insertSceneRow(int32_t at, int32_t copyFrom, bool capturePlaying);+ void remapPlayers(const std::function<int32_t(int32_t)>& map); // shift players after a row insert/remove+ void launchSlotImpl(Track& t, int32_t scene, float velocity, bool fromScene);+ void serviceSessionFollow(); // poll(): scene follow + fixed-length capture+ std::atomic<bool> sessionFollow_{true};+ double sessionRecordLen_ = 0.0; // fixed session record length, beats (0 = off)+ int32_t sceneFollowScene_ = -1; // last launched scene (for scene follow)+ double sceneFollowStart_ = 0.0; // beat it started at (quantized)+ // A launched scene's tempo / signature, applied by poll() on the boundary it starts on.+ bool sceneTempoPending_ = false;+ double sceneTempo_ = 0.0, sceneTempoAt_ = 0.0;+ int32_t sceneSigNum_ = 0, sceneSigDen_ = 0;+ void applySceneTempo();+ bool sceneTempoApplied_ = false;+ // A fresh MIDI take into an empty slot grows until stopped (no fixed length), then is+ // cut to whole quanta.+ static constexpr double kGrowingTakeBeats = 4096.0;+ bool recordSessionGrowing_ = false;+ double roundedTakeBeats(double beats) const;// recording target (message thread)int32_t recordTrackId_ = 0;diff --git a/src/native/nota.engine/src/Engine_Modulation.cpp b/src/native/nota.engine/src/Engine_Modulation.cppindex ef8fc0f5..25211dab 100644--- a/src/native/nota.engine/src/Engine_Modulation.cpp+++ b/src/native/nota.engine/src/Engine_Modulation.cpp@@ -308,6 +308,7 @@ void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex,bool anyChange = false;auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());diff --git a/src/native/nota.engine/src/Engine_Recording.cpp b/src/native/nota.engine/src/Engine_Recording.cppindex 0a3a6cc7..e38960e6 100644--- a/src/native/nota.engine/src/Engine_Recording.cpp+++ b/src/native/nota.engine/src/Engine_Recording.cpp@@ -425,6 +425,8 @@ void Engine::stopAudioRecording() {const double deviceFrames = sample->frames * (sr > 0 ? sr / sample->sourceSampleRate : 1.0);s.lengthBeats = spb > 0 ? deviceFrames / spb : 4.0;if (s.lengthBeats <= 0.0) s.lengthBeats = 4.0;+ // Fixed-length capture keeps its length; an open-ended take is cut to whole quanta.+ s.lengthBeats = sessionRecordLen_ > 0.0 ? sessionRecordLen_ : roundedTakeBeats(s.lengthBeats);}republishWithTrack(trackId, nt);return;diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cppindex 821d26e5..d29c8cb7 100644--- a/src/native/nota.engine/src/Engine_Render.cpp+++ b/src/native/nota.engine/src/Engine_Render.cpp@@ -94,6 +94,7 @@ void Engine::applyMidiCcRouting(Track& t) {void Engine::poll() {if (audioRecording_) drainInputQueue(); // keep the capture buffer flowing while recording+ serviceSessionFollow(); // scene follow + fixed-length session capture// Automation write/record (M9-C). Message thread: a transport stop ends any// latched gesture, and active gestures are sampled at the live playhead.@@ -514,13 +515,15 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double sMidiEv evs[1024];int n = 0;const long i0 = static_cast<long>(std::floor(p / L));+ const float velGain = sp.gain;for (long it = i0; it <= i0 + 1; ++it) {+ if (!s.loop && it > 0) break; // one-shot: a single passfor (const Note& note : s.midi.notes) {if (note.startBeat < 0.0 || note.startBeat >= L) continue;const double onAbs = it * L + note.startBeat;const double offAbs = onAbs + note.lengthBeats;if (onAbs >= p && onAbs < p + db && n < 1024)- evs[n++] = {static_cast<int32_t>((onAbs - p) * spb), true, note.pitch, note.velocity, static_cast<float>(note.lengthBeats)};+ evs[n++] = {static_cast<int32_t>((onAbs - p) * spb), true, note.pitch, note.velocity * velGain, static_cast<float>(note.lengthBeats)};if (offAbs >= p && offAbs < p + db && n < 1024)evs[n++] = {static_cast<int32_t>((offAbs - p) * spb), false, note.pitch, 0.0f};}@@ -566,9 +569,10 @@ void Engine::renderSessionAudioSlotRaw(Track& t, float* dst, int32_t frames, douconst double sr = transport_.sampleRate();const double ratio = sr > 0 ? sb.sourceSampleRate / sr : 1.0; // source frames per device frameconst double L = s.lengthBeats > 0 ? s.lengthBeats : 4.0;- const float gain = s.audio.gain;+ const float gain = s.audio.gain * sp.gain;for (int32_t i = 0; i < frames; ++i) {+ if (!s.loop && sp.localBeats + i / spb >= L) break; // one-shot: silence past the enddouble loopBeat = std::fmod(sp.localBeats + i / spb, L);if (loopBeat < 0.0) loopBeat += L;const double srcPos = loopBeat * spb * ratio; // -> source frames@@ -982,6 +986,8 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, bbool sessionActive = false;if (!frozenActive && !capturing && !monitoring) if (auto& sp = t.sessionPlayer) {+ // Follow actions + Repeat launch mode queue the next request before it applies.+ if (playing) sessionPreApply(t, frames / spb);if (sp->maybeApply(blockStart / spb, frames / spb, launchQuant_.load(std::memory_order_relaxed))) {if (t.instrument) t.instrument->allNotesOff();for (auto& md : t.midiEffects) if (md) md->reset(); // clock switch → flush arp@@ -1007,9 +1013,9 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, bif (monitoring)renderMonitorInput(g, t, scratch_.data(), frames);else if (sessionActive && t.type() == TrackType::Instrument)- renderSessionSlotRaw(t, scratch_.data(), frames, spb);+ { renderSessionSlotRaw(t, scratch_.data(), frames, spb); sessionPostRender(t, frames / spb); }else if (sessionActive && t.type() == TrackType::Audio)- renderSessionAudioSlotRaw(t, scratch_.data(), frames, spb);+ { renderSessionAudioSlotRaw(t, scratch_.data(), frames, spb); sessionPostRender(t, frames / spb); }else if (t.type() == TrackType::Instrument)renderInstrumentRaw(g, t, scratch_.data(), frames, blockStart, spb, playing);else if (playing && arrangementActive)diff --git a/src/native/nota.engine/src/Engine_Session.cpp b/src/native/nota.engine/src/Engine_Session.cppindex 7fce9a79..4da99da8 100644--- a/src/native/nota.engine/src/Engine_Session.cpp+++ b/src/native/nota.engine/src/Engine_Session.cpp@@ -111,6 +111,7 @@ std::shared_ptr<Graph> Engine::rebuildScenes(int32_t newCount,const std::function<void(std::vector<SessionSlot>&)>& mutate) {auto g = std::make_shared<Graph>();g->sceneCount = newCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -132,13 +133,15 @@ int32_t Engine::addScene() {bool Engine::removeScene(int32_t scene) {if (authoring_->sceneCount <= 1) return false; // always keep at least one sceneif (scene < 0 || scene >= authoring_->sceneCount) return false;- // Removing a row shifts every later slot up, so stop all session playback to avoid a- // player pointing at the wrong (or gone) slot.- for (auto& t : authoring_->tracks)- if (t->sessionPlayer) t->sessionPlayer->requestStop();- publish(rebuildScenes(authoring_->sceneCount - 1, [scene](std::vector<SessionSlot>& slots) {+ // Removing a row shifts every later slot up: a take recording into the row ends first,+ // players on the row stop, players below it follow their slot up.+ if (recordSessionScene_ == scene) finalizeSessionRecord(false);+ auto g = rebuildScenes(authoring_->sceneCount - 1, [scene](std::vector<SessionSlot>& slots) {if (scene < static_cast<int32_t>(slots.size())) slots.erase(slots.begin() + scene);- }));+ });+ if (scene < static_cast<int32_t>(g->scenes.size())) g->scenes.erase(g->scenes.begin() + scene);+ publish(std::move(g));+ remapPlayers([scene](int32_t x) { return x == scene ? -1 : (x > scene ? x - 1 : x); });return true;}@@ -150,28 +153,78 @@ static inline bool sessionLaunchable(const Track& t) {return t.type() == TrackType::Instrument || t.type() == TrackType::Audio;}-void Engine::launchSlot(int32_t trackId, int32_t scene) {+void Engine::launchSlot(int32_t trackId, int32_t scene) { launchSlotVel(trackId, scene, 1.0f); }++void Engine::launchSlotVel(int32_t trackId, int32_t scene, float velocity) {auto t = findTrackAuthoring(trackId);if (!t || !t->sessionPlayer) return;- const bool hasClip = scene >= 0 && scene < static_cast<int32_t>(t->sessionSlots.size())- && t->sessionSlots[scene].hasClip;- if (hasClip && sessionLaunchable(*t)) t->sessionPlayer->requestLaunch(scene);- else t->sessionPlayer->requestStop();+ launchSlotImpl(*t, scene, velocity, false);// Start the clock for quantize — but session-only: launching a clip must NOT roll the// whole Arrangement. If the Arrangement is already playing, leave it (clips layer over it).if (!transport_.uiIsPlaying()) { arrangementActive_.store(false, std::memory_order_relaxed); playClock(); }}+// One track's launch request. An empty slot stops the track — unless the request comes from+// a scene and the slot's stop button was removed. A clip launches with its own quantum,+// legato and launch-velocity gain; Toggle stops a playing slot and Repeat keeps retriggering+// until releaseSlot (direct launches only — a scene always just starts its clips).+void Engine::launchSlotImpl(Track& t, int32_t scene, float velocity, bool fromScene) {+ auto& sp = *t.sessionPlayer;+ const bool inRange = scene >= 0 && scene < static_cast<int32_t>(t.sessionSlots.size());+ const bool hasClip = inRange && t.sessionSlots[scene].hasClip;+ if (!hasClip || !sessionLaunchable(t)) {+ if (fromScene && inRange && !t.sessionSlots[scene].stopButton) return;+ sp.requestStop();+ return;+ }+ const SessionSlot& s = t.sessionSlots[scene];+ if (!fromScene && s.launchMode == LaunchMode::Toggle+ && sp.playing.load(std::memory_order_relaxed) == scene+ && sp.pending.load(std::memory_order_relaxed) == SessionPlayer::kNone) {+ sp.requestStop();+ return;+ }+ const float v = std::clamp(velocity, 0.0f, 1.0f);+ const float gain = 1.0f - std::clamp(s.velocityAmount, 0.0f, 1.0f) * (1.0f - v);+ sp.repeatSlot.store(!fromScene && s.launchMode == LaunchMode::Repeat ? scene : -1, std::memory_order_relaxed);+ sp.requestLaunch(scene, s.quantBeats, s.legato, gain);+}++void Engine::releaseSlot(int32_t trackId, int32_t scene) {+ auto t = findTrackAuthoring(trackId);+ if (!t || !t->sessionPlayer || scene < 0 || scene >= static_cast<int32_t>(t->sessionSlots.size())) return;+ const SessionSlot& s = t->sessionSlots[scene];+ if (!s.hasClip || (s.launchMode != LaunchMode::Gate && s.launchMode != LaunchMode::Repeat)) return;+ auto& sp = *t->sessionPlayer;+ if (sp.playing.load(std::memory_order_relaxed) == scene || sp.pending.load(std::memory_order_relaxed) == scene)+ sp.requestStop();+}+void Engine::launchScene(int32_t scene) {// Launch the whole row at once: every track's slot in this scene fires on the- // next quantize boundary; tracks with an empty slot here are stopped (scene-launch semantics).- for (auto& t : authoring_->tracks) {- if (!t->sessionPlayer) continue;- const bool hasClip = scene >= 0 && scene < static_cast<int32_t>(t->sessionSlots.size())- && t->sessionSlots[scene].hasClip;- if (hasClip && sessionLaunchable(*t)) t->sessionPlayer->requestLaunch(scene);- else t->sessionPlayer->requestStop();+ // next quantize boundary; tracks with an empty slot here are stopped (scene-launch+ // semantics) unless that slot's stop button was removed.+ for (auto& t : authoring_->tracks)+ if (t->sessionPlayer) launchSlotImpl(*t, scene, 1.0f, true);++ // Scene follow counts from the boundary the row actually starts on.+ const double q = launchQuant_.load(std::memory_order_relaxed);+ const double pos = transport_.uiPositionBeats();+ sceneFollowScene_ = scene;+ sceneFollowStart_ = (q > 0.0 && pos > 1e-9) ? std::ceil(pos / q - 1e-9) * q : pos;++ // Scene tempo / signature apply on that boundary too (at once when the clock is stopped).+ sceneTempoPending_ = false;+ if (scene >= 0 && scene < static_cast<int32_t>(authoring_->scenes.size())) {+ const SceneInfo& si = authoring_->scenes[scene];+ if (si.tempo > 0.0 || (si.sigNum > 0 && si.sigDen > 0)) {+ sceneTempo_ = si.tempo; sceneSigNum_ = si.sigNum; sceneSigDen_ = si.sigDen;+ sceneTempoAt_ = sceneFollowStart_;+ sceneTempoPending_ = true;+ if (!transport_.uiIsPlaying()) applySceneTempo();+ }}+// Start the clock for quantize — but session-only: launching a clip must NOT roll the// whole Arrangement. If the Arrangement is already playing, leave it (clips layer over it).if (!transport_.uiIsPlaying()) { arrangementActive_.store(false, std::memory_order_relaxed); playClock(); }@@ -194,9 +247,30 @@ void Engine::stopScene(int32_t scene) {void Engine::stopAllSession() {for (auto& t : authoring_->tracks)if (t->sessionPlayer) t->sessionPlayer->requestStop();+ sceneFollowScene_ = -1;stopSessionRecord();}+void Engine::trackBackToArrangement(int32_t trackId) {+ auto t = findTrackAuthoring(trackId);+ if (t && t->sessionPlayer) t->sessionPlayer->requestStopNow();+}++int32_t Engine::sessionPlayingSlot(int32_t trackId) const {+ auto t = findTrackAuthoring(trackId);+ return (t && t->sessionPlayer) ? t->sessionPlayer->playing.load(std::memory_order_relaxed) : -1;+}++double Engine::sessionSlotPosition(int32_t trackId) const {+ auto t = findTrackAuthoring(trackId);+ if (!t || !t->sessionPlayer) return 0.0;+ const int32_t p = t->sessionPlayer->playing.load(std::memory_order_relaxed);+ if (p < 0 || p >= static_cast<int32_t>(t->sessionSlots.size())) return 0.0;+ const double L = t->sessionSlots[p].lengthBeats > 0 ? t->sessionSlots[p].lengthBeats : 4.0;+ double x = std::fmod(t->sessionPlayer->uiLocalBeats.load(std::memory_order_relaxed), L);+ return x < 0.0 ? x + L : x;+}+void Engine::recordSessionSlot(int32_t trackId, int32_t scene) {auto t = findTrackAuthoring(trackId);if (!t) return;@@ -224,7 +298,14 @@ void Engine::recordSessionSlot(int32_t trackId, int32_t scene) {// Make sure the slot holds a clip we can overdub into.const bool hasClip = scene < static_cast<int32_t>(t->sessionSlots.size())&& t->sessionSlots[scene].hasClip;- if (!hasClip) { addSessionMidiClip(trackId, scene, 4.0); t = findTrackAuthoring(trackId); if (!t) return; }+ // An empty slot records a fresh take: with a fixed length it is that long; otherwise it+ // runs until stopped and is cut to whole quanta then (finalizeSessionRecord).+ recordSessionGrowing_ = false;+ if (!hasClip) {+ recordSessionGrowing_ = sessionRecordLen_ <= 0.0;+ addSessionMidiClip(trackId, scene, recordSessionGrowing_ ? kGrowingTakeBeats : sessionRecordLen_);+ t = findTrackAuthoring(trackId); if (!t) return;+ }recordSessionTrackId_ = trackId;recordSessionScene_ = scene;@@ -247,20 +328,57 @@ void Engine::finalizeSessionRecord(bool relaunch) {stopAudioRecording();if (relaunch && tid > 0 && sc >= 0) launchSlot(tid, sc);}+ // A fresh MIDI take that ran open-ended: cut it to whole launch quanta (a bar when+ // launching is unquantized) — no undo step of its own, so undo drops the whole take.+ if (recordSessionGrowing_ && recordSessionScene_ >= 0) {+ recordSessionGrowing_ = false;+ const int32_t tid = recordSessionTrackId_, sc = recordSessionScene_;+ double el = 0.0;+ if (auto* sp = recordSlotPlayer_.load(std::memory_order_acquire))+ if (sp->playing.load(std::memory_order_relaxed) == sc) el = sp->playedBeats.load(std::memory_order_relaxed);+ if (auto old = findTrackAuthoring(tid); old && sc < static_cast<int32_t>(old->sessionSlots.size())) {+ auto nt = cloneTrack(*old);+ SessionSlot& sl = nt->sessionSlots[sc];+ const double len = roundedTakeBeats(el);+ sl.lengthBeats = len;+ sl.midi.lengthBeats = len;+ republishWithTrackRaw(tid, nt);+ }+ }recording_.store(false, std::memory_order_relaxed);recordSlotPlayer_.store(nullptr, std::memory_order_release);recordSessionScene_ = -1;recordSessionTrackId_ = 0;}+// A take's loop length: the recorded beats rounded to whole launch quanta (bars when+// launching is unquantized or finer than a beat), never shorter than one quantum.+double Engine::roundedTakeBeats(double beats) const {+ double q = launchQuant_.load(std::memory_order_relaxed);+ if (q < 1.0) q = 4.0;+ return std::max(q, std::round(beats / q) * q);+}+int32_t Engine::sessionSlotToArrangement(int32_t trackId, int32_t scene, double startBeat) {auto old = findTrackAuthoring(trackId);- if (!old || old->type() != TrackType::Instrument) return -1;+ if (!old || (old->type() != TrackType::Instrument && old->type() != TrackType::Audio)) return -1;if (scene < 0 || scene >= static_cast<int32_t>(old->sessionSlots.size())) return -1;const SessionSlot& s = old->sessionSlots[scene];if (!s.hasClip) return -1;auto nt = cloneTrack(*old);+ if (old->type() == TrackType::Audio) {+ // An audio take lands as a plain clip of the slot's sample (one pass of the loop).+ if (!s.audio.sample) return -1;+ AudioClip c = s.audio;+ c.startBeat = startBeat < 0.0 ? 0.0 : startBeat;+ c.name = s.name;+ nt->clips.push_back(c);+ const int32_t idx = static_cast<int32_t>(nt->clips.size()) - 1;+ republishWithTrack(trackId, nt);+ return idx;+ }MidiClip c;+ c.name = s.name;c.startBeat = startBeat < 0.0 ? 0.0 : startBeat;c.lengthBeats = s.lengthBeats > 0 ? s.lengthBeats : 4.0;c.notes = s.midi.notes; // slot notes are already relative to clip start@@ -284,6 +402,7 @@ bool Engine::arrangementClipToSession(int32_t trackId, int32_t clipIndex, int32_s.lengthBeats = src.lengthBeats > 0 ? src.lengthBeats : 4.0;s.midi = src;s.midi.startBeat = 0.0; // slot content is relative to slot start+ s.name = src.name;republishWithTrack(trackId, nt);return true;}@@ -296,6 +415,7 @@ bool Engine::arrangementAudioClipToSession(int32_t trackId, int32_t clipIndex, iconst auto sample = old->clips[clipIndex].sample;if (!sample) return false;const float gain = old->clips[clipIndex].gain;+ const std::string clipName = old->clips[clipIndex].name;auto nt = cloneTrack(*old);if (static_cast<int32_t>(nt->sessionSlots.size()) < authoring_->sceneCount)nt->sessionSlots.resize(authoring_->sceneCount);@@ -306,6 +426,7 @@ bool Engine::arrangementAudioClipToSession(int32_t trackId, int32_t clipIndex, is.audio.sourceOffsetFrames = 0.0;s.audio.lengthFrames = sample->frames;s.audio.gain = gain;+ s.name = clipName;// Loop length = the sample's real duration in beats at the current tempo (like a file drop).const double sr = transport_.sampleRate();const double spb = transport_.samplesPerBeat();@@ -420,4 +541,419 @@ int32_t Engine::sessionNoteCount(int32_t trackId, int32_t scene) const {return static_cast<int32_t>(t->sessionSlots[scene].midi.notes.size());}+// --- Session P0: clip + scene properties --------------------------------------++namespace {+SessionSlot* slotAt(Track& t, int32_t scene) {+ return (scene >= 0 && scene < static_cast<int32_t>(t.sessionSlots.size())) ? &t.sessionSlots[scene] : nullptr;+}+const SessionSlot* slotAt(const Track& t, int32_t scene) {+ return (scene >= 0 && scene < static_cast<int32_t>(t.sessionSlots.size())) ? &t.sessionSlots[scene] : nullptr;+}+} // namespace++bool Engine::sessionClipProps(int32_t trackId, int32_t scene, NotaSessionClipProps* out) const {+ auto t = findTrackAuthoring(trackId);+ const SessionSlot* s = t ? slotAt(*t, scene) : nullptr;+ if (!s || !s->hasClip || !out) return false;+ out->color = s->color;+ out->launch_mode = static_cast<int32_t>(s->launchMode);+ out->quant_beats = s->quantBeats;+ out->legato = s->legato ? 1 : 0;+ out->loop = s->loop ? 1 : 0;+ out->velocity_amount = s->velocityAmount;+ out->follow_a = static_cast<int32_t>(s->followA);+ out->follow_b = static_cast<int32_t>(s->followB);+ out->chance_a = s->chanceA;+ out->chance_b = s->chanceB;+ out->follow_beats = s->followBeats;+ out->jump_scene = s->jumpScene;+ return true;+}++bool Engine::setSessionClipProps(int32_t trackId, int32_t scene, const NotaSessionClipProps& p) {+ auto old = findTrackAuthoring(trackId);+ const SessionSlot* cur = old ? slotAt(*old, scene) : nullptr;+ if (!cur || !cur->hasClip) return false;+ auto nt = cloneTrack(*old);+ SessionSlot& s = nt->sessionSlots[scene];+ s.color = p.color < 0 ? -1 : p.color;+ s.launchMode = static_cast<LaunchMode>(std::clamp(p.launch_mode, 0, 3));+ s.quantBeats = p.quant_beats < 0.0 ? -1.0 : p.quant_beats;+ s.legato = p.legato != 0;+ s.loop = p.loop != 0;+ s.velocityAmount = std::clamp(p.velocity_amount, 0.0f, 1.0f);+ s.followA = static_cast<FollowAction>(std::clamp(p.follow_a, 0, 9));+ s.followB = static_cast<FollowAction>(std::clamp(p.follow_b, 0, 9));+ s.chanceA = std::clamp(p.chance_a, 0, 100);+ s.chanceB = std::clamp(p.chance_b, 0, 100);+ s.followBeats = p.follow_beats > 0.0 ? p.follow_beats : 0.0;+ s.jumpScene = std::max(0, p.jump_scene);+ republishWithTrack(trackId, nt);+ // A slot leaving Repeat mode must not keep retriggering.+ if (s.launchMode != LaunchMode::Repeat && old->sessionPlayer+ && old->sessionPlayer->repeatSlot.load(std::memory_order_relaxed) == scene)+ old->sessionPlayer->repeatSlot.store(-1, std::memory_order_relaxed);+ return true;+}++bool Engine::sessionClipName(int32_t trackId, int32_t scene, std::string& out) const {+ auto t = findTrackAuthoring(trackId);+ const SessionSlot* s = t ? slotAt(*t, scene) : nullptr;+ if (!s || !s->hasClip) return false;+ out = s->name;+ return true;+}++bool Engine::setSessionClipName(int32_t trackId, int32_t scene, const std::string& name) {+ auto old = findTrackAuthoring(trackId);+ const SessionSlot* cur = old ? slotAt(*old, scene) : nullptr;+ if (!cur || !cur->hasClip) return false;+ if (cur->name == name) return true;+ auto nt = cloneTrack(*old);+ nt->sessionSlots[scene].name = name;+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::sessionSlotStopButton(int32_t trackId, int32_t scene) const {+ auto t = findTrackAuthoring(trackId);+ const SessionSlot* s = t ? slotAt(*t, scene) : nullptr;+ return !s || s->stopButton;+}++bool Engine::setSessionSlotStopButton(int32_t trackId, int32_t scene, bool on) {+ auto old = findTrackAuthoring(trackId);+ if (!old || scene < 0 || scene >= authoring_->sceneCount) return false;+ if (sessionSlotStopButton(trackId, scene) == on) return true;+ auto nt = cloneTrack(*old);+ if (static_cast<int32_t>(nt->sessionSlots.size()) < authoring_->sceneCount)+ nt->sessionSlots.resize(authoring_->sceneCount);+ nt->sessionSlots[scene].stopButton = on;+ republishWithTrack(trackId, nt);+ return true;+}++bool Engine::copySessionSlot(int32_t srcTrack, int32_t srcScene, int32_t dstTrack, int32_t dstScene) {+ auto src = findTrackAuthoring(srcTrack);+ auto dst = findTrackAuthoring(dstTrack);+ if (!src || !dst || src->type() != dst->type() || !sessionLaunchable(*dst)) return false;+ const SessionSlot* from = slotAt(*src, srcScene);+ if (!from || !from->hasClip || dstScene < 0 || dstScene >= authoring_->sceneCount) return false;+ if (srcTrack == dstTrack && srcScene == dstScene) return true;+ const SessionSlot copy = *from; // before cloning: src may be dst+ auto nt = cloneTrack(*dst);+ if (static_cast<int32_t>(nt->sessionSlots.size()) < authoring_->sceneCount)+ nt->sessionSlots.resize(authoring_->sceneCount);+ nt->sessionSlots[dstScene] = copy;+ republishWithTrack(dstTrack, nt);+ return true;+}++namespace {+SceneInfo sceneOr(const Graph& g, int32_t scene) {+ return (scene >= 0 && scene < static_cast<int32_t>(g.scenes.size())) ? g.scenes[scene] : SceneInfo{};+}+} // namespace++bool Engine::sceneProps(int32_t scene, NotaSceneProps* out) const {+ if (!out || scene < 0 || scene >= authoring_->sceneCount) return false;+ const SceneInfo si = sceneOr(*authoring_, scene);+ out->color = si.color;+ out->tempo = si.tempo;+ out->sig_num = si.sigNum;+ out->sig_den = si.sigDen;+ out->follow = si.follow ? 1 : 0;+ out->follow_beats = si.followBeats;+ return true;+}++bool Engine::setSceneProps(int32_t scene, const NotaSceneProps& p) {+ if (scene < 0 || scene >= authoring_->sceneCount) return false;+ auto g = std::make_shared<Graph>(*authoring_); // tracks shared; only scene metadata changes+ if (static_cast<int32_t>(g->scenes.size()) < g->sceneCount) g->scenes.resize(g->sceneCount);+ SceneInfo& si = g->scenes[scene];+ si.color = p.color < 0 ? -1 : p.color;+ si.tempo = p.tempo > 0.0 ? std::clamp(p.tempo, 20.0, 999.0) : 0.0;+ const bool sig = p.sig_num > 0 && p.sig_den > 0;+ si.sigNum = sig ? std::clamp(p.sig_num, 1, 32) : 0;+ si.sigDen = sig ? std::clamp(p.sig_den, 1, 32) : 0;+ si.follow = p.follow != 0;+ si.followBeats = p.follow_beats > 0.0 ? p.follow_beats : 32.0;+ publish(std::move(g));+ return true;+}++bool Engine::sceneName(int32_t scene, std::string& out) const {+ if (scene < 0 || scene >= authoring_->sceneCount) return false;+ out = sceneOr(*authoring_, scene).name;+ return true;+}++bool Engine::setSceneName(int32_t scene, const std::string& name) {+ if (scene < 0 || scene >= authoring_->sceneCount) return false;+ if (sceneOr(*authoring_, scene).name == name) return true;+ auto g = std::make_shared<Graph>(*authoring_);+ if (static_cast<int32_t>(g->scenes.size()) < g->sceneCount) g->scenes.resize(g->sceneCount);+ g->scenes[scene].name = name;+ publish(std::move(g));+ return true;+}++// --- Session P0: scene rows ------------------------------------------------------++// Shift every player (and the recording / follow targets) after a row insert or removal.+// map(x) returns the row's new index, or -1 when it is gone. Players are atomics shared with+// the audio thread, so each is moved with a CAS: a launch racing the edit wins.+void Engine::remapPlayers(const std::function<int32_t(int32_t)>& map) {+ for (auto& t : authoring_->tracks) {+ if (!t->sessionPlayer) continue;+ auto& sp = *t->sessionPlayer;+ int32_t p = sp.playing.load(std::memory_order_relaxed);+ if (p >= 0) { const int32_t n = map(p); sp.playing.compare_exchange_strong(p, n < 0 ? -1 : n, std::memory_order_relaxed); }+ int32_t q = sp.pending.load(std::memory_order_relaxed);+ if (q >= 0) { const int32_t n = map(q); sp.pending.compare_exchange_strong(q, n < 0 ? SessionPlayer::kNone : n, std::memory_order_relaxed); }+ int32_t r = sp.repeatSlot.load(std::memory_order_relaxed);+ if (r >= 0) sp.repeatSlot.compare_exchange_strong(r, map(r), std::memory_order_relaxed);+ }+ if (recordSessionScene_ >= 0) { const int32_t n = map(recordSessionScene_); if (n >= 0) recordSessionScene_ = n; }+ if (sceneFollowScene_ >= 0) sceneFollowScene_ = map(sceneFollowScene_);+}++// Insert a row at `at`: empty, a copy of row `copyFrom` (old index), or each track's+// currently playing clip (capture). One undo step.+int32_t Engine::insertSceneRow(int32_t at, int32_t copyFrom, bool capturePlaying) {+ const int32_t count = authoring_->sceneCount;+ if (at < 0 || at > count || copyFrom >= count) return -1;+ auto g = std::make_shared<Graph>();+ g->sceneCount = count + 1;+ g->scenes = authoring_->scenes;+ g->masterVolume = authoring_->masterVolume;+ g->masterTrack = authoring_->masterTrack;+ if (static_cast<int32_t>(g->scenes.size()) < count) g->scenes.resize(count);+ g->scenes.insert(g->scenes.begin() + at, copyFrom >= 0 ? g->scenes[copyFrom] : SceneInfo{});+ g->tracks.reserve(authoring_->tracks.size());+ for (auto& t : authoring_->tracks) {+ auto nt = cloneTrack(*t);+ auto& slots = nt->sessionSlots;+ if (static_cast<int32_t>(slots.size()) < count) slots.resize(count);+ SessionSlot row;+ if (copyFrom >= 0) row = slots[copyFrom];+ else if (capturePlaying && t->sessionPlayer) {+ const int32_t p = t->sessionPlayer->playing.load(std::memory_order_relaxed);+ if (p >= 0 && p < count) row = slots[p];+ }+ slots.insert(slots.begin() + at, row);+ g->tracks.push_back(nt);+ }+ publish(std::move(g));+ remapPlayers([at](int32_t x) { return x >= at ? x + 1 : x; });+ return at;+}++int32_t Engine::insertScene(int32_t at) { return insertSceneRow(at, -1, false); }+int32_t Engine::duplicateScene(int32_t scene) {+ if (scene < 0 || scene >= authoring_->sceneCount) return -1;+ return insertSceneRow(scene + 1, scene, false);+}+int32_t Engine::captureScene(int32_t at) { return insertSceneRow(at, -1, true); }++// Reorder a row: every track's slot and the scene's metadata move together; players follow.+bool Engine::moveScene(int32_t from, int32_t to) {+ const int32_t count = authoring_->sceneCount;+ if (from < 0 || from >= count || to < 0 || to >= count) return false;+ if (from == to) return true;+ auto move = [from, to](auto& v) {+ auto item = v[from];+ v.erase(v.begin() + from);+ v.insert(v.begin() + to, item);+ };+ auto g = rebuildScenes(count, [&](std::vector<SessionSlot>& slots) {+ if (static_cast<int32_t>(slots.size()) < count) slots.resize(count);+ move(slots);+ });+ if (static_cast<int32_t>(g->scenes.size()) < count) g->scenes.resize(count);+ move(g->scenes);+ publish(std::move(g));+ remapPlayers([from, to](int32_t x) {+ if (x == from) return to;+ if (from < to && x > from && x <= to) return x - 1;+ if (to < from && x >= to && x < from) return x + 1;+ return x;+ });+ return true;+}++// --- Session P0: recording ---------------------------------------------------------++int32_t Engine::recordSessionScene(int32_t scene) {+ if (scene < 0 || scene >= authoring_->sceneCount) return 0;+ for (auto& t : authoring_->tracks) {+ if (!t->armed() || !sessionLaunchable(*t)) continue;+ const SessionSlot* s = slotAt(*t, scene);+ if (s && s->hasClip) continue;+ recordSessionSlot(t->id(), scene);+ return t->id();+ }+ return 0;+}++bool Engine::sessionRecordTarget(int32_t* trackId, int32_t* scene, double* elapsed) const {+ if (!recording_.load(std::memory_order_relaxed) || recordSessionScene_ < 0 || recordSessionTrackId_ <= 0) return false;+ double el = 0.0;+ if (recordSessionAudio_) el = std::max(0.0, transport_.uiPositionBeats() - audioRecordStartBeat_);+ else if (auto* sp = recordSlotPlayer_.load(std::memory_order_acquire))+ if (sp->playing.load(std::memory_order_relaxed) == recordSessionScene_)+ el = sp->playedBeats.load(std::memory_order_relaxed);+ if (trackId) *trackId = recordSessionTrackId_;+ if (scene) *scene = recordSessionScene_;+ if (elapsed) *elapsed = el;+ return true;+}++// poll(): fixed-length capture ends a take by itself, and a following scene queues the next+// row one launch quantum ahead so it lands on the boundary where this one's time runs out.+bool Engine::takeSceneTempoChange(double* bpm, int32_t* num, int32_t* den) {+ if (!sceneTempoApplied_) return false;+ sceneTempoApplied_ = false;+ if (bpm) *bpm = sceneTempo_;+ if (num) *num = sceneSigNum_;+ if (den) *den = sceneSigDen_;+ return true;+}++void Engine::applySceneTempo() {+ sceneTempoPending_ = false;+ sceneTempoApplied_ = true; // the UI's transport picks the new values up (takeSceneTempoChange)+ if (sceneTempo_ > 0.0) setBpm(sceneTempo_);+ if (sceneSigNum_ > 0 && sceneSigDen_ > 0) setTimeSignature(sceneSigNum_, sceneSigDen_);+}++void Engine::serviceSessionFollow() {+ if (sceneTempoPending_ && transport_.uiPositionBeats() + 1e-6 >= sceneTempoAt_) applySceneTempo();+ if (sessionRecordLen_ > 0.0) {+ double el = 0.0;+ if (sessionRecordTarget(nullptr, nullptr, &el) && el >= sessionRecordLen_ - 1e-6) stopSessionRecord();+ }+ if (!transport_.uiIsPlaying()) { sceneFollowScene_ = -1; return; }+ const int32_t sc = sceneFollowScene_;+ if (sc < 0 || sc >= authoring_->sceneCount || !sessionFollow()) return;+ const SceneInfo si = sceneOr(*authoring_, sc);+ if (!si.follow || si.followBeats <= 0.0) return;+ const double q = launchQuant_.load(std::memory_order_relaxed);+ const double lead = q > 0.0 ? std::min(q, si.followBeats) : 0.0;+ const double due = sceneFollowStart_ + si.followBeats;+ if (transport_.uiPositionBeats() + lead + 1e-6 < due) return;+ launchScene((sc + 1) % authoring_->sceneCount);+ sceneFollowStart_ = due; // exactly where the outgoing scene's time ran out+}++// Peaks of an audio slot's take (whole sample) for the grid / inspector preview.+int32_t Engine::sessionSlotPeaks(int32_t trackId, int32_t scene, float* outMinMax, int32_t maxPoints) const {+ if (!outMinMax || maxPoints <= 0) return 0;+ auto t = findTrackAuthoring(trackId);+ const SessionSlot* s = t ? slotAt(*t, scene) : nullptr;+ if (!s || !s->hasClip || !s->audio.sample) return 0;+ const SampleBuffer& sb = *s->audio.sample;+ const int64_t total = sb.frames;+ if (total <= 0) return 0;+ const int32_t buckets = static_cast<int32_t>(std::min<int64_t>(maxPoints, total));+ const int64_t per = total / buckets;+ for (int32_t b = 0; b < buckets; ++b) {+ float mn, mx;+ sb.peakRange(b * per, (b + 1) * per, mn, mx);+ outMinMax[b * 2] = mn; outMinMax[b * 2 + 1] = mx;+ }+ return buckets;+}++// --- Session P0: audio thread ---------------------------------------------------++int32_t Engine::followTarget(const Track& t, int32_t cur, FollowAction a) {+ const int32_t n = static_cast<int32_t>(t.sessionSlots.size());+ auto filled = [&](int32_t i) { return i >= 0 && i < n && t.sessionSlots[i].hasClip; };+ auto rnd = [&]() { uint32_t x = followRng_; x ^= x << 13; x ^= x >> 17; x ^= x << 5; followRng_ = x; return x; };+ switch (a) {+ case FollowAction::Stop: return -1;+ case FollowAction::Again: return cur;+ case FollowAction::Next:+ for (int32_t k = 1; k <= n; ++k) if (filled((cur + k) % n)) return (cur + k) % n;+ return cur;+ case FollowAction::Previous:+ for (int32_t k = 1; k <= n; ++k) if (filled(((cur - k) % n + n) % n)) return ((cur - k) % n + n) % n;+ return cur;+ case FollowAction::First:+ for (int32_t i = 0; i < n; ++i) if (filled(i)) return i;+ return cur;+ case FollowAction::Last:+ for (int32_t i = n - 1; i >= 0; --i) if (filled(i)) return i;+ return cur;+ case FollowAction::Any:+ case FollowAction::Other: {+ int32_t pool[256]; int32_t m = 0;+ for (int32_t i = 0; i < n && m < 256; ++i)+ if (filled(i) && (a == FollowAction::Any || i != cur)) pool[m++] = i;+ return m ? pool[rnd() % static_cast<uint32_t>(m)] : cur;+ }+ case FollowAction::Jump: {+ const int32_t j = t.sessionSlots[cur].jumpScene;+ return filled(j) ? j : -1;+ }+ default: return cur;+ }+}++void Engine::sessionPreApply(Track& t, double blockBeats) {+ auto& sp = *t.sessionPlayer;+ const int32_t cur = sp.playing.load(std::memory_order_relaxed);+ if (cur < 0 || cur >= static_cast<int32_t>(t.sessionSlots.size())) return;+ if (sp.pending.load(std::memory_order_relaxed) != SessionPlayer::kNone) return;+ const SessionSlot& s = t.sessionSlots[cur];++ // Repeat: while held, queue a relaunch of the same slot at every quantum.+ if (sp.repeatSlot.load(std::memory_order_relaxed) == cur) {+ double q = s.quantBeats >= 0.0 ? s.quantBeats : launchQuant_.load(std::memory_order_relaxed);+ if (q <= 0.0) q = 0.25;+ sp.pendingQuant.store(q, std::memory_order_relaxed);+ sp.pendingLegato.store(false, std::memory_order_relaxed);+ sp.pendingGain.store(sp.gain, std::memory_order_relaxed);+ int32_t expect = SessionPlayer::kNone;+ sp.pending.compare_exchange_strong(expect, cur, std::memory_order_relaxed);+ return;+ }++ // Follow action: once the slot has played its follow time, pick A or B by weight.+ if (!sessionFollow_.load(std::memory_order_relaxed)) return;+ if (s.followA == FollowAction::None && s.followB == FollowAction::None) return;+ const double due = s.followBeats > 0.0 ? s.followBeats : (s.lengthBeats > 0.0 ? s.lengthBeats : 4.0);+ if (sp.playedBeats.load(std::memory_order_relaxed) + blockBeats * 0.5 < due) return;+ const int32_t total = s.chanceA + s.chanceB;+ uint32_t x = followRng_; x ^= x << 13; x ^= x >> 17; x ^= x << 5; followRng_ = x;+ const FollowAction a = (total <= 0 || static_cast<int32_t>(x % 100u) * total < s.chanceA * 100) ? s.followA : s.followB;+ if (a == FollowAction::None) { sp.playedBeats.store(0.0, std::memory_order_relaxed); return; }+ const int32_t target = followTarget(t, cur, a);+ int32_t expect = SessionPlayer::kNone;+ if (target < 0) { sp.pending.compare_exchange_strong(expect, SessionPlayer::kStopNow, std::memory_order_relaxed); return; }+ sp.pendingQuant.store(0.0, std::memory_order_relaxed); // follow time is exact, not quantized+ sp.pendingLegato.store(false, std::memory_order_relaxed);+ sp.pendingGain.store(sp.gain, std::memory_order_relaxed);+ sp.pending.compare_exchange_strong(expect, target, std::memory_order_relaxed);+}++void Engine::sessionPostRender(Track& t, double blockBeats) {+ auto& sp = *t.sessionPlayer;+ sp.publish(blockBeats);+ const int32_t cur = sp.playing.load(std::memory_order_relaxed);+ if (cur < 0 || cur >= static_cast<int32_t>(t.sessionSlots.size())) return;+ const SessionSlot& s = t.sessionSlots[cur];+ const double L = s.lengthBeats > 0.0 ? s.lengthBeats : 4.0;+ if (s.loop || sp.localBeats < L) return;+ // One-shot reached its end: stop the track (a queued launch still applies next block).+ int32_t expect = cur;+ if (sp.playing.compare_exchange_strong(expect, -1, std::memory_order_relaxed)) {+ if (t.instrument) t.instrument->allNotesOff();+ for (auto& md : t.midiEffects) if (md) md->reset();+ }+}+} // namespace notadiff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cppindex 931c7665..ac4e51be 100644--- a/src/native/nota.engine/src/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/Engine_Tracks.cpp@@ -350,6 +350,7 @@ void Engine::reconfigureAllWarpStreams(double spb, double devSR) {bool any = false;auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -1219,6 +1220,7 @@ bool Engine::moveClipToTrack(int32_t srcTrackId, int32_t clipIndex, int32_t sourpushUndo();auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -1338,6 +1340,7 @@ bool Engine::moveClipBlock(const std::vector<ClipMoveReq>& moves) {pushUndo();auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -1369,6 +1372,7 @@ bool Engine::deleteClipsInRange(const std::vector<int32_t>& trackIds, double stabool any = false;auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -1398,6 +1402,7 @@ bool Engine::splitClipsAtRange(const std::vector<int32_t>& trackIds, double starbool any = false;auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -1452,6 +1457,7 @@ double Engine::duplicateRange(const std::vector<int32_t>& trackIds, double startbool any = false;auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -1606,6 +1612,7 @@ bool Engine::consolidateRange(const std::vector<int32_t>& trackIds, double startstd::vector<std::pair<int32_t,int32_t>> placed;auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -2144,6 +2151,7 @@ void Engine::placeBlock(const std::vector<BlockClip>& items, double placedStart,pushUndo();auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -2195,6 +2203,7 @@ bool Engine::cutClipBlock(const std::vector<std::pair<int32_t,int32_t>>& sel) {pushUndo();auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -2381,6 +2390,7 @@ int32_t Engine::duplicateTrack(int32_t trackId) {// Insert the copy right after the source (new snapshot; checkpoints undo).auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size() + 1);@@ -2404,6 +2414,7 @@ bool Engine::removeTrack(int32_t trackId) {for (auto& d : rt->devices) if (d) d->closeEditor();auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -2434,6 +2445,7 @@ bool Engine::moveTrack(int32_t trackId, int32_t toIndex) {regular.insert(regular.begin() + to, tr);auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(regular.size() + returns.size());@@ -2471,6 +2483,7 @@ int32_t Engine::createGroup(const int32_t* ids, int32_t n) {auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size() + 1);@@ -2496,6 +2509,7 @@ bool Engine::ungroup(int32_t groupId) {const int32_t parent = grp->groupId(); // children reparent up one levelauto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -2525,6 +2539,7 @@ bool Engine::setTrackGroup(int32_t trackId, int32_t groupId) {}auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());@@ -2574,6 +2589,7 @@ std::vector<int32_t> Engine::insertTrackClones(const std::vector<std::shared_ptrauto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size() + clones.size());@@ -2617,6 +2633,7 @@ bool Engine::removeTracks(const int32_t* ids, int32_t n) {}auto g = std::make_shared<Graph>();g->sceneCount = authoring_->sceneCount;+ g->scenes = authoring_->scenes;g->masterVolume = authoring_->masterVolume;g->masterTrack = authoring_->masterTrack;g->tracks.reserve(authoring_->tracks.size());diff --git a/src/native/nota.engine/src/Graph.h b/src/native/nota.engine/src/Graph.hindex db2ab303..e66d0184 100644--- a/src/native/nota.engine/src/Graph.h+++ b/src/native/nota.engine/src/Graph.h@@ -21,6 +21,9 @@ namespace nota {struct Graph {std::vector<std::shared_ptr<Track>> tracks;int32_t sceneCount = 8; // Session view rows (M5)+ // Scene names / colours / tempo / follow (Session P0). May be shorter than sceneCount+ // (missing rows read as defaults). Carried forward wherever sceneCount is.+ std::vector<SceneInfo> scenes;// Master-volume automation (M9 follow-up): a graph-level lane (not tied to a// track), applied to the master gain in applyAutomation. Undo-free via the// snapshot, like track lanes. NB: fresh-graph builds must carry it forwarddiff --git a/src/native/nota.engine/src/SessionPlayer.h b/src/native/nota.engine/src/SessionPlayer.hindex 76d61c63..660284c5 100644--- a/src/native/nota.engine/src/SessionPlayer.h+++ b/src/native/nota.engine/src/SessionPlayer.h@@ -16,28 +16,47 @@ namespace nota {class SessionPlayer {public:- static constexpr int32_t kNone = -2; // no pending request- static constexpr int32_t kStop = -1; // pending stop+ static constexpr int32_t kNone = -2; // no pending request+ static constexpr int32_t kStop = -1; // pending stop (quantized)+ static constexpr int32_t kStopNow = -3; // pending stop, applied at the next block (per-track "back to arrangement")// Audio thread reads; message thread writes.std::atomic<int32_t> playing{-1}; // playing slot, or -1- std::atomic<int32_t> pending{kNone}; // kNone / kStop / slot index+ std::atomic<int32_t> pending{kNone}; // kNone / kStop / kStopNow / slot index+ // Launch options travelling with the pending request (Session P0).+ std::atomic<double> pendingQuant{-1.0}; // <0 = the global launch quantum+ std::atomic<bool> pendingLegato{false}; // keep the loop position across the switch+ std::atomic<float> pendingGain{1.0f}; // launch-velocity gain for the incoming slot+ std::atomic<int32_t> repeatSlot{-1}; // Repeat mode: retrigger this slot every quantum while held+ // Audio thread writes, UI reads: the playing slot's loop position (progress) and beats+ // played since it launched (follow actions / fixed-length capture).+ std::atomic<double> uiLocalBeats{0.0};+ std::atomic<double> playedBeats{0.0};// Audio-thread-only.double localBeats = 0.0; // absolute position within the loop clock+ float gain = 1.0f; // launch-velocity gain of the playing slot- void requestLaunch(int32_t slot) { pending.store(slot, std::memory_order_relaxed); }- void requestStop() { pending.store(kStop, std::memory_order_relaxed); }+ void requestLaunch(int32_t slot, double quant = -1.0, bool legato = false, float g = 1.0f) {+ pendingQuant.store(quant, std::memory_order_relaxed);+ pendingLegato.store(legato, std::memory_order_relaxed);+ pendingGain.store(g, std::memory_order_relaxed);+ pending.store(slot, std::memory_order_relaxed);+ }+ void requestStop() { repeatSlot.store(-1, std::memory_order_relaxed); pending.store(kStop, std::memory_order_relaxed); }+ void requestStopNow() { repeatSlot.store(-1, std::memory_order_relaxed); pending.store(kStopNow, std::memory_order_relaxed); }// Audio thread: if a pending request exists and a quantize boundary falls in// this block (or quant<=0), apply it. Returns true if `playing` changed// (so the caller can flush hanging notes).- bool maybeApply(double blockStartBeats, double blockBeats, double quant) {+ bool maybeApply(double blockStartBeats, double blockBeats, double globalQuant) {const int32_t p = pending.load(std::memory_order_relaxed);if (p == kNone) return false;+ const double pq = pendingQuant.load(std::memory_order_relaxed);+ const double quant = (p == kStop || p == kStopNow || pq < 0.0) ? globalQuant : pq;bool boundary;- if (quant <= 0.0) {+ if (p == kStopNow || quant <= 0.0) {boundary = true;} else {const double b1 = blockStartBeats + blockBeats;@@ -46,15 +65,28 @@ public:}if (!boundary) return false;- pending.store(kNone, std::memory_order_relaxed);- if (p == kStop) {+ // A launch may have replaced the request between our two loads; only consume it if not.+ int32_t expect = p;+ if (!pending.compare_exchange_strong(expect, kNone, std::memory_order_relaxed)) return false;+ if (p == kStop || p == kStopNow) {playing.store(-1, std::memory_order_relaxed);} else {+ const bool legato = pendingLegato.load(std::memory_order_relaxed)+ && playing.load(std::memory_order_relaxed) >= 0;playing.store(p, std::memory_order_relaxed);- localBeats = 0.0;+ if (!legato) localBeats = 0.0;+ gain = pendingGain.load(std::memory_order_relaxed);+ playedBeats.store(0.0, std::memory_order_relaxed);}return true;}++ // Audio thread, after rendering a block: advance the played counter and publish the+ // loop position for the UI.+ void publish(double blockBeats) {+ playedBeats.store(playedBeats.load(std::memory_order_relaxed) + blockBeats, std::memory_order_relaxed);+ uiLocalBeats.store(localBeats, std::memory_order_relaxed);+ }};} // namespace notadiff --git a/src/native/nota.engine/src/Track.h b/src/native/nota.engine/src/Track.hindex 8ac0e0da..87d75b76 100644--- a/src/native/nota.engine/src/Track.h+++ b/src/native/nota.engine/src/Track.h@@ -114,11 +114,43 @@ struct AudioClip {// A Session-view clip slot (M5). One per scene on each track. Holds a MIDI clip// (instrument tracks) or a captured audio take (audio tracks, M5-4); the type is// implied by the track type. Immutable in a snapshot.+// Follow actions (Session P0): what a slot does once it has played followBeats.+enum class FollowAction : int32_t { None = 0, Stop, Again, Previous, Next, First, Last, Any, Other, Jump };+// How a slot reacts to its launch button: Trigger starts, Gate plays while held, Toggle+// starts / stops, Repeat retriggers at the launch quantum while held.+enum class LaunchMode : int32_t { Trigger = 0, Gate, Toggle, Repeat };+struct SessionSlot {bool hasClip = false;MidiClip midi; // instrument tracks: notes relative to slot startAudioClip audio; // audio tracks: captured sample, looped over lengthBeats (M5-4)double lengthBeats = 4.0; // loop length++ // Clip properties (Session P0). Message thread writes them on a clone; the audio+ // thread reads only the POD fields of the published snapshot.+ std::string name; // empty = "<track> <scene>" in the UI+ int32_t color = -1; // track-palette index, -1 = the track's colour+ LaunchMode launchMode = LaunchMode::Trigger;+ double quantBeats = -1.0; // <0 = the global launch quantum+ bool legato = false; // launch at the outgoing slot's position+ bool loop = true; // false = one-shot: stops after lengthBeats+ float velocityAmount = 0.0f; // 0..1: how far launch velocity scales the clip+ FollowAction followA = FollowAction::None;+ FollowAction followB = FollowAction::None;+ int32_t chanceA = 100, chanceB = 0; // relative weights, 0..100+ double followBeats = 0.0; // 0 = after one pass (lengthBeats)+ int32_t jumpScene = 0; // FollowAction::Jump target+ bool stopButton = true; // an EMPTY slot stops its track on scene launch+};++// Scene metadata (Session P0). Graph-level, one per scene row; kept in step with sceneCount.+struct SceneInfo {+ std::string name;+ int32_t color = -1; // track-palette index, -1 = neutral+ double tempo = 0.0; // >0: launching the scene sets the tempo+ int32_t sigNum = 0, sigDen = 0; // >0: launching the scene sets the time signature+ bool follow = false; // launch the next scene after followBeats+ double followBeats = 32.0;};enum class TrackType { Audio, Instrument, Return, Group };diff --git a/src/native/nota.engine/src/nota_engine_session.cpp b/src/native/nota.engine/src/nota_engine_session.cppindex 132f9da6..9facda9d 100644--- a/src/native/nota.engine/src/nota_engine_session.cpp+++ b/src/native/nota.engine/src/nota_engine_session.cpp@@ -6,6 +6,8 @@#include "nota_engine_internal.h"+#include <algorithm>+#include <cstring>#include <string>extern "C" {@@ -138,4 +140,109 @@ int32_t nota_session_add_audio_file(NotaEngine* e, int32_t track_id, int32_t scereturn ENG(e)->addSessionAudioFile(track_id, scene, std::string(path)) ? 1 : 0;}+// ---- Session P0: clip + scene properties, scene/slot editing, follow ------++static int32_t copyOut(const std::string& v, char* out, int32_t cap) {+ if (out && cap > 0) {+ const int32_t n = std::min<int32_t>(cap - 1, static_cast<int32_t>(v.size()));+ std::memcpy(out, v.data(), static_cast<size_t>(n));+ out[n] = '\0';+ }+ return static_cast<int32_t>(v.size());+}++int32_t nota_session_get_clip_props(const NotaEngine* e, int32_t track_id, int32_t scene, NotaSessionClipProps* out) {+ return (e && out && CENG(e)->sessionClipProps(track_id, scene, out)) ? 1 : 0;+}+NotaResult nota_session_set_clip_props(NotaEngine* e, int32_t track_id, int32_t scene, const NotaSessionClipProps* p) {+ if (!e || !p) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setSessionClipProps(track_id, scene, *p) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_session_get_clip_name(const NotaEngine* e, int32_t track_id, int32_t scene, char* out, int32_t cap) {+ std::string v;+ if (!e || !CENG(e)->sessionClipName(track_id, scene, v)) { if (out && cap > 0) out[0] = '\0'; return 0; }+ return copyOut(v, out, cap);+}+NotaResult nota_session_set_clip_name(NotaEngine* e, int32_t track_id, int32_t scene, const char* name) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setSessionClipName(track_id, scene, name ? std::string(name) : std::string()) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_session_get_slot_stop_button(const NotaEngine* e, int32_t track_id, int32_t scene) {+ return (!e || CENG(e)->sessionSlotStopButton(track_id, scene)) ? 1 : 0;+}+NotaResult nota_session_set_slot_stop_button(NotaEngine* e, int32_t track_id, int32_t scene, int32_t on) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setSessionSlotStopButton(track_id, scene, on != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+NotaResult nota_session_copy_slot(NotaEngine* e, int32_t st, int32_t ss, int32_t dt, int32_t ds) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->copySessionSlot(st, ss, dt, ds) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_session_get_scene_props(const NotaEngine* e, int32_t scene, NotaSceneProps* out) {+ return (e && out && CENG(e)->sceneProps(scene, out)) ? 1 : 0;+}+NotaResult nota_session_set_scene_props(NotaEngine* e, int32_t scene, const NotaSceneProps* p) {+ if (!e || !p) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setSceneProps(scene, *p) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_session_get_scene_name(const NotaEngine* e, int32_t scene, char* out, int32_t cap) {+ std::string v;+ if (!e || !CENG(e)->sceneName(scene, v)) { if (out && cap > 0) out[0] = '\0'; return 0; }+ return copyOut(v, out, cap);+}+NotaResult nota_session_set_scene_name(NotaEngine* e, int32_t scene, const char* name) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->setSceneName(scene, name ? std::string(name) : std::string()) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}+int32_t nota_session_insert_scene(NotaEngine* e, int32_t at) { return e ? ENG(e)->insertScene(at) : -1; }+int32_t nota_session_duplicate_scene(NotaEngine* e, int32_t scene) { return e ? ENG(e)->duplicateScene(scene) : -1; }+int32_t nota_session_capture_scene(NotaEngine* e, int32_t at) { return e ? ENG(e)->captureScene(at) : -1; }+NotaResult nota_session_launch_slot_vel(NotaEngine* e, int32_t track_id, int32_t scene, float velocity) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ ENG(e)->launchSlotVel(track_id, scene, velocity);+ return NOTA_OK;+}+NotaResult nota_session_release_slot(NotaEngine* e, int32_t track_id, int32_t scene) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ ENG(e)->releaseSlot(track_id, scene);+ return NOTA_OK;+}+NotaResult nota_session_track_back_to_arrangement(NotaEngine* e, int32_t track_id) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ ENG(e)->trackBackToArrangement(track_id);+ return NOTA_OK;+}+int32_t nota_session_playing_slot(const NotaEngine* e, int32_t track_id) { return e ? CENG(e)->sessionPlayingSlot(track_id) : -1; }+double nota_session_slot_position(const NotaEngine* e, int32_t track_id) { return e ? CENG(e)->sessionSlotPosition(track_id) : 0.0; }+double nota_session_get_launch_quant(const NotaEngine* e) { return e ? CENG(e)->launchQuant() : 0.0; }+NotaResult nota_session_set_follow(NotaEngine* e, int32_t on) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ ENG(e)->setSessionFollow(on != 0);+ return NOTA_OK;+}+int32_t nota_session_get_follow(const NotaEngine* e) { return (e && CENG(e)->sessionFollow()) ? 1 : 0; }+NotaResult nota_session_set_record_length(NotaEngine* e, double beats) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ ENG(e)->setSessionRecordLength(beats);+ return NOTA_OK;+}+double nota_session_get_record_length(const NotaEngine* e) { return e ? CENG(e)->sessionRecordLength() : 0.0; }+int32_t nota_session_record_scene(NotaEngine* e, int32_t scene) { return e ? ENG(e)->recordSessionScene(scene) : 0; }+int32_t nota_session_record_target(const NotaEngine* e, int32_t* track_id, int32_t* scene, double* elapsed) {+ return (e && CENG(e)->sessionRecordTarget(track_id, scene, elapsed)) ? 1 : 0;+}++int32_t nota_session_slot_peaks(const NotaEngine* e, int32_t track_id, int32_t scene, float* out_min_max, int32_t max_points) {+ return e ? CENG(e)->sessionSlotPeaks(track_id, scene, out_min_max, max_points) : 0;+}++NotaResult nota_session_move_scene(NotaEngine* e, int32_t from, int32_t to) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ return ENG(e)->moveScene(from, to) ? NOTA_OK : NOTA_ERR_INVALID_ARG;+}++int32_t nota_session_take_scene_tempo(NotaEngine* e, double* bpm, int32_t* num, int32_t* den) {+ return (e && ENG(e)->takeSceneTempoChange(bpm, num, den)) ? 1 : 0;+}+} // extern "C"diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex ddce709d..3093c9ed 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -7783,6 +7783,185 @@ engine.StopTransport();Check(e.SceneCount == scenes0, $"scene count shrank back ({e.SceneCount})");}+// -- Session P0: clip + scene properties, editing, launch modes, follow, capture --+{+ using var e = new NotaEngine();+ e.SetBpm(120); e.SetLaunchQuant(0.0);+ var pb = new float[256 * 2];+ // Render until the transport has moved `beats` (the offline rate isn't the device's).+ void Run(double beats)+ {+ double from = e.PositionBeats;+ for (int guard = 0; guard < 20000 && e.PositionBeats - from < beats; guard++) { e.RenderOffline(pb, 256); e.Poll(); }+ }+ void Start() { e.StopTransport(); e.Seek(0); e.RenderOffline(pb, 64); }++ int t = e.AddInstrumentTrack();+ e.AddSessionMidiClip(t, 0, 4.0);+ e.SetSessionNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.9f) });++ // Clip name + properties round-trip.+ e.SetSessionClipName(t, 0, "Sub Line");+ Check(e.GetSessionClipName(t, 0) == "Sub Line", "session clip name round-trips");+ Check(e.TryGetSessionClipProps(t, 0, out var cp) && cp.Color == -1 && cp.Loop == 1 && cp.QuantBeats < 0 && cp.ChanceA == 100,+ "session clip props default (track colour, loop, global quant)");+ cp.Color = 5; cp.LaunchMode = (int)SessionLaunchMode.Gate; cp.QuantBeats = 2; cp.Legato = 1;+ cp.FollowA = (int)SessionFollowAction.Next; cp.FollowBeats = 8;+ Check(e.SetSessionClipProps(t, 0, cp), "set session clip props");+ Check(e.TryGetSessionClipProps(t, 0, out var cp2) && cp2.Color == 5 && cp2.LaunchMode == 1 && Math.Abs(cp2.QuantBeats - 2) < 1e-9+ && cp2.Legato == 1 && cp2.FollowA == (int)SessionFollowAction.Next && Math.Abs(cp2.FollowBeats - 8) < 1e-9,+ "session clip props round-trip");+ Check(!e.TryGetSessionClipProps(t, 5, out _), "empty slot has no clip props");++ // Copy keeps notes, name and props; undo removes the copy in one step.+ Check(e.CopySessionSlot(t, 0, t, 2), "copy a slot onto another");+ Check(e.GetSessionNotes(t, 2).Length == 1 && e.GetSessionClipName(t, 2) == "Sub Line"+ && e.TryGetSessionClipProps(t, 2, out var cp3) && cp3.Color == 5, "copied slot carries notes, name and props");+ e.Undo();+ Check(e.SessionSlotState(t, 2) == 0, "undo removes the copied slot");+ int audioT = e.AddAudioTrack();+ Check(!e.CopySessionSlot(t, 0, audioT, 0), "a MIDI slot does not copy onto an audio track");++ // Scene metadata.+ e.SetSceneName(1, "Drop");+ e.SetSceneProps(1, new NotaSceneProps { Color = 2, Tempo = 128, SigNum = 3, SigDen = 4, Follow = 1, FollowBeats = 8 });+ Check(e.GetSceneName(1) == "Drop" && e.TryGetSceneProps(1, out var sp) && sp.Color == 2 && Math.Abs(sp.Tempo - 128) < 1e-9+ && sp.SigNum == 3 && sp.Follow == 1, "scene name + props round-trip");++ // Insert / duplicate / move keep slots and the scene's metadata with their row.+ int scenes0 = e.SceneCount;+ Check(e.InsertScene(0) == 0 && e.SceneCount == scenes0 + 1, "insert scene at the top");+ Check(e.SessionSlotState(t, 1) == 1 && e.GetSessionClipName(t, 1) == "Sub Line", "insert shifts slots down");+ Check(e.GetSceneName(2) == "Drop", "insert shifts scene metadata down");+ Check(e.DuplicateScene(1) == 2 && e.GetSessionNotes(t, 2).Length == 1, "duplicate scene copies its slots below");+ Check(e.MoveScene(2, 0) && e.SessionSlotState(t, 0) == 1 && e.SessionSlotState(t, 1) == 0 && e.SessionSlotState(t, 2) == 1 && e.GetSceneName(3) == "Drop",+ "move scene takes its slots and metadata along");+ while (e.SceneCount > scenes0) e.RemoveScene(0);++ // Insert keeps a playing clip playing (its player follows the row).+ e.ClearSessionSlot(t, 0); e.AddSessionMidiClip(t, 0, 4.0);+ e.SetSessionNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.9f) });+ var trig = default(NotaSessionClipProps); e.TryGetSessionClipProps(t, 0, out trig);+ trig.LaunchMode = 0; trig.QuantBeats = -1; trig.FollowA = 0; trig.Legato = 0; e.SetSessionClipProps(t, 0, trig);+ Start(); e.LaunchSlot(t, 0); Run(0.5);+ Check(e.SessionPlayingSlot(t) == 0, "slot 0 playing");+ double posBefore = e.SessionSlotPosition(t);+ Check(posBefore > 0.3 && posBefore < 0.7, $"slot position runs on the slot's own clock ({posBefore:F2})");+ e.InsertScene(0);+ Check(e.SessionPlayingSlot(t) == 1 && e.SessionSlotState(t, 1) == 3, "inserting a scene above keeps the clip playing (remapped)");+ e.RemoveScene(0);+ Check(e.SessionPlayingSlot(t) == 0, "removing a scene above remaps the player back");++ // Capture: the playing clip lands in the new row.+ int cap = e.CaptureScene(e.SceneCount);+ Check(cap >= 0 && e.SessionSlotState(t, cap) == 1, "capture scene copies the playing clip");+ e.RemoveScene(cap);+ e.StopAllSession(); Run(0.1);++ // Toggle: a second launch stops it.+ trig.LaunchMode = (int)SessionLaunchMode.Toggle; e.SetSessionClipProps(t, 0, trig);+ Start(); e.LaunchSlot(t, 0); Run(0.25);+ Check(e.SessionSlotState(t, 0) == 3, "toggle clip starts");+ e.LaunchSlot(t, 0); Run(0.25);+ Check(e.SessionSlotState(t, 0) == 1, "toggle clip stops on the second launch");++ // Gate: plays while held.+ trig.LaunchMode = (int)SessionLaunchMode.Gate; e.SetSessionClipProps(t, 0, trig);+ Start(); e.LaunchSlot(t, 0); Run(0.25);+ Check(e.SessionSlotState(t, 0) == 3, "gate clip plays while held");+ e.ReleaseSlot(t, 0); Run(0.25);+ Check(e.SessionSlotState(t, 0) == 1, "gate clip stops on release");++ // One-shot: loop off stops after one pass.+ trig.LaunchMode = 0; trig.Loop = 0; e.SetSessionSlotLength(t, 0, 1.0); e.SetSessionClipProps(t, 0, trig);+ Start(); e.LaunchSlot(t, 0); Run(0.5);+ Check(e.SessionSlotState(t, 0) == 3, "one-shot clip plays");+ Run(1.0);+ Check(e.SessionSlotState(t, 0) == 1, "one-shot clip stops after one pass");+ trig.Loop = 1; e.SetSessionClipProps(t, 0, trig);++ // Follow action: Next after 1 beat moves to the next filled slot; global off disables it.+ e.AddSessionMidiClip(t, 1, 4.0);+ e.SetSessionNotes(t, 1, new[] { new NotaNote(64, 0.0, 1.0, 0.9f) });+ trig.FollowA = (int)SessionFollowAction.Next; trig.ChanceA = 100; trig.ChanceB = 0; trig.FollowBeats = 1.0;+ e.SetSessionClipProps(t, 0, trig);+ e.SessionFollow = false;+ Start(); e.LaunchSlot(t, 0); Run(1.5);+ Check(e.SessionPlayingSlot(t) == 0, "follow actions off globally: clip keeps looping");+ e.SessionFollow = true;+ Start(); e.LaunchSlot(t, 0); Run(1.5);+ Check(e.SessionPlayingSlot(t) == 1, $"follow action Next moved to slot 1 (playing {e.SessionPlayingSlot(t)})");+ e.StopAllSession(); Run(0.1);++ // Empty slot without a stop button: launching its scene leaves the track playing.+ int t2 = e.AddInstrumentTrack();+ e.AddSessionMidiClip(t2, 0, 4.0);+ e.SetSessionNotes(t2, 0, new[] { new NotaNote(48, 0.0, 1.0, 0.9f) });+ e.SetSessionSlotStopButton(t2, 3, false);+ Check(!e.GetSessionSlotStopButton(t2, 3) && e.GetSessionSlotStopButton(t2, 4), "stop button flag per empty slot");+ Start(); e.LaunchSlot(t2, 0); Run(0.25);+ e.LaunchScene(3); Run(0.25);+ Check(e.SessionPlayingSlot(t2) == 0, "scene launch skips a slot without a stop button");+ e.LaunchScene(4); Run(0.25);+ Check(e.SessionPlayingSlot(t2) == -1, "scene launch stops a track at a slot with a stop button");++ // Per-track back to arrangement stops just that track, right away.+ e.LaunchScene(0); Run(0.25);+ e.TrackBackToArrangement(t2); Run(0.05);+ Check(e.SessionPlayingSlot(t2) == -1 && e.SessionPlayingSlot(t) == 0, "track back-to-arrangement stops only that track");+ e.StopAllSession(); Run(0.1);++ // Scene tempo + signature apply on launch, and the transport is told once.+ e.SetSceneProps(2, new NotaSceneProps { Color = -1, Tempo = 140, FollowBeats = 32 });+ e.StopTransport(); e.RenderOffline(pb, 64);+ e.LaunchScene(2);+ Check(e.TakeSceneTempoChange(out double sBpm, out _, out _) && Math.Abs(sBpm - 140) < 1e-9, "launching a scene applies its tempo");+ Check(!e.TakeSceneTempoChange(out _, out _, out _), "scene tempo change is reported once");+ e.SetBpm(120);+ e.StopAllSession(); Run(0.1);++ // Scene follow: Next after 1 beat launches the next scene.+ e.SetSceneProps(0, new NotaSceneProps { Color = -1, Follow = 1, FollowBeats = 1 });+ Start(); e.LaunchScene(0); Run(1.5);+ Check(e.SessionPlayingSlot(t) == 1, $"scene follow launched the next scene (playing {e.SessionPlayingSlot(t)})");+ e.SetSceneProps(0, new NotaSceneProps { Color = -1, FollowBeats = 32 });+ e.StopAllSession(); Run(0.1); e.StopTransport();++ // Session Rec: an open-ended take is cut to whole bars; Fixed Length stops by itself.+ int r = e.AddInstrumentTrack();+ e.SetTrackArmed(r, true);+ Start();+ Check(e.RecordSessionScene(6) == r, "session record picks the armed track");+ Run(5.2);+ e.StopSessionRecord();+ Check(Math.Abs(e.SessionSlotLength(r, 6) - 4.0) < 1e-9, $"open-ended take rounds to whole bars ({e.SessionSlotLength(r, 6)})");+ e.StopAllSession(); Run(0.1);+ e.SessionRecordLength = 8.0;+ Start();+ e.RecordSessionSlot(r, 7);+ Check(Math.Abs(e.SessionSlotLength(r, 7) - 8.0) < 1e-9, "fixed-length take is created at that length");+ Run(8.5);+ Check(!e.TryGetSessionRecordTarget(out _, out _, out _), "fixed-length take stops recording by itself");+ Check(e.SessionSlotState(r, 7) == 3, "fixed-length take keeps playing");+ e.SessionRecordLength = 0;+ e.StopAllSession(); Run(0.1); e.StopTransport();++ // Persistence: names, props, stop buttons and scenes survive save/load.+ var w = new System.Collections.Generic.List<string>();+ var doc = ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), w);+ string bundle = Path.Combine(Path.GetTempPath(), "nota-session-" + System.Guid.NewGuid().ToString("N") + ".nota");+ ProjectService.Save(doc, bundle, e);+ using var e2 = new NotaEngine();+ ProjectService.Apply(ProjectService.Load(bundle), e2, bundle);+ int t1b = -1, t2b = -1;+ for (int i = 0, nInst = 0; i < e2.TrackCount; i++)+ if (e2.TryGetTrackInfo(i, out var ti) && ti.IsInstrument) { if (nInst == 0) t1b = ti.Id; else if (nInst == 1) t2b = ti.Id; nInst++; }+ Check(t1b > 0 && e2.TryGetSessionClipProps(t1b, 0, out var lp) && lp.FollowA == (int)SessionFollowAction.Next && lp.Loop == 1,+ "clip props survive save/load");+ Check(t2b > 0 && !e2.GetSessionSlotStopButton(t2b, 3), "removed stop button survives save/load");+ Check(e2.TryGetSceneProps(2, out var lsp) && Math.Abs(lsp.Tempo - 140) < 1e-9, "scene props survive save/load");+}+// -- Session: copy an arrangement AUDIO clip into a slot --{using var e = new NotaEngine();@@ -12867,6 +13046,30 @@ Console.WriteLine("-- MCP tools --");Check(mcpSessNotes.Length == 2 && mcpSnap.SceneCount > 0 && Array.Exists(mcpSnap.FilledSlots, s => s.TrackId == mcpT && s.Scene == 0 && s.State == "filled"),$"MCP session fill + get_session ({mcpSnap.FilledSlots.Length} filled)");+ // Session P0 over MCP: clip properties, scenes, copy/move, stop buttons, follow switch.+ mcpSession.SetSessionClip(mcpT, 0, name: "Bassline", color: 6, launchMode: "toggle", quantBeats: 2, loop: false,+ followA: "next", chanceA: 70, followB: "again", chanceB: 30, followBeats: 8).Wait();+ mcpSession.SetScene(0, name: "Intro", color: 3, tempo: 124, signature: "3/4", followNextAfterBeats: 16).Wait();+ mcpSession.CopySessionSlot(mcpT, 0, mcpT, 2).Wait();+ mcpSession.CopySessionSlot(mcpT, 2, mcpT, 3, move: true).Wait();+ mcpSession.SetSessionSlotStopButton(mcpT, 5, false).Wait();+ int mcpIns = mcpSession.InsertScene(1).Result;+ mcpSession.SetSessionFollow(false).Wait();+ var mcpSesSnap = mcpSession.GetSession().Result;+ var mcpSesClip = Array.Find(mcpSesSnap.FilledSlots, x => x.TrackId == mcpT && x.Scene == 0);+ Check(mcpSesClip is { Name: "Bassline", Color: 6, LaunchMode: "toggle", Loop: false } && mcpSesClip.QuantBeats == 2+ && mcpSesClip.A.Action == "next" && mcpSesClip.A.Chance == 70 && mcpSesClip.B.Action == "again" && mcpSesClip.FollowBeats == 8,+ "MCP set_session_clip round-trips through get_session");+ Check(mcpSesSnap.Scenes[0] is { Name: "Intro", Color: 3, Tempo: 124, Signature: "3/4", FollowNextAfterBeats: 16 },+ "MCP set_scene round-trips through get_session");+ Check(mcpIns == 1 && !Array.Exists(mcpSesSnap.FilledSlots, x => x.TrackId == mcpT && x.Scene == 3)+ && Array.Exists(mcpSesSnap.FilledSlots, x => x.TrackId == mcpT && x.Scene == 4 && x.Name == "Bassline"),+ "MCP copy / move slot + insert_scene shift the grid");+ Check(Array.Exists(mcpSesSnap.NoStopButton, x => x.TrackId == mcpT && x.Scene == 6) && !mcpSesSnap.FollowActions,+ "MCP stop button + follow switch show in get_session");+ Check(mcpSession.MoveScene(4, 0).Result && mcpSession.DeleteScene(1).Result, "MCP move_scene + delete_scene");+ mcpSession.SetSessionFollow(true).Wait();+// Rack: build an Instrument Rack, add a chain, drive a macro + trigger note.int mcpRackT = mcpInstr.AddInstrumentTrack(3).Result; // 3 = Instrument Rackint mcpChain = mcpRack.AddRackChain(mcpRackT, 6).Result; // 6 = Volt chain