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
Redesign or Arp and Chord
Egor Khindikaynen9450336fefd6
diff --git a/.agents/skills/nota-instrument/SKILL.md b/.agents/skills/nota-instrument/SKILL.mdindex 31a1d340..6e4d45ff 100644--- a/.agents/skills/nota-instrument/SKILL.md+++ b/.agents/skills/nota-instrument/SKILL.md@@ -145,6 +145,22 @@ Follow the mockup language:Signal Path / Modulation) with a segmented toggle styled like the Devices/Clipsegment, swapping a `ContentControl`. One section = one horizontal row that fits260px tall.+- **Card sizes (S / L) are views of ONE device, never two devices.** When a mockup gives a+ device a mini (S, 260) and a full (L) size (Nota Arp is the reference):+ - **Presets belong to the device, not to the size.** Both sizes show the same preset+ picker with the **full** preset list and the **same current preset** — pick a preset in+ L, flip to S, it is still selected there (and vice versa). S may edit fewer params, but+ a preset still sets all of them. Never swap the picker for another control in S; the+ shell's `ShellSpec.Compact` only narrows it (and hides the type badge).+ - Every value is shared; S just exposes a subset (e.g. 4 knobs). No per-size params.+ - The size itself is **editor state**: store it in an appended param (`View`, 0 = L,+ 1 = S) so it persists with the project and clones, but keep it out of presets (in-place+ preset apply skips `View`), and out of the automation menu.+ - Plumbing (MIDI effects): `IMidiDeviceBody.WidthFor(engine, track, index)` returns 260/700+ from `View`; `HeaderAccessory(ctx, index)` puts the S/L toggle (and L-only extras) in the+ shell header; the toggle writes `View` and calls `ctx.RequestRebuild()`. Per-card UI+ state that should survive the rebuild (active tab, selected lane) lives in a static map+ keyed by (track, index), not in the singleton body.- **Lay panels as a signal chain**: bordered titled sections left→right with `▸`arrows (Osc → Noise → Filter → Amp). Each panel = `Border` (SurfaceCard fill,1px border, radius 7) with a bold section title.diff --git a/.claude/skills/nota-instrument/SKILL.md b/.claude/skills/nota-instrument/SKILL.mdindex 31a1d340..6e4d45ff 100644--- a/.claude/skills/nota-instrument/SKILL.md+++ b/.claude/skills/nota-instrument/SKILL.md@@ -145,6 +145,22 @@ Follow the mockup language:Signal Path / Modulation) with a segmented toggle styled like the Devices/Clipsegment, swapping a `ContentControl`. One section = one horizontal row that fits260px tall.+- **Card sizes (S / L) are views of ONE device, never two devices.** When a mockup gives a+ device a mini (S, 260) and a full (L) size (Nota Arp is the reference):+ - **Presets belong to the device, not to the size.** Both sizes show the same preset+ picker with the **full** preset list and the **same current preset** — pick a preset in+ L, flip to S, it is still selected there (and vice versa). S may edit fewer params, but+ a preset still sets all of them. Never swap the picker for another control in S; the+ shell's `ShellSpec.Compact` only narrows it (and hides the type badge).+ - Every value is shared; S just exposes a subset (e.g. 4 knobs). No per-size params.+ - The size itself is **editor state**: store it in an appended param (`View`, 0 = L,+ 1 = S) so it persists with the project and clones, but keep it out of presets (in-place+ preset apply skips `View`), and out of the automation menu.+ - Plumbing (MIDI effects): `IMidiDeviceBody.WidthFor(engine, track, index)` returns 260/700+ from `View`; `HeaderAccessory(ctx, index)` puts the S/L toggle (and L-only extras) in the+ shell header; the toggle writes `View` and calls `ctx.RequestRebuild()`. Per-card UI+ state that should survive the rebuild (active tab, selected lane) lives in a static map+ keyed by (track, index), not in the singleton body.- **Lay panels as a signal chain**: bordered titled sections left→right with `▸`arrows (Osc → Noise → Filter → Amp). Each panel = `Border` (SurfaceCard fill,1px border, radius 7) with a bold section title.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b98d4af4..2bfc6f27 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,40 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]+### Changed+- Nota Arp has a new look and two sizes: a full card and a small 260-pixel one. Switch+ between them with S / L in the card's header. Both sizes share the same presets, and the+ preset you pick stays selected when you switch size. The Pattern view shows the notes the arp+ will play, one step at a time, and the Groove view has the per-step lanes. As it plays, a+ marker moves across the steps.+- Nota Arp's note orders now use every octave you set. For example, Up · Down over two+ octaves goes up to the top note and back down. There are two new orders, Down · Up and+ Diverge. A ratchet now repeats that step's note.+- New in Nota Arp: Vel Amt sets how much the Velocity lane shapes the notes. Retrig has a+ new Beat mode that starts the pattern again on every bar. Restart starts it from step 1.+- Nota Arp has 30 presets. Switching presets now also resets the steps the new preset+ doesn't set.+- The automation menu lists all of Nota Arp's settings, and every step is under Groove.+ MCP gets new tools for the arp: `get_arp`, `set_arp`, `set_arp_lane`, `set_arp_step` and+ `restart_arp`.+- Nota Chord has a new look in the same two sizes as the arp, a full card and a small+ 260-pixel one. Each of the six shifts now has its own on/off switch, a ruler from −12 to+ +12 semitones with the interval's name, and a velocity offset you drag sideways. The+ keyboard shows three octaves and lights the chord as it's strummed: live while you hold a+ key, and once per bar as a preview while the transport runs.+- Nota Chord's Fold in scale can use any key, major or minor (it used the major scale of+ each played note). Spread now opens the chord in two steps: first every other shift goes+ up an octave, then all of them. Velocity offsets are in MIDI steps (−64…+63), and the+ default is Maj7 with a 30 ms strum. Projects and presets from older versions load with the+ same shifts switched on as before.+- Nota Chord has 34 presets. The automation menu lists its settings, and each shift's+ semitones, switch and velocity are under Shifts. MCP gets new tools for it: `get_chord`,+ `set_chord` and `set_chord_shift`.++### Fixed+- Nota Chord no longer leaves notes hanging when you change its shifts while a key is held,+ or when two held keys share a note.+## [0.41.5] — 2026-09-25### Highlightsdiff --git a/FEATURES.md b/FEATURES.mdindex 5781568d..7562ffcd 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -522,8 +522,13 @@ and user presets, automation, persistence and cloning.(Off/2×/4×/8×) to suppress aliasing under heavy drive.### MIDI effects-- **Nota Arp** — arpeggiator: step sequencer with Velocity/Length/Chance/Ratchet/Transpose- lanes, Order, Oct 1–4, Dir (↑↓↕?), Hold/Retrig, Free/Sync, Gate/Swing.+- **Nota Arp** — arpeggiator in two sizes (L 700 / S 260, S·L toggle; one preset list and+ current preset for both): 9 orders (Up, Down,+ Up·Down, Down·Up, Converge, Diverge, Random, Chord, As played) over 1–4 octaves; a live+ Pattern view of the notes each step plays and a Groove view of five per-step lanes+ (Velocity/Length/Chance/Ratchet/Transpose) plus step mute; Free/Sync (1/1…1/32), Gate,+ Swing, Vel Amt, Retrig Off/Note/Beat, Transpose, Steps 1–16, Hold, Restart. 30 presets,+ full automation, MCP tools (`get_arp` / `set_arp` / `set_arp_lane` / `set_arp_step` / `restart_arp`).- **Nota Scale** — snap to a scale: Root, Major/Minor/Dorian/Phryg/Penta/Custom, Fold(Nearest/Down/Up), NOTE MAP, Range, Follow Key, Learn/Clear.- **Nota Length** (formerly Note Length) — note lengths: Sync/ms/Gate %, Vel→Len, Key→Len,@@ -532,8 +537,12 @@ and user presets, automation, persistence and cloning.Range, Random Dir, and a Last 12 histogram.- **Nota Random** — randomization: Chance, Gauss/Even/Walk, Lock seed / Re-roll,Note/Velocity/Timing/Skip/Octave amounts, Distribution, Rate, Stay in scale.-- **Nota Chord** — chord generator: Maj7/Min7/Sus4/5th/Custom, 6 voices with offset and- velocity, Strum, Keep root, Fold in scale, Spread; a preview keyboard.+- **Nota Chord** — chord generator in two sizes (L 700 / S 260, S·L toggle; one preset list+ for both): TYPE Maj7/Min7/Sus4/5th/Custom, six switchable shifts (±12 st ruler + interval+ name + velocity offset), Strum 0–100 ms (low → high), Spread (every other / all shifts up an+ octave), Keep root, Fold in scale (any key, major / minor); a three-octave RESULT keyboard+ that lights a held chord as it strums (and previews the strum once per bar). 34 presets,+ full automation, MCP tools (`get_chord` / `set_chord` / `set_chord_shift`).### Racks- **Nota Instrument Rack** — 8 named macros (mapped with Linear/Exp/Log/S curves), chainsdiff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.csindex 38486b99..3f5a59b0 100644--- a/src/managed/Nota.App/ArrangementView.Automation.cs+++ b/src/managed/Nota.App/ArrangementView.Automation.cs@@ -441,12 +441,61 @@ public sealed partial class ArrangementViewint mpc = e.MidiEffectParamCount(t.Id, m);if (mpc <= 0) continue;var mMenu = new MenuItem { Header = e.MidiEffectName(t.Id, m) };- int shown = Math.Min(mpc, 16); // globals (+ a few lanes); per-step lanes are edited in the grid- for (int p = 0; p < shown; p++)+ MenuItem MLeaf(int mm, int pp, string? label = null) => Leaf(label ?? e.MidiEffectParamName(t.Id, mm, pp), $"M:{mm}:{pp}",+ () => SetAutoTarget(t, AutomationTarget.MidiDeviceParam, mm, pp), automated);+ if (e.MidiEffectKind(t.Id, m) == 0 && mpc > ArpGrid.PView){- int mm = m, pp = p;- mMenu.Items.Add(Leaf(e.MidiEffectParamName(t.Id, m, p), $"M:{mm}:{pp}",- () => SetAutoTarget(t, AutomationTarget.MidiDeviceParam, mm, pp), automated));+ // Nota Arp: its globals by name, then Groove ▸ lane ▸ step 1–16 (the View+ // size toggle is editor state, not a sound parameter).+ (int p, string label)[] globals =+ {+ (ArpGrid.GRate, "Rate"), (ArpGrid.GSync, "Sync"), (ArpGrid.GFreeRate, "Free Rate"), (ArpGrid.GOrder, "Order"),+ (ArpGrid.GGate, "Gate"), (ArpGrid.GSwing, "Swing"), (ArpGrid.PVelAmt, "Vel Amt"), (ArpGrid.GOctaves, "Octaves"),+ (ArpGrid.GOctaveMode, "Octave Mode"), (ArpGrid.GRetrig, "Retrig"), (ArpGrid.GHold, "Hold"),+ (ArpGrid.GTranspose, "Transpose"), (ArpGrid.GLoop, "Steps"), (ArpGrid.GLoopMode, "Loop Mode"),+ };+ foreach (var (p, label) in globals) mMenu.Items.Add(MLeaf(m, p, label));+ var groove = new MenuItem { Header = "Groove" };+ (string name, int b)[] lanes =+ {+ ("Velocity", ArpGrid.LVel), ("Length", ArpGrid.LLen), ("Chance", ArpGrid.LChance), ("Ratchet", ArpGrid.LRatchet),+ ("Transpose", ArpGrid.LTransp), ("Step On", ArpGrid.LOn), ("CC", ArpGrid.LCC),+ };+ foreach (var (name, b) in lanes)+ {+ var lm = new MenuItem { Header = name };+ for (int st = 0; st < ArpGrid.Steps; st++) lm.Items.Add(MLeaf(m, b + st, $"Step {st + 1}"));+ groove.Items.Add(lm);+ }+ mMenu.Items.Add(new Separator());+ mMenu.Items.Add(groove);+ }+ else if (e.MidiEffectKind(t.Id, m) == 1 && mpc > ChordMidiBody.PView)+ {+ // Nota Chord: the globals, then Shifts ▸ Shift N ▸ semitones / on / velocity+ // (View, the card size, is editor state).+ (int p, string label)[] globals =+ {+ (ChordMidiBody.Strum, "Strum"), (ChordMidiBody.Spread, "Spread"), (ChordMidiBody.KeepRoot, "Keep Root"),+ (ChordMidiBody.Fold, "Fold in Scale"), (ChordMidiBody.FoldKey, "Fold Key"), (ChordMidiBody.FoldMode, "Fold Mode"),+ };+ foreach (var (p, label) in globals) mMenu.Items.Add(MLeaf(m, p, label));+ var shifts = new MenuItem { Header = "Shifts" };+ for (int s = 0; s < ChordMidiBody.Slots; s++)+ {+ var sm = new MenuItem { Header = $"Shift {s + 1}" };+ sm.Items.Add(MLeaf(m, ChordMidiBody.Voice1 + s, "Semitones"));+ sm.Items.Add(MLeaf(m, ChordMidiBody.On1 + s, "On"));+ sm.Items.Add(MLeaf(m, ChordMidiBody.Vel1 + s, "Velocity"));+ shifts.Items.Add(sm);+ }+ mMenu.Items.Add(new Separator());+ mMenu.Items.Add(shifts);+ }+ else+ {+ int shown = Math.Min(mpc, 16); // globals (+ a few lanes); per-step lanes are edited in the grid+ for (int p = 0; p < shown; p++) mMenu.Items.Add(MLeaf(m, p));}flyout.Items.Add(mMenu);}diff --git a/src/managed/Nota.App/Controls/ArpGrid.cs b/src/managed/Nota.App/Controls/ArpGrid.csindex 14713613..a958d0c9 100644--- a/src/managed/Nota.App/Controls/ArpGrid.cs+++ b/src/managed/Nota.App/Controls/ArpGrid.cs@@ -1,14 +1,21 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Arp step sequencer (mockup 2k): 16 columns for the selected lane — bar height =-// value with fill opacity tracking it (velocity), bar-line shading every 4 steps, step-// numbers under each column (click to mute via the On lane), the playing step lit-// accent-bright, muted steps as empty wells, and ratchet counts «×2/×3» in teal above.-// Drag to draw; ⌥ ramps a line across the dragged steps. Steps beyond the loop dim.+// Nota Arp window (mockup 1a / 1b) — one custom-drawn well with two faces:+// • Pattern: rows = the chord over every octave (root rows striped, note names in a left+// gutter), one cell per step = the note that step plays. Cell width = Gate × Length,+// odd steps pushed right by Swing, a ratchet splits the cell, a muted step is an empty+// outline. Played steps are Brass Deep, the sounding one Brass Light, the rest Brass Edge.+// • Groove: the selected lane's per-step bars (Velocity / Length / Chance / Ratchet as+// stacked quarters / Transpose bipolar from the centre); drag across the well to draw+// (⌥ draws a ramp); the step-number strip under it mutes a step.+// A brass head band marks the sounding step; it moves with the engine's telemetry.+// ArpPattern mirrors Arpeggiator.h so the picture is exactly what will play.using System;+using System.Collections.Generic;using System.Globalization;+using System.Linq;using Avalonia;using Avalonia.Controls;using Avalonia.Input;@@ -17,110 +24,331 @@ using Nota.Application;namespace Nota.App;+/// <summary>A C# mirror of the Nota Arp note order (Arpeggiator.h buildSequence / emitStep).</summary>+internal static class ArpPattern+{+ public const int OrdUp = 0, OrdDown = 1, OrdUpDown = 2, OrdConverge = 3, OrdAsPlayed = 4, OrdChord = 5, OrdRandom = 6, OrdDownUp = 7, OrdDiverge = 8;+ public const int OctUp = 0, OctDown = 1, OctUpDown = 2, OctRandom = 3;+ public const int LoopFwd = 0, LoopBack = 1, LoopPing = 2, LoopRandom = 3;++ /// <summary>The walked note order: the chord expanded over the octaves, then ordered.</summary>+ public static List<int> Sequence(IReadOnlyList<int> held, int order, int octaves, int octMode)+ {+ var res = new List<int>();+ if (held.Count == 0) return res;+ var baseNotes = order == OrdAsPlayed ? held.ToList() : held.OrderBy(p => p).ToList();+ octaves = Math.Clamp(octaves, 1, 8);+ var oo = new List<int>();+ switch (octMode)+ {+ case OctDown: for (int o = octaves - 1; o >= 0; o--) oo.Add(o); break;+ case OctUpDown: for (int o = 0; o < octaves; o++) oo.Add(o); for (int o = octaves - 2; o >= 1; o--) oo.Add(o); break;+ case OctRandom: oo.Add(0); break;+ default: for (int o = 0; o < octaves; o++) oo.Add(o); break;+ }+ var a = new List<int>();+ foreach (int o in oo) foreach (int p in baseNotes) a.Add(p + 12 * o);+ int n = a.Count;+ switch (order)+ {+ case OrdDown: for (int i = n - 1; i >= 0; i--) res.Add(a[i]); break;+ case OrdUpDown: res.AddRange(a); for (int i = n - 2; i >= 1; i--) res.Add(a[i]); break;+ case OrdDownUp: for (int i = n - 1; i >= 0; i--) res.Add(a[i]); for (int i = 1; i <= n - 2; i++) res.Add(a[i]); break;+ case OrdConverge: case OrdDiverge:+ {+ var c = new List<int>(); int lo = 0, hi = n - 1;+ while (lo <= hi) { c.Add(a[lo]); if (lo != hi) c.Add(a[hi]); lo++; hi--; }+ if (order == OrdDiverge) c.Reverse();+ res.AddRange(c); break;+ }+ default: res.AddRange(a); break;+ }+ return res.Take(256).ToList();+ }++ /// <summary>The pitches pattern step <paramref name="kp"/> plays (all of them for Chord).</summary>+ public static IEnumerable<int> NotesAt(List<int> seq, int order, long kp, int octaves, int octMode)+ {+ if (seq.Count == 0) yield break;+ int oc = octMode == OctRandom ? 12 * (int)(Rnd01(kp, 5) * Math.Clamp(octaves, 1, 8)) : 0;+ if (order == OrdChord) { foreach (int p in seq) yield return p + oc; yield break; }+ long idx = order == OrdRandom ? (long)(Rnd01(kp, 7) * seq.Count) : kp % seq.Count;+ idx = ((idx % seq.Count) + seq.Count) % seq.Count;+ yield return seq[(int)idx] + oc;+ }++ private static uint Hash32(uint x) { x ^= x >> 16; x *= 0x7feb352du; x ^= x >> 15; x *= 0x846ca68bu; x ^= x >> 16; return x; }+ public static double Rnd01(long stepAbs, int salt)+ => (Hash32(unchecked((uint)(stepAbs * 2654435761u) + (uint)salt * 40503u)) & 0xffffff) / (double)0x1000000;+}+internal sealed class ArpGrid : Control{- private static readonly IBrush Bg = NotaPalette.BgSunken;- private static readonly IBrush Group = new SolidColorBrush(Color.FromArgb(0x30, 0x00, 0x00, 0x00));- private static readonly IBrush Play = NotaPalette.Wash(NotaPalette.AccentBright, 0x2A);- private static readonly IBrush Teal = NotaPalette.Teal;- private static readonly IBrush WellPen = NotaPalette.Wash(NotaPalette.BorderStrong, 0x60);- private static readonly IBrush Muted = NotaPalette.TextTertiary;- private static readonly IBrush Txt = NotaPalette.TextSecondary;- private static readonly IBrush AccentBright = NotaPalette.AccentBright;- private static readonly Typeface Face = NotaFonts.Mono;- private const int Vel = 13, Ratchet = 61, On = 93, Loop = 11, kSteps = 16, NumH = 15;+ // Param layout (mirrors Arpeggiator.h): 13 globals, 7 lanes × 16 steps, then VelAmt / View.+ internal const int GRate = 0, GSync = 1, GFreeRate = 2, GGate = 3, GOctaves = 4, GOctaveMode = 5,+ GOrder = 6, GSwing = 7, GHold = 8, GRetrig = 9, GTranspose = 10, GLoop = 11, GLoopMode = 12;+ internal const int LVel = 13, LLen = 29, LChance = 45, LRatchet = 61, LTransp = 77, LOn = 93, LCC = 109;+ internal const int PVelAmt = 125, PView = 126;+ internal const int Steps = 16;++ /// <summary>A Groove lane: its first param, the engine range, and the range the editor draws.</summary>+ internal sealed record Lane(string Label, int Base, double Min, double Max, Func<double, double> ToDisp, Func<double, double> FromDisp, Func<double, string> Fmt, bool Bipolar = false);++ internal static readonly Lane[] Lanes =+ {+ new("Velocity", LVel, 1, 127, v => Math.Round(v * 127), d => d / 127.0, d => $"{d:0}"),+ new("Length", LLen, 5, 100, v => Math.Round(v * 100), d => d / 100.0, d => $"{d:0} %"),+ new("Chance", LChance, 0, 100, v => Math.Round(v * 100), d => d / 100.0, d => $"{d:0} %"),+ new("Ratchet", LRatchet, 1, 4, v => Math.Round(v), d => d, d => $"×{d:0}"),+ new("Transpose", LTransp, -12, 12, v => Math.Round(v), d => d, d => d == 0 ? "0\u2009st" : $"{(d > 0 ? "+" : "−")}{Math.Abs(d):0} st", Bipolar: true),+ };++ private static readonly IBrush Stripe = NotaPalette.Panel;+ private static readonly IBrush ColMinor = NotaPalette.GridSubBeat;+ private static readonly IBrush ColMajor = NotaPalette.GraphBorder;+ private static readonly IBrush Head = NotaPalette.Wash(NotaPalette.Accent, 0x14);+ private static readonly IBrush Zero = NotaPalette.BorderDefault;+ private static readonly Typeface Mono = NotaFonts.Mono;+ private const double GutterW = 20, NumsH = 13;private readonly IAudioEngine _e; private readonly int _t, _mi;- private int _base = Vel; private double _min, _max = 1; private bool _vel = true, _int;- private int _playStep = -1, _dragStep = -1; private double _dragNorm;+ private readonly float[] _scope = new float[40];+ private bool _groove;+ private int _lane;+ private int _dragStep = -1; private double _dragDisp;+ private int _pos = -1; private long _k = -1; private int _heldLive;+ private List<int> _chord = new();++ /// <summary>Mini (S) face: no key gutter and no step-number strip; the lowest note sits in the well.</summary>+ public bool Mini { get; init; }+ /// <summary>Last Groove edit (step, display value) for the header readout; cleared on lane/tab change.</summary>+ public (int Step, double Value)? LastEdit { get; private set; }+ public event Action? Edited;++ public ArpGrid(IAudioEngine e, int t, int mi) { _e = e; _t = t; _mi = mi; MinHeight = 60; ClipToBounds = true; Poll(); }++ public bool Groove { get => _groove; set { if (_groove == value) return; _groove = value; LastEdit = null; Cursor = value ? new Cursor(StandardCursorType.Cross) : Cursor.Default; InvalidateVisual(); } }+ public int LaneIndex { get => _lane; set { value = Math.Clamp(value, 0, Lanes.Length - 1); if (_lane == value) return; _lane = value; LastEdit = null; InvalidateVisual(); } }++ /// <summary>Loop position of the sounding step (-1 = idle).</summary>+ public int Position => _pos;+ /// <summary>The chord the Pattern shows (held, or the last one played; empty = none yet).</summary>+ public IReadOnlyList<int> Chord => _chord;+ /// <summary>True while notes are held (or latched by Hold) and the arp runs.</summary>+ public bool Running => _heldLive > 0;+ /// <summary>The preview chord drawn before anything has been played.</summary>+ internal static readonly int[] PreviewChord = { 48, 52, 55, 59 };++ private double G(int p) => _e.MidiEffectGetParam(_t, _mi, p);+ private int GI(int p) => (int)Math.Round(G(p));+ public int StepCount => Math.Clamp(GI(GLoop), 1, Steps);++ /// <summary>Re-read the engine telemetry (60 Hz) and repaint.</summary>+ public void Poll()+ {+ int n = _e.MidiEffectScope(_t, _mi, _scope);+ if (n >= 4)+ {+ _pos = (int)_scope[0]; _k = (long)_scope[1]; _heldLive = (int)_scope[2];+ int cn = Math.Min((int)_scope[3], n - 4);+ if (cn != _chord.Count || Enumerable.Range(0, cn).Any(i => (int)_scope[4 + i] != _chord[i]))+ _chord = Enumerable.Range(0, cn).Select(i => (int)_scope[4 + i]).ToList();+ }+ InvalidateVisual();+ }- public ArpGrid(IAudioEngine e, int t, int mi) { _e = e; _t = t; _mi = mi; MinHeight = 90; }- public void SetLane(int b, double min, double max, bool vel, bool isInt) { _base = b; _min = min; _max = max; _vel = vel; _int = isInt; InvalidateVisual(); }- public void SetPlayhead(int s) { if (s != _playStep) { _playStep = s; InvalidateVisual(); } }+ public IReadOnlyList<int> ShownChord => _chord.Count > 0 ? _chord : PreviewChord;+ public List<int> CurrentSequence() => ArpPattern.Sequence(ShownChord, GI(GOrder), GI(GOctaves), GI(GOctaveMode));- private double Get(int p) => _e.MidiEffectGetParam(_t, _mi, p);- private int LoopLen() => Math.Clamp((int)Math.Round(Get(Loop)), 1, kSteps);- private int StepAt(double x) => Math.Clamp((int)(x / Bounds.Width * kSteps), 0, kSteps - 1);- private double BarH() => Math.Max(1, Bounds.Height - NumH);+ // ---- geometry ---------------------------------------------------------------+ private Rect Well()+ {+ double gx = !Groove && !Mini ? GutterW + 4 : 0;+ double nb = Groove && !Mini ? NumsH + 2 : 0;+ return new Rect(gx, 0, Math.Max(1, Bounds.Width - gx), Math.Max(1, Bounds.Height - nb));+ }+ // ---- input (Groove) -------------------------------------------------------------protected override void OnPointerPressed(PointerPressedEventArgs e){- var p = e.GetPosition(this);- if (p.Y >= Bounds.Height - NumH) { int s = StepAt(p.X); _e.MidiEffectSetParam(_t, _mi, On + s, Get(On + s) > 0.5 ? 0f : 1f); InvalidateVisual(); e.Pointer.Capture(this); e.Handled = true; _dragStep = -1; return; }- _dragStep = StepAt(p.X); _dragNorm = NormAt(p.Y); Apply(_dragStep, _dragNorm);+ if (!Groove || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ var p = e.GetPosition(this); var w = Well();+ int n = StepCount;+ if (!Mini && p.Y > w.Bottom)+ {+ int s = Math.Clamp((int)((p.X - w.X) / w.Width * n), 0, n - 1);+ _e.MidiEffectSetParam(_t, _mi, LOn + s, G(LOn + s) > 0.5 ? 0f : 1f);+ e.Handled = true; InvalidateVisual(); Edited?.Invoke(); return;+ }+ _dragStep = StepAt(p.X); _dragDisp = DispAt(p.Y);+ Apply(_dragStep, _dragDisp);e.Pointer.Capture(this); e.Handled = true;}protected override void OnPointerMoved(PointerEventArgs e){if (_dragStep < 0) return;- var p = e.GetPosition(this); int s = StepAt(p.X); double n = NormAt(p.Y);+ var p = e.GetPosition(this); int s = StepAt(p.X); double d = DispAt(p.Y);if (e.KeyModifiers.HasFlag(KeyModifiers.Alt) && s != _dragStep){- int a = _dragStep, b = s; double na = _dragNorm, nb = n;- int lo = Math.Min(a, b), hi = Math.Max(a, b);- for (int i = lo; i <= hi; i++) { double t = a == b ? 0 : (double)(i - a) / (b - a); Apply(i, na + (nb - na) * t); }+ int lo = Math.Min(_dragStep, s), hi = Math.Max(_dragStep, s);+ for (int i = lo; i <= hi; i++) Apply(i, _dragDisp + (d - _dragDisp) * (i - _dragStep) / (double)(s - _dragStep));}- else Apply(s, n);+ else Apply(s, d);}- protected override void OnPointerReleased(PointerReleasedEventArgs e) { _dragStep = -1; e.Pointer.Capture(null); }+ protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_dragStep >= 0) { _dragStep = -1; e.Pointer.Capture(null); } }- private double NormAt(double y) => Math.Clamp(1 - y / BarH(), 0, 1);- private void Apply(int s, double norm)+ private int StepAt(double x) { var w = Well(); int n = StepCount; return Math.Clamp((int)((x - w.X) / w.Width * n), 0, n - 1); }+ private double DispAt(double y){- double v = _min + norm * (_max - _min); if (_int) v = Math.Round(v);- _e.MidiEffectSetParam(_t, _mi, _base + s, (float)Math.Clamp(v, _min, _max));- InvalidateVisual();+ var w = Well(); var l = Lanes[_lane];+ double f = Math.Clamp(1 - (y - w.Y) / w.Height, 0, 1);+ return Math.Round(l.Min + f * (l.Max - l.Min));+ }+ private void Apply(int s, double disp)+ {+ var l = Lanes[_lane];+ disp = Math.Clamp(Math.Round(disp), l.Min, l.Max);+ _e.MidiEffectSetParam(_t, _mi, l.Base + s, (float)l.FromDisp(disp));+ LastEdit = (s, disp);+ InvalidateVisual(); Edited?.Invoke();+ }++ // ---- render ---------------------------------------------------------------------+ private static void Text(DrawingContext ctx, string t, double x, double y, IBrush b, double size = 7, bool right = false, bool centre = false)+ {+ var ft = new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, size, b);+ double px = right ? x - ft.Width : centre ? x - ft.Width / 2 : x;+ ctx.DrawText(ft, new Point(px, y - ft.Height / 2));}- private void DrawText(DrawingContext ctx, string t, double cx, double y, IBrush b, double size = 8)- { var ft = new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, size, b); ctx.DrawText(ft, new Point(cx - ft.Width / 2, y)); }+ private IBrush Tone(int c, bool muted, IBrush future)+ => muted ? NotaPalette.TrackOff : c == _pos ? NotaPalette.AccentBright : _pos >= 0 && c < _pos ? NotaPalette.AccentDeep : future;public override void Render(DrawingContext ctx){- double w = Bounds.Width, h = Bounds.Height; if (w <= 0 || h <= 0) return;- NotaGraph.Window(ctx, new Rect(0, 0, w, h));- double cw = w / kSteps, barH = BarH(), numY = h - NumH + 2;- int loop = LoopLen();- double zero = _min < 0 ? barH * (_max / (_max - _min)) : barH; // baseline for signed lanes+ if (Bounds.Width <= 2 || Bounds.Height <= 2) return;+ var w = Well();+ int n = StepCount; double cw = w.Width / n;+ var seq = CurrentSequence();+ var chord = ShownChord;+ int octs = Math.Clamp(GI(GOctaves), 1, 8);+ int rootPc = ((chord.Count > 0 ? chord.Min() : 48) % 12 + 12) % 12;+ // Rows: every pitch the order can reach, high → low.+ var rows = ArpPattern.Sequence(chord, ArpPattern.OrdUp, octs, ArpPattern.OctUp).Distinct().OrderByDescending(p => p).ToList();+ if (rows.Count == 0) rows.Add(60);+ double rh = w.Height / rows.Count;- for (int s = 0; s < kSteps; s++)+ // Well.+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.GraphBorder, 1), w.Deflate(0.5), 4, 4);+ using (ctx.PushClip(new RoundedRect(w.Deflate(1), 3))){- double x = s * cw;- if ((s / 4) % 2 == 1) ctx.FillRectangle(Group, new Rect(x, 0, cw, barH));- if (s == _playStep) ctx.FillRectangle(Play, new Rect(x, 0, cw, h));- bool active = s < loop;- bool muted = Get(On + s) < 0.5;- var cell = new Rect(x + 2, 2, cw - 4, barH - 4);-- if (muted)+ if (!Groove)+ for (int r = 0; r < rows.Count; r++)+ if (((rows[r] % 12) + 12) % 12 == rootPc) ctx.FillRectangle(Stripe, new Rect(w.X, w.Y + r * rh, w.Width, rh));+ for (int c = 1; c < n; c++)+ ctx.FillRectangle(c % 4 == 0 ? ColMajor : ColMinor, new Rect(w.X + Math.Round(c * cw), w.Y, 1, w.Height));+ var lane = Lanes[_lane];+ if (Groove && lane.Bipolar) ctx.FillRectangle(Zero, new Rect(w.X, w.Y + Math.Round(w.Height / 2), w.Width, 1));++ // Head band on the sounding step.+ if (_pos >= 0 && _pos < n){- ctx.DrawRectangle(null, new Pen(WellPen, 1), cell, 2, 2);+ var hr = new Rect(w.X + _pos * cw, w.Y, cw, w.Height);+ ctx.FillRectangle(Head, hr);+ ctx.FillRectangle(NotaPalette.BorderBrass, new Rect(hr.X, hr.Y, 1, hr.Height));}- else++ if (!Groove) DrawPattern(ctx, w, n, cw, seq, rows, rh, octs);+ else DrawGroove(ctx, w, n, cw, lane);+ }++ // Key gutter (L Pattern): note names, root rows brighter; all names while it stays legible.+ if (!Groove && !Mini)+ for (int r = 0; r < rows.Count; r++){- double v = Get(_base + s), norm = (v - _min) / (_max - _min);- byte a = (byte)(active ? (_vel ? 70 + norm * 175 : 210) : 70);- var ac = NotaPalette.Accent.Color; // the live accent, so the light variant gets bronze- var brush = new SolidColorBrush(Color.FromArgb(a, ac.R, ac.G, ac.B));- if (_min < 0)- {- double top = barH - norm * barH, y0 = Math.Min(top, zero), y1 = Math.Max(top, zero);- ctx.FillRectangle(brush, new Rect(x + 2, y0, cw - 4, Math.Max(1, y1 - y0)));- }- else+ bool root = ((rows[r] % 12) + 12) % 12 == rootPc;+ if (rows.Count > 8 && !root) continue;+ Text(ctx, DeviceCardKit.NoteName(rows[r]), GutterW, w.Y + (r + 0.5) * rh, root ? NotaPalette.TextMuted : NotaPalette.TextDisabled, 7, right: true);+ }+ if (!Groove && Mini && rows.Count > 0)+ Text(ctx, DeviceCardKit.NoteName(rows[^1]), w.X + 4, w.Bottom - 7, NotaPalette.TextAxis, 7);++ // Step numbers (L Groove): click mutes.+ if (Groove && !Mini)+ {+ double y = w.Bottom + 2 + NumsH / 2;+ for (int c = 0; c < n; c++)+ {+ bool muted = G(LOn + c) < 0.5;+ var ink = muted ? NotaPalette.TextAxis : c == _pos ? NotaPalette.AccentBright : NotaPalette.TextMuted;+ double cx = w.X + (c + 0.5) * cw;+ Text(ctx, (c + 1).ToString(), cx, y, ink, 7, centre: true);+ if (muted) ctx.FillRectangle(ink, new Rect(cx - 4, y, 8, 1));+ }+ }+ }++ private void DrawPattern(DrawingContext ctx, Rect w, int n, double cw, List<int> seq, List<int> rows, double rh, int octs)+ {+ if (seq.Count == 0) return;+ int order = GI(GOrder), octMode = GI(GOctaveMode);+ double gate = Math.Clamp(G(GGate), 0, 2), swing = Math.Clamp(G(GSwing), 0, 1);+ long page = _k >= 0 ? (_k / n) * n : 0;+ var rowOf = new Dictionary<int, int>();+ for (int i = 0; i < rows.Count; i++) rowOf[rows[i]] = i;+ for (int c = 0; c < n; c++)+ {+ bool muted = G(LOn + c) < 0.5;+ double len = Math.Clamp(G(LLen + c), 0.05, 2);+ int rat = Math.Clamp(GI(LRatchet + c), 1, 8);+ double wFrac = Math.Clamp(gate * len, 0.12, 1.0);+ double off = c % 2 == 1 ? swing * 0.5 * cw : 0;+ double cellW = wFrac * cw;+ IBrush fill = muted ? Brushes.Transparent : c == _pos ? NotaPalette.AccentBright : _pos >= 0 && c < _pos ? NotaPalette.AccentDeep : NotaPalette.AccentEdge;+ IBrush border = muted ? NotaPalette.BorderStrong : fill;+ foreach (int p in ArpPattern.NotesAt(seq, order, page + c, octs, octMode))+ {+ if (!rowOf.TryGetValue(p, out int r)) continue; // a random octave above the drawn range+ for (int k = 0; k < rat; k++){- double bh = norm * (barH - 4);- ctx.FillRectangle(brush, new Rect(x + 2, barH - bh - 2, cw - 4, Math.Max(1, bh)));+ double x = w.X + c * cw + off + k * cellW / rat + 1;+ var rc = new Rect(x, w.Y + r * rh + 1, Math.Max(1, cellW / rat - 2), Math.Max(1, rh - 2));+ if (muted) ctx.DrawRectangle(null, new Pen(border, 1), rc.Deflate(0.5), 2, 2);+ else ctx.DrawRectangle(fill, null, rc, 2, 2);}- // Ratchet marker above the bar.- int r = (int)Math.Round(Get(Ratchet + s));- if (r >= 2) DrawText(ctx, "×" + r, x + cw / 2, 1, active ? Teal : Muted, 8);}+ }+ }- // Step number strip (click to mute).- var numBrush = s == _playStep ? AccentBright : muted ? NotaPalette.Wash(NotaPalette.TextTertiary, 0x66) : Txt;- DrawText(ctx, (s + 1).ToString(), x + cw / 2, numY, numBrush, 8);+ private void DrawGroove(DrawingContext ctx, Rect w, int n, double cw, Lane lane)+ {+ for (int c = 0; c < n; c++)+ {+ bool muted = G(LOn + c) < 0.5;+ double d = Math.Clamp(lane.ToDisp(G(lane.Base + c)), lane.Min, lane.Max);+ double f = (d - lane.Min) / (lane.Max - lane.Min);+ var fill = Tone(c, muted, NotaPalette.AccentDim);+ double x = w.X + c * cw + 2, bw = Math.Max(1, cw - 4);+ if (lane.Base == LRatchet)+ {+ double q = w.Height / 4;+ for (int k = 0; k < (int)d; k++) ctx.DrawRectangle(fill, null, new Rect(x, w.Bottom - (k + 1) * q + 2, bw, Math.Max(1, q - 3)), 1, 1);+ }+ else if (lane.Bipolar)+ {+ double h = Math.Abs(f - 0.5) * w.Height, mid = w.Y + w.Height / 2;+ ctx.DrawRectangle(fill, null, new Rect(x, f >= 0.5 ? mid - h : mid, bw, Math.Max(h, 1)), 1, 1);+ }+ else+ {+ double h = Math.Max(f, 0.02) * w.Height;+ ctx.DrawRectangle(fill, null, new Rect(x, w.Bottom - h, bw, h), 1, 1);+ }+ }+ if (!Mini)+ {+ Text(ctx, lane.Fmt(lane.Max), w.Right - 5, w.Y + 7, NotaPalette.TextAxis, 7, right: true);+ Text(ctx, lane.Fmt(lane.Min), w.Right - 5, w.Bottom - 7, NotaPalette.TextAxis, 7, right: true);}- if (_min < 0) ctx.DrawLine(new Pen(WellPen, 1), new Point(0, zero), new Point(w, zero));}}diff --git a/src/managed/Nota.App/Controls/ChordKeysViz.cs b/src/managed/Nota.App/Controls/ChordKeysViz.csindex afc9893f..95cc898b 100644--- a/src/managed/Nota.App/Controls/ChordKeysViz.cs+++ b/src/managed/Nota.App/Controls/ChordKeysViz.cs@@ -1,11 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Chord result keyboard (mockup 3b): a two-octave stylised keyboard, one bar per-// semitone (white keys tall, black keys short), lighting the played root bright and each-// added chord note amber — a live preview of what the current voicing does to one key.+// Nota Chord RESULT keyboard (almanac mockups 1a / 1b): three octaves from the C at or below+// the chord's lowest note — 21 white keys with the black keys over them. A sounding note is+// lit: the played key Brass Light, an added note Brass Deep. With Keep root off the root is+// only outlined in brass. The owner drives the strum animation by passing the notes lit so+// far each tick; Set() repaints only when something changed.using System;+using System.Collections.Generic;using Avalonia;using Avalonia.Controls;using Avalonia.Media;@@ -15,44 +18,88 @@ namespace Nota.App;internal sealed class ChordKeysViz : Control{private static readonly IBrush Well = NotaPalette.BgSunken;- private static readonly IBrush WhiteKey = NotaPalette.SurfaceRaised;- private static readonly IBrush BlackKey = NotaPalette.SurfaceInset;- private static readonly IBrush Line = NotaPalette.BorderDefault;- private static readonly IBrush Added = NotaPalette.Accent;+ private static readonly IBrush WellEdge = NotaPalette.GraphBorder;+ private static readonly IBrush WhiteKey = NotaPalette.MiniKeyWhite;+ private static readonly IBrush BlackKey = NotaPalette.KeyBlack;+ internal static readonly IBrush Added = NotaPalette.Wash(NotaPalette.Accent, 0xC8); // Brass Deep in Graphite (≈ #B8862E), clearly lighter than Played in Paperprivate static readonly IBrush Played = NotaPalette.AccentBright;+ private static readonly IBrush Label = NotaPalette.TextAxis;+ private static readonly IPen RootRing = new Pen(NotaPalette.Accent, 1);- private int _root = 60, _low = 60;- private const int Span = 25; // two octaves + 1- private bool[] _added = new bool[Span];+ private static readonly int[] WhiteIndex = { 0, -1, 1, -1, 2, 3, -1, 4, -1, 5, -1, 6 }; // pc → white slot+ private static readonly int[] BlackPos = { 0, 1, 0, 2, 0, 0, 4, 0, 5, 0, 6, 0 }; // pc → boundary it sits on- public ChordKeysViz() { MinHeight = 34; }+ private int _start = 48, _ring = -1;+ private readonly Dictionary<int, bool> _lit = new(); // pitch → played (true) / added (false)+ private string _sig = "";- public void Set(int root, System.Collections.Generic.IEnumerable<int> added)+ /// <summary>Draw the C labels under each octave (the large card; the mini one has no room).</summary>+ public bool Labels { get; init; } = true;++ /// <summary>Corner radius of the key bottoms (L 2, S square).</summary>+ public double KeyRadius { get; init; } = NotaRadius.ClipValue;++ public ChordKeysViz() { MinHeight = 24; ClipToBounds = true; }++ /// <summary>The first C shown (three octaves from it), the lit notes, and the root to outline+ /// when it is not played (-1 = none).</summary>+ public void Set(int start, IEnumerable<(int Pitch, bool Played)> lit, int ringPitch){- _root = root;- _low = root - ((root % 12) + 12) % 12; // octave floor at/below root- _added = new bool[Span];- foreach (var p in added) { int s = p - _low; if (s >= 0 && s < Span) _added[s] = true; }+ var sb = new System.Text.StringBuilder();+ sb.Append(start).Append('|').Append(ringPitch).Append('|');+ _lit.Clear();+ foreach (var (p, pl) in lit) { _lit[p] = pl; sb.Append(p).Append(pl ? 'p' : 'a').Append(','); }+ string sig = sb.ToString();+ _start = start; _ring = ringPitch;+ if (sig == _sig) return;+ _sig = sig;InvalidateVisual();}- private static bool IsBlack(int pc) => pc == 1 || pc == 3 || pc == 6 || pc == 8 || pc == 10;-public override void Render(DrawingContext ctx){double w = Bounds.Width, h = Bounds.Height;if (w <= 0 || h <= 0) return;- NotaGraph.Window(ctx, new Rect(0, 0, w, h));- double bw = w / Span;- for (int s = 0; s < Span; s++)+ var frame = new Rect(0, 0, w, h);+ ctx.DrawRectangle(Well, null, frame, NotaRadius.BadgeValue, NotaRadius.BadgeValue);+ var inner = frame.Deflate(1);+ double ww = inner.Width / 21.0;+ var clip = ctx.PushClip(inner);++ IBrush Fill(int p, bool white) => _lit.TryGetValue(p, out bool pl) ? (pl ? Played : Added) : white ? WhiteKey : BlackKey;+ // Only the bottom corners round: the key starts above the clip by its radius.+ void Key(Rect rc, IBrush fill, int p){- int pitch = _low + s, pc = ((pitch % 12) + 12) % 12;- bool black = IsBlack(pc);- double bh = black ? h * 0.62 : h; // black keys shorter- var rect = new Rect(s * bw, h - bh, Math.Max(1, bw - 0.6), bh);- IBrush fill = pitch == _root ? Played : _added[s] ? Added : black ? BlackKey : WhiteKey;- ctx.DrawRectangle(fill, null, rect, 1, 1);- ctx.DrawLine(new Pen(Line, 0.5), new Point(s * bw, h - bh), new Point(s * bw, h));+ var k = new Rect(rc.X, rc.Y - KeyRadius, rc.Width, rc.Height + KeyRadius);+ ctx.DrawRectangle(fill, null, k, KeyRadius, KeyRadius);+ if (p == _ring) ctx.DrawRectangle(null, RootRing, k.Deflate(0.5), KeyRadius, KeyRadius);}++ for (int o = 0; o < 3; o++)+ for (int pc = 0; pc < 12; pc++)+ {+ if (WhiteIndex[pc] < 0) continue;+ int p = _start + o * 12 + pc;+ double x = inner.X + (o * 7 + WhiteIndex[pc]) * ww;+ Key(new Rect(x, inner.Y, Math.Max(1, ww - 1), inner.Height), Fill(p, true), p); // 1px well gap = the key divider+ }+ for (int o = 0; o < 3; o++)+ for (int pc = 0; pc < 12; pc++)+ {+ if (WhiteIndex[pc] >= 0) continue;+ int p = _start + o * 12 + pc;+ double cx = inner.X + (o * 7 + BlackPos[pc]) * ww;+ Key(new Rect(cx - ww * 0.3, inner.Y, ww * 0.6, inner.Height * 0.58), Fill(p, false), p);+ }+ if (Labels)+ for (int o = 0; o < 3; o++)+ {+ var ft = new FormattedText(DeviceCardKit.NoteName(_start + o * 12), System.Globalization.CultureInfo.InvariantCulture,+ FlowDirection.LeftToRight, new Typeface(NotaFonts.MonoFamily), 6, Label);+ double x = inner.X + o * 7 * ww + (ww - ft.Width) / 2;+ ctx.DrawText(ft, new Point(x, inner.Bottom - ft.Height - 1));+ }+ clip.Dispose();+ ctx.DrawRectangle(null, new Pen(WellEdge, 1), frame.Deflate(0.5), NotaRadius.BadgeValue, NotaRadius.BadgeValue);}}diff --git a/src/managed/Nota.App/Controls/ChordShiftTrack.cs b/src/managed/Nota.App/Controls/ChordShiftTrack.csnew file mode 100644index 00000000..df951da6--- /dev/null+++ b/src/managed/Nota.App/Controls/ChordShiftTrack.cs@@ -0,0 +1,121 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A Nota Chord shift (almanac mockups 1a / 1b): a bipolar −12..+12 semitone track centred+// on zero. Horizontal (L): a 3px well groove with a centre tick, a brass fill from the+// centre and a 6×9 handle. Vertical (S): a framed well with a centre rule and a bar+// growing up (positive) or down (negative). Unlike the generic SliderTrack the value is+// positional — press or drag anywhere sets the semitone under the pointer — because the+// track is a pitch ruler. A switched-off slot draws its fill in Border strong.+// GestureBegin / GestureEnd bracket the drag for automation writes; double-click resets+// to 0; right-click bubbles to MIDI Learn.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;++namespace Nota.App;++internal sealed class ChordShiftTrack : Control+{+ private static readonly IBrush Groove = NotaPalette.BgSunken;+ private static readonly IBrush Frame = NotaPalette.GraphBorder;+ private static readonly IBrush Fill = NotaPalette.Accent;+ private static readonly IBrush FillOff = NotaPalette.BorderStrong;+ private static readonly IBrush Handle = NotaPalette.TextSecondary;+ private static readonly IBrush Centre = NotaPalette.BorderStrong;+ private static readonly IBrush CentreV = NotaPalette.BorderDefault;++ public const int Range = 12;++ private int _value;+ private bool _on = true, _drag;++ public bool Vertical { get; init; }+ public bool Dragging => _drag;++ public int Value { get => _value; set { var v = Math.Clamp(value, -Range, Range); if (v == _value) return; _value = v; InvalidateVisual(); } }+ public bool On { get => _on; set { if (_on == value) return; _on = value; InvalidateVisual(); } }++ public event Action<int>? Changed;+ public event Action? GestureBegin;+ public event Action? GestureEnd;++ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)+ {+ base.OnAttachedToVisualTree(e);+ Cursor = new Cursor(Vertical ? StandardCursorType.SizeNorthSouth : StandardCursorType.SizeWestEast);+ }++ private int At(Point p)+ {+ double f = Vertical ? 1 - p.Y / Math.Max(1, Bounds.Height) : p.X / Math.Max(1, Bounds.Width);+ return (int)Math.Round(Math.Clamp(f, 0, 1) * 2 * Range - Range);+ }++ private void Set(Point p)+ {+ int v = At(p);+ if (v == _value && _on) return;+ _value = v; InvalidateVisual();+ Changed?.Invoke(v);+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ if (e.ClickCount == 2) { _value = 0; InvalidateVisual(); GestureBegin?.Invoke(); Changed?.Invoke(0); GestureEnd?.Invoke(); return; }+ _drag = true;+ e.Pointer.Capture(this);+ GestureBegin?.Invoke();+ Set(e.GetPosition(this));+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ if (_drag) Set(e.GetPosition(this));+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ if (!_drag) return;+ _drag = false;+ e.Pointer.Capture(null);+ GestureEnd?.Invoke();+ }++ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ if (_drag) { _drag = false; GestureEnd?.Invoke(); }+ base.OnPointerCaptureLost(e);+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ ctx.DrawRectangle(Brushes.Transparent, null, new Rect(0, 0, w, h)); // hit area+ double f = (_value + Range) / (2.0 * Range);+ var fill = _on ? Fill : FillOff;+ if (Vertical)+ {+ ctx.DrawRectangle(Groove, new Pen(Frame, 1), new Rect(0.5, 0.5, w - 1, h - 1), 3, 3);+ double mid = Math.Round(h / 2);+ ctx.DrawRectangle(CentreV, null, new Rect(1, mid - 0.5, w - 2, 1));+ double bh = Math.Max(Math.Abs(f - 0.5) * (h - 2), 1);+ double top = f >= 0.5 ? mid - bh : mid;+ ctx.DrawRectangle(fill, null, new Rect(3, top, Math.Max(1, w - 6), bh), 1, 1);+ }+ else+ {+ double cy = Math.Round(h / 2), x = f * w, c = w / 2;+ ctx.DrawRectangle(Groove, null, new Rect(0, cy - 1.5, w, 3), 2, 2);+ ctx.DrawRectangle(Centre, null, new Rect(Math.Round(c) - 0.5, cy - 4.5, 1, 9));+ ctx.DrawRectangle(fill, null, new Rect(Math.Min(c, x), cy - 1.5, Math.Abs(x - c), 3), 2, 2);+ ctx.DrawRectangle(Handle, null, new Rect(Math.Clamp(x - 3, 0, w - 6), cy - 4.5, 6, 9), 2, 2);+ }+ }+}diff --git a/src/managed/Nota.App/DeviceCardKit.cs b/src/managed/Nota.App/DeviceCardKit.csindex f195076a..32ce8057 100644--- a/src/managed/Nota.App/DeviceCardKit.cs+++ b/src/managed/Nota.App/DeviceCardKit.cs@@ -327,7 +327,7 @@ internal static class DeviceCardKit// Clicks are handled so they neither select nor start dragging the card. Shared by the// card shell and the rack chain full-UI popups.internal static Control PresetPicker(IReadOnlyList<string> presets, int cur, string current,- Action<int> apply, Action<int> step)+ Action<int> apply, Action<int> step, double nameWidth = 132){const double H = 18;var label = new TextBlock@@ -339,7 +339,7 @@ internal static class DeviceCardKitDockPanel.SetDock(chevron, Dock.Right);var name = new Border{- Width = 132, Padding = new Thickness(7, 0, 6, 0), Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Width = nameWidth, Padding = new Thickness(7, 0, 6, 0), Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),Child = new DockPanel { Children = { chevron, label } },};ToolTip.SetTip(name, "Choose a preset");diff --git a/src/managed/Nota.App/DeviceCards/Midi/ArpMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/ArpMidiBody.csindex 93f36800..c2199657 100644--- a/src/managed/Nota.App/DeviceCards/Midi/ArpMidiBody.cs+++ b/src/managed/Nota.App/DeviceCards/Midi/ArpMidiBody.cs@@ -1,201 +1,500 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the Nota Arp editor (MIDI effect kind 0), rebuilt to mockup 2k-// (700×260 on the shared shell): a LIVE strip (Sync/Free · rate divisions · Gate · Swing-// · Hold/Retrig) over a body of lane-rail (78: Velocity/Length/Chance/Ratchet/Transpose-// as the tab rail + step count) | the step sequencer (velocities, playhead, ratchets,-// muted wells) | a right rail (120: Order · Octaves · Direction · Transpose · CC→lane).-// Toggles are outlined; brass fill encodes only a value or the active choice.+// Detail · Devices — the Nota Arp editor (MIDI effect kind 0), almanac mockups 1a / 1b.+// Two sizes share every value; the S / L toggle in the shell header flips the card (the+// choice is the device's "View" param, so it persists with the project):+// • L 700 × 260 — ORDER list | Pattern / Groove window over the Free·Sync + division+// strip | PLAY (Gate · Swing · Vel Amt sliders, Octaves, Retrig, Transpose, Steps,+// Hold, Restart) — over a status line (held chord · order · rate · steps · retrig).+// • S 260 × 260 — the window with a Pattern / Groove toggle (the lane picked by clicking+// its name) over four knobs (Rate · Gate · Oct · Swing). The header keeps the full preset+// picker (same list, same current preset as L); what S can't edit, presets still set.+// The window (ArpGrid) animates from the engine's telemetry: the head band walks the+// steps, played cells turn Brass Deep and the sounding one Brass Light.using System;+using System.Collections.Generic;+using System.Linq;using Avalonia;using Avalonia.Controls;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;using Nota.Application;-using static Nota.App.DeviceCardKit;+using static Nota.App.ArpGrid;namespace Nota.App;internal sealed class ArpMidiBody : IMidiDeviceBody{- // Param layout (mirrors Arpeggiator.h): 13 globals then 7 lanes × 16 steps.- internal const int GRate = 0, GSync = 1, GFreeRate = 2, GGate = 3, GOctaves = 4, GOctaveMode = 5,- GOrder = 6, GSwing = 7, GHold = 8, GRetrig = 9, GTranspose = 10, GLoop = 11;- internal const int LVel = 13, LLen = 29, LChance = 45, LRatchet = 61, LTransp = 77, LOn = 93, LCC = 109;-- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;- private static readonly IBrush Border2 = NotaPalette.BorderDefault;- private static readonly IBrush Inset = NotaPalette.BgSunken;- private static readonly IBrush Amber = NotaPalette.Accent;- private static readonly IBrush AmberLit = NotaPalette.AccentBright;- private static readonly IBrush TealC = NotaPalette.Teal;- private static readonly IBrush TxtC = NotaPalette.TextPrimary;- private static readonly IBrush MutedC = NotaPalette.TextTertiary;- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);-- private static readonly string[] RateNames = { "1/1", "1/2", "1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32" };- private static readonly string[] OrderNames = { "Up", "Down", "Up-Dn", "Converge", "As played", "Chord", "Random" };- private static readonly string[] DirGlyphs = { "↑", "↓", "↕", "?" };+ internal static readonly string[] RateNames = { "1/1", "1/2", "1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32" };internal static readonly double[] RateDivisions = { 4.0, 2.0, 1.0, 0.5, 1.0 / 3.0, 0.25, 1.0 / 6.0, 0.125 };+ // The ORDER list, in musical order → the persisted Order value (new orders were appended).+ internal static readonly (string Name, int Value)[] Orders =+ {+ ("Up", ArpPattern.OrdUp), ("Down", ArpPattern.OrdDown), ("Up · Down", ArpPattern.OrdUpDown),+ ("Down · Up", ArpPattern.OrdDownUp), ("Converge", ArpPattern.OrdConverge), ("Diverge", ArpPattern.OrdDiverge),+ ("Random", ArpPattern.OrdRandom), ("Chord", ArpPattern.OrdChord), ("As played", ArpPattern.OrdAsPlayed),+ };+ private static readonly string[] RetrigNames = { "Off", "Note", "Beat" };+ private const double FreeMsMin = 20, FreeMsMax = 1000, LabelW = 50;++ private static readonly IBrush Ground = NotaPalette.SurfaceInset;+ private static readonly IBrush Island = NotaPalette.SurfaceCard;+ private static readonly IBrush Bd = NotaPalette.BorderDefault;+ private static readonly IBrush Rule = NotaPalette.GraphBorder;+ private static readonly IBrush Well = NotaPalette.BgSunken;+ private static readonly IBrush Chip = NotaPalette.GridBeat;+ private static readonly IBrush Brass = NotaPalette.Accent;+ private static readonly IBrush BrassLit = NotaPalette.AccentBright;+ private static readonly IBrush Txt = NotaPalette.TextPrimary;+ private static readonly IBrush Sub = NotaPalette.TextSecondary;+ private static readonly IBrush Cap = NotaPalette.TextTertiary;+ private static readonly IBrush Ink = NotaPalette.TextOnAccent;++ // Per-card editor state that survives rebuilds (tab + Groove lane) — UI only, not persisted.+ private sealed class Ui { public bool Groove; public int Lane; }+ private static readonly Dictionary<(int, int), Ui> UiState = new();+ private static Ui UiFor(int track, int mi) { if (!UiState.TryGetValue((track, mi), out var u)) UiState[(track, mi)] = u = new Ui(); return u; }public double Width => 700;public bool FullBleed => true;+ private static bool IsMini(IAudioEngine e, int track, int mi) => e.MidiEffectParamCount(track, mi) > PView && e.MidiEffectGetParam(track, mi, PView) >= 0.5f;+ public double WidthFor(IAudioEngine engine, int trackId, int index) => IsMini(engine, trackId, index) ? 260 : 700;++ // ---- small builders -------------------------------------------------------------------+ private static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, LetterSpacing = 0.6, Foreground = c ?? Cap, VerticalAlignment = VerticalAlignment.Center };+ private static TextBlock Mono(string t, IBrush c, double fs = 8) => new()+ { Text = t, FontSize = fs, FontFamily = NotaFonts.MonoFamily, Foreground = c, VerticalAlignment = VerticalAlignment.Center };++ private static string RateLabel(IAudioEngine e, int t, int mi)+ => e.MidiEffectGetParam(t, mi, GSync) > 0.5f ? RateNames[Math.Clamp((int)Math.Round(e.MidiEffectGetParam(t, mi, GRate)), 0, 7)]+ : $"{FreeMs(e.MidiEffectGetParam(t, mi, GFreeRate)):0}\u2009ms";+ private static double FreeMs(double hz) => Math.Clamp(1000.0 / Math.Max(0.1, hz), FreeMsMin, FreeMsMax);+ private static string OrderName(int v) => Orders.FirstOrDefault(o => o.Value == v).Name ?? "Up";++ // ---- header accessory: L = MIDI Learn · tempo · S/L; S = S/L only (the shell keeps the same+ // preset picker in both sizes — presets belong to the device, not to the card size) ----+ public Control? HeaderAccessory(DeviceCardContext ctx, int index)+ {+ var e = ctx.Engine; int t = ctx.TrackId, mi = index;+ if (e.MidiEffectParamCount(t, mi) <= PView) return null;+ bool mini = IsMini(e, t, mi);+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };++ if (!mini)+ {+ var bpm = Mono("", Cap);+ ctx.AddDeviceRefresher(() => bpm.Text = $"{e.Bpm:0.0} BPM");+ bpm.Text = $"{e.Bpm:0.0} BPM";+ row.Children.Add(MidiCardHeader.LearnButton(ctx)); row.Children.Add(bpm);+ }++ row.Children.Add(MidiCardHeader.SizeToggle(ctx, mi, PView, () => IsMini(e, t, mi)));+ return row;+ }++ private static T WithDock<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }++ // ---- body -------------------------------------------------------------------------------public Control Build(DeviceCardContext ctx, int index){var engine = ctx.Engine; int track = ctx.TrackId, mi = index;+ if (engine.MidiEffectParamCount(track, mi) <= PView) return new TextBlock { Text = "Nota Arp", Margin = new Thickness(8) };float G(int p) => engine.MidiEffectGetParam(track, mi, p);- void S(int p, double v) => engine.MidiEffectSetParam(track, mi, p, (float)v);int GI(int p) => (int)Math.Round(G(p));+ void S(int p, double v) => engine.MidiEffectSetParam(track, mi, p, (float)v);+ float Def(int p) => engine.MidiEffectParamDefault(track, mi, p);+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.MidiDeviceParam, mi, p, "");+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.MidiDeviceParam, mi, p, "");+ void Learn(Control c, int p, string name) => MidiLearn.Bind(c, MidiTarget.MidiDeviceParam(track, mi, p), name);++ var ui = UiFor(track, mi);+ bool mini = IsMini(engine, track, mi);+ var readouts = new List<Action>();+ void Refresh() { foreach (var r in readouts) r(); }- var readouts = new System.Collections.Generic.List<Action>();+ var grid = new ArpGrid(engine, track, mi) { Mini = mini, Groove = ui.Groove, LaneIndex = ui.Lane };+ grid.Edited += Refresh;- // Param-backed segmented control (fill = active choice).- Control Seg(int p, string[] names, double fs = 9, double padX = 6, int off = 0)+ // Segmented control bound to a param (value = index + off).+ Border Seg(int p, string[] names, int off = 0, bool fill = true, double padX = 6){- var seg = DeviceCardKit.Segments(names, () => Math.Clamp(GI(p) - off, 0, names.Length - 1), iv => S(p, iv + off), out var sync);+ var seg = DeviceCardKit.Segments(names, () => { int c = GI(p) - off; return c >= 0 && c < names.Length ? c : -1; },+ i => { S(p, i + off); Refresh(); }, out var sync, fill: fill, padX: padX, fontSize: 8);readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));+ Learn(seg, p, engine.MidiEffectParamName(track, mi, p));return seg;}- // Outlined toggle: filled only when on.- Control OutToggle(int p, string label)++ // ---- the status strings ----+ string ChordText(){- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(9, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.SemiBold } };- void Hi() { bool on = G(p) > 0.5f; b.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent; b.BorderBrush = on ? NotaPalette.BorderBrass : Border2; ((TextBlock)b.Child!).Foreground = on ? NotaPalette.AccentHover : MutedC; }- b.PointerPressed += (_, _) => { S(p, G(p) > 0.5f ? 0 : 1); Hi(); };- readouts.Add(Hi); Hi();- MidiLearn.Bind(b, MidiTarget.MidiDeviceParam(track, mi, p), label);- return b;+ var c = grid.Chord;+ return c.Count == 0 ? "no notes yet" : string.Join(" ", c.Select(DeviceCardKit.NoteName));+ }+ string RetrigText() => RetrigNames[Math.Clamp(GI(GRetrig), 0, 2)].ToLowerInvariant();++ // ---- the window's header readout ----+ string InfoText(bool shortForm)+ {+ if (grid.Groove)+ {+ var lane = Lanes[grid.LaneIndex];+ (int s, double v) = grid.LastEdit ?? (Math.Max(0, grid.Position), lane.ToDisp(G(lane.Base + Math.Max(0, grid.Position))));+ v = Math.Clamp(v, lane.Min, lane.Max);+ return shortForm ? $"{s + 1} · {lane.Fmt(v)}" : $"step {s + 1} · {lane.Fmt(v)}";+ }+ int len = Math.Max(1, grid.CurrentSequence().Count);+ if (shortForm) return $"{(grid.Position >= 0 ? grid.Position + 1 : 1)}/{grid.StepCount}";+ if (grid.Chord.Count == 0) return "preview · play a chord";+ return $"{grid.Chord.Count} notes · {Math.Clamp(GI(GOctaves), 1, 8)} oct · cycle {len} steps";+ }++ Control root = mini ? BuildMini() : BuildLarge();+ ctx.AddDeviceRefresher(() => { grid.Poll(); Refresh(); });+ Refresh();+ return root;++ // =======================================================================================+ Control BuildLarge()+ {+ // ---- ORDER ----+ var list = new StackPanel { Margin = new Thickness(0, 3) };+ foreach (var (name, value) in Orders)+ {+ int v = value;+ var bar = new Border { Width = 2, Margin = new Thickness(0, 3), HorizontalAlignment = HorizontalAlignment.Left };+ var tb = new TextBlock { Text = name, FontSize = 9, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 0, 0) };+ var rowB = new Border { Height = 18, Cursor = new Cursor(StandardCursorType.Hand), Child = new Panel { Children = { bar, tb } } };+ bool hover = false;+ void Paint()+ {+ bool on = GI(GOrder) == v;+ rowB.Background = on ? NotaPalette.AccentSubtle : hover ? NotaPalette.SurfaceRaised : Brushes.Transparent;+ bar.Background = on ? Brass : Brushes.Transparent;+ tb.Foreground = on ? Txt : Sub; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ rowB.PointerEntered += (_, _) => { hover = true; Paint(); };+ rowB.PointerExited += (_, _) => { hover = false; Paint(); };+ rowB.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(rowB).Properties.IsLeftButtonPressed) return; S(GOrder, v); Refresh(); ev.Handled = true; };+ Learn(rowB, GOrder, "Order");+ readouts.Add(Paint);+ list.Children.Add(rowB);+ }+ var orderIsland = IslandBox(IslandHead(Caps("ORDER"), null), list, 100);++ // ---- center: tabs + window + rate strip ----+ var info = Mono("", Cap, 7); info.Margin = new Thickness(0, 0, 8, 0);+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };+ var tabs = new (Border b, TextBlock tb)[2];+ Action layoutFor = () => { };+ string[] tabNames = { "Pattern", "Groove" };+ for (int i = 0; i < 2; i++)+ {+ bool groove = i == 1;+ var tb = new TextBlock { Text = tabNames[i], FontSize = 9, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; ui.Groove = grid.Groove = groove; layoutFor(); Refresh(); ev.Handled = true; };+ tabs[i] = (b, tb); tabRow.Children.Add(b);+ }+ var tabHead = new Border { Height = 20, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1),+ Child = new DockPanel { Children = { WithDock(info, Dock.Right), tabRow } } };++ // Groove lane chips.+ var laneGrid = new Grid { Height = 15, ColumnSpacing = 2, Margin = new Thickness(0, 0, 0, 4) };+ var laneChips = new (Border b, TextBlock tb)[Lanes.Length];+ for (int i = 0; i < Lanes.Length; i++)+ {+ int li = i;+ laneGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));+ var tb = new TextBlock { Text = Lanes[i].Label, FontSize = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { CornerRadius = NotaRadius.Clip, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; ui.Lane = grid.LaneIndex = li; Refresh(); ev.Handled = true; };+ Grid.SetColumn(b, i); laneGrid.Children.Add(b); laneChips[i] = (b, tb);+ }++ // Rate strip: Free / Sync + divisions, or the free-rate slider.+ var mode = Seg(GSync, new[] { "Free", "Sync" }, fill: false);+ var rateGrid = new Grid { ColumnSpacing = 2, Height = 15, VerticalAlignment = VerticalAlignment.Center };+ var rateChips = new (Border b, TextBlock tb)[RateNames.Length];+ for (int i = 0; i < RateNames.Length; i++)+ {+ int ri = i;+ rateGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));+ var tb = Mono(RateNames[i], Cap); tb.HorizontalAlignment = HorizontalAlignment.Center;+ var b = new Border { CornerRadius = NotaRadius.Clip, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; S(GRate, ri); Refresh(); ev.Handled = true; };+ Learn(b, GRate, "Rate");+ Grid.SetColumn(b, i); rateGrid.Children.Add(b); rateChips[i] = (b, tb);+ }+ var freeTrack = new SliderTrack { Margin = new Thickness(3, 0), Reset = () => { S(GFreeRate, Def(GFreeRate)); Refresh(); } };+ freeTrack.Changed += n => { S(GFreeRate, 1000.0 / (FreeMsMin + n * (FreeMsMax - FreeMsMin))); Refresh(); };+ freeTrack.GestureBegin += () => Begin(GFreeRate); freeTrack.GestureEnd += () => End(GFreeRate);+ Learn(freeTrack, GFreeRate, "Free rate");+ var freeVal = Mono("", Txt); freeVal.Width = 40; freeVal.TextAlignment = TextAlignment.Right;+ var freeRow = new DockPanel { Children = { WithDock(freeVal, Dock.Right), freeTrack } };+ var rateHost = new Panel { Margin = new Thickness(4, 0, 0, 0), Children = { rateGrid, freeRow } };+ var rateStrip = new DockPanel { Height = 16, Margin = new Thickness(0, 4, 0, 0), Children = { WithDock(mode, Dock.Left), rateHost } };++ var winRow = new DockPanel { Children = { WithDock(laneGrid, Dock.Top), WithDock(rateStrip, Dock.Bottom), grid } };+ var centerIsland = IslandBox(tabHead, new Border { Padding = new Thickness(8, 5), Child = winRow }, double.NaN);++ void LayoutFor()+ {+ laneGrid.IsVisible = grid.Groove;+ for (int i = 0; i < 2; i++)+ {+ bool on = (i == 1) == grid.Groove;+ tabs[i].b.Background = on ? Chip : Brushes.Transparent;+ tabs[i].b.BorderBrush = on ? Brass : Brushes.Transparent;+ tabs[i].tb.Foreground = on ? BrassLit : Cap;+ tabs[i].tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ }+ layoutFor = LayoutFor;+ LayoutFor();+ readouts.Add(() =>+ {+ info.Text = InfoText(false);+ info.Foreground = grid.Groove ? BrassLit : Cap;+ for (int i = 0; i < Lanes.Length; i++)+ {+ bool on = i == grid.LaneIndex;+ laneChips[i].b.Background = on ? Brass : Chip;+ laneChips[i].tb.Foreground = on ? Ink : Sub;+ laneChips[i].tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ bool sync = G(GSync) > 0.5f;+ rateGrid.IsVisible = sync; freeRow.IsVisible = !sync;+ int rate = GI(GRate);+ for (int i = 0; i < RateNames.Length; i++)+ {+ bool on = i == rate;+ rateChips[i].b.Background = on ? Brass : Chip;+ rateChips[i].tb.Foreground = on ? Ink : Cap;+ }+ double ms = FreeMs(G(GFreeRate));+ if (!freeTrack.Dragging) freeTrack.Norm = (ms - FreeMsMin) / (FreeMsMax - FreeMsMin);+ freeVal.Text = $"{ms:0}\u2009ms";+ });++ // ---- PLAY ----+ var play = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto,*,Auto,*,Auto,*,Auto,*,Auto,*,Auto") };+ var playRows = new List<Control>+ {+ SliderLine("GATE", GGate, v => v / 2, n => n * 2, v => $"{v * 100:0}\u2009%"),+ SliderLine("SWING", GSwing, v => v, n => n, v => $"{v * 50:0}\u2009%"),+ SliderLine("VEL AMT", PVelAmt, v => v, n => n, v => $"{v * 100:0}\u2009%"),+ Ruled(Line("OCTAVES", Seg(GOctaves, new[] { "1", "2", "3", "4" }, off: 1))),+ Line("RETRIG", Seg(GRetrig, RetrigNames)),+ Stepper("TRANSPOSE", GTranspose, -24, 24, v => v == 0 ? "0\u2009st" : $"{(v > 0 ? "+" : "−")}{Math.Abs(v)}\u2009st"),+ Stepper("STEPS", GLoop, 1, 16, v => v.ToString()),+ Ruled(ButtonsRow()),+ };+ for (int i = 0; i < playRows.Count; i++) { Grid.SetRow(playRows[i], i * 2); play.Children.Add(playRows[i]); }+ var playHead = IslandHead(Caps("PLAY"), Mono("MIDI out · ch 1", Cap, 7));+ var playIsland = IslandBox(playHead, new Border { Padding = new Thickness(8, 5), Child = play }, 176);++ var islands = new DockPanel { Background = Ground, Children = { WithDock(orderIsland, Dock.Left), WithDock(playIsland, Dock.Right), centerIsland } };+ islands.Margin = new Thickness(0);+ orderIsland.Margin = new Thickness(0, 0, 5, 0); playIsland.Margin = new Thickness(5, 0, 0, 0);++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"{ChordText()} · {OrderName(GI(GOrder))} · {Math.Clamp(GI(GOctaves), 1, 8)} oct · {RateLabel(engine, track, mi)} · {grid.StepCount} steps · retrig {RetrigText()}{(G(GHold) > 0.5f ? " · hold" : "")}";+ statusR.Text = engine.MidiEffectBypassed(track, mi) ? "bypassed" : grid.Running ? "MIDI · latency 0 smp" : "MIDI · waiting for notes";+ });+ return Framed(islands, statusL, statusR);}- // Compact drag value (label above a field you drag; double-click resets).- Control DragVal(int p, string name, double min, double max, Func<double, string> fmt)++ // =======================================================================================+ Control BuildMini(){- var val = new TextBlock { Text = fmt(G(p)), FontSize = 9, Foreground = TxtC, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };- val.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- var field = new Border { MinWidth = 44, Height = 17, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(3, 0), Cursor = new Cursor(StandardCursorType.SizeWestEast), Child = val };- bool drag = false; double sx = 0, sv = 0;- field.PointerPressed += (_, e) =>- {- if (e.ClickCount == 2) { float d = engine.MidiEffectParamDefault(track, mi, p); S(p, d); val.Text = fmt(d); e.Handled = true; return; }- drag = true; sx = e.GetPosition(field).X; sv = G(p); e.Pointer.Capture(field); e.Handled = true;+ var tabs = DeviceCardKit.Segments(new[] { "Pattern", "Groove" }, () => grid.Groove ? 1 : 0,+ i => { ui.Groove = grid.Groove = i == 1; Refresh(); }, out var tabSync, padX: 6, fontSize: 8);+ readouts.Add(tabSync);+ var laneName = new TextBlock { FontSize = 8, Foreground = Txt, VerticalAlignment = VerticalAlignment.Center };+ var laneBtn = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent,+ Children = { laneName, new Glyph { Kind = GlyphKind.ChevronDown, Width = 6, Height = 6, Foreground = Cap, VerticalAlignment = VerticalAlignment.Center } } };+ ToolTip.SetTip(laneBtn, "Next Groove lane");+ laneBtn.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(laneBtn).Properties.IsLeftButtonPressed) return;+ ui.Lane = grid.LaneIndex = (grid.LaneIndex + 1) % Lanes.Length; Refresh(); ev.Handled = true;};- field.PointerMoved += (_, e) => { if (!drag) return; double v = Math.Clamp(sv + (e.GetPosition(field).X - sx) / 120.0 * (max - min), min, max); S(p, v); val.Text = fmt(v); };- field.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- MidiLearn.Bind(field, MidiTarget.MidiDeviceParam(track, mi, p), name);- readouts.Add(() => { if (!drag) val.Text = fmt(G(p)); });- return new StackPanel { Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center, Children = { new TextBlock { Text = name, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center }, field } };+ var info = Mono("", Cap, 7);+ var head = new DockPanel { Height = 14, Margin = new Thickness(0, 0, 0, 4),+ Children = { WithDock(tabs, Dock.Left), WithDock(info, Dock.Right), laneBtn } };+ laneBtn.Margin = new Thickness(6, 0, 0, 0);++ var knobs = new Grid { Height = 53, ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), Margin = new Thickness(0, 3, 0, 0) };+ var cells = new[]+ {+ KnobCell("RATE", GRate,+ () => G(GSync) > 0.5f ? GI(GRate) / 7.0 : (FreeMs(G(GFreeRate)) - FreeMsMin) / (FreeMsMax - FreeMsMin),+ n => { if (G(GSync) > 0.5f) S(GRate, Math.Round(n * 7)); else S(GFreeRate, 1000.0 / (FreeMsMin + n * (FreeMsMax - FreeMsMin))); },+ () => RateLabel(engine, track, mi), () => G(GSync) > 0.5f ? GRate : GFreeRate),+ KnobCell("GATE", GGate, () => G(GGate) / 2, n => S(GGate, n * 2), () => $"{G(GGate) * 100:0}\u2009%"),+ KnobCell("OCT", GOctaves, () => (Math.Clamp(GI(GOctaves), 1, 4) - 1) / 3.0, n => S(GOctaves, Math.Round(n * 3) + 1), () => $"{GI(GOctaves)}"),+ KnobCell("SWING", GSwing, () => G(GSwing), n => S(GSwing, n), () => $"{G(GSwing) * 50:0}\u2009%"),+ };+ for (int i = 0; i < cells.Length; i++) { Grid.SetColumn(cells[i], i); knobs.Children.Add(cells[i]); }++ var inner = new DockPanel { Children = { WithDock(head, Dock.Top), WithDock(knobs, Dock.Bottom), grid } };+ var island = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,+ Padding = new Thickness(6, 5, 6, 0), Child = inner };++ readouts.Add(() =>+ {+ laneBtn.IsVisible = grid.Groove;+ laneName.Text = Lanes[grid.LaneIndex].Label;+ info.Text = InfoText(true);+ info.Foreground = grid.Groove ? BrassLit : Cap;+ });++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"{ChordText()} · {Math.Clamp(GI(GOctaves), 1, 8)} oct";+ statusR.Text = engine.MidiEffectBypassed(track, mi) ? "bypassed" : RateLabel(engine, track, mi);+ });+ return Framed(new Border { Background = Ground, Child = island }, statusL, statusR);}- Control Stepper(int p, int min, int max)++ // ---- shared pieces ---------------------------------------------------------------------+ Control Framed(Control main, TextBlock left, TextBlock right){- var val = new TextBlock { Text = GI(p).ToString(), FontSize = 9, Foreground = TxtC, MinWidth = 18, TextAlignment = TextAlignment.Center, VerticalAlignment = VerticalAlignment.Center };- val.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- Border Btn(string t, int d) { var b = new Border { Width = 18, Height = 18, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = t, FontSize = 9, Foreground = TxtC, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center } }; b.PointerPressed += (_, _) => { int v = Math.Clamp(GI(p) + d, min, max); S(p, v); val.Text = v.ToString(); }; return b; }- readouts.Add(() => val.Text = GI(p).ToString());- return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = { Btn("−", -1), val, Btn("+", +1) } };+ var status = new Border { Height = 18, Background = Well, BorderBrush = Bd, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0),+ Child = new DockPanel { Children = { WithDock(right, Dock.Right), left } } };+ right.Margin = new Thickness(8, 0, 0, 0);+ return new DockPanel { Background = Ground, Children = { WithDock(status, Dock.Bottom), new Border { Padding = new Thickness(5), Child = main } } };}- // ---- LIVE strip ----- string Pct(double v) => $"{v * 100:0}\u2009%";- var live = new Border { Height = 34, Background = HdrBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1),- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(9, 0), Children = {- Seg(GSync, new[] { "Free", "Sync" }, 9, 7),- Seg(GRate, RateNames, 8, 4),- DragVal(GGate, "GATE", 0, 2, Pct), DragVal(GSwing, "SWING", 0, 1, Pct),- OutToggle(GHold, "Hold"), OutToggle(GRetrig, "Retrig") } } };-- // ---- step grid + lane rail ----- var grid = new ArpGrid(engine, track, mi);- (string name, int b, double min, double max, bool vel, bool isInt)[] lanes =+ Control IslandHead(Control left, Control? right){- ("Velocity", LVel, 0, 1, true, false), ("Length", LLen, 0, 2, false, false), ("Chance", LChance, 0, 1, false, false),- ("Ratchet", LRatchet, 1, 8, false, true), ("Transpose", LTransp, -24, 24, false, true),- };- var laneName = new TextBlock { Text = "VELOCITY", FontSize = 9, FontWeight = FontWeight.Bold, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center };- var stepRead = new TextBlock { FontSize = 9, Foreground = TealC, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right };- stepRead.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- int laneSel = 0;- var laneBtns = new Border[lanes.Length];- void SelectLane(int li)+ var d = new DockPanel { Margin = new Thickness(8, 0) };+ if (right is not null) d.Children.Add(WithDock(right, Dock.Right));+ d.Children.Add(left);+ return new Border { Height = 20, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Child = d };+ }++ Border IslandBox(Control head, Control content, double width){- var l = lanes[li]; laneSel = li;- grid.SetLane(l.b, l.min, l.max, l.vel, l.isInt);- laneName.Text = l.name.ToUpperInvariant();- for (int i = 0; i < lanes.Length; i++) { bool on = i == li; laneBtns[i].Background = on ? NotaPalette.SurfaceRaised : Brushes.Transparent; laneBtns[i].BorderBrush = on ? Amber : Brushes.Transparent; ((TextBlock)laneBtns[i].Child!).Foreground = on ? TxtC : MutedC; }+ var b = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true,+ Child = new DockPanel { Children = { WithDock(head, Dock.Top), content } } };+ if (!double.IsNaN(width)) b.Width = width;+ return b;}- var railCol = new StackPanel { Spacing = 2 };- for (int i = 0; i < lanes.Length; i++)++ Control Line(string label, Control c){- int li = i;- var b = new Border { Height = 22, CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 0), BorderThickness = new Thickness(2, 0, 0, 0), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = lanes[i].name, FontSize = 9, FontWeight = FontWeight.Medium, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center } };- b.PointerPressed += (_, _) => SelectLane(li);- laneBtns[i] = b; railCol.Children.Add(b);+ var l = Caps(label); l.Width = LabelW;+ return new DockPanel { Children = { WithDock(l, Dock.Left), c } };}- var stepsBox = new StackPanel { Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center, Children = { new TextBlock { Text = "STEPS", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center }, Stepper(GLoop, 1, 16) } };- DockPanel.SetDock(railCol, Dock.Top); DockPanel.SetDock(stepsBox, Dock.Bottom);- var laneRail = new Border { Width = 78, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(5, 8),- Child = new DockPanel { LastChildFill = false, Children = { railCol, stepsBox } } };-- var gridHeader = new DockPanel { Margin = new Thickness(0, 0, 0, 4), LastChildFill = false, Children = { laneName,- new TextBlock { Text = "drag to draw · ⌥ ramp · click # to mute", FontSize = 8, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 0, 0) } } };- DockPanel.SetDock(stepRead, Dock.Right); gridHeader.Children.Add(stepRead);- grid.VerticalAlignment = VerticalAlignment.Stretch;- DockPanel.SetDock(gridHeader, Dock.Top);- var stepArea = new Border { Padding = new Thickness(8, 6), Child = new DockPanel { LastChildFill = true, Children = { gridHeader, grid } } };-- // ---- right rail ----- var orderGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 2, RowSpacing = 2 };- for (int i = 0; i < 4; i++) orderGrid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));- var orderChips = new Border[OrderNames.Length];- void HiOrder() { int cur = Math.Clamp(GI(GOrder), 0, OrderNames.Length - 1); for (int i = 0; i < OrderNames.Length; i++) { bool on = i == cur; orderChips[i].Background = on ? Amber : Inset; orderChips[i].BorderBrush = on ? Amber : Border2; ((TextBlock)orderChips[i].Child!).Foreground = on ? NotaPalette.TextOnAccent : MutedC; } }- for (int i = 0; i < OrderNames.Length; i++)+ Control Ruled(Control c) => new Border { BorderBrush = Rule, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 4, 0, 0), Child = c };++ // A PLAY slider: label brightens to brass once moved off its default.+ Control SliderLine(string label, int p, Func<double, double> toNorm, Func<double, double> fromNorm, Func<double, string> fmt){- int iv = i; var c = new Border { BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(2, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = OrderNames[i], FontSize = 8, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center } };- c.PointerPressed += (_, _) => { S(GOrder, iv); HiOrder(); };- Grid.SetColumn(c, i % 2); Grid.SetRow(c, i / 2); orderChips[i] = c; orderGrid.Children.Add(c);+ var l = Caps(label); l.Width = LabelW;+ var val = Mono("", Txt); val.Width = 30; val.TextAlignment = TextAlignment.Right;+ var track = new SliderTrack { Height = 11, Reset = () => { S(p, Def(p)); Refresh(); } };+ track.Changed += n => { S(p, fromNorm(n)); Refresh(); };+ track.GestureBegin += () => Begin(p); track.GestureEnd += () => End(p);+ Learn(track, p, label);+ readouts.Add(() =>+ {+ double v = G(p);+ if (!track.Dragging) track.Norm = toNorm(v);+ bool mod = Math.Abs(v - Def(p)) > 0.005;+ l.Foreground = mod ? BrassLit : Cap;+ val.Foreground = mod ? BrassLit : Txt;+ val.Text = fmt(v);+ });+ track.Margin = new Thickness(0, 0, 4, 0);+ return new DockPanel { Children = { WithDock(l, Dock.Left), WithDock(val, Dock.Right), track } };}- readouts.Add(HiOrder); HiOrder();- Control Block(string label, IBrush lc, Control ctl) => new StackPanel { Spacing = 2, Children = { new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = lc, VerticalAlignment = VerticalAlignment.Center }, ctl } };- // Full-width segmented control: equal-star columns so the buttons fill the rail evenly.- Control SegFill(int p, string[] names, int off = 0)+ Control Stepper(string label, int p, int min, int max, Func<int, string> fmt){- var seg = DeviceCardKit.Segments(names, () => Math.Clamp(GI(p) - off, 0, names.Length - 1), iv => S(p, iv + off), out var sync, fill: true);- readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));- return seg;+ var l = Caps(label); l.Width = LabelW;+ var val = Mono("", Txt); val.HorizontalAlignment = HorizontalAlignment.Center;+ Border Btn(string glyph, int d)+ {+ var tb = Mono(glyph, NotaPalette.TextMuted, 9); tb.HorizontalAlignment = HorizontalAlignment.Center;+ var b = new Border { Width = 18, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerEntered += (_, _) => tb.Foreground = Txt; b.PointerExited += (_, _) => tb.Foreground = NotaPalette.TextMuted;+ b.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ S(p, Math.Clamp(GI(p) + d, min, max)); Refresh(); ev.Handled = true;+ };+ return b;+ }+ var box = new Border { Height = 14, Background = Well, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,+ Child = new DockPanel { Children = { WithDock(Btn("−", -1), Dock.Left), WithDock(Btn("+", +1), Dock.Right), val } } };+ box.PointerPressed += (_, ev) => { if (ev.ClickCount == 2) { S(p, Def(p)); Refresh(); } };+ Learn(box, p, label);+ readouts.Add(() =>+ {+ int v = GI(p);+ bool mod = Math.Abs(v - Def(p)) > 0.5;+ l.Foreground = mod ? BrassLit : Cap;+ val.Foreground = mod ? BrassLit : Txt;+ val.Text = fmt(v);+ });+ return new DockPanel { Children = { WithDock(l, Dock.Left), box } };}- var rightRail = new Border { Width = 120, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 7),- Child = new StackPanel { Spacing = 5, Children = {- Block("ORDER", TxtC, orderGrid),- Block("OCT", MutedC, SegFill(GOctaves, new[] { "1", "2", "3", "4" }, off: 1)),- Block("DIR", MutedC, SegFill(GOctaveMode, DirGlyphs)),- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { new TextBlock { Text = "TRANSPOSE", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center }, DragVal(GTranspose, "", -24, 24, v => $"{v:+0;−0;0}\u2009st") } } } } };-- // ---- assemble ----- DockPanel.SetDock(laneRail, Dock.Left); DockPanel.SetDock(rightRail, Dock.Right);- var body = new DockPanel { LastChildFill = true, Children = { laneRail, rightRail, stepArea } };- DockPanel.SetDock(live, Dock.Top);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };-- SelectLane(0);- // Live playhead + step readout.- ctx.AddDeviceRefresher(() =>++ Control ButtonsRow(){- int loop = Math.Clamp(GI(GLoop), 1, 16);- double stepBeats = G(GSync) > 0.5f ? RateDivisions[Math.Clamp(GI(GRate), 0, 7)] : 0.25;- int cur = -1;- if (engine.IsPlaying && stepBeats > 1e-6) cur = (int)(Math.Floor(engine.PositionBeats / stepBeats) % loop);- grid.SetPlayhead(cur);- int rs = cur >= 0 ? cur : 0;- stepRead.Text = $"step {rs + 1} · {(int)Math.Round(G(LVel + rs) * 127)}";- foreach (var a in readouts) a();- });- foreach (var a in readouts) a();- return root;+ Border Btn(string text, Action click, out TextBlock tb)+ {+ var t = new TextBlock { Text = text, FontSize = 8, Foreground = Txt, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Background = NotaPalette.TrackOff, BorderBrush = NotaPalette.TrackOff, Cursor = new Cursor(StandardCursorType.Hand), Child = t };+ b.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); ev.Handled = true; };+ tb = t; return b;+ }+ var hold = Btn("Hold", () => { S(GHold, G(GHold) > 0.5f ? 0 : 1); Refresh(); }, out var holdTb);+ ToolTip.SetTip(hold, "Hold: keep arpeggiating after the keys are released");+ Learn(hold, GHold, "Hold");+ readouts.Add(() =>+ {+ bool on = G(GHold) > 0.5f;+ hold.Background = on ? NotaPalette.AccentSubtle : NotaPalette.TrackOff;+ hold.BorderBrush = on ? NotaPalette.BorderBrass : NotaPalette.TrackOff;+ holdTb.Foreground = on ? NotaPalette.AccentHover : Txt;+ holdTb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ });+ var restart = Btn("Restart", () => engine.MidiEffectCommand(track, mi, 1), out var rTb);+ restart.PointerEntered += (_, _) => restart.Background = NotaPalette.SurfaceHover;+ restart.PointerExited += (_, _) => restart.Background = NotaPalette.TrackOff;+ ToolTip.SetTip(restart, "Restart the pattern from step 1");+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };+ Grid.SetColumn(restart, 1); g.Children.Add(hold); g.Children.Add(restart);+ return g;+ }++ // A mini-view knob: 34px gauge, caps label, mono value. `learnParam` names the param the+ // knob drives right now (Rate is the division when synced, the free rate otherwise).+ Control KnobCell(string label, int p, Func<double> norm, Action<double> set, Func<string> text, Func<int>? learnParam = null)+ {+ var knob = new Knob(norm(), 1.0) { Accent = true, Width = 34, Height = 34, HorizontalAlignment = HorizontalAlignment.Center };+ int LP() => learnParam?.Invoke() ?? p;+ knob.ValueChanged += n => { set(n); Refresh(); };+ knob.GestureBegin += () => Begin(LP()); knob.GestureEnd += () => End(LP());+ Learn(knob, p, label);+ var val = Mono("", Sub, 7); val.HorizontalAlignment = HorizontalAlignment.Center;+ readouts.Add(() => { double n = norm(); if (!knob.Dragging && Math.Abs(knob.Value - n) > 1e-6) knob.Value = n; val.Text = text(); });+ return new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, Cursor = new Cursor(StandardCursorType.SizeNorthSouth),+ Children = { knob, new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.6, Foreground = Cap, HorizontalAlignment = HorizontalAlignment.Center, LineHeight = 9 }, val } };+ }}}diff --git a/src/managed/Nota.App/DeviceCards/Midi/ChordMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/ChordMidiBody.csindex 4b79317f..3560e5c5 100644--- a/src/managed/Nota.App/DeviceCards/Midi/ChordMidiBody.cs+++ b/src/managed/Nota.App/DeviceCards/Midi/ChordMidiBody.cs@@ -1,15 +1,24 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the Nota Chord editor (MIDI effect kind 1), mockup 3b (700×260 on the-// shared shell): a LIVE strip (chord-type presets · Strum · Keep root · Fold in scale) over-// a body of a SHIFTS stack (six voices — semitone offset + relative velocity, active voices-// lit) beside a RESULT panel (the resulting chord for a reference C3 as note names + a-// two-octave keyboard preview lighting played vs added, plus Voices count + Spread).-// Detune is intentionally absent — the note stream carries integer pitch to the instrument.+// Detail · Devices — the Nota Chord editor (MIDI effect kind 1), almanac mockups 1a / 1b.+// Two sizes share every value; the S / L toggle in the shell header flips the card (the+// choice is the device's "View" param, so it persists with the project):+// • L 700 × 260 — TYPE list (Maj7 / Min7 / Sus4 / 5th / Custom, Keep root, Fold in scale ++// its key) | SHIFTS: six rows — switch dot, semitones, a bipolar ±12 ruler, the interval+// name and a draggable velocity offset | RESULT: the chord's note names, a three-octave+// keyboard (played Brass Light, added Brass Deep, an unplayed root outlined), Strum and+// Spread — over a status line.+// • S 260 × 260 — note names + the keyboard over six vertical bipolar shift bars (the+// number under each toggles it), Strum / Spread knobs and the two flags. The header keeps+// the same preset picker as L; presets set everything, S just edits less.+// Editing a shift turns TYPE to Custom. The keyboard animates: a held chord lights as the+// engine strums it (telemetry), and otherwise the preview strums once per bar while the+// transport runs, and once after each edit.using System;using System.Collections.Generic;+using System.Diagnostics;using System.Linq;using Avalonia;using Avalonia.Controls;@@ -17,205 +26,542 @@ using Avalonia.Controls.Shapes;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;+using Nota.Application;namespace Nota.App;internal sealed class ChordMidiBody : IMidiDeviceBody{// Param indices — mirror MidiChord.h.- private const int Voice1 = 0, Strum = 6, KeepRoot = 7, Spread = 8, Fold = 9, Vel1 = 10;- private const int Voices = 6;+ internal const int Voice1 = 0, Strum = 6, KeepRoot = 7, Spread = 8, Fold = 9, Vel1 = 10, On1 = 16,+ FoldKey = 22, FoldMode = 23, PView = 24, Slots = 6;+ private const int DefaultRoot = 48; // C3 — the preview's input before any note was played- private static readonly string[] NoteNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };- private static readonly (string name, int[] semis)[] Templates =+ internal static readonly (string Name, int[]? Shifts)[] Types ={- ("Maj7", new[] { 4, 7, 11 }), ("Min7", new[] { 3, 7, 10 }),- ("Sus4", new[] { 5, 7 }), ("5th", new[] { 7, 12 }),+ ("Maj7", new[] { 4, 7, 11 }), ("Min7", new[] { 3, 7, 10 }), ("Sus4", new[] { 5, 7 }), ("5th", new[] { 7 }), ("Custom", null),};+ private static readonly string[] Intervals = { "P1", "m2", "M2", "m3", "M3", "P4", "TT", "P5", "m6", "M6", "m7", "M7", "P8" };+ private static readonly string[] KeyNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ private static readonly bool[] MajorPc = { true, false, true, false, true, true, false, true, false, true, false, true };+ private static readonly bool[] MinorPc = { true, false, true, true, false, true, false, true, true, false, true, false };- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;+ private static readonly IBrush Ground = NotaPalette.SurfaceInset;+ private static readonly IBrush Island = NotaPalette.SurfaceCard;private static readonly IBrush Bd = NotaPalette.BorderDefault;- private static readonly IBrush Inset = NotaPalette.BgSunken;- private static readonly IBrush Amber = NotaPalette.Accent;- private static readonly IBrush AmberLit = NotaPalette.AccentBright;+ private static readonly IBrush Rule = NotaPalette.GraphBorder;+ private static readonly IBrush Well = NotaPalette.BgSunken;+ private static readonly IBrush BrassLit = NotaPalette.AccentBright;private static readonly IBrush Txt = NotaPalette.TextPrimary;- private static readonly IBrush Muted = NotaPalette.TextTertiary;private static readonly IBrush Sub = NotaPalette.TextSecondary;- private static readonly IBrush Green = NotaPalette.Success;- private static readonly IBrush Card = NotaPalette.SurfaceRaised;- private static readonly IBrush Ink = NotaPalette.TextOnAccent;- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x24);+ private static readonly IBrush Cap = NotaPalette.TextTertiary;+ private static readonly IBrush Axis = NotaPalette.TextAxis;++ // Per-card editor state that survives rebuilds — UI only, not persisted.+ private sealed class Ui { public bool CustomPinned; public long EditTicks; }+ private static readonly Dictionary<(int, int), Ui> UiState = new();+ private static Ui UiFor(int track, int mi) { if (!UiState.TryGetValue((track, mi), out var u)) UiState[(track, mi)] = u = new Ui(); return u; }public double Width => 700;public bool FullBleed => true;+ private static bool HasLayout(IAudioEngine e, int track, int mi) => e.MidiEffectParamCount(track, mi) > PView;+ private static bool IsMini(IAudioEngine e, int track, int mi) => HasLayout(e, track, mi) && e.MidiEffectGetParam(track, mi, PView) >= 0.5f;+ public double WidthFor(IAudioEngine engine, int trackId, int index) => IsMini(engine, trackId, index) ? 260 : 700;++ public Control? HeaderAccessory(DeviceCardContext ctx, int index)+ {+ var e = ctx.Engine; int t = ctx.TrackId;+ if (!HasLayout(e, t, index)) return null;+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };+ if (!IsMini(e, t, index)) row.Children.Add(MidiCardHeader.LearnButton(ctx));+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, index, PView, () => IsMini(e, t, index)));+ return row;+ }++ // ---- the chord model (mirrors MidiChord::process) ------------------------------------------+ internal readonly record struct Note(int Pitch, bool Played, int Vel);++ internal static List<Note> Compute(Func<int, float> g, int root, int inVel = 100)+ {+ bool keep = g(KeepRoot) >= 0.5f, fold = g(Fold) >= 0.5f, minor = g(FoldMode) >= 0.5f;+ int key = (((int)Math.Round(g(FoldKey))) % 12 + 12) % 12;+ int level = Math.Min(2, (int)Math.Floor(Math.Clamp(g(Spread) / 100.0, 0, 1) * 3 + 1e-9));+ var list = new List<Note>();+ void Add(int p, int v, bool played)+ {+ if (p is < 0 or > 127) return;+ int i = list.FindIndex(n => n.Pitch == p);+ if (i >= 0) { if (played) list[i] = new Note(p, true, v); return; }+ list.Add(new Note(p, played, v));+ }+ if (keep) Add(root, inVel, true);+ int k = 0;+ for (int s = 0; s < Slots; s++)+ {+ if (g(On1 + s) < 0.5f) continue;+ int p = root + Math.Clamp((int)Math.Round(g(Voice1 + s)), -24, 24);+ if (fold && !(minor ? MinorPc : MajorPc)[((p - key) % 12 + 12) % 12]) p -= 1;+ if ((k % 2 == 0 && level >= 1) || (k % 2 == 1 && level >= 2)) p += 12;+ k++;+ Add(p, Math.Clamp(inVel + (int)Math.Round(g(Vel1 + s)), 1, 127), false);+ }+ list.Sort((a, b) => a.Pitch.CompareTo(b.Pitch));+ return list;+ }++ /// <summary>The TYPE row the active shifts match (Custom when none).</summary>+ internal static int MatchType(Func<int, float> g)+ {+ var on = Enumerable.Range(0, Slots).Where(s => g(On1 + s) >= 0.5f).Select(s => (int)Math.Round(g(Voice1 + s))).OrderBy(x => x).ToArray();+ for (int i = 0; i < Types.Length; i++)+ if (Types[i].Shifts is { } iv && on.SequenceEqual(iv.OrderBy(x => x))) return i;+ return Types.Length - 1;+ }++ internal static string Sgn(int v) => v > 0 ? $"+{v}" : v < 0 ? $"−{-v}" : "0";+ internal static string IntervalName(int st) => Math.Abs(st) <= 12 ? (st < 0 ? "−" : "") + Intervals[Math.Abs(st)] : Sgn(st);+ internal static string ScaleName(Func<int, float> g, bool shortForm)+ {+ string key = KeyNames[(((int)Math.Round(g(FoldKey))) % 12 + 12) % 12];+ bool minor = g(FoldMode) >= 0.5f;+ return shortForm ? $"{key} {(minor ? "min" : "maj")}" : $"{key} {(minor ? "minor" : "major")}";+ }++ // ---- small builders -------------------------------------------------------------------------+ private static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, LetterSpacing = 0.8, Foreground = c ?? Cap, VerticalAlignment = VerticalAlignment.Center };+ private static TextBlock Mono(string t, IBrush c, double fs = 8) => new()+ { Text = t, FontSize = fs, FontFamily = NotaFonts.MonoFamily, Foreground = c, VerticalAlignment = VerticalAlignment.Center };+ private static T WithDock<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }++ // ---- body -------------------------------------------------------------------------------------public Control Build(DeviceCardContext ctx, int index){- var engine = ctx.Engine;- int track = ctx.TrackId, mi = index;+ var engine = ctx.Engine; int track = ctx.TrackId, mi = index;+ if (!HasLayout(engine, track, mi)) return new TextBlock { Text = "Nota Chord", Margin = new Thickness(8) };float G(int p) => engine.MidiEffectGetParam(track, mi, p);- void S(int p, double v) => engine.MidiEffectSetParam(track, mi, p, (float)v);- int Semi(int v) => (int)Math.Round(G(Voice1 + v));+ int GI(int p) => (int)Math.Round(G(p));+ float Def(int p) => engine.MidiEffectParamDefault(track, mi, p);+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.MidiDeviceParam, mi, p, "");+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.MidiDeviceParam, mi, p, "");+ void Learn(Control c, int p, string name) => MidiLearn.Bind(c, MidiTarget.MidiDeviceParam(track, mi, p), name);+ var ui = UiFor(track, mi);+ bool mini = IsMini(engine, track, mi);var readouts = new List<Action>();- static TextBlock Mono(string t, IBrush c, double fs = 9) { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }- static TextBlock Cap(string t, IBrush? c = null, double fs = 8) => new() { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? Muted, VerticalAlignment = VerticalAlignment.Center };- static string IntervalLabel(int s) => s == 0 ? "off" : s == 12 ? "+oct" : s == -12 ? "−oct" : (s > 0 ? "+" : "−") + Math.Abs(s);-- // ---- chord preview (reference root C3=60), mirroring MidiChord.h ----- static int FoldMajor(int iv) { int[] d = { 0, 2, 4, 5, 7, 9, 11 }; int within = ((iv % 12) + 12) % 12, octs = (iv - within) / 12, best = 0, bd = 99; foreach (int g in d) { int df = Math.Abs(g - within); if (df < bd) { bd = df; best = g; } } return octs * 12 + best; }- var keys = new ChordKeysViz { VerticalAlignment = VerticalAlignment.Stretch };- List<int> Chord(int root)- {- bool keep = G(KeepRoot) >= 0.5f, fold = G(Fold) >= 0.5f;- double sp = Math.Clamp(G(Spread) / 100.0, 0, 1);- var list = new List<int>();- if (keep) list.Add(root);- for (int v = 0; v < Voices; v++) { int s = Semi(v); if (s == 0) continue; int p = root + (fold ? FoldMajor(s) : s); if (sp > 0) p += 12 * (int)Math.Floor(sp * (v + 1) + 1e-9); if (p is >= 0 and <= 127) list.Add(p); }- return list.Distinct().OrderBy(x => x).ToList();- }void Refresh() { foreach (var r in readouts) r(); }-- // ---- generic controls -------------------------------------------------- Control RawSlider(int p, double min, double max, Func<double, string> fmt, double w, bool bipolar = false, double valW = 40)- {- var val = Mono(fmt(G(p)), Txt); val.Width = valW; val.TextAlignment = TextAlignment.Right;- var fill = new Border { Height = 3, Background = Amber, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var handle = new Border { Width = 7, Height = 9, Background = Sub, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var slot = new Panel { Height = 9, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent };- if (w > 0) slot.Width = w;- slot.Children.Add(new Border { Height = 3, Background = Inset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center });- if (bipolar) slot.Children.Add(new Border { Width = 1, Background = Bd, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch, Margin = new Thickness(0, 1) });- slot.Children.Add(fill); slot.Children.Add(handle);- double Norm(double v) => (v - min) / (max - min);- void Vis(double v) { double W = slot.Bounds.Width, n = Norm(v); if (bipolar) { double c = W / 2, x = n * W; fill.Width = Math.Abs(x - c); fill.HorizontalAlignment = HorizontalAlignment.Left; fill.Margin = new Thickness(Math.Min(c, x), 0, 0, 0); } else { fill.Width = n * W; fill.Margin = new Thickness(0); } handle.Margin = new Thickness(Math.Clamp(n * W - 3.5, 0, Math.Max(0, W - 7)), 0, 0, 0); }- bool drag = false;- void SetX(double x) { double n = Math.Clamp(x / Math.Max(1, slot.Bounds.Width), 0, 1); double v = min + n * (max - min); S(p, v); Vis(v); val.Text = fmt(v); Refresh(); }- slot.PointerPressed += (_, e) => { drag = true; e.Pointer.Capture(slot); SetX(e.GetPosition(slot).X); };- slot.PointerMoved += (_, e) => { if (drag) SetX(e.GetPosition(slot).X); };- slot.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- MidiLearn.Bind(slot, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));- slot.SizeChanged += (_, _) => Vis(G(p)); // flexible-width sliders reposition once laid out- readouts.Add(() => { if (!drag) { double v = G(p); Vis(v); val.Text = fmt(v); } });- var g = new Grid { ColumnDefinitions = new ColumnDefinitions(w > 0 ? "Auto,Auto" : "*,Auto"), ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center };- Grid.SetColumn(val, 1); g.Children.Add(slot); g.Children.Add(val);- return g;- }- // Vertical-drag numeric (velocity offset).- Control DragNum(int p, double min, double max, Func<double, string> fmt, double w)- {- var tb = Mono(fmt(G(p)), Sub, 8); tb.Width = w; tb.TextAlignment = TextAlignment.Right; tb.Cursor = new Cursor(StandardCursorType.SizeNorthSouth);- bool drag = false; double sy = 0, sv = 0;- tb.PointerPressed += (_, e) => { drag = true; sy = e.GetPosition(tb).Y; sv = G(p); e.Pointer.Capture(tb); };- tb.PointerMoved += (_, e) => { if (drag) { double dv = (sy - e.GetPosition(tb).Y) / 100.0 * (max - min); S(p, Math.Clamp(sv + dv, min, max)); tb.Text = fmt(G(p)); Refresh(); } };- tb.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- readouts.Add(() => { if (!drag) tb.Text = fmt(G(p)); });- return tb;- }- Control Toggle(int p, string label)- {- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.SemiBold } };- void Sync() { bool on = G(p) >= 0.5f; b.Background = on ? NotaPalette.AccentSubtle : Card; b.BorderBrush = on ? NotaPalette.BorderBrass : Bd; ((TextBlock)b.Child!).Foreground = on ? NotaPalette.AccentHover : Sub; }- b.PointerPressed += (_, _) => { S(p, G(p) >= 0.5f ? 0 : 1); Refresh(); };- readouts.Add(Sync); Sync();- MidiLearn.Bind(b, MidiTarget.MidiDeviceParam(track, mi, p), label);- return b;+ void Edited() { ui.EditTicks = Stopwatch.GetTimestamp(); Refresh(); }+ void S(int p, double v) { engine.MidiEffectSetParam(track, mi, p, (float)v); }+ void SetShift(int s, int st) { S(Voice1 + s, st); S(On1 + s, 1); ui.CustomPinned = false; Edited(); }+ void ApplyType(int i)+ {+ if (Types[i].Shifts is not { } iv) { ui.CustomPinned = true; Edited(); return; }+ for (int s = 0; s < Slots; s++) { S(Voice1 + s, s < iv.Length ? iv[s] : 0); S(On1 + s, s < iv.Length ? 1 : 0); S(Vel1 + s, 0); }+ ui.CustomPinned = false; Edited();}- // Chord-type presets: highlight the template matching the current voices (else Custom).- Control ChordChips()+ int TypeIndex() => ui.CustomPinned ? Types.Length - 1 : MatchType(G);+ int StrumMs() => (int)Math.Round(Math.Clamp(G(Strum), 0, 200));+ string SpreadText() => $"{G(Spread):0} %";++ // ---- live model: the held chord from telemetry, else the preview for the last root -----+ var scope = new float[4 + 2 * (Slots + 1)];+ int root = DefaultRoot, voices = 0;+ var notes = new List<Note>();+ var lit = new List<(int, bool)>();+ void Poll(){- var names = Templates.Select(t => t.name).Append("Custom").ToArray();- var arr = new Border[names.Length];- int MatchIdx()+ int sn = engine.MidiEffectScope(track, mi, scope);+ int lastRoot = sn >= 4 ? (int)scope[0] : -1, held = sn >= 4 ? (int)scope[1] : 0;+ bool bypassed = engine.MidiEffectBypassed(track, mi);+ bool keep = G(KeepRoot) >= 0.5f;+ lit.Clear();+ if (held > 0 && !bypassed && lastRoot >= 0){- var active = Enumerable.Range(0, Voices).Select(Semi).Where(s => s != 0).OrderBy(x => x).ToArray();- for (int i = 0; i < Templates.Length; i++) if (active.SequenceEqual(Templates[i].semis.OrderBy(x => x))) return i;- return Templates.Length; // Custom+ root = lastRoot;+ int n = Math.Min((int)scope[3], (sn - 4) / 2), sounded = (int)scope[2];+ notes = new List<Note>(n);+ for (int i = 0; i < n; i++) { int p = (int)scope[4 + i]; notes.Add(new Note(p, keep && p == root, (int)scope[4 + n + i])); }+ for (int i = 0; i < Math.Min(sounded, n); i++) lit.Add((notes[i].Pitch, notes[i].Played));}- void Hi() { int cur = MatchIdx(); for (int i = 0; i < names.Length; i++) { bool on = i == cur; arr[i].Background = on ? Amber : Brushes.Transparent; ((TextBlock)arr[i].Child!).Foreground = on ? Ink : Muted; } }- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };- for (int i = 0; i < names.Length; i++)+ else{- int iv = i;- var c = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = Muted } };- c.PointerPressed += (_, _) =>+ root = lastRoot >= 0 ? lastRoot : DefaultRoot;+ notes = Compute(G, root);+ int strum = StrumMs();+ double ms = double.PositiveInfinity;+ if (strum > 0 && !bypassed){- if (iv < Templates.Length) { var t = Templates[iv].semis; for (int v = 0; v < Voices; v++) S(Voice1 + v, v < t.Length ? t[v] : 0); }- Refresh();- };- arr[i] = c; row.Children.Add(c);+ double sinceEdit = Stopwatch.GetElapsedTime(ui.EditTicks).TotalMilliseconds;+ if (ui.EditTicks != 0 && sinceEdit < strum * notes.Count + 250) ms = sinceEdit; // replay after an edit+ else if (engine.IsPlaying && engine.Bpm > 0) ms = (engine.PositionBeats % 4.0 + 4.0) % 4.0 * 60000.0 / engine.Bpm; // once per bar+ }+ for (int i = 0; i < notes.Count; i++) if (ms >= i * strum) lit.Add((notes[i].Pitch, notes[i].Played));}- readouts.Add(Hi); Hi();- return new Border { Background = Inset, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = row };- }-- // ---- LIVE strip ----- var strumBlock = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("STRUM"), RawSlider(Strum, 0, 120, v => $"{v:0}\u2009ms", 52, false, 40) } };- var liveL = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("CHORD"), ChordChips(), strumBlock } };- var liveR = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right, Children = { Toggle(KeepRoot, "Keep root"), Toggle(Fold, "Fold in scale") } };- var liveGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };- Grid.SetColumn(liveR, 1); liveGrid.Children.Add(liveL); liveGrid.Children.Add(liveR);- var liveStrip = new Border { Height = 34, Background = HdrBg, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child = liveGrid };-- // ---- SHIFTS stack ----- Control ShiftRow(int v)- {- var dot = new Ellipse { Width = 6, Height = 6, VerticalAlignment = VerticalAlignment.Center };- var lbl = new TextBlock { FontSize = 9, FontWeight = FontWeight.SemiBold, Width = 30, VerticalAlignment = VerticalAlignment.Center };- var semi = RawSlider(Voice1 + v, -24, 24, s => { int i = (int)Math.Round(s); return i == 0 ? "·" : (i > 0 ? "+" : "") + i; }, 0, true, 26);- var vel = DragNum(Vel1 + v, -100, 100, x => { int i = (int)Math.Round(x); return (i >= 0 ? "+" : "") + i; }, 30);- readouts.Add(() => { int s = Semi(v); bool on = s != 0; dot.Fill = on ? Green : Bd; lbl.Text = IntervalLabel(s); lbl.Foreground = on ? Txt : Muted; });- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), ColumnSpacing = 7, VerticalAlignment = VerticalAlignment.Center };- var cells = new Control[] { dot, lbl, semi, vel };- for (int c = 0; c < cells.Length; c++) { Grid.SetColumn(cells[c], c); g.Children.Add(cells[c]); }- return new Border { Background = NotaPalette.BgApp, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 0), Height = 26, Child = g };- }- var shiftHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 11 };- var sh1 = Cap("semitones · velocity"); sh1.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(sh1, 1);- shiftHead.Children.Add(Cap("SHIFTS")); shiftHead.Children.Add(sh1);- var shiftStack = new StackPanel { Spacing = 3 };- shiftStack.Children.Add(shiftHead);- for (int v = 0; v < Voices; v++) shiftStack.Children.Add(ShiftRow(v));- var shiftPanel = new Border { Width = 330, Padding = new Thickness(8, 6), Child = shiftStack };-- // ---- RESULT panel ----- var noteText = Mono("", AmberLit); noteText.HorizontalAlignment = HorizontalAlignment.Right;- var resHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 11 };- Grid.SetColumn(noteText, 1); resHead.Children.Add(Cap("RESULT")); resHead.Children.Add(noteText);- var legend = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children =- {- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { new Border { Width = 8, Height = 8, Background = AmberLit, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center }, Cap("played", Sub) } },- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { new Border { Width = 8, Height = 8, Background = Amber, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center }, Cap("added", Sub) } },- } };- var voicesText = Mono("", Txt);- var voicesRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("VOICES"), voicesText } };- var spreadRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("SPREAD"), RawSlider(Spread, 0, 100, v => $"{v:0}\u2009%", 0, false, 34) } };- var resBottom = new StackPanel { Spacing = 4, Children = { voicesRow, spreadRow } };- var resDock = new DockPanel { LastChildFill = true };- DockPanel.SetDock(resHead, Dock.Top); DockPanel.SetDock(legend, Dock.Top);- DockPanel.SetDock(resBottom, Dock.Bottom);- var keyBox = new Border { Height = 44, Margin = new Thickness(0, 4), Child = keys };- // Docked children first (top: header+legend, bottom: voices/spread), fill (keyboard) last.- resDock.Children.Add(resHead); resDock.Children.Add(legend); resDock.Children.Add(resBottom); resDock.Children.Add(keyBox);- var resPanel = new Border { Background = RailBg, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(9, 6), Child = resDock };-- // result-driven readouts- readouts.Add(() =>- {- var chord = Chord(60);- keys.Set(60, chord);- noteText.Text = string.Join(" ", chord.Select(p => NoteNames[((p % 12) + 12) % 12] + (p / 12 - 2))); // C3 = 60- int active = Enumerable.Range(0, Voices).Count(v => Semi(v) != 0);- voicesText.Text = $"{active} of {Voices}";- });-- var body = new DockPanel { LastChildFill = true };- DockPanel.SetDock(shiftPanel, Dock.Left); body.Children.Add(shiftPanel); body.Children.Add(resPanel);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp };- DockPanel.SetDock(liveStrip, Dock.Top); root.Children.Add(liveStrip); root.Children.Add(body);+ voices = notes.Count;+ }+ int KeyStart() { int lo = notes.Count > 0 ? Math.Min(root, notes[0].Pitch) : root; return (int)Math.Floor(lo / 12.0) * 12; }+ string NoteList() => notes.Count == 0 ? "—" : string.Join(" ", notes.Select(n => DeviceCardKit.NoteName(n.Pitch)));+ int RingPitch() => G(KeepRoot) >= 0.5f ? -1 : root;+ string StatusRight() => engine.MidiEffectBypassed(track, mi) ? "bypassed" : "MIDI · latency 0 smp";+ Poll();+ Control rootView = mini ? BuildMini() : BuildLarge();+ ctx.AddDeviceRefresher(() => { Poll(); Refresh(); });Refresh();- return root;+ return rootView;++ // =========================================================================================+ Control BuildLarge()+ {+ // ---- TYPE ----+ var list = new StackPanel { Margin = new Thickness(0, 3) };+ for (int i = 0; i < Types.Length; i++)+ {+ int ti = i;+ var bar = new Border { Width = 2, Margin = new Thickness(0, 3), HorizontalAlignment = HorizontalAlignment.Left };+ var name = new TextBlock { Text = Types[i].Name, FontSize = 9, VerticalAlignment = VerticalAlignment.Center };+ var hint = Mono(Types[i].Shifts is { } iv ? string.Join(" ", iv.Select(Sgn)) : "", Axis, 7);+ hint.HorizontalAlignment = HorizontalAlignment.Right;+ var rowB = new Border { Height = 18, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new Panel { Children = { bar, new DockPanel { Margin = new Thickness(8, 0), Children = { WithDock(hint, Dock.Right), name } } } } };+ bool hover = false;+ void Paint()+ {+ bool on = TypeIndex() == ti;+ rowB.Background = on ? NotaPalette.AccentSubtle : hover ? NotaPalette.GridBeat : Brushes.Transparent;+ bar.Background = on ? NotaPalette.Accent : Brushes.Transparent;+ name.Foreground = on ? Txt : Sub; name.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ rowB.PointerEntered += (_, _) => { hover = true; Paint(); };+ rowB.PointerExited += (_, _) => { hover = false; Paint(); };+ rowB.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(rowB).Properties.IsLeftButtonPressed) return; ApplyType(ti); ev.Handled = true; };+ ToolTip.SetTip(rowB, Types[i].Shifts is null ? "Custom: your own shifts" : $"{Types[i].Name}: set the shifts to {hint.Text}");+ readouts.Add(Paint);+ list.Children.Add(rowB);+ }+ var flags = new StackPanel { Spacing = 4, Children = { Flag(KeepRoot, "Keep root", "Play the note you pressed as well as the added notes"),+ Flag(Fold, "Fold in scale", "Drop added notes outside the scale a semitone into it") } };+ flags.Children.Add(ScaleLabel());+ var typeFoot = new Border { BorderBrush = Rule, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 6), Child = flags };+ var typeIsland = IslandBox(IslandHead(Caps("TYPE"), null), new DockPanel { Children = { WithDock(typeFoot, Dock.Bottom), list } }, 100);++ // ---- SHIFTS ----+ var rows = new Grid { Margin = new Thickness(6, 5) };+ for (int s = 0; s < Slots; s++)+ {+ rows.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));+ var r = ShiftRow(s); Grid.SetRow(r, s); rows.Children.Add(r);+ }+ var shiftsIsland = IslandBox(IslandHead(Caps("SHIFTS"), Mono("semitones · interval · velocity", Cap, 7)), rows, 292);++ // ---- RESULT ----+ var noteText = Mono("", BrassLit); noteText.FontWeight = FontWeight.Medium;+ var range = Mono("", Axis, 7); range.HorizontalAlignment = HorizontalAlignment.Right;+ var legend = new DockPanel { Children = { WithDock(range, Dock.Right), new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Children =+ {+ Swatch(NotaPalette.AccentBright, null, "played"), Swatch(ChordKeysViz.Added, null, "added"), Swatch(null, NotaPalette.Accent, "root off"),+ } } } };+ var keys = new ChordKeysViz { Labels = true };+ var sliders = new StackPanel { Spacing = 6, Children =+ {+ SliderLine("STRUM", Strum, v => v / 100, n => Math.Round(n * 100), v => $"{v:0} ms"),+ SliderLine("SPREAD", Spread, v => v / 100, n => Math.Round(n * 100), v => $"{v:0} %"),+ } };+ var resBody = new DockPanel { Margin = new Thickness(8, 6), Children =+ {+ WithDock(legend, Dock.Top), WithDock(sliders, Dock.Bottom), new Border { Margin = new Thickness(0, 6), Child = keys },+ } };+ var resultIsland = IslandBox(IslandHead(Caps("RESULT"), noteText), resBody, double.NaN);+ readouts.Add(() =>+ {+ noteText.Text = NoteList();+ int start = KeyStart();+ range.Text = $"{DeviceCardKit.NoteName(start)} – {DeviceCardKit.NoteName(start + 35)}";+ keys.Set(start, lit, RingPitch());+ });++ typeIsland.Margin = new Thickness(0, 0, 5, 0); shiftsIsland.Margin = new Thickness(0, 0, 5, 0);+ var islands = new DockPanel { Children = { WithDock(typeIsland, Dock.Left), WithDock(shiftsIsland, Dock.Left), resultIsland } };++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"In {DeviceCardKit.NoteName(root)} · {Types[TypeIndex()].Name} · {voices} voices · strum {StrumMs()}\u2009ms · spread {SpreadText()}"+ + (G(Fold) >= 0.5f ? $" · fold {ScaleName(G, true)}" : "");+ statusR.Text = StatusRight();+ });+ return Framed(islands, statusL, statusR);+ }++ // =========================================================================================+ Control BuildMini()+ {+ var noteText = Mono("", BrassLit); noteText.FontWeight = FontWeight.Medium;+ var voicesText = Mono("", Cap, 7);+ var head = new DockPanel { Height = 12, Children = { WithDock(voicesText, Dock.Right), noteText } };+ var keys = new ChordKeysViz { Labels = false, KeyRadius = 0, Height = 40 };++ var bars = new Grid { ColumnSpacing = 3 };+ for (int s = 0; s < Slots; s++)+ {+ bars.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));+ var c = ShiftColumn(s); Grid.SetColumn(c, s); bars.Children.Add(c);+ }++ var knobs = new Grid { Height = 53, ColumnDefinitions = new ColumnDefinitions("*,*,78") };+ var strum = KnobCell("STRUM", Strum, () => G(Strum) / 100, n => S(Strum, Math.Round(n * 100)), () => $"{StrumMs()} ms");+ var spread = KnobCell("SPREAD", Spread, () => G(Spread) / 100, n => S(Spread, Math.Round(n * 100)), SpreadText);+ var flags = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children =+ {+ Flag(KeepRoot, "Keep root", "Play the note you pressed as well as the added notes"),+ Flag(Fold, "Fold in scale", $"Drop added notes outside {ScaleName(G, false)} a semitone into it"),+ } };+ Grid.SetColumn(spread, 1); Grid.SetColumn(flags, 2);+ knobs.Children.Add(strum); knobs.Children.Add(spread); knobs.Children.Add(flags);++ var inner = new DockPanel { Children =+ {+ WithDock(head, Dock.Top), WithDock(new Border { Margin = new Thickness(0, 4), Child = keys }, Dock.Top),+ WithDock(knobs, Dock.Bottom), bars,+ } };+ var island = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,+ Padding = new Thickness(6, 5, 6, 0), Child = inner };+ readouts.Add(() =>+ {+ noteText.Text = NoteList();+ voicesText.Text = $"{voices} of {Slots + 1}";+ keys.Set(KeyStart(), lit, RingPitch());+ });++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"In {DeviceCardKit.NoteName(root)} · {Types[TypeIndex()].Name} · {voices} voices";+ statusR.Text = engine.MidiEffectBypassed(track, mi) ? "bypassed" : $"strum {StrumMs()}\u2009ms";+ });+ return Framed(island, statusL, statusR);+ }++ // ---- shared pieces -----------------------------------------------------------------------+ Control Framed(Control main, TextBlock left, TextBlock right)+ {+ var status = new Border { Height = 18, Background = Well, BorderBrush = Bd, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0),+ Child = new DockPanel { Children = { WithDock(right, Dock.Right), left } } };+ right.Margin = new Thickness(8, 0, 0, 0);+ return new DockPanel { Background = Ground, Children = { WithDock(status, Dock.Bottom), new Border { Padding = new Thickness(5), Child = main } } };+ }++ Control IslandHead(Control left, Control? right)+ {+ var d = new DockPanel { Margin = new Thickness(8, 0) };+ if (right is not null) { right.HorizontalAlignment = HorizontalAlignment.Right; d.Children.Add(WithDock(right, Dock.Right)); }+ d.Children.Add(left);+ return new Border { Height = 20, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Child = d };+ }++ Border IslandBox(Control head, Control content, double width)+ {+ var b = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true,+ Child = new DockPanel { Children = { WithDock(head, Dock.Top), content } } };+ if (!double.IsNaN(width)) b.Width = width;+ return b;+ }++ Control Swatch(IBrush? fill, IBrush? ring, string label)+ {+ var sw = new Border { Width = 7, Height = 7, CornerRadius = NotaRadius.Clip, Background = fill, BorderBrush = ring,+ BorderThickness = new Thickness(ring is null ? 0 : 1), VerticalAlignment = VerticalAlignment.Center };+ return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { sw, new TextBlock { Text = label, FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center } } };+ }++ // A switch flag (Keep root / Fold in scale), brass-washed when on.+ Control Flag(int p, string label, string tip)+ {+ var tb = new TextBlock { Text = label, FontSize = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ S(p, G(p) >= 0.5f ? 0 : 1); Edited(); ev.Handled = true;+ };+ ToolTip.SetTip(b, tip);+ Learn(b, p, label);+ readouts.Add(() =>+ {+ bool on = G(p) >= 0.5f;+ b.Background = on ? NotaPalette.AccentSubtle : NotaPalette.TrackOff;+ b.BorderBrush = on ? NotaPalette.BorderBrass : NotaPalette.TrackOff;+ tb.Foreground = on ? NotaPalette.AccentHover : Txt;+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ });+ return b;+ }++ // "scale C major": click the key for the next one (Shift = previous, wheel scrolls), the mode to flip it.+ Control ScaleLabel()+ {+ var keyTb = Mono("", Axis, 7); var modeTb = Mono("", Axis, 7);+ keyTb.Cursor = modeTb.Cursor = new Cursor(StandardCursorType.Hand);+ void StepKey(int d) { S(FoldKey, ((GI(FoldKey) + d) % 12 + 12) % 12); Edited(); }+ keyTb.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(keyTb).Properties.IsLeftButtonPressed) return;+ StepKey(ev.KeyModifiers.HasFlag(KeyModifiers.Shift) ? -1 : 1); ev.Handled = true;+ };+ keyTb.PointerWheelChanged += (_, ev) => { StepKey(ev.Delta.Y > 0 ? 1 : -1); ev.Handled = true; };+ modeTb.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(modeTb).Properties.IsLeftButtonPressed) return;+ S(FoldMode, G(FoldMode) >= 0.5f ? 0 : 1); Edited(); ev.Handled = true;+ };+ ToolTip.SetTip(keyTb, "Fold key — click for the next, Shift-click for the previous");+ ToolTip.SetTip(modeTb, "Fold scale — major / natural minor");+ Learn(keyTb, FoldKey, "Fold Key"); Learn(modeTb, FoldMode, "Fold Mode");+ readouts.Add(() =>+ {+ var ink = G(Fold) >= 0.5f ? Sub : Axis;+ keyTb.Text = KeyNames[((GI(FoldKey)) % 12 + 12) % 12]; modeTb.Text = G(FoldMode) >= 0.5f ? "minor" : "major";+ keyTb.Foreground = modeTb.Foreground = ink;+ });+ return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, HorizontalAlignment = HorizontalAlignment.Center,+ Children = { Mono("scale", Axis, 7), keyTb, modeTb } };+ }++ // One SHIFTS row: switch dot · semitones · ±12 ruler · interval · velocity offset.+ Control ShiftRow(int s)+ {+ int pSt = Voice1 + s, pOn = On1 + s, pVel = Vel1 + s;+ var dot = new Ellipse { Width = 6, Height = 6 };+ var dotHit = new Border { Width = 14, Height = 14, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = dot };+ dotHit.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(dotHit).Properties.IsLeftButtonPressed) return;+ S(pOn, G(pOn) >= 0.5f ? 0 : 1); ui.CustomPinned = false; Edited(); ev.Handled = true;+ };+ ToolTip.SetTip(dotHit, $"Shift {s + 1} on / off");+ Learn(dotHit, pOn, $"Shift {s + 1} on");+ var st = Mono("", Txt, 9); st.FontWeight = FontWeight.SemiBold; st.Width = 24;+ var ruler = new ChordShiftTrack { Height = 14, Margin = new Thickness(0, 0, 2, 0) };+ ruler.Changed += v => SetShift(s, v);+ ruler.GestureBegin += () => { Begin(pSt); Begin(pOn); }; ruler.GestureEnd += () => { End(pSt); End(pOn); };+ Learn(ruler, pSt, $"Shift {s + 1}");+ var iv = Mono("", Sub); iv.Width = 22; iv.TextAlignment = TextAlignment.Center;+ var vel = VelDrag(pVel, s);+ var g = new DockPanel { Children = { WithDock(dotHit, Dock.Left), WithDock(st, Dock.Left), WithDock(vel, Dock.Right), WithDock(iv, Dock.Right), ruler } };+ st.Margin = new Thickness(6, 0, 6, 0); iv.Margin = new Thickness(6, 0, 6, 0);+ var row = new Border { Height = 24, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(5, 0, 7, 0),+ VerticalAlignment = VerticalAlignment.Center, Child = g };+ readouts.Add(() =>+ {+ bool on = G(pOn) >= 0.5f; int v = GI(pSt);+ row.Background = on ? Ground : NotaPalette.GridRow;+ row.BorderBrush = on ? Bd : NotaPalette.GridBeat;+ dot.Fill = on ? NotaPalette.Accent : NotaPalette.BorderStrong;+ st.Text = on ? Sgn(v) : "off"; st.Foreground = on ? Txt : NotaPalette.TextDisabled;+ iv.Text = on ? IntervalName(v) : "·"; iv.Foreground = on ? Sub : NotaPalette.BorderStrong;+ if (!ruler.Dragging) ruler.Value = v;+ ruler.On = on;+ });+ return row;+ }++ // Velocity offset: drag sideways (2px per step), double-click resets.+ Control VelDrag(int p, int s)+ {+ var tb = Mono("", Cap); tb.Width = 28; tb.TextAlignment = TextAlignment.Right;+ var hit = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeWestEast), Child = tb, VerticalAlignment = VerticalAlignment.Stretch };+ bool drag = false; double x0 = 0; int v0 = 0;+ hit.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(hit).Properties.IsLeftButtonPressed) return;+ ev.Handled = true;+ if (ev.ClickCount == 2) { Begin(p); S(p, 0); End(p); Edited(); return; }+ drag = true; x0 = ev.GetPosition(hit).X; v0 = GI(p); ev.Pointer.Capture(hit); Begin(p);+ };+ hit.PointerMoved += (_, ev) =>+ {+ if (!drag) return;+ int v = Math.Clamp((int)Math.Round(v0 + (ev.GetPosition(hit).X - x0) / 2), -64, 63);+ if (v != GI(p)) { S(p, v); ui.CustomPinned = true; Refresh(); }+ };+ void Stop() { if (!drag) return; drag = false; End(p); Edited(); }+ hit.PointerReleased += (_, ev) => { if (drag) ev.Pointer.Capture(null); Stop(); };+ hit.PointerCaptureLost += (_, _) => Stop();+ ToolTip.SetTip(hit, $"Shift {s + 1} velocity offset — drag sideways, double-click resets");+ Learn(hit, p, $"Shift {s + 1} velocity");+ readouts.Add(() => { int v = GI(p); tb.Text = Sgn(v); tb.Foreground = v != 0 ? BrassLit : Cap; });+ return hit;+ }++ // A mini-view shift: a vertical ±12 bar over its number (click the number to switch it).+ Control ShiftColumn(int s)+ {+ int pSt = Voice1 + s, pOn = On1 + s;+ var bar = new ChordShiftTrack { Vertical = true };+ bar.Changed += v => SetShift(s, v);+ bar.GestureBegin += () => { Begin(pSt); Begin(pOn); }; bar.GestureEnd += () => { End(pSt); End(pOn); };+ Learn(bar, pSt, $"Shift {s + 1}");+ ToolTip.SetTip(bar, $"Shift {s + 1}: drag up / down (±12 semitones)");+ var lbl = Mono("", Txt); lbl.HorizontalAlignment = HorizontalAlignment.Center;+ var lblHit = new Border { Height = 11, Margin = new Thickness(0, 2, 0, 0), Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = lbl };+ bool hover = false;+ lblHit.PointerEntered += (_, _) => { hover = true; Refresh(); };+ lblHit.PointerExited += (_, _) => { hover = false; Refresh(); };+ lblHit.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(lblHit).Properties.IsLeftButtonPressed) return;+ S(pOn, G(pOn) >= 0.5f ? 0 : 1); ui.CustomPinned = false; Edited(); ev.Handled = true;+ };+ Learn(lblHit, pOn, $"Shift {s + 1} on");+ readouts.Add(() =>+ {+ bool on = G(pOn) >= 0.5f; int v = GI(pSt);+ if (!bar.Dragging) bar.Value = v;+ bar.On = on;+ lbl.Text = on ? Sgn(v) : "off";+ lbl.Foreground = hover ? Txt : on ? Txt : NotaPalette.TextDisabled;+ });+ return new DockPanel { Children = { WithDock(lblHit, Dock.Bottom), bar } };+ }++ // A RESULT slider: the label brightens to brass once moved off its default.+ Control SliderLine(string label, int p, Func<double, double> toNorm, Func<double, double> fromNorm, Func<double, string> fmt)+ {+ var l = Caps(label); l.Width = 40;+ var val = Mono("", Txt); val.Width = 34; val.TextAlignment = TextAlignment.Right;+ var track = new SliderTrack { Height = 11, Reset = () => { S(p, Def(p)); Edited(); } };+ track.Changed += n => { S(p, fromNorm(n)); Refresh(); };+ track.GestureBegin += () => Begin(p);+ track.GestureEnd += () => { End(p); Edited(); };+ Learn(track, p, label);+ readouts.Add(() =>+ {+ double v = G(p);+ if (!track.Dragging) track.Norm = toNorm(v);+ bool mod = Math.Abs(v - Def(p)) > 0.5;+ l.Foreground = mod ? BrassLit : Cap;+ val.Foreground = mod ? BrassLit : Txt;+ val.Text = fmt(v);+ });+ track.Margin = new Thickness(6, 0, 6, 0);+ return new DockPanel { Children = { WithDock(l, Dock.Left), WithDock(val, Dock.Right), track } };+ }++ // A mini-view knob: 34px gauge, caps label, mono value.+ Control KnobCell(string label, int p, Func<double> norm, Action<double> set, Func<string> text)+ {+ var knob = new Knob(norm(), 1.0) { Accent = true, Width = 34, Height = 34, HorizontalAlignment = HorizontalAlignment.Center };+ knob.ValueChanged += n => { set(n); Refresh(); };+ knob.GestureBegin += () => Begin(p);+ knob.GestureEnd += () => { End(p); Edited(); };+ Learn(knob, p, label);+ var val = Mono("", Sub, 7); val.HorizontalAlignment = HorizontalAlignment.Center;+ readouts.Add(() => { double n = norm(); if (!knob.Dragging && Math.Abs(knob.Value - n) > 1e-6) knob.Value = n; val.Text = text(); });+ return new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.SizeNorthSouth),+ Children = { knob, new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.6, Foreground = Cap, HorizontalAlignment = HorizontalAlignment.Center, LineHeight = 9 }, val } };+ }}}diff --git a/src/managed/Nota.App/DeviceCards/Midi/IMidiDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Midi/IMidiDeviceBody.csindex d4bccb12..48b73e39 100644--- a/src/managed/Nota.App/DeviceCards/Midi/IMidiDeviceBody.cs+++ b/src/managed/Nota.App/DeviceCards/Midi/IMidiDeviceBody.cs@@ -13,6 +13,14 @@ internal interface IMidiDeviceBody{double Width { get; }+ /// <summary>The card width for this device instance — a body with a size toggle (Nota+ /// Arp S / L) reads its own state. Default: <see cref="Width"/>.</summary>+ double WidthFor(Nota.Application.IAudioEngine engine, int trackId, int index) => Width;++ /// <summary>Optional controls shown in the shell header, left of the bypass switch+ /// (Nota Arp: MIDI Learn · tempo · the S / L size toggle). Default: none.</summary>+ Control? HeaderAccessory(DeviceCardContext ctx, int index) => null;+/// <summary>When true the body manages its own padding (e.g. a full-width LIVE strip)/// and the shell wraps it with no inset. Default false = the shell pads the body 8px.</summary>bool FullBleed => false;diff --git a/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.cs b/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.csnew file mode 100644index 00000000..8fb4620e--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.cs@@ -0,0 +1,51 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Shell-header pieces shared by the MIDI-effect cards that come in two sizes (Nota Arp,+// Nota Chord): the MIDI Learn button that mirrors the transport's Learn toggle, and the+// S / L size toggle bound to the device's "View" param (0 = L, 1 = S).++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;++namespace Nota.App;++internal static class MidiCardHeader+{+ public static Control LearnButton(DeviceCardContext ctx)+ {+ var tb = new TextBlock { Text = "MIDI Learn", FontSize = 8, VerticalAlignment = VerticalAlignment.Center };+ var learn = new Border { Height = 16, CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 0), BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ ToolTip.SetTip(learn, "Map a hardware control: arm, touch a control on the card, move a knob or key");+ void Sync()+ {+ bool on = TopLevel.GetTopLevel(learn) is MainWindow w && w.MidiLearnArmed;+ learn.Background = on ? NotaPalette.AccentSubtle : NotaPalette.TrackOff;+ learn.BorderBrush = on ? NotaPalette.BorderBrass : NotaPalette.TrackOff;+ tb.Foreground = on ? NotaPalette.AccentHover : NotaPalette.TextPrimary;+ }+ learn.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(learn).Properties.IsLeftButtonPressed) return;+ ev.Handled = true;+ if (TopLevel.GetTopLevel(learn) is MainWindow w) w.ToggleMidiLearn();+ Sync();+ };+ ctx.AddDeviceRefresher(Sync);+ learn.AttachedToVisualTree += (_, _) => Sync();+ return learn;+ }++ public static Control SizeToggle(DeviceCardContext ctx, int index, int viewParam, Func<bool> isMini)+ {+ var e = ctx.Engine; int t = ctx.TrackId;+ var size = DeviceCardKit.Segments(new[] { "S", "L" }, () => isMini() ? 0 : 1,+ i => { e.MidiEffectSetParam(t, index, viewParam, i == 0 ? 1f : 0f); ctx.RequestRebuild(); }, out _, padX: 0, minSegWidth: 16, fontSize: 8);+ ToolTip.SetTip(size, "Card size: S (mini) / L (full)");+ return size;+ }+}diff --git a/src/managed/Nota.App/DeviceChainView.Midi.cs b/src/managed/Nota.App/DeviceChainView.Midi.csindex 8035613d..d33fd078 100644--- a/src/managed/Nota.App/DeviceChainView.Midi.cs+++ b/src/managed/Nota.App/DeviceChainView.Midi.cs@@ -19,10 +19,13 @@ public sealed partial class DeviceChainViewstring name = _engine.MidiEffectName(_trackId, index);int kind = _engine.MidiEffectKind(_trackId, index);var body = _midiFactory.Resolve(kind);+ var ctx = NewCardContext();+ double width = body.WidthFor(_engine, _trackId, index);var spec = new ShellSpec(Name: name, Subtitle: "MIDI", DeviceIndex: index, Count: count, Bypassed: bypassed, Bypassable: true,- CanMove: true, CanDelete: true, PresetKind: kind, IsInstrument: false, Width: body.Width, Kind: ChainKind.Midi);- var content = body.Build(NewCardContext(), index);+ CanMove: true, CanDelete: true, PresetKind: kind, IsInstrument: false, Width: width, Kind: ChainKind.Midi,+ HeaderExtra: body.HeaderAccessory(ctx, index), Compact: width < 300);+ var content = body.Build(ctx, index);return BuildCardShell(spec, body.FullBleed ? content : new Border { Padding = new Thickness(NotaSpace.DeviceInset), Child = content });}}diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.csindex 1dc57a07..0f474d18 100644--- a/src/managed/Nota.App/DeviceChainView.Shell.cs+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs@@ -91,7 +91,7 @@ public sealed partial class DeviceChainViewstring Name, string Subtitle, int DeviceIndex, int Count, bool Bypassed, bool Bypassable,bool CanMove, bool CanDelete, int PresetKind, bool IsInstrument, double Width, ChainKind Kind,Func<Nota.Application.IAudioEngine, int, int, string?>? VoiceLabel = null,- CardPresets? Presets = null);+ CardPresets? Presets = null, Control? HeaderExtra = null, bool Compact = false); // Compact: a mini card — no type badge, a narrower preset picker/// <summary>A card's own preset list, in place of the factory presets for its kind — the/// Drum Rack's kits, which load pads rather than set parameters. <paramref name="Current"/>@@ -115,7 +115,8 @@ public sealed partial class DeviceChainView// a new slot; Delete removes the selected card.var name = new TextBlock{- Text = s.Name, FontSize = NotaType.DeviceName, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary,+ // A compact card drops the family prefix ("Nota Arp" → "Arp") to leave room for the presets.+ Text = s.Compact && s.Name.StartsWith("Nota ", StringComparison.Ordinal) ? s.Name[5..] : s.Name, FontSize = NotaType.DeviceName, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary,VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,};@@ -139,7 +140,8 @@ public sealed partial class DeviceChainViewbadge.Text = type.Length > 0 ? $"{type} · {voices}" : voices;});}- if (badge.Text.Length > 0 || s.IsInstrument) right.Children.Add(badge);+ if ((badge.Text.Length > 0 || s.IsInstrument) && !s.Compact) right.Children.Add(badge);+ if (s.HeaderExtra is { } headerExtra) right.Children.Add(headerExtra);if (s.Bypassable){@@ -200,7 +202,10 @@ public sealed partial class DeviceChainViewint n = presets.Count; if (n == 0) return;ApplyPreset(curPreset < 0 ? (dir > 0 ? 0 : n - 1) : ((curPreset + dir) % n + n) % n);}- if (presets.Count > 0) right.Children.Insert(0, PresetPicker(presets.Select(p => p.Name).ToList(), curPreset, extra.Preset, ApplyPreset, StepPreset));+ // A compact (mini) card keeps the same picker — same list, same current preset — only narrower:+ // the preset belongs to the device, not to the card size.+ if (presets.Count > 0) right.Children.Insert(0, PresetPicker(presets.Select(p => p.Name).ToList(), curPreset, extra.Preset, ApplyPreset, StepPreset,+ nameWidth: s.Compact ? 78 : 132));void Move(int to) { if (s.Kind == ChainKind.Midi) _engine.MoveMidiEffect(_trackId, di, to); else _engine.MoveDevice(_trackId, di, to); ExtrasMoved(s.Kind, di, to); Rebuild(); Changed?.Invoke(); }diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 5ba467d0..ea79bb90 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -578,6 +578,17 @@ public partial class MainWindow : Windowif (_vm is not null) _vm.StatusText = on ? "Snap on" : "Snap off — clips position freely";}+ /// <summary>Whether MIDI Learn is armed — device cards with their own Learn button+ /// (Nota Arp) mirror it.</summary>+ internal bool MidiLearnArmed => _learn?.Armed == true;++ /// <summary>Flip MIDI Learn exactly as the transport-bar button does.</summary>+ internal void ToggleMidiLearn()+ {+ MidiLearnBtn.IsChecked = MidiLearnBtn.IsChecked != true;+ OnToggleMidiLearn(MidiLearnBtn, new RoutedEventArgs());+ }+// MIDI Learn: arm/disarm the overlay and reveal the mappings tab so the user// can see what they're binding.private void OnToggleMidiLearn(object? sender, RoutedEventArgs e)diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 8cc27cd1..0fb7977c 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -410,6 +410,8 @@ public interface IAudioEngine : IDisposableint MidiEffectLastOut(int trackId, int index);/// <summary>Float scope buffer for a MIDI effect editor (Nota Velocity in/out pairs); returns count written.</summary>int MidiEffectScope(int trackId, int index, float[] outv);+ /// <summary>Send an editor command to a MIDI effect (Nota Arp: 1 = restart the pattern).</summary>+ void MidiEffectCommand(int trackId, int index, int cmd);string MidiEffectName(int trackId, int index);int MidiEffectParamCount(int trackId, int index);string MidiEffectParamName(int trackId, int index, int paramIndex);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.csindex ba5b9145..79c38a5b 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs@@ -103,6 +103,9 @@ internal static partial class NativeMethodsinternal static partial int MidiEffectLastOut(IntPtr engine, int trackId, int index);[LibraryImport(Lib, EntryPoint = "nota_midi_effect_scope")]internal static partial int MidiEffectScope(IntPtr engine, int trackId, int index, [Out] float[] outv, int maxN);++ [LibraryImport(Lib, EntryPoint = "nota_midi_effect_command")]+ internal static partial void MidiEffectCommand(IntPtr engine, int trackId, int index, int cmd);[LibraryImport(Lib, EntryPoint = "nota_midi_effect_name")]internal static partial IntPtr MidiEffectName(IntPtr engine, int trackId, int index);[LibraryImport(Lib, EntryPoint = "nota_midi_effect_param_count")]diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.csindex af03db44..2548e8e4 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs@@ -143,6 +143,7 @@ public sealed partial class NotaEnginepublic int MidiEffectLastIn(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectLastIn(_handle, trackId, index); }public int MidiEffectLastOut(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectLastOut(_handle, trackId, index); }public int MidiEffectScope(int trackId, int index, float[] outv) { ThrowIfDisposed(); return NativeMethods.MidiEffectScope(_handle, trackId, index, outv, outv.Length); }+ public void MidiEffectCommand(int trackId, int index, int cmd) { ThrowIfDisposed(); NativeMethods.MidiEffectCommand(_handle, trackId, index, cmd); }public string MidiEffectName(int trackId, int index) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiEffectName(_handle, trackId, index)) ?? ""; }public int MidiEffectParamCount(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectParamCount(_handle, trackId, index); }public string MidiEffectParamName(int trackId, int index, int paramIndex) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiEffectParamName(_handle, trackId, index, paramIndex)) ?? ""; }diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex 88eb0dd0..554a9921 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -8,6 +8,7 @@// (param names). Apply reuses PresetService.Apply — the same path as user presets.using System.Collections.Generic;+using System.Linq;using Nota.Application;namespace Nota.Infrastructure;@@ -2111,26 +2112,92 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsFx("strata", 15, "Reverse Tape", ("Feedback", 90f), ("InputGain", 0f), ("Speed", 1f), ("Quantize", 1f), ("CountIn", 0f), ("SetTempo", 0f), ("Reverse", 1f));Fx("strata", 15, "Free Overdub", ("Feedback", 100f), ("InputGain", 0f), ("Speed", 1f), ("Quantize", 0f), ("CountIn", 0f), ("SetTempo", 0f), ("Reverse", 0f));- // ---- Nota Arp (MIDI, kind 0) — Rate idx (5=1/16, 6=1/16T); Order 0 Up/1 Down/- // 2 UpDown/3 Converge/4 AsPlayed/5 Chord/6 Random; OctMode/LoopMode 0..3.- Midi("arp", 0, "Up 1/16", ("Rate", 5f), ("Order", 0f), ("Octaves", 1f), ("Gate", 0.9f), ("Loop", 16f));- Midi("arp", 0, "Octave Up-Down",("Rate", 5f), ("Order", 2f), ("Octaves", 2f), ("OctMode", 2f), ("Gate", 0.85f));- Midi("arp", 0, "Triplet Roll", ("Rate", 6f), ("Order", 0f), ("Octaves", 1f), ("Gate", 0.8f));- Midi("arp", 0, "Trance Gate", ("Rate", 5f), ("Order", 5f), ("Gate", 0.5f), ("Loop", 16f),- ("On 2", 0f), ("On 4", 0f), ("On 6", 0f), ("On 8", 0f),- ("On 10", 0f), ("On 12", 0f), ("On 14", 0f), ("On 16", 0f));- Midi("arp", 0, "Random Walk", ("Rate", 5f), ("Order", 6f), ("Octaves", 2f), ("OctMode", 3f), ("LoopMode", 3f), ("Gate", 0.8f));- Midi("arp", 0, "Ratchet Build", ("Rate", 5f), ("Order", 0f), ("Octaves", 1f), ("Gate", 0.9f), ("Loop", 8f),- ("Rat 1", 1f), ("Rat 2", 1f), ("Rat 3", 2f), ("Rat 4", 2f),- ("Rat 5", 3f), ("Rat 6", 3f), ("Rat 7", 4f), ("Rat 8", 4f));-- // ---- Nota Chord (MIDI, kind 1) — Voice N semitone offsets (0 = off) + Strum/Spread/Fold- Midi("chord", 1, "Major Triad", ("Voice 1", 4f), ("Voice 2", 7f));- Midi("chord", 1, "Minor Triad", ("Voice 1", 3f), ("Voice 2", 7f));- Midi("chord", 1, "Power Chord", ("Voice 1", 7f), ("Voice 2", 12f));- Midi("chord", 1, "Octaves", ("Voice 1", 12f), ("Voice 2", -12f));- Midi("chord", 1, "Maj7 Wide", ("Voice 1", 4f), ("Voice 2", 7f), ("Voice 3", 11f), ("Voice 4", 16f), ("Spread", 40f));- Midi("chord", 1, "Strummed Guitar", ("Voice 1", 7f), ("Voice 2", 12f), ("Voice 3", 16f), ("Voice 4", 19f), ("Strum", 22f), ("Vel 4", -20f));+ // ---- Nota Arp (MIDI, kind 0) — Rate idx 0 1/1 … 3 1/8, 4 1/8T, 5 1/16, 6 1/16T, 7 1/32;+ // Order 0 Up/1 Down/2 Up·Down/3 Converge/4 As played/5 Chord/6 Random/7 Down·Up/+ // 8 Diverge; Retrig 0 Off/1 Note/2 Beat (bar); OctMode/LoopMode 0..3; Gate 0..2;+ // FreeRate in Hz. Groove lanes per step: vel/chn 0..1, len 0..2, rat 1..8, trn ±24,+ // steps = "x" on / "." muted. Unlisted params reset to their defaults.+ Arp("Up 1/16", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.9f });+ Arp("Down 1/8", new() { ["Rate"] = 3, ["Order"] = 1, ["Octaves"] = 2, ["Gate"] = 0.8f });+ Arp("Octave Up-Down", new() { ["Rate"] = 5, ["Order"] = 2, ["Octaves"] = 2, ["Gate"] = 0.85f });+ Arp("Down-Up Cascade", new() { ["Rate"] = 5, ["Order"] = 7, ["Octaves"] = 3, ["Gate"] = 0.7f });+ Arp("Converge", new() { ["Rate"] = 5, ["Order"] = 3, ["Octaves"] = 2, ["Gate"] = 0.8f });+ Arp("Diverge Bloom", new() { ["Rate"] = 6, ["Order"] = 8, ["Octaves"] = 2, ["Gate"] = 1.2f });+ Arp("As Played Hook", new() { ["Rate"] = 5, ["Order"] = 4, ["Octaves"] = 1, ["Gate"] = 0.6f, ["Retrig"] = 1 });+ Arp("Triplet Roll", new() { ["Rate"] = 6, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.8f });+ Arp("Trance Gate", new() { ["Rate"] = 5, ["Order"] = 5, ["Gate"] = 0.5f }, steps: "x.x.x.x.x.x.x.x.");+ Arp("House Offbeat Stab", new() { ["Rate"] = 3, ["Order"] = 5, ["Gate"] = 0.35f, ["Loop"] = 8 }, steps: ".x.x.x.x");+ Arp("Random Walk", new() { ["Rate"] = 5, ["Order"] = 6, ["Octaves"] = 2, ["OctMode"] = 3, ["LoopMode"] = 3, ["Gate"] = 0.8f });+ Arp("Ratchet Build", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.9f, ["Loop"] = 8 },+ rat: new[] { 1, 1, 2, 2, 3, 3, 4, 4 });+ Arp("Swing Groove", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 2, ["Gate"] = 0.7f, ["Swing"] = 0.6f },+ vel: new[] { 1f, .55f, .75f, .55f, 1f, .55f, .75f, .6f, 1f, .55f, .75f, .55f, 1f, .6f, .8f, .65f });+ Arp("Staccato Pluck", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 2, ["Gate"] = 0.25f });+ Arp("Legato Glide", new() { ["Rate"] = 4, ["Order"] = 2, ["Octaves"] = 2, ["Gate"] = 1.6f });+ Arp("Octave Jumper", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.6f },+ trn: new[] { 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12 });+ Arp("Fifth Echo", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.7f, ["Loop"] = 8 },+ trn: new[] { 0, 0, 7, 0, 12, 0, 7, 0 }, vel: new[] { 1f, .6f, .8f, .6f, .9f, .6f, .8f, .5f });+ Arp("Chance Sparkle", new() { ["Rate"] = 7, ["Order"] = 6, ["Octaves"] = 3, ["Gate"] = 0.5f },+ chn: new[] { 1f, .4f, .7f, .4f, .9f, .3f, .6f, .5f, 1f, .4f, .7f, .3f, .8f, .5f, .6f, .4f });+ Arp("Velocity Accents", new() { ["Rate"] = 5, ["Order"] = 2, ["Octaves"] = 2, ["Gate"] = 0.75f, ["VelAmt"] = 1 },+ vel: new[] { 1f, .35f, .5f, .35f, .85f, .35f, .5f, .35f, 1f, .35f, .5f, .35f, .85f, .35f, .6f, .45f });+ Arp("Ratchet Rolls", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 2, ["Gate"] = 0.8f },+ rat: new[] { 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 3, 4 });+ Arp("Slow Chord Pad", new() { ["Rate"] = 1, ["Order"] = 5, ["Octaves"] = 1, ["Gate"] = 1.9f });+ Arp("Stutter 1/32", new() { ["Rate"] = 7, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.5f, ["Loop"] = 4 });+ Arp("Bar Retrig Riff", new() { ["Rate"] = 5, ["Order"] = 2, ["Octaves"] = 2, ["Gate"] = 0.7f, ["Retrig"] = 2, ["Loop"] = 12 });+ Arp("Free Run 150 ms", new() { ["Sync"] = 0, ["FreeRate"] = 6.667f, ["Order"] = 0, ["Octaves"] = 2, ["Gate"] = 0.8f });+ Arp("Four-Octave Rise", new() { ["Rate"] = 6, ["Order"] = 0, ["Octaves"] = 4, ["Gate"] = 0.6f });+ Arp("Hold Drone", new() { ["Rate"] = 4, ["Order"] = 3, ["Octaves"] = 2, ["Gate"] = 0.9f, ["Hold"] = 1 });+ Arp("Ping-Pong Steps", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 2, ["Gate"] = 0.9f, ["Loop"] = 8, ["LoopMode"] = 2 },+ len: new[] { 1f, .3f, .6f, .3f, 1f, .3f, .8f, .4f });+ Arp("Ghost Notes", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.6f },+ vel: new[] { 1f, .2f, .2f, .7f, .2f, .2f, .9f, .2f, 1f, .2f, .2f, .7f, .2f, .2f, .8f, .25f },+ chn: new[] { 1f, .6f, .6f, 1f, .6f, .6f, 1f, .6f, 1f, .6f, .6f, 1f, .6f, .6f, 1f, .6f });+ Arp("Minimal Techno", new() { ["Rate"] = 5, ["Order"] = 1, ["Octaves"] = 1, ["Gate"] = 0.4f }, steps: "x..x..x.x..x..x.",+ len: new[] { .5f, 1f, 1f, .4f, 1f, 1f, .6f, 1f, .5f, 1f, 1f, .4f, 1f, 1f, .7f, 1f });+ Arp("Trap Roll", new() { ["Rate"] = 5, ["Order"] = 0, ["Octaves"] = 1, ["Gate"] = 0.6f },+ rat: new[] { 1, 1, 2, 1, 1, 1, 3, 1, 1, 2, 1, 1, 4, 1, 2, 3 },+ vel: new[] { 1f, .6f, .7f, .6f, .9f, .6f, .7f, .6f, 1f, .7f, .6f, .6f, .9f, .6f, .75f, .8f });++ // ---- Nota Chord (MIDI, kind 1) — up to six shifts (−12..+12 st, each switched on), optional+ // velocity offsets (MIDI units), Strum ms 0..100, Spread % (⅓ = every other shift up an+ // octave, ⅔ = all of them), Keep Root, Fold into a key (0 C … 11 B, major / minor).+ Chord("Major Triad", new[] { 4, 7 });+ Chord("Minor Triad", new[] { 3, 7 });+ Chord("Maj7", new[] { 4, 7, 11 }, strum: 30);+ Chord("Min7", new[] { 3, 7, 10 }, strum: 30);+ Chord("Dominant 7", new[] { 4, 7, 10 });+ Chord("Sus2", new[] { 2, 7 });+ Chord("Sus4", new[] { 5, 7 });+ Chord("Power Chord", new[] { 7, 12 });+ Chord("Octaves", new[] { 12, -12 });+ Chord("Sixth", new[] { 4, 7, 9 });+ Chord("Minor 6", new[] { 3, 7, 9 });+ Chord("Diminished 7", new[] { 3, 6, 9 });+ Chord("Half-Diminished", new[] { 3, 6, 10 });+ Chord("Augmented", new[] { 4, 8 });+ Chord("Maj7 Wide", new[] { 4, 7, 11, 12 }, spread: 40);+ Chord("Add9 Open", new[] { 4, 7, 2 }, spread: 40);+ Chord("Min9 Open", new[] { 10, 3, 7, 2 }, spread: 40, strum: 20);+ Chord("Neo-Soul m11", new[] { 3, 7, 10, 5 }, spread: 40, strum: 45, vel: new[] { -6, -10, -14, -18 });+ Chord("Rootless Maj9", new[] { -10, 4, 7, 11 }, keepRoot: false);+ Chord("Rootless Dom9", new[] { -10, 4, 7, 10 }, keepRoot: false);+ Chord("Quartal", new[] { -7, 5, 10 });+ Chord("Stacked Fifths", new[] { -12, -5, 7 });+ Chord("Organ Drawbars", new[] { -12, 7, 12 }, vel: new[] { -10, -20, -15 });+ Chord("Strummed Guitar", new[] { 7, 12, -12, 4 }, strum: 25, vel: new[] { -4, -8, -12, -16 });+ Chord("Harp Roll", new[] { 4, 7, 11, 12, -12 }, strum: 90, spread: 70, vel: new[] { -20, -15, -10, -5, -25 });+ Chord("Slow Strum Pad", new[] { 3, 7, 10, 12 }, strum: 65, vel: new[] { -8, -12, -16, -20 });+ Chord("Diatonic Triads C", new[] { 4, 7 }, fold: true);+ Chord("Diatonic 7ths C", new[] { 4, 7, 11 }, fold: true, strum: 20);+ Chord("Diatonic Triads Am", new[] { 4, 7 }, fold: true, key: 9, minor: true);+ Chord("Diatonic 9ths Am", new[] { 4, 7, 11, 2 }, fold: true, key: 9, minor: true, spread: 40);+ Chord("Octave Doubler", new[] { 12 });+ Chord("Sub Octave", new[] { -12 });+ Chord("Soft Fifth + Oct", new[] { 7, 12 }, vel: new[] { -20, -35 });+ Chord("Tone Cluster", new[] { 1, 2, 3 }, vel: new[] { -10, -15, -20 });// ---- Nota Scale (MIDI, kind 2) — Root 0..11, Scale 0..9 preset / 10 Custom; Fold 0 Near/1 Down/2 UpMidi("scale", 2, "C Minor", ("Root", 0f), ("Scale", 1f));Midi("scale", 2, "Penta Minor", ("Root", 0f), ("Scale", 8f), ("Fold", 1f));@@ -2331,6 +2398,36 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsFx("eq", 0, name, ps.ToArray());}+ // A Nota Chord preset: every slot is written (shifts listed in order are switched on, the rest off).+ private void Chord(string name, int[] shifts, float strum = 0, float spread = 0, bool keepRoot = true, bool fold = false,+ int key = 0, bool minor = false, int[]? vel = null)+ {+ var ps = new List<(string, float)>();+ for (int v = 0; v < 6; v++)+ {+ bool on = v < shifts.Length;+ ps.Add(($"Voice {v + 1}", on ? shifts[v] : 0));+ ps.Add(($"On {v + 1}", on ? 1 : 0));+ ps.Add(($"Vel {v + 1}", vel is not null && v < vel.Length ? vel[v] : 0));+ }+ ps.Add(("Strum", strum)); ps.Add(("Spread", spread));+ ps.Add(("Keep Root", keepRoot ? 1 : 0)); ps.Add(("Fold", fold ? 1 : 0));+ ps.Add(("Fold Key", key)); ps.Add(("Fold Mode", minor ? 1 : 0));+ Midi("chord", 1, name, ps.ToArray());+ }++ // A Nota Arp preset: globals by name + optional per-step Groove lanes ("Vel N", "Len N", …).+ private void Arp(string name, Dictionary<string, float> g, float[]? vel = null, float[]? len = null, float[]? chn = null,+ int[]? rat = null, int[]? trn = null, string? steps = null)+ {+ var ps = g.Select(kv => (kv.Key, kv.Value)).ToList();+ void Lane(string prefix, IEnumerable<float>? vals) { if (vals is null) return; int i = 1; foreach (var v in vals) ps.Add(($"{prefix} {i++}", v)); }+ Lane("Vel", vel); Lane("Len", len); Lane("Chn", chn);+ Lane("Rat", rat?.Select(v => (float)v)); Lane("Trn", trn?.Select(v => (float)v));+ Lane("On", steps?.Select(c => c == 'x' ? 1f : 0f));+ Midi("arp", 0, name, ps.ToArray());+ }+private void Midi(string group, int kind, string name, params (string Name, float Value)[] ps)=> Add(group, name, "builtin-midi-effect", kind, isInstrument: false, isMidi: true, ps);diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.csindex bd4b0461..663de523 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs@@ -127,6 +127,15 @@ public static class PresetService/// instrument presets always create a new track. Returns "" on success or a user-facing warning.</summary>// Nota EQ-3 (kind 16) appended Range, the fader law. A preset saved before it names no// Range (or holds only the first 10 values) and was made in the Classic ±15 dB law.+ /// <summary>Nota Chord (MIDI kind 1) before the almanac rework had no per-slot switches —+ /// a slot was off when its offset was 0. Derive On 1..6 (params 16..21) from Voice 1..6.</summary>+ public static void ChordLegacySwitches(IAudioEngine engine, int trackId, int index)+ {+ if (engine.MidiEffectParamCount(trackId, index) < 22) return;+ for (int v = 0; v < 6; v++)+ engine.MidiEffectSetParam(trackId, index, 16 + v, Math.Abs(engine.MidiEffectGetParam(trackId, index, v)) >= 0.5f ? 1f : 0f);+ }+private static void LegacyRange(PresetDocument doc, IAudioEngine engine, int trackId, int deviceIndex){if (doc.BuiltinKind != 16 || engine.DeviceParamCount(trackId, deviceIndex) <= 10) return;@@ -167,6 +176,7 @@ public static class PresetServicefor (int i = 0; i < pc; i++)if (doc.NamedParams.TryGetValue(engine.MidiEffectParamName(targetTrackId, mi, i), out var v))engine.MidiEffectSetParam(targetTrackId, mi, i, v);+ if (doc.BuiltinKind == 1 && !doc.NamedParams.ContainsKey("On 1")) ChordLegacySwitches(engine, targetTrackId, mi);}return "";}@@ -276,10 +286,19 @@ public static class PresetServiceif (deviceIndex < 0) return "Not a MIDI effect.";if (doc.NamedParams is { Count: > 0 }){+ // Params the preset leaves out go back to their defaults, so switching presets+ // never inherits a previous one's steps. "View" (the card size) is editor+ // state and stays as it is.int pc = engine.MidiEffectParamCount(trackId, deviceIndex);for (int i = 0; i < pc; i++)- if (doc.NamedParams.TryGetValue(engine.MidiEffectParamName(trackId, deviceIndex, i), out var v))- engine.MidiEffectSetParam(trackId, deviceIndex, i, v);+ {+ string pn = engine.MidiEffectParamName(trackId, deviceIndex, i);+ if (doc.NamedParams.TryGetValue(pn, out var v)) engine.MidiEffectSetParam(trackId, deviceIndex, i, v);+ else if (pn != "View") engine.MidiEffectSetParam(trackId, deviceIndex, i, engine.MidiEffectParamDefault(trackId, deviceIndex, i));+ }+ // A Nota Chord preset saved before its slots had switches: "0 semitones" meant off.+ if (engine.MidiEffectKind(trackId, deviceIndex) == 1 && !doc.NamedParams.ContainsKey("On 1"))+ ChordLegacySwitches(engine, trackId, deviceIndex);}return "";}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex 52575aa8..8256cec1 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -605,6 +605,7 @@ public sealed class ProjectServiceif (mi < 0) { warnings.Add($"Couldn't recreate a MIDI effect (kind {m.Kind})."); continue; }int mpc = engine.MidiEffectParamCount(id, mi);for (int p = 0; p < m.Params.Length && p < mpc; p++) engine.MidiEffectSetParam(id, mi, p, m.Params[p]);+ if (m.Kind == 1 && m.Params.Length <= 16) PresetService.ChordLegacySwitches(engine, id, mi); // pre-switch Nota Chordif (m.Bypassed) engine.SetMidiEffectBypassed(id, mi, true);if (m.CcDestDevice >= 0 && m.CcDestParam >= 0){diff --git a/src/managed/Nota.Mcp/Tools/AutomationTools.cs b/src/managed/Nota.Mcp/Tools/AutomationTools.csindex 94c914bb..fbe2cddf 100644--- a/src/managed/Nota.Mcp/Tools/AutomationTools.cs+++ b/src/managed/Nota.Mcp/Tools/AutomationTools.cs@@ -40,7 +40,8 @@ public sealed class AutomationTools(IAudioEngine engine, IEngineDispatch dispatc=> Mutate(() => E.SetAutomationPoints(trackId, laneIndex, Array.ConvertAll(points, p => new AutomationPoint(p.Beat, p.Value, p.Curve))));[McpServerTool(Name = "add_automation_lane"), Description(- "Add an automation lane. target: \"volume\", \"pan\", or \"device_param\" (with deviceIndex+paramIndex). "+ "Add an automation lane. target: \"volume\", \"pan\", \"device_param\" (with deviceIndex+paramIndex) or "+ + "\"midi_param\" (a MIDI effect: deviceIndex = its index from list_midi_fx, paramIndex from get_midi_fx_params). "+ "Returns the lane index.")]public Task<int> AddAutomationLane(int trackId, string target, int deviceIndex = -1, int paramIndex = -1) => Mutate(() =>{diff --git a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs b/src/managed/Nota.Mcp/Tools/MidiFxTools.csindex 3fcb4ad8..2e702a40 100644--- a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs+++ b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs@@ -55,4 +55,221 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I[McpServerTool(Name = "set_midi_fx_param"), Description("Set a MIDI effect parameter by index (value in the param's min..max range).")]public Task SetMidiFxParam(int trackId, int index, int paramIndex, float value) => Mutate(() => E.MidiEffectSetParam(trackId, index, paramIndex, value));++ // ---- Nota Arp (kind 0) — named access to its globals and 16-step Groove lanes ----------+ // Param layout mirrors Arpeggiator.h: 13 globals, 7 lanes × 16 steps, then VelAmt / View.+ private const int GRate = 0, GSync = 1, GFreeRate = 2, GGate = 3, GOctaves = 4, GOctMode = 5, GOrder = 6, GSwing = 7,+ GHold = 8, GRetrig = 9, GTranspose = 10, GLoop = 11, GLoopMode = 12, PVelAmt = 125, PView = 126, ArpSteps = 16;+ private static readonly string[] ArpRates = { "1/1", "1/2", "1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32" };+ // Persisted Order values: 0 up, 1 down, 2 up-down, 3 converge, 4 as-played, 5 chord, 6 random, 7 down-up, 8 diverge.+ private static readonly string[] ArpOrders = { "up", "down", "up-down", "converge", "as-played", "chord", "random", "down-up", "diverge" };+ private static readonly string[] ArpOctModes = { "up", "down", "up-down", "random" };+ private static readonly string[] ArpRetrigs = { "off", "note", "beat" };+ private static readonly string[] ArpLoopModes = { "forward", "backward", "ping-pong", "random" };+ // lane → (first param, to display units, from display units)+ private static readonly Dictionary<string, (int Base, Func<float, float> To, Func<float, float> From)> ArpLanes = new()+ {+ ["velocity"] = (13, v => MathF.Round(v * 127), d => Math.Clamp(d, 0, 127) / 127f),+ ["length"] = (29, v => MathF.Round(v * 100), d => Math.Clamp(d, 0, 200) / 100f),+ ["chance"] = (45, v => MathF.Round(v * 100), d => Math.Clamp(d, 0, 100) / 100f),+ ["ratchet"] = (61, v => MathF.Round(v), d => Math.Clamp(MathF.Round(d), 1, 8)),+ ["transpose"] = (77, v => MathF.Round(v), d => Math.Clamp(MathF.Round(d), -24, 24)),+ ["on"] = (93, v => v >= 0.5f ? 1 : 0, d => d >= 0.5f ? 1 : 0),+ ["cc"] = (109, v => MathF.Round(v), d => Math.Clamp(MathF.Round(d), 0, 127)),+ };++ public sealed record ArpLanesDto(float[] Velocity, float[] Length, float[] Chance, float[] Ratchet, float[] Transpose, bool[] On, float[] Cc);+ public sealed record ArpState(+ string Order, bool Sync, string Rate, float FreeMs, float GatePercent, float SwingPercent, float VelAmtPercent,+ int Octaves, string OctaveMode, string Retrig, bool Hold, int Transpose, int Steps, string LoopMode, string View,+ ArpLanesDto Lanes, int CurrentStep, int[] Chord, bool Running);++ private void RequireArp(int trackId, int index)+ {+ if (E.MidiEffectKind(trackId, index) != 0 || E.MidiEffectParamCount(trackId, index) <= PView)+ throw new ArgumentException($"MIDI effect {index} on track {trackId} is not a Nota Arp.");+ }+ private static int Pick(string[] names, string value, string what)+ {+ int i = Array.FindIndex(names, n => string.Equals(n, value.Trim().Replace(' ', '-').Replace('_', '-'), StringComparison.OrdinalIgnoreCase));+ return i >= 0 ? i : throw new ArgumentException($"Unknown {what} '{value}'. Use one of: {string.Join(", ", names)}.");+ }++ [McpServerTool(Name = "get_arp"), Description(+ "Read a Nota Arp (MIDI effect kind 0) in musical units: order, sync/rate or free ms, gate/swing/vel-amt %, octaves, "+ + "retrig, hold, transpose, steps, loop mode, card view, the 16-step Groove lanes (velocity 1..127, length %, chance %, "+ + "ratchet ×, transpose st, on) and live state (current step 0-based or -1, the chord it plays, running).")]+ public Task<ArpState> GetArp(int trackId, int index) => Read(() =>+ {+ RequireArp(trackId, index);+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);+ int GI(int p) => (int)MathF.Round(G(p));+ float[] Lane(string n) { var l = ArpLanes[n]; var a = new float[ArpSteps]; for (int s = 0; s < ArpSteps; s++) a[s] = l.To(G(l.Base + s)); return a; }+ var scope = new float[40];+ int sn = E.MidiEffectScope(trackId, index, scope);+ int cn = sn >= 4 ? Math.Min((int)scope[3], sn - 4) : 0;+ var chord = new int[cn]; for (int i = 0; i < cn; i++) chord[i] = (int)scope[4 + i];+ return new ArpState(+ ArpOrders[Math.Clamp(GI(GOrder), 0, ArpOrders.Length - 1)], G(GSync) > 0.5f, ArpRates[Math.Clamp(GI(GRate), 0, 7)],+ MathF.Round(1000f / MathF.Max(0.1f, G(GFreeRate))), MathF.Round(G(GGate) * 100), MathF.Round(G(GSwing) * 50), MathF.Round(G(PVelAmt) * 100),+ GI(GOctaves), ArpOctModes[Math.Clamp(GI(GOctMode), 0, 3)], ArpRetrigs[Math.Clamp(GI(GRetrig), 0, 2)], G(GHold) > 0.5f,+ GI(GTranspose), GI(GLoop), ArpLoopModes[Math.Clamp(GI(GLoopMode), 0, 3)], G(PView) >= 0.5f ? "S" : "L",+ new ArpLanesDto(Lane("velocity"), Lane("length"), Lane("chance"), Lane("ratchet"), Lane("transpose"),+ Array.ConvertAll(Lane("on"), v => v > 0.5f), Lane("cc")),+ sn >= 4 ? (int)scope[0] : -1, chord, sn >= 4 && scope[2] > 0);+ });++ [McpServerTool(Name = "set_arp"), Description(+ "Set a Nota Arp's globals by name; omit what you don't change. order: up | down | up-down | down-up | converge | diverge | "+ + "random | chord | as-played. rate: 1/1 1/2 1/4 1/8 1/8T 1/16 1/16T 1/32 (turns sync on); freeMs 20..1000 (turns sync off). "+ + "gatePercent 0..200, swingPercent 0..50, velAmtPercent 0..100 (how much the Groove velocity lane shapes velocity), "+ + "octaves 1..8, octaveMode up|down|up-down|random, retrig off|note|beat (beat = restart every bar), hold, "+ + "transpose −24..24 st, steps 1..16, loopMode forward|backward|ping-pong|random, view S|L (card size).")]+ public Task SetArp(int trackId, int index, string? order = null, string? rate = null, float? freeMs = null,+ float? gatePercent = null, float? swingPercent = null, float? velAmtPercent = null, int? octaves = null,+ string? octaveMode = null, string? retrig = null, bool? hold = null, int? transpose = null, int? steps = null,+ string? loopMode = null, string? view = null) => Mutate(() =>+ {+ RequireArp(trackId, index);+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);+ if (order is not null) S(GOrder, Pick(ArpOrders, order, "order"));+ if (rate is not null) { S(GRate, Pick(ArpRates, rate, "rate")); S(GSync, 1); }+ if (freeMs is { } ms) { S(GFreeRate, 1000f / Math.Clamp(ms, 20, 1000)); S(GSync, 0); }+ if (gatePercent is { } g) S(GGate, Math.Clamp(g, 0, 200) / 100f);+ if (swingPercent is { } sw) S(GSwing, Math.Clamp(sw, 0, 50) / 50f);+ if (velAmtPercent is { } va) S(PVelAmt, Math.Clamp(va, 0, 100) / 100f);+ if (octaves is { } o) S(GOctaves, Math.Clamp(o, 1, 8));+ if (octaveMode is not null) S(GOctMode, Pick(ArpOctModes, octaveMode, "octave mode"));+ if (retrig is not null) S(GRetrig, Pick(ArpRetrigs, retrig, "retrig"));+ if (hold is { } h) S(GHold, h ? 1 : 0);+ if (transpose is { } tr) S(GTranspose, Math.Clamp(tr, -24, 24));+ if (steps is { } st) S(GLoop, Math.Clamp(st, 1, 16));+ if (loopMode is not null) S(GLoopMode, Pick(ArpLoopModes, loopMode, "loop mode"));+ if (view is not null) S(PView, view.Trim().Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 0);+ });++ [McpServerTool(Name = "set_arp_lane"), Description(+ "Write a Nota Arp Groove lane from step 1 (up to 16 values, extra ignored). lane: velocity (1..127), length (% of the step, "+ + "5..200), chance (%), ratchet (1..8 repeats), transpose (semitones ±24), on (1 = play, 0 = muted), cc (0..127, Map/CC).")]+ public Task SetArpLane(int trackId, int index, string lane, float[] values) => Mutate(() =>+ {+ RequireArp(trackId, index);+ if (!ArpLanes.TryGetValue(lane.Trim().ToLowerInvariant(), out var l))+ throw new ArgumentException($"Unknown lane '{lane}'. Use one of: {string.Join(", ", ArpLanes.Keys)}.");+ for (int s = 0; s < values.Length && s < ArpSteps; s++) E.MidiEffectSetParam(trackId, index, l.Base + s, l.From(values[s]));+ });++ [McpServerTool(Name = "set_arp_step"), Description(+ "Edit one Nota Arp step (1..16) across lanes; omit what you don't change. Units as in set_arp_lane; on = false mutes the step.")]+ public Task SetArpStep(int trackId, int index, int step, float? velocity = null, float? length = null, float? chance = null,+ int? ratchet = null, int? transpose = null, bool? on = null) => Mutate(() =>+ {+ RequireArp(trackId, index);+ int s = Math.Clamp(step, 1, ArpSteps) - 1;+ void L(string n, float? v) { if (v is { } x) { var l = ArpLanes[n]; E.MidiEffectSetParam(trackId, index, l.Base + s, l.From(x)); } }+ L("velocity", velocity); L("length", length); L("chance", chance);+ L("ratchet", ratchet); L("transpose", transpose); L("on", on is { } b ? (b ? 1 : 0) : null);+ });++ [McpServerTool(Name = "restart_arp"), Description("Restart a Nota Arp's pattern from step 1 (like its Restart button).")]+ public Task RestartArp(int trackId, int index) => Mutate(() => { RequireArp(trackId, index); E.MidiEffectCommand(trackId, index, 1); });++ // ---- Nota Chord (kind 1) — named access to its six shifts and globals ------------------+ // Param layout mirrors MidiChord.h: Voice 1..6 (0..5), Strum 6, Keep Root 7, Spread 8, Fold 9,+ // Vel 1..6 (10..15), On 1..6 (16..21), Fold Key 22, Fold Mode 23, View 24.+ private const int CVoice = 0, CStrum = 6, CKeep = 7, CSpread = 8, CFold = 9, CVel = 10, COn = 16, CKey = 22, CMode = 23, CView = 24, CSlots = 6;+ private static readonly (string Name, int[] Shifts)[] ChordTypes =+ {+ ("maj7", new[] { 4, 7, 11 }), ("min7", new[] { 3, 7, 10 }), ("sus4", new[] { 5, 7 }), ("5th", new[] { 7 }),+ ("major", new[] { 4, 7 }), ("minor", new[] { 3, 7 }), ("dom7", new[] { 4, 7, 10 }), ("sus2", new[] { 2, 7 }),+ ("dim7", new[] { 3, 6, 9 }), ("m7b5", new[] { 3, 6, 10 }), ("aug", new[] { 4, 8 }), ("6", new[] { 4, 7, 9 }),+ ("m6", new[] { 3, 7, 9 }), ("power", new[] { 7, 12 }), ("octave", new[] { 12 }),+ };+ private static readonly string[] ChordKeys = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };++ public sealed record ChordShift(int Slot, bool On, int Semitones, int Velocity);+ public sealed record ChordState(+ string Type, ChordShift[] Shifts, float StrumMs, float SpreadPercent, bool KeepRoot, bool Fold, string FoldKey, string FoldMode,+ string View, int LastRoot, int HeldKeys, int[] LastChord, int SoundedNotes);++ private void RequireChord(int trackId, int index)+ {+ if (E.MidiEffectKind(trackId, index) != 1 || E.MidiEffectParamCount(trackId, index) <= CView)+ throw new ArgumentException($"MIDI effect {index} on track {trackId} is not a Nota Chord.");+ }++ [McpServerTool(Name = "get_chord"), Description(+ "Read a Nota Chord (MIDI effect kind 1): the matching type (maj7 / min7 / sus4 / 5th … or custom), the six shifts "+ + "(slot 1..6, on, semitones −12..+12, velocity offset −64..+63 MIDI units), strum ms, spread %, keep root, fold into "+ + "a scale (key + major/minor), card view, and live state: the last root played (MIDI note, -1 none), keys held now, "+ + "the last chord it produced (MIDI notes low → high) and how many of them have sounded so far (the strum's progress).")]+ public Task<ChordState> GetChord(int trackId, int index) => Read(() =>+ {+ RequireChord(trackId, index);+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);+ int GI(int p) => (int)MathF.Round(G(p));+ var shifts = new ChordShift[CSlots];+ for (int s = 0; s < CSlots; s++) shifts[s] = new ChordShift(s + 1, G(COn + s) >= 0.5f, GI(CVoice + s), GI(CVel + s));+ var active = shifts.Where(x => x.On).Select(x => x.Semitones).OrderBy(x => x).ToArray();+ string type = ChordTypes.FirstOrDefault(t => t.Shifts.OrderBy(x => x).SequenceEqual(active)).Name ?? "custom";+ var scope = new float[18];+ int sn = E.MidiEffectScope(trackId, index, scope);+ int n = sn >= 4 ? Math.Min((int)scope[3], (sn - 4) / 2) : 0;+ var last = new int[n]; for (int i = 0; i < n; i++) last[i] = (int)scope[4 + i];+ return new ChordState(type, shifts, G(CStrum), G(CSpread), G(CKeep) >= 0.5f, G(CFold) >= 0.5f,+ ChordKeys[((GI(CKey)) % 12 + 12) % 12], G(CMode) >= 0.5f ? "minor" : "major", G(CView) >= 0.5f ? "S" : "L",+ sn >= 4 ? (int)scope[0] : -1, sn >= 4 ? (int)scope[1] : 0, last, sn >= 4 ? (int)scope[2] : 0);+ });++ [McpServerTool(Name = "set_chord"), Description(+ "Set a Nota Chord's globals by name; omit what you don't change. type sets the shifts from a chord type (and clears "+ + "their velocity offsets): maj7 min7 sus4 5th major minor dom7 sus2 dim7 m7b5 aug 6 m6 power octave. shifts: up to six "+ + "semitone offsets (−12..+12) — listed ones are switched on in order, the rest off (overrides type). strumMs 0..100 "+ + "(chord note-ons low → high this far apart), spreadPercent 0..100 (≥34 lifts every other shift an octave, ≥67 all), "+ + "keepRoot (play the pressed note too), fold + foldKey (C..B) + foldMode (major|minor): added notes outside the "+ + "scale drop a semitone into it. view S|L (card size).")]+ public Task SetChord(int trackId, int index, string? type = null, int[]? shifts = null, float? strumMs = null, float? spreadPercent = null,+ bool? keepRoot = null, bool? fold = null, string? foldKey = null, string? foldMode = null, string? view = null) => Mutate(() =>+ {+ RequireChord(trackId, index);+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);+ int[]? iv = shifts;+ if (iv is null && type is not null)+ {+ var t = ChordTypes.FirstOrDefault(c => string.Equals(c.Name, type.Trim(), StringComparison.OrdinalIgnoreCase));+ iv = t.Shifts ?? throw new ArgumentException($"Unknown chord type '{type}'. Use one of: {string.Join(", ", ChordTypes.Select(c => c.Name))}.");+ for (int s = 0; s < CSlots; s++) S(CVel + s, 0);+ }+ if (iv is not null)+ {+ if (iv.Length > CSlots) throw new ArgumentException("At most six shifts.");+ for (int s = 0; s < CSlots; s++) { bool on = s < iv.Length; S(CVoice + s, on ? Math.Clamp(iv[s], -12, 12) : 0); S(COn + s, on ? 1 : 0); }+ }+ if (strumMs is { } st) S(CStrum, Math.Clamp(st, 0, 100));+ if (spreadPercent is { } sp) S(CSpread, Math.Clamp(sp, 0, 100));+ if (keepRoot is { } k) S(CKeep, k ? 1 : 0);+ if (fold is { } f) S(CFold, f ? 1 : 0);+ if (foldKey is not null)+ {+ int ki = Array.FindIndex(ChordKeys, x => string.Equals(x, foldKey.Trim(), StringComparison.OrdinalIgnoreCase));+ if (ki < 0) throw new ArgumentException($"Unknown key '{foldKey}'. Use one of: {string.Join(" ", ChordKeys)}.");+ S(CKey, ki);+ }+ if (foldMode is not null) S(CMode, foldMode.Trim().StartsWith("min", StringComparison.OrdinalIgnoreCase) ? 1 : 0);+ if (view is not null) S(CView, view.Trim().Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 0);+ });++ [McpServerTool(Name = "set_chord_shift"), Description(+ "Edit one Nota Chord shift (slot 1..6); omit what you don't change. semitones −12..+12 (setting it switches the slot on "+ + "unless on is given), on, velocity offset −64..+63 (MIDI units added to the played velocity).")]+ public Task SetChordShift(int trackId, int index, int slot, int? semitones = null, bool? on = null, int? velocity = null) => Mutate(() =>+ {+ RequireChord(trackId, index);+ if (slot is < 1 or > CSlots) throw new ArgumentException("slot must be 1..6.");+ int s = slot - 1;+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);+ if (semitones is { } st) { S(CVoice + s, Math.Clamp(st, -12, 12)); if (on is null) S(COn + s, 1); }+ if (on is { } o) S(COn + s, o ? 1 : 0);+ if (velocity is { } v) S(CVel + s, Math.Clamp(v, -64, 63));+ });}diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex c871f20e..45f294c8 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -889,6 +889,8 @@ NOTA_API int32_t nota_midi_effect_last_in(const NotaEngine* engine, int32_tNOTA_API int32_t nota_midi_effect_last_out(const NotaEngine* engine, int32_t track_id, int32_t index);/* Float scope buffer for a MIDI effect editor (Nota Velocity in/out pairs); returns count written. */NOTA_API int32_t nota_midi_effect_scope(const NotaEngine* engine, int32_t track_id, int32_t index, float* out, int32_t max_n);+/* An editor command to a MIDI effect (Nota Arp: 1 = restart the pattern). */+NOTA_API void nota_midi_effect_command(NotaEngine* engine, int32_t track_id, int32_t index, int32_t cmd);/* Map/CC routing: the effect's CC lane modulates an audio-device param on the track. */NOTA_API void nota_midi_effect_set_cc_dest(NotaEngine* engine, int32_t track_id, int32_t index, int32_t dest_device, int32_t dest_param);NOTA_API void nota_midi_effect_set_cc_depth(NotaEngine* engine, int32_t track_id, int32_t index, float depth);diff --git a/src/native/nota.engine/src/Arpeggiator.h b/src/native/nota.engine/src/Arpeggiator.hindex d66b68b6..cd37270a 100644--- a/src/native/nota.engine/src/Arpeggiator.h+++ b/src/native/nota.engine/src/Arpeggiator.h@@ -2,10 +2,16 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Nota Arp — the built-in step arpeggiator (MidiDevice, midiKind 0). Classic "Step-// Arp"-style: global controls (rate/sync, octaves, note order, gate, swing, hold,-// key-retrig, transpose, loop length + mode) plus six 16-step lanes (Velocity /-// Length / Chance / Ratchet / Transpose / On) and an inert Map-CC lane. It consumes-// the incoming held notes and emits a generated sequence to the instrument.+// Arp"-style: global controls (rate/sync, octaves, note order, gate, swing, velocity+// amount, hold, retrigger Off/Note/Beat, transpose, loop length + mode) plus six 16-step+// Groove lanes (Velocity / Length / Chance / Ratchet / Transpose / On) and an inert+// Map-CC lane. It consumes the incoming held notes and emits a generated sequence.+//+// The note order walks the whole octave-expanded range (Up·Down over two octaves climbs+// C3…B4 and back down), one note per step; a ratchet repeats that step's note. Step k of+// the pattern plays note k of the order, so the editor can draw exactly what will play.+// midiScope() publishes the live step and the held chord for the editor's Pattern view;+// midiCommand(1) restarts the pattern at the next block.//// The step schedule is a PURE FUNCTION of the absolute step index (derived from the// beat position), not an accumulator — so it is robust to transport seeks/loops and@@ -33,9 +39,14 @@ public:enum { GRate = 0, GSync, GFreeRate, GGate, GOctaves, GOctaveMode, GNoteOrder,GSwing, GHold, GKeyRetrig, GTranspose, GLoop, GLoopMode, kNumGlobals };enum { LVel = 0, LLen, LChance, LRatchet, LTransp, LOn, LCC, kNumLanes };- static constexpr int kNumParams = kNumGlobals + kNumLanes * kSteps; // 13 + 7*16 = 125-- enum { OrdUp = 0, OrdDown, OrdUpDown, OrdConverge, OrdAsPlayed, OrdChord, OrdRandom };+ // Appended after the lanes (param order = persisted layout, append only).+ static constexpr int PVelAmt = kNumGlobals + kNumLanes * kSteps; // 125: Groove velocity depth+ static constexpr int PView = PVelAmt + 1; // 126: editor size (0 = L, 1 = S) — UI state+ static constexpr int kNumParams = PView + 1; // 127++ // Order values are persisted: new orders are appended, the editor lists them musically.+ enum { OrdUp = 0, OrdDown, OrdUpDown, OrdConverge, OrdAsPlayed, OrdChord, OrdRandom, OrdDownUp, OrdDiverge };+ enum { RetrigOff = 0, RetrigNote, RetrigBeat };enum { OctUp = 0, OctDown, OctUpDown, OctRandom };enum { LoopFwd = 0, LoopBack, LoopPing, LoopRandom };@@ -55,13 +66,15 @@ public:p_[GLoopMode].store(0.0f);for (int s = 0; s < kSteps; ++s) {lane(LVel, s).store(0.8f);- lane(LLen, s).store(0.9f);+ lane(LLen, s).store(1.0f);lane(LChance, s).store(1.0f);lane(LRatchet, s).store(1.0f);lane(LTransp, s).store(0.0f);lane(LOn, s).store(1.0f);lane(LCC, s).store(0.0f);}+ p_[PVelAmt].store(1.0f);+ p_[PView].store(0.0f);}int32_t midiKind() const override { return 0; }@@ -77,21 +90,26 @@ public:"Order", "Swing", "Hold", "Retrig", "Transpose", "Loop", "LoopMode" };return g[i];}+ if (i == PVelAmt) return "VelAmt";+ if (i == PView) return "View";static thread_local char buf[16];static const char* ln[] = { "Vel", "Len", "Chn", "Rat", "Trn", "On", "CC" };std::snprintf(buf, sizeof(buf), "%s %d", ln[(i - kNumGlobals) / kSteps], (i - kNumGlobals) % kSteps + 1);return buf;}float paramMin(int32_t i) const override {+ if (i >= PVelAmt) return 0.0f;if (i < kNumGlobals) {switch (i) { case GTranspose: return -24.0f; case GFreeRate: return 0.1f; case GLoop: return 1.0f; default: return 0.0f; }}switch ((i - kNumGlobals) / kSteps) { case LTransp: return -24.0f; case LRatchet: return 1.0f; default: return 0.0f; }}float paramMax(int32_t i) const override {+ if (i >= PVelAmt) return 1.0f;if (i < kNumGlobals) {- switch (i) { case GRate: return 7.0f; case GFreeRate: return 40.0f; case GGate: return 2.0f;- case GOctaves: return 8.0f; case GOctaveMode: return 3.0f; case GNoteOrder: return 6.0f;+ switch (i) { case GRate: return 7.0f; case GFreeRate: return 50.0f; case GGate: return 2.0f;+ case GOctaves: return 8.0f; case GOctaveMode: return 3.0f; case GNoteOrder: return 8.0f;+ case GKeyRetrig: return 2.0f;case GTranspose: return 24.0f; case GLoop: return 16.0f; case GLoopMode: return 3.0f; default: return 1.0f; }}switch ((i - kNumGlobals) / kSteps) { case LLen: return 2.0f; case LRatchet: return 8.0f;@@ -110,7 +128,28 @@ public:return a; // transient live state (held/pending/phase) starts fresh}- void reset() override { held_ = 0; physDown_ = 0; nOffs_ = 0; nOns_ = 0; arpBeat_ = 0.0; phaseRef_ = 0.0; }+ void reset() override {+ held_ = 0; physDown_ = 0; nOffs_ = 0; nOns_ = 0; arpBeat_ = 0.0; phaseRef_ = 0.0;+ curLp_.store(-1, std::memory_order_relaxed); curK_.store(-1, std::memory_order_relaxed);+ heldLive_.store(0, std::memory_order_relaxed);+ }++ // Editor commands: 1 = restart the pattern (step 1) at the next block.+ void midiCommand(int32_t cmd) override { if (cmd == 1) restartReq_.store(true, std::memory_order_relaxed); }++ // Editor telemetry: [0] loop position of the sounding step (-1 = idle), [1] its pattern+ // step counter, [2] notes held right now, [3] n = chord size, [4..4+n) the chord in held+ // order — the held notes, or the last chord played once released.+ int32_t midiScope(float* out, int32_t maxN) const override {+ if (!out || maxN < 4) return 0;+ out[0] = (float)curLp_.load(std::memory_order_relaxed);+ out[1] = (float)curK_.load(std::memory_order_relaxed);+ out[2] = (float)heldLive_.load(std::memory_order_relaxed);+ int n = std::min(chordN_.load(std::memory_order_acquire), std::min(kMaxHeld, (int)maxN - 4));+ out[3] = (float)n;+ for (int i = 0; i < n; ++i) out[4 + i] = (float)chord_[i].load(std::memory_order_relaxed);+ return 4 + n;+ }// Map/CC routing (the CC lane modulates a target audio-device param).int32_t ccDestDevice() const override { return ccDev_.load(std::memory_order_relaxed); }@@ -128,8 +167,9 @@ public:const double b0 = playing ? beatStart : arpBeat_;const double b1 = b0 + frames / spb;- const bool retrig = p_[GKeyRetrig].load(std::memory_order_relaxed) > 0.5f;+ const int retrig = std::clamp((int)std::lround(p_[GKeyRetrig].load(std::memory_order_relaxed)), 0, 2);const bool hold = p_[GHold].load(std::memory_order_relaxed) > 0.5f;+ if (restartReq_.exchange(false, std::memory_order_relaxed)) { phaseRef_ = b0; nOns_ = 0; }// 1) Fold input into the held set (input notes are consumed by the arp).for (int i = 0; i < nIn; ++i) {@@ -140,13 +180,15 @@ public:if (fresh) held_ = 0;if (physDown_ < 127) physDown_++;addHeld(e.pitch, e.vel);- if (fresh && retrig) phaseRef_ = b0 + e.off / spb; // restart the pattern at the key-press+ if (fresh && retrig == RetrigNote) phaseRef_ = b0 + e.off / spb; // restart the pattern at the key-press} else {if (physDown_ > 0) physDown_--;if (!hold) removeHeld(e.pitch);}}+ publishChord();+// 2) Fire due pending note-ons (ratchet tails) and note-offs from earlier blocks.firePendingOns(out, nOut, maxOut, b0, b1, spb, frames);firePendingOffs(out, nOut, maxOut, b0, b1, spb, frames);@@ -155,18 +197,31 @@ public:const double stepBeats = currentStepBeats(spb);if (stepBeats > 1e-6 && held_ > 0) {const double swing = std::clamp(p_[GSwing].load(std::memory_order_relaxed), 0.0f, 1.0f);- long kLo = (long)std::floor((b0 - phaseRef_) / stepBeats) - 1;- long kHi = (long)std::ceil((b1 - phaseRef_) / stepBeats) + 1;+ const double ref = retrig == RetrigBeat ? 0.0 : phaseRef_; // Beat: bar-aligned grid+ long kLo = (long)std::floor((b0 - ref) / stepBeats) - 1;+ long kHi = (long)std::ceil((b1 - ref) / stepBeats) + 1;for (long k = kLo; k <= kHi; ++k) {if (k < 0) continue;- double stepBeat = phaseRef_ + k * stepBeats;+ double stepBeat = ref + k * stepBeats;if (k % 2 == 1) stepBeat += swing * stepBeats * 0.5;if (stepBeat < b0 || stepBeat >= b1) continue;- // Publish the step's CC-lane value (independent of note gating) for Map routing.+ // Beat retrigger: the pattern starts over on every bar (4 beats).+ long kp = k;+ if (retrig == RetrigBeat) {+ const double bar = std::floor(k * stepBeats / 4.0 + 1e-9) * 4.0;+ kp = k - (long)std::ceil(bar / stepBeats - 1e-9);+ if (kp < 0) kp = 0;+ }const int loop = std::clamp((int)std::lround(p_[GLoop].load(std::memory_order_relaxed)), 1, kSteps);- ccOut_.store(lane(LCC, loopPos(k, loop)).load(std::memory_order_relaxed) / 127.0f, std::memory_order_relaxed);- emitStep(k, stepBeat, stepBeats, b0, b1, spb, frames, out, nOut, maxOut);+ const int lp = loopPos(kp, loop);+ curLp_.store(lp, std::memory_order_relaxed);+ curK_.store((int32_t)std::min<long>(kp, 1 << 30), std::memory_order_relaxed);+ // Publish the step's CC-lane value (independent of note gating) for Map routing.+ ccOut_.store(lane(LCC, lp).load(std::memory_order_relaxed) / 127.0f, std::memory_order_relaxed);+ emitStep(k, kp, lp, stepBeat, stepBeats, b0, b1, spb, frames, out, nOut, maxOut);}+ } else if (held_ == 0 && nOns_ == 0 && nOffs_ == 0) {+ curLp_.store(-1, std::memory_order_relaxed);}arpBeat_ = b1;}@@ -224,11 +279,9 @@ private:}}- // --- one step ---- void emitStep(long stepAbs, double stepBeat, double stepBeats, double b0, double b1, double spb, int32_t frames,+ // --- one step --- (stepAbs seeds chance; kp = pattern step picks the note; lp = lane slot)+ void emitStep(long stepAbs, long kp, int lp, double stepBeat, double stepBeats, double b0, double b1, double spb, int32_t frames,MidiEv* out, int& nOut, int maxOut) {- const int loop = std::clamp((int)std::lround(p_[GLoop].load(std::memory_order_relaxed)), 1, kSteps);- const int lp = loopPos(stepAbs, loop);if (lane(LOn, lp).load(std::memory_order_relaxed) < 0.5f) return;if (rnd01(stepAbs, 11) >= std::clamp(lane(LChance, lp).load(std::memory_order_relaxed), 0.0f, 1.0f)) return;@@ -236,24 +289,26 @@ private:const float lenL = std::clamp(lane(LLen, lp).load(std::memory_order_relaxed), 0.0f, 2.0f);const int ratch = std::clamp((int)std::lround(lane(LRatchet, lp).load(std::memory_order_relaxed)), 1, 8);const float velL = std::clamp(lane(LVel, lp).load(std::memory_order_relaxed), 0.0f, 1.0f);+ const float amt = std::clamp(p_[PVelAmt].load(std::memory_order_relaxed), 0.0f, 1.0f);+ const float velK = 1.0f - amt + amt * velL; // Groove velocity, scaled by VelAmtconst int trn = (int)std::lround(p_[GTranspose].load(std::memory_order_relaxed) + lane(LTransp, lp).load(std::memory_order_relaxed));const int order = (int)std::lround(p_[GNoteOrder].load(std::memory_order_relaxed));int seqLen = 0; buildSequence(seqBuf_, seqVel_, seqLen);if (seqLen <= 0) return;+ const int oc = 12 * octaveRandom(kp);const double subLen = stepBeats / ratch;+ long idx = (order == OrdRandom) ? (long)(rnd01(kp, 7) * seqLen) : kp % seqLen;+ idx = ((idx % seqLen) + seqLen) % seqLen;for (int r = 0; r < ratch; ++r) {const double onBeat = stepBeat + r * subLen;const double offBeat = onBeat + std::max(0.05, (double)lenL) * subLen * gate;if (order == OrdChord) {- const int oc = octaveRandom(stepAbs);- for (int h = 0; h < held_; ++h)- place(heldBuf_[h].pitch + 12 * oc + trn, velL * heldBuf_[h].vel, onBeat, offBeat, b0, b1, spb, frames, out, nOut, maxOut);+ for (int h = 0; h < seqLen; ++h)+ place(seqBuf_[h] + oc + trn, velK * seqVel_[h], onBeat, offBeat, b0, b1, spb, frames, out, nOut, maxOut);} else {- long idx = (order == OrdRandom) ? (long)(rnd01(stepAbs * 8 + r, 7) * seqLen) : ((stepAbs * ratch + r) % seqLen);- idx = ((idx % seqLen) + seqLen) % seqLen;- place(seqBuf_[idx] + trn, velL * seqVel_[idx], onBeat, offBeat, b0, b1, spb, frames, out, nOut, maxOut);+ place(seqBuf_[idx] + oc + trn, velK * seqVel_[idx], onBeat, offBeat, b0, b1, spb, frames, out, nOut, maxOut);}}}@@ -271,9 +326,11 @@ private:}}- // --- note sequence (ordered + octave-expanded pitches from the held chord) ---+ // --- note sequence: the held chord expanded over the octaves (blocks in OctMode order),+ // then walked in the note order across that whole range. Chord = all of it at once.static constexpr int kSeqMax = 256;int seqBuf_[kSeqMax]; float seqVel_[kSeqMax];+ int rangeBuf_[kSeqMax]; float rangeVel_[kSeqMax];void buildSequence(int* seq, float* vel, int& len) {len = 0; if (held_ <= 0) return;int idx[kMaxHeld], m = held_;@@ -281,16 +338,6 @@ private:const int order = (int)std::lround(p_[GNoteOrder].load(std::memory_order_relaxed));if (order != OrdAsPlayed)std::sort(idx, idx + m, [&](int a, int b) { return heldBuf_[a].pitch < heldBuf_[b].pitch; });- int pat[kMaxHeld * 2], pn = 0;- switch (order) {- case OrdDown: for (int i = m - 1; i >= 0; --i) pat[pn++] = idx[i]; break;- case OrdUpDown: for (int i = 0; i < m; ++i) pat[pn++] = idx[i];- for (int i = m - 2; i >= 1; --i) pat[pn++] = idx[i]; break;- case OrdConverge: { int lo = 0, hi = m - 1; bool low = true;- while (lo <= hi) { pat[pn++] = low ? idx[lo++] : idx[hi--]; low = !low; } break; }- default: for (int i = 0; i < m; ++i) pat[pn++] = idx[i]; break; // Up / AsPlayed / Random- }- if (pn == 0) pat[pn++] = idx[0];const int octs = std::clamp((int)std::lround(p_[GOctaves].load(std::memory_order_relaxed)), 1, 8);const int octMode = (int)std::lround(p_[GOctaveMode].load(std::memory_order_relaxed));int oo[16], on = 0;@@ -298,18 +345,42 @@ private:case OctDown: for (int o = octs - 1; o >= 0; --o) oo[on++] = o; break;case OctUpDown: for (int o = 0; o < octs; ++o) oo[on++] = o;for (int o = octs - 2; o >= 1; --o) oo[on++] = o; break;- default: for (int o = 0; o < octs; ++o) oo[on++] = o; break; // Up / Random+ case OctRandom: oo[on++] = 0; break; // a random octave per step instead+ default: for (int o = 0; o < octs; ++o) oo[on++] = o; break;}- if (on == 0) oo[on++] = 0;- for (int oi = 0; oi < on && len < kSeqMax; ++oi)- for (int pi = 0; pi < pn && len < kSeqMax; ++pi) {- seq[len] = heldBuf_[pat[pi]].pitch + 12 * oo[oi];- vel[len] = heldBuf_[pat[pi]].vel; ++len;+ int n = 0;+ for (int oi = 0; oi < on && n < kSeqMax; ++oi)+ for (int i = 0; i < m && n < kSeqMax; ++i) {+ rangeBuf_[n] = heldBuf_[idx[i]].pitch + 12 * oo[oi];+ rangeVel_[n] = heldBuf_[idx[i]].vel; ++n;+ }+ auto push = [&](int i) { if (len < kSeqMax) { seq[len] = rangeBuf_[i]; vel[len] = rangeVel_[i]; ++len; } };+ switch (order) {+ case OrdDown: for (int i = n - 1; i >= 0; --i) push(i); break;+ case OrdUpDown: for (int i = 0; i < n; ++i) push(i); for (int i = n - 2; i >= 1; --i) push(i); break;+ case OrdDownUp: for (int i = n - 1; i >= 0; --i) push(i); for (int i = 1; i <= n - 2; ++i) push(i); break;+ case OrdConverge: case OrdDiverge: {+ int c[kSeqMax], cn = 0, lo = 0, hi = n - 1;+ while (lo <= hi) { c[cn++] = lo; if (lo != hi) c[cn++] = hi; ++lo; --hi; }+ if (order == OrdConverge) for (int i = 0; i < cn; ++i) push(c[i]);+ else for (int i = cn - 1; i >= 0; --i) push(c[i]);+ break;}+ default: for (int i = 0; i < n; ++i) push(i); break; // Up / AsPlayed / Random / Chord+ }}- int octaveRandom(long stepAbs) {+ int octaveRandom(long kp) {const int octs = std::clamp((int)std::lround(p_[GOctaves].load(std::memory_order_relaxed)), 1, 8);- return ((int)std::lround(p_[GOctaveMode].load(std::memory_order_relaxed)) == OctRandom) ? (int)(rnd01(stepAbs, 5) * octs) : 0;+ return ((int)std::lround(p_[GOctaveMode].load(std::memory_order_relaxed)) == OctRandom) ? (int)(rnd01(kp, 5) * octs) : 0;+ }++ // Snapshot the chord for the editor (audio thread → UI): the held notes, or — once all are+ // released — the last chord that played, so the Pattern view keeps showing it.+ void publishChord() {+ heldLive_.store(held_, std::memory_order_relaxed);+ if (held_ <= 0) return;+ for (int i = 0; i < held_; ++i) chord_[i].store(heldBuf_[i].pitch, std::memory_order_relaxed);+ chordN_.store(held_, std::memory_order_release);}int loopPos(long stepAbs, int loop) {@@ -342,6 +413,9 @@ private:double sr_ = 44100.0, arpBeat_ = 0.0, phaseRef_ = 0.0;std::atomic<float> ccOut_{0.0f}, ccDepth_{1.0f};+ std::atomic<bool> restartReq_{false};+ std::atomic<int32_t> curLp_{-1}, curK_{-1}, heldLive_{0}, chordN_{0};+ std::atomic<int32_t> chord_[kMaxHeld] {};std::atomic<int32_t> ccDev_{-2}, ccParam_{-1};std::atomic<float> p_[kNumParams];};diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex 5d84dbcf..1b60d974 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -638,6 +638,7 @@ public:int32_t midiEffectLastIn(int32_t trackId, int32_t index) const; // last remapped note-on IN value (Scale pitch / Velocity vel), -1 = noneint32_t midiEffectLastOut(int32_t trackId, int32_t index) const; // last remapped note-on OUT value, -1 = noneint32_t midiEffectScope(int32_t trackId, int32_t index, float* out, int32_t maxN) const; // float scope (Nota Velocity in/out pairs)+ void midiEffectCommand(int32_t trackId, int32_t index, int32_t cmd); // editor command (Nota Arp: 1 = restart)const char* midiEffectName(int32_t trackId, int32_t index) const;int32_t midiEffectParamCount(int32_t trackId, int32_t index) const;const char* midiEffectParamName(int32_t trackId, int32_t index, int32_t paramIndex) const;diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cppindex 33d88331..92bfe8fe 100644--- a/src/native/nota.engine/src/Engine_Devices.cpp+++ b/src/native/nota.engine/src/Engine_Devices.cpp@@ -727,6 +727,7 @@ bool Engine::midiEffectBypassed(int32_t t, int32_t i) const { auto* m = mint32_t Engine::midiEffectLastIn(int32_t t, int32_t i) const { auto* m = midiDeviceAt(t, i); return m ? m->midiLastIn() : -1; }int32_t Engine::midiEffectLastOut(int32_t t, int32_t i) const { auto* m = midiDeviceAt(t, i); return m ? m->midiLastOut() : -1; }int32_t Engine::midiEffectScope(int32_t t, int32_t i, float* out, int32_t maxN) const { auto* m = midiDeviceAt(t, i); return m ? m->midiScope(out, maxN) : 0; }+void Engine::midiEffectCommand(int32_t t, int32_t i, int32_t cmd) { if (auto* m = midiDeviceAt(t, i)) m->midiCommand(cmd); }void Engine::setMidiEffectCcDest(int32_t t, int32_t i, int32_t dev, int32_t param) { if (auto* m = midiDeviceAt(t, i)) m->setCcDest(dev, param); }void Engine::setMidiEffectCcDepth(int32_t t, int32_t i, float d) { if (auto* m = midiDeviceAt(t, i)) m->setCcDepth(d); }int32_t Engine::midiEffectCcDestDevice(int32_t t, int32_t i) const { auto* m = midiDeviceAt(t, i); return m ? m->ccDestDevice() : -2; }diff --git a/src/native/nota.engine/src/MidiChord.h b/src/native/nota.engine/src/MidiChord.hindex 8b9a14f9..185ae29a 100644--- a/src/native/nota.engine/src/MidiChord.h+++ b/src/native/nota.engine/src/MidiChord.h@@ -1,15 +1,22 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Chord — a MIDI effect (midiKind 1), reworked to mockup 3b. Each incoming note is-// played (optionally) plus up to six added voices at fixed semitone offsets (0 = voice-// off), each with its own relative velocity. Extra shaping: Strum (spread the note-ons-// over time), Spread (open the voicing by octaves), Fold (snap added notes into the-// played note's major scale) and Keep Root. Like a classic chord MIDI effect, but with strum + fold.+// Nota Chord — a MIDI effect (midiKind 1), almanac mockups 1a / 1b. Each incoming note is+// played (Keep Root) plus up to six added voices ("shifts"): each slot has an on/off switch,+// a semitone offset (−12..+12) and a velocity offset (MIDI units, −64..+63). Shaping:+// • Strum — the chord's note-ons spread low → high, Strum ms apart;+// • Spread — opens the voicing: from ⅓ every other active shift goes up an octave, from ⅔+// the rest too (the mockup's two levels);+// • Fold — an added note outside the fold scale (Fold Key + major / natural minor) drops+// a semitone into it.+// What each key produced is remembered, so its note-off releases exactly those notes even+// if the shifts changed while it was held; overlapping chords share output notes by count.//-// Param layout is APPEND-ONLY so old projects load unchanged: indices 0..4 stay the-// original Voice 1..5 semitone offsets; index 5 adds Voice 6; 6..9 add the globals; 10..15-// add the per-voice velocities. New params default to neutral (Keep Root on, rest off).+// Param layout is APPEND-ONLY so old projects load unchanged: 0..5 Voice 1..6 semitones,+// 6..9 Strum / Keep Root / Spread / Fold, 10..15 Vel 1..6, then (appended in the almanac+// rework) 16..21 On 1..6, 22 Fold Key, 23 Fold Mode, 24 View (editor size — UI state).+// Projects saved before On N existed treated "0 semitones" as off; ProjectService derives+// On N from Voice N when the saved blob stops at 16 params.#pragma once@@ -19,29 +26,39 @@#include <cmath>#include <cstdint>#include <memory>-#include <cstdio>namespace nota {class MidiChord final : public MidiDevice {public:static constexpr int kVoices = 6;+ static constexpr int kMaxOut = kVoices + 1;enum Param {- Voice1 = 0, Voice2, Voice3, Voice4, Voice5, Voice6, // semitone offsets (0 = off)+ Voice1 = 0, Voice2, Voice3, Voice4, Voice5, Voice6, // semitone offsetsStrum, KeepRoot, Spread, Fold,- Vel1, Vel2, Vel3, Vel4, Vel5, Vel6, // per-voice velocity offset (%)+ Vel1, Vel2, Vel3, Vel4, Vel5, Vel6, // velocity offsets (MIDI units)+ On1, On2, On3, On4, On5, On6, // slot switches+ FoldKey, FoldMode, // fold scale: key 0..11 (C..B), 0 major / 1 minor+ View, // editor size (0 = L, 1 = S) — UI statekNumParams};MidiChord() {- p_[Voice1].store(4.0f); // major third- p_[Voice2].store(7.0f); // fifth- for (int v = Voice3; v <= Voice6; ++v) p_[v].store(0.0f);- p_[Strum].store(0.0f);- p_[KeepRoot].store(1.0f); // pass the played note (matches the pre-rework behaviour)+ // Default: Maj7 (+4 +7 +11) with a light 30 ms strum — the mockup's opening state.+ const float semis[kVoices] = { 4.0f, 7.0f, 11.0f, 0.0f, 0.0f, 0.0f };+ for (int v = 0; v < kVoices; ++v) {+ p_[Voice1 + v].store(semis[v]);+ p_[Vel1 + v].store(0.0f);+ p_[On1 + v].store(v < 3 ? 1.0f : 0.0f);+ }+ p_[Strum].store(30.0f);+ p_[KeepRoot].store(1.0f);p_[Spread].store(0.0f);p_[Fold].store(0.0f);- for (int v = Vel1; v <= Vel6; ++v) p_[v].store(0.0f);+ p_[FoldKey].store(0.0f);+ p_[FoldMode].store(0.0f);+ p_[View].store(0.0f);+ resetLive();}int32_t midiKind() const override { return 1; }@@ -51,26 +68,27 @@ public:int32_t paramCount() const override { return kNumParams; }const char* paramName(int32_t i) const override {- switch (i) {- case Voice1: return "Voice 1"; case Voice2: return "Voice 2"; case Voice3: return "Voice 3";- case Voice4: return "Voice 4"; case Voice5: return "Voice 5"; case Voice6: return "Voice 6";- case Strum: return "Strum"; case KeepRoot: return "Keep Root"; case Spread: return "Spread"; case Fold: return "Fold";- case Vel1: return "Vel 1"; case Vel2: return "Vel 2"; case Vel3: return "Vel 3";- case Vel4: return "Vel 4"; case Vel5: return "Vel 5"; case Vel6: return "Vel 6";- default: return "";- }+ static const char* const names[kNumParams] = {+ "Voice 1", "Voice 2", "Voice 3", "Voice 4", "Voice 5", "Voice 6",+ "Strum", "Keep Root", "Spread", "Fold",+ "Vel 1", "Vel 2", "Vel 3", "Vel 4", "Vel 5", "Vel 6",+ "On 1", "On 2", "On 3", "On 4", "On 5", "On 6",+ "Fold Key", "Fold Mode", "View",+ };+ return (i >= 0 && i < kNumParams) ? names[i] : "";}float paramMin(int32_t i) const override {- if (i >= Voice1 && i <= Voice6) return -24.0f;- if (i >= Vel1 && i <= Vel6) return -100.0f;- return 0.0f; // strum / keeproot / spread / fold+ if (i >= Voice1 && i <= Voice6) return -12.0f;+ if (i >= Vel1 && i <= Vel6) return -64.0f;+ return 0.0f;}float paramMax(int32_t i) const override {- if (i >= Voice1 && i <= Voice6) return 24.0f;- if (i >= Vel1 && i <= Vel6) return 100.0f;- if (i == Strum) return 120.0f;+ if (i >= Voice1 && i <= Voice6) return 12.0f;+ if (i >= Vel1 && i <= Vel6) return 63.0f;+ if (i == Strum) return 100.0f;if (i == Spread) return 100.0f;- return 1.0f; // keeproot / fold+ if (i == FoldKey) return 11.0f;+ return 1.0f; // switches, fold mode, view}float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(v, std::memory_order_relaxed); }@@ -78,98 +96,183 @@ public:std::shared_ptr<MidiDevice> clone() const override {auto c = std::make_shared<MidiChord>();for (int i = 0; i < kNumParams; ++i) c->p_[i].store(p_[i].load(std::memory_order_relaxed));+ c->setSampleRate(sr_, 0);c->setBypassed(bypassed());return c;}- void reset() override { nPend_ = 0; clock_ = 0; }+ void reset() override { resetLive(); }++ // Editor telemetry: [0] root of the latest chord (-1 = none yet), [1] keys held now,+ // [2] how many of its notes have sounded (the strum's progress), [3] n = chord size,+ // [4..4+n) its pitches low → high, [4+n..4+2n) their velocities 1..127.+ int32_t midiScope(float* out, int32_t maxN) const override {+ if (!out || maxN < 4) return 0;+ out[0] = (float)lastRoot_.load(std::memory_order_relaxed);+ out[1] = (float)heldLive_.load(std::memory_order_relaxed);+ out[2] = (float)sounded_.load(std::memory_order_relaxed);+ int n = std::min(lastN_.load(std::memory_order_acquire), std::min(kMaxOut, (int)(maxN - 4) / 2));+ out[3] = (float)n;+ for (int i = 0; i < n; ++i) {+ out[4 + i] = (float)lastPit_[i].load(std::memory_order_relaxed);+ out[4 + n + i] = (float)lastVel_[i].load(std::memory_order_relaxed);+ }+ return 4 + 2 * n;+ }void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut,int32_t frames, double, double, bool) override {nOut = 0;- if (bypassed()) { for (int i = 0; i < nIn && nOut < maxOut; ++i) out[nOut++] = in[i]; clock_ += frames; return; }-const int64_t blockEnd = clock_ + frames;- const bool keepRoot = p_[KeepRoot].load(std::memory_order_relaxed) >= 0.5f;- const bool fold = p_[Fold].load(std::memory_order_relaxed) >= 0.5f;- const double spread01 = std::clamp(p_[Spread].load(std::memory_order_relaxed) / 100.0, 0.0, 1.0);- const double strumSamp = std::max(0.0f, p_[Strum].load(std::memory_order_relaxed)) * 0.001 * sr_;- int semi[kVoices]; float velo[kVoices];- for (int v = 0; v < kVoices; ++v) {- semi[v] = (int)std::lround(p_[Voice1 + v].load(std::memory_order_relaxed));- velo[v] = p_[Vel1 + v].load(std::memory_order_relaxed);- }+ auto emit = [&](int64_t at, bool on, int pitch, float vel) {+ if (nOut >= maxOut) return;+ int off = (int)(at - clock_);+ out[nOut++] = { std::clamp(off, 0, std::max(0, frames - 1)), on, pitch, vel };+ };- // 1) Drain pending (strummed) note-ons that now fall inside this block.+ // 1) Strummed note-ons that now fall inside this block (still flushed when bypassed,+ // so a chord started before the bypass completes and its offs stay balanced).for (int k = 0; k < nPend_;) {if (pend_[k].abs < blockEnd) {- if (nOut < maxOut) { int off = (int)(pend_[k].abs - clock_); out[nOut++] = { off < 0 ? 0 : off, true, pend_[k].pitch, pend_[k].vel }; }+ emit(pend_[k].abs, true, pend_[k].pitch, pend_[k].vel);+ if (pend_[k].chord == chordSeq_) sounded_.fetch_add(1, std::memory_order_relaxed);pend_[k] = pend_[--nPend_];} else ++k;}- // 2) Process input events.+ if (bypassed()) {+ // Pass through, but a key that was chorded still releases its chord.+ for (int i = 0; i < nIn; ++i) {+ const MidiEv& e = in[i];+ if (!e.on && keys_[e.pitch].n > 0) releaseKey(e, clock_ + e.off, emit);+ else emit(clock_ + e.off, e.on, e.pitch, e.vel);+ }+ clock_ = blockEnd;+ return;+ }++ const bool keepRoot = p_[KeepRoot].load(std::memory_order_relaxed) >= 0.5f;+ const bool fold = p_[Fold].load(std::memory_order_relaxed) >= 0.5f;+ const int key = ((int)std::lround(p_[FoldKey].load(std::memory_order_relaxed)) % 12 + 12) % 12;+ const bool minor = p_[FoldMode].load(std::memory_order_relaxed) >= 0.5f;+ const double spread01 = std::clamp(p_[Spread].load(std::memory_order_relaxed) / 100.0, 0.0, 1.0);+ const int level = std::min(2, (int)std::floor(spread01 * 3.0 + 1e-9));+ const double strumSamp = std::clamp(p_[Strum].load(std::memory_order_relaxed), 0.0f, 200.0f) * 0.001 * sr_;+for (int i = 0; i < nIn; ++i) {const MidiEv& e = in[i];const int64_t absEv = clock_ + e.off;+ if (!e.on) { releaseKey(e, absEv, emit); continue; }++ // A retriggered key first releases what it played before.+ if (keys_[e.pitch].n > 0) releaseKey({ e.off, false, e.pitch, 0.0f }, absEv, emit);- // Build the output pitches for this key (root + active added voices).- int pit[kVoices + 1]; float vel[kVoices + 1]; int n = 0;- if (keepRoot) { pit[n] = e.pitch; vel[n] = e.vel; ++n; }+ // Build the chord for this key: root + active shifts, deduplicated, low → high.+ int pit[kMaxOut]; float vel[kMaxOut]; bool played[kMaxOut]; int n = 0;+ auto add = [&](int p, float v, bool isRoot) {+ if (p < 0 || p > 127) return;+ for (int k = 0; k < n; ++k) if (pit[k] == p) { if (isRoot) { vel[k] = v; played[k] = true; } return; }+ pit[n] = p; vel[n] = v; played[n] = isRoot; ++n;+ };+ if (keepRoot) add(e.pitch, e.vel, true);+ const int vIn = (int)std::lround(std::clamp(e.vel, 0.0f, 1.0f) * 127.0f);+ int k = 0;for (int v = 0; v < kVoices; ++v) {- if (semi[v] == 0) continue;- int p = e.pitch + (fold ? foldToMajor(semi[v]) : semi[v]);- if (spread01 > 0.0) p += 12 * (int)std::floor(spread01 * (v + 1) + 1e-9); // open the voicing- if (p < 0 || p > 127) continue;- float vl = std::clamp(e.vel * (1.0f + velo[v] / 100.0f), 0.0f, 1.0f);- pit[n] = p; vel[n] = vl; ++n;+ if (p_[On1 + v].load(std::memory_order_relaxed) < 0.5f) continue;+ int semi = std::clamp((int)std::lround(p_[Voice1 + v].load(std::memory_order_relaxed)), -24, 24);+ int p = e.pitch + semi;+ if (fold) p = foldInto(p, key, minor);+ if ((k % 2 == 0 && level >= 1) || (k % 2 == 1 && level >= 2)) p += 12;+ ++k;+ int vv = std::clamp(vIn + (int)std::lround(p_[Vel1 + v].load(std::memory_order_relaxed)), 1, 127);+ add(p, vv / 127.0f, false);}+ sortByPitch(pit, vel, played, n);- if (e.on) {- // Strum: order the sounding notes low→high and delay each by its rank.- sortByPitch(pit, vel, n);- for (int k = 0; k < n; ++k) {- int64_t at = absEv + (int64_t)std::llround(strumSamp * k);- if (at < blockEnd) { if (nOut < maxOut) { int off = (int)(at - clock_); out[nOut++] = { off < 0 ? 0 : off, true, pit[k], vel[k] }; } }- else if (nPend_ < kMaxPend) pend_[nPend_++] = { at, pit[k], vel[k] };- }- } else {- // Note-off: for each output pitch, cancel a still-pending on, else emit the off.- for (int k = 0; k < n; ++k) {- if (cancelPending(pit[k])) continue;- if (nOut < maxOut) out[nOut++] = { e.off, false, pit[k], e.vel };- }+ // Publish the chord for the editor before any of it sounds.+ ++chordSeq_;+ lastRoot_.store(e.pitch, std::memory_order_relaxed);+ sounded_.store(0, std::memory_order_relaxed);+ for (int q = 0; q < n; ++q) {+ lastPit_[q].store(pit[q], std::memory_order_relaxed);+ lastVel_[q].store((int)std::lround(vel[q] * 127.0f), std::memory_order_relaxed);}+ lastN_.store(n, std::memory_order_release);++ Key& kk = keys_[e.pitch];+ kk.n = 0;+ for (int q = 0; q < n; ++q) {+ kk.out[kk.n++] = pit[q];+ if (outCount_[pit[q]]++ > 0) { sounded_.fetch_add(1, std::memory_order_relaxed); continue; } // already sounding+ int64_t at = absEv + (int64_t)std::llround(strumSamp * q);+ if (at < blockEnd) { emit(at, true, pit[q], vel[q]); sounded_.fetch_add(1, std::memory_order_relaxed); }+ else if (nPend_ < kMaxPend) pend_[nPend_++] = { at, pit[q], vel[q], chordSeq_ };+ }+ ++held_;}+ heldLive_.store(held_, std::memory_order_relaxed);clock_ = blockEnd;}private:- static int foldToMajor(int iv) {- static const int deg[7] = { 0, 2, 4, 5, 7, 9, 11 };- int within = ((iv % 12) + 12) % 12;- int octs = (iv - within) / 12;- int best = deg[0], bd = 99;- for (int d = 0; d < 7; ++d) { int diff = std::abs(deg[d] - within); if (diff < bd) { bd = diff; best = deg[d]; } }- return octs * 12 + best;+ struct Key { int n = 0; int out[kMaxOut] = {}; };++ template <class Emit>+ void releaseKey(const MidiEv& e, int64_t at, Emit& emit) {+ Key& kk = keys_[e.pitch];+ if (kk.n == 0) { emit(at, false, e.pitch, e.vel); return; } // not ours (e.g. after reset)+ for (int q = 0; q < kk.n; ++q) {+ int p = kk.out[q];+ if (outCount_[p] > 0 && --outCount_[p] > 0) continue; // another key still holds it+ if (cancelPending(p)) continue; // never sounded+ emit(at, false, p, e.vel);+ }+ kk.n = 0;+ if (held_ > 0) --held_;+ heldLive_.store(held_, std::memory_order_relaxed);+ }++ // Drop a pitch outside the scale a semitone — for major and natural minor that always+ // lands on a scale degree.+ static int foldInto(int p, int key, bool minor) {+ static const bool maj[12] = { 1,0,1,0,1,1,0,1,0,1,0,1 };+ static const bool min[12] = { 1,0,1,1,0,1,0,1,1,0,1,0 };+ int deg = ((p - key) % 12 + 12) % 12;+ return (minor ? min : maj)[deg] ? p : p - 1;}- static void sortByPitch(int* pit, float* vel, int n) {- for (int a = 1; a < n; ++a) { int p = pit[a]; float v = vel[a]; int b = a - 1;- for (; b >= 0 && pit[b] > p; --b) { pit[b + 1] = pit[b]; vel[b + 1] = vel[b]; }- pit[b + 1] = p; vel[b + 1] = v; }+ static void sortByPitch(int* pit, float* vel, bool* pl, int n) {+ for (int a = 1; a < n; ++a) {+ int p = pit[a]; float v = vel[a]; bool r = pl[a]; int b = a - 1;+ for (; b >= 0 && pit[b] > p; --b) { pit[b + 1] = pit[b]; vel[b + 1] = vel[b]; pl[b + 1] = pl[b]; }+ pit[b + 1] = p; vel[b + 1] = v; pl[b + 1] = r;+ }}bool cancelPending(int pitch) {for (int k = 0; k < nPend_; ++k) if (pend_[k].pitch == pitch) { pend_[k] = pend_[--nPend_]; return true; }return false;}+ void resetLive() {+ nPend_ = 0; held_ = 0;+ for (auto& k : keys_) k.n = 0;+ for (auto& c : outCount_) c = 0;+ heldLive_.store(0, std::memory_order_relaxed);+ }static constexpr int kMaxPend = 256;- struct Pend { int64_t abs; int32_t pitch; float vel; };- Pend pend_[kMaxPend];- int nPend_ = 0;- int64_t clock_ = 0;- double sr_ = 44100.0;+ struct Pend { int64_t abs; int32_t pitch; float vel; uint32_t chord; };+ Pend pend_[kMaxPend];+ int nPend_ = 0;+ Key keys_[128];+ int outCount_[128] = {};+ int held_ = 0;+ int64_t clock_ = 0;+ uint32_t chordSeq_ = 0;+ double sr_ = 44100.0;std::atomic<float> p_[kNumParams];++ // Editor telemetry (audio thread writes, message thread reads).+ std::atomic<int> lastRoot_{ -1 }, heldLive_{ 0 }, sounded_{ 0 }, lastN_{ 0 };+ std::atomic<int> lastPit_[kMaxOut] = {}, lastVel_[kMaxOut] = {};};} // namespace notadiff --git a/src/native/nota.engine/src/MidiDevice.h b/src/native/nota.engine/src/MidiDevice.hindex 10d039a5..1c7828b4 100644--- a/src/native/nota.engine/src/MidiDevice.h+++ b/src/native/nota.engine/src/MidiDevice.h@@ -71,6 +71,10 @@ public:// up to maxN floats into out, returns the count. 0 = no scope. Message-thread read.virtual int32_t midiScope(float* /*out*/, int32_t /*maxN*/) const { return 0; }+ // An editor command (e.g. Nota Arp: 1 = restart the pattern). Message thread; the+ // device hands it to the audio thread itself (an atomic flag). Unknown = ignored.+ virtual void midiCommand(int32_t /*cmd*/) {}+// Deep copy for track duplication (rebuilt by midiKind() + copied params by the// engine; live state starts fresh). Returns nullptr if the engine should handle it.virtual std::shared_ptr<MidiDevice> clone() const { return nullptr; }diff --git a/src/native/nota.engine/src/nota_engine_device.cpp b/src/native/nota.engine/src/nota_engine_device.cppindex fba399bc..59d2dac6 100644--- a/src/native/nota.engine/src/nota_engine_device.cpp+++ b/src/native/nota.engine/src/nota_engine_device.cpp@@ -133,6 +133,7 @@ int32_t nota_midi_effect_kind(const NotaEngine* e, int32_t t, int32_t i) { rint32_t nota_midi_effect_last_in(const NotaEngine* e, int32_t t, int32_t i) { return e ? CENG(e)->midiEffectLastIn(t, i) : -1; }int32_t nota_midi_effect_last_out(const NotaEngine* e, int32_t t, int32_t i) { return e ? CENG(e)->midiEffectLastOut(t, i) : -1; }int32_t nota_midi_effect_scope(const NotaEngine* e, int32_t t, int32_t i, float* out, int32_t max_n) { return e ? CENG(e)->midiEffectScope(t, i, out, max_n) : 0; }+void nota_midi_effect_command(NotaEngine* e, int32_t t, int32_t i, int32_t cmd) { if (e) ENG(e)->midiEffectCommand(t, i, cmd); }const char* nota_midi_effect_name(const NotaEngine* e, int32_t t, int32_t i) { return e ? CENG(e)->midiEffectName(t, i) : ""; }int32_t nota_midi_effect_param_count(const NotaEngine* e, int32_t t, int32_t i) { return e ? CENG(e)->midiEffectParamCount(t, i) : 0; }const char* nota_midi_effect_param_name(const NotaEngine* e, int32_t t, int32_t i, int32_t p) { return e ? CENG(e)->midiEffectParamName(t, i, p) : ""; }diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 591f7b92..40de501c 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -6267,7 +6267,9 @@ Console.WriteLine("-- Nota Arp (MIDI effect) --");Check(ae.MidiEffectKind(t, 0) == 0, "MIDI effect kind is 0 (Arp)");Check(ae.MidiEffectName(t, 0) == "Nota Arp", $"MIDI effect name is Nota Arp (got '{ae.MidiEffectName(t, 0)}')");int pc = ae.MidiEffectParamCount(t, 0);- Check(pc == 125, $"Nota Arp exposes 125 params (got {pc})");+ Check(pc == 127, $"Nota Arp exposes 127 params (got {pc})");+ Check(ae.MidiEffectParamName(t, 0, 125) == "VelAmt" && ae.MidiEffectParamName(t, 0, 126) == "View", "Nota Arp appends VelAmt + View");+ Check(ae.MidiEffectParamMax(t, 0, 6) == 8f && ae.MidiEffectParamMax(t, 0, 9) == 2f, "Nota Arp: 9 orders, 3 retrig modes");// Param round-trip (Gate).int gate = -1; for (int i = 0; i < pc; i++) if (ae.MidiEffectParamName(t, 0, i) == "Gate") gate = i;@@ -6318,45 +6320,214 @@ Console.WriteLine("-- Nota Arp (MIDI effect) --");int t2 = ae.AddInstrumentTrack();string fw = factory.Apply(ae, tpl.Id, t2);Check(fw.Length == 0 && ae.TrackMidiEffectCount(t2) == 1, $"factory arp template '{tpl.DisplayName}' applies");++ // Factory presets: at least 25, each resolving only real param names; applying in place+ // resets what the preset leaves out (Ratchet Build → Up 1/16 clears the ratchets) but+ // keeps the card size (View).+ var arpPresets = factory.All().Where(p => p.IsMidiEffect && p.BuiltinKind == 0).ToList();+ Check(arpPresets.Count >= 25, $"Nota Arp ships >= 25 presets (got {arpPresets.Count})");+ int pt = ae.AddInstrumentTrack(); int pm = ae.AddMidiEffect(pt, 0);+ var arpNames = Enumerable.Range(0, ae.MidiEffectParamCount(pt, pm)).Select(i => ae.MidiEffectParamName(pt, pm, i)).ToHashSet();+ foreach (var ap in arpPresets)+ {+ var doc = factory.Document(ap.Id);+ var bad = doc?.NamedParams?.Keys.Where(k => !arpNames.Contains(k)).ToList() ?? new();+ Check(doc != null && bad.Count == 0, $"arp preset '{ap.DisplayName}' names real params{(bad.Count > 0 ? " (bad: " + string.Join(",", bad) + ")" : "")}");+ }+ ae.MidiEffectSetParam(pt, pm, 126, 1f); // S view+ factory.ApplyInPlace(ae, arpPresets.First(p => p.DisplayName == "Ratchet Build").Id, pt, pm);+ Check(ae.MidiEffectGetParam(pt, pm, 61 + 6) == 4f, "Ratchet Build sets step-7 ratchet ×4");+ factory.ApplyInPlace(ae, arpPresets.First(p => p.DisplayName == "Up 1/16").Id, pt, pm);+ Check(ae.MidiEffectGetParam(pt, pm, 61 + 6) == 1f && ae.MidiEffectGetParam(pt, pm, 11) == 16f, "preset switch resets unlisted ratchets + steps");+ Check(ae.MidiEffectGetParam(pt, pm, 126) == 1f, "preset switch keeps the card size (View)");+}++// Nota Arp — note orders walk the whole octave range, one note per step. The played pitches+// are read back through a Nota Scale placed after the arp (its last-IN = the arp's output).+Console.WriteLine("-- Nota Arp orders / retrig / telemetry --");+{+ int[] Played(int order, int octaves, int retrig = 1, int steps = 10)+ {+ using var e = new NotaEngine();+ e.SetBpm(120); e.SetTimeSignature(4, 4);+ int t = e.AddInstrumentTrack();+ e.AddMidiClip(t, 0.0, 16.0);+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 16.0, 0.9f), new NotaNote(64, 0.0, 16.0, 0.9f), new NotaNote(67, 0.0, 16.0, 0.9f) });+ e.AddMidiEffect(t, 0); e.AddMidiEffect(t, 2); // Arp → Scale (probe)+ e.MidiEffectSetParam(t, 0, 0, 5f); e.MidiEffectSetParam(t, 0, 6, order); e.MidiEffectSetParam(t, 0, 4, octaves);+ e.MidiEffectSetParam(t, 0, 9, retrig); e.MidiEffectSetParam(t, 0, 3, 0.5f);+ var got = new List<int>(); var buf = new float[256 * 2]; int last = -1;+ e.Seek(0); e.Play();+ for (int b = 0; b < 44100 * 4 / 256 && got.Count < steps; b++)+ {+ e.RenderOffline(buf, 256);+ int p = e.MidiEffectLastIn(t, 1);+ if (p >= 0 && p != last) { got.Add(p); last = p; }+ }+ e.StopTransport();+ return got.ToArray();+ }+ string J(IEnumerable<int> a) => string.Join(",", a);+ var upDown = Played(2, 2);+ Check(J(upDown) == "60,64,67,72,76,79,76,72,67,64", $"Up·Down walks both octaves and back (got {J(upDown)})");+ var downUp = Played(7, 2);+ Check(J(downUp) == "79,76,72,67,64,60,64,67,72,76", $"Down·Up (got {J(downUp)})");+ var conv = Played(3, 2, steps: 6);+ Check(J(conv) == "60,79,64,76,67,72", $"Converge alternates the outer notes inward (got {J(conv)})");+ var div = Played(8, 2, steps: 6);+ Check(J(div) == "72,67,76,64,79,60", $"Diverge spreads from the middle (got {J(div)})");++ // Telemetry + Restart + Beat retrigger.+ using var e = new NotaEngine();+ e.SetBpm(120); e.SetTimeSignature(4, 4);+ int t = e.AddInstrumentTrack();+ e.AddMidiClip(t, 0.0, 16.0);+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 16.0, 0.9f), new NotaNote(64, 0.0, 16.0, 0.9f) });+ e.AddMidiEffect(t, 0);+ var sc = new float[40]; var blk = new float[512 * 2];+ e.Seek(0); e.Play();+ for (int b = 0; b < 44100 / 512; b++) e.RenderOffline(blk, 512); // 1 s = 8 sixteenths+ int n = e.MidiEffectScope(t, 0, sc);+ Check(n == 6 && sc[2] == 2 && sc[3] == 2 && sc[4] == 60 && sc[5] == 64, $"arp telemetry reports the held chord (n={n}, held={sc[2]}, chord={sc[4]},{sc[5]})");+ Check(sc[0] >= 6 && sc[0] <= 8 && sc[1] >= 6, $"arp telemetry reports the sounding step (lp={sc[0]}, k={sc[1]})");+ e.MidiEffectCommand(t, 0, 1); // Restart+ e.RenderOffline(blk, 512); e.RenderOffline(blk, 512);+ e.MidiEffectScope(t, 0, sc);+ Check(sc[1] <= 1, $"Restart starts the pattern over (k={sc[1]})");+ e.MidiEffectSetParam(t, 0, 9, 2f); // Beat: restarts every bar+ e.MidiEffectSetParam(t, 0, 0, 4f); // 1/8T → 12 steps per bar+ int maxK = 0;+ for (int b = 0; b < 44100 * 4 / 512; b++) { e.RenderOffline(blk, 512); e.MidiEffectScope(t, 0, sc); maxK = Math.Max(maxK, (int)sc[1]); }+ e.StopTransport();+ Check(maxK == 11, $"Beat retrigger restarts the pattern every bar (max step {maxK}, expected 11)");}-// ===================== Nota Chord (MIDI kind 1) rework =====================+// ===================== Nota Chord (MIDI kind 1) — almanac rework =====================Console.WriteLine("-- Nota Chord --");{using var e = new NotaEngine();e.SetBpm(120); e.SetTimeSignature(4, 4);int t = e.AddInstrumentTrack();int m = e.AddMidiEffect(t, 1);- Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Chord", "add Nota Chord");+ Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Chord" && e.MidiEffectKind(t, 0) == 1, "add Nota Chord");int pc = e.MidiEffectParamCount(t, 0);- Check(pc == 16, $"Nota Chord exposes 16 params (got {pc})");- var pnames = new System.Collections.Generic.HashSet<string>();- for (int i = 0; i < pc; i++) pnames.Add(e.MidiEffectParamName(t, 0, i));- Check(pnames.Contains("Voice 6") && pnames.Contains("Strum") && pnames.Contains("Keep Root")- && pnames.Contains("Spread") && pnames.Contains("Fold") && pnames.Contains("Vel 1"),- "mockup-3b params present (Voice 6 / Strum / Keep Root / Spread / Fold / Vel 1)");- // Keep Root defaults on (backward-compatible: root passes through).- SetByName(e, t, 0, "Keep Root", 1f);- Check(GetByName(e, t, 0, "Keep Root") >= 0.5f, "Keep Root defaults on");-+ Check(pc == 25, $"Nota Chord exposes 25 params (got {pc})");+ string[] expect = { "Voice 1", "Voice 6", "Strum", "Keep Root", "Spread", "Fold", "Vel 1", "Vel 6", "On 1", "On 6", "Fold Key", "Fold Mode", "View" };+ int[] at = { 0, 5, 6, 7, 8, 9, 10, 15, 16, 21, 22, 23, 24 };+ bool layout = true; for (int i = 0; i < expect.Length; i++) layout &= e.MidiEffectParamName(t, 0, at[i]) == expect[i];+ Check(layout, "param layout is append-only (Voice/Strum/Keep/Spread/Fold/Vel then On/Fold Key/Fold Mode/View)");+ Check(e.MidiEffectParamMin(t, 0, 0) == -12f && e.MidiEffectParamMax(t, 0, 0) == 12f && e.MidiEffectParamMax(t, 0, 10) == 63f,+ "shifts span ±12 st, velocity offsets −64..+63");+ Check(GetByName(e, t, 0, "Voice 3") == 11f && GetByName(e, t, 0, "On 3") == 1f && GetByName(e, t, 0, "On 4") == 0f+ && GetByName(e, t, 0, "Strum") == 30f && GetByName(e, t, 0, "Keep Root") == 1f, "defaults: Maj7 with a 30 ms strum");++ // The chord a key produces, read from the editor telemetry after one short note.+ var sc = new float[32];+ int[] ChordOf(int pitch, float vel = 0.9f)+ {+ e.StopTransport();+ e.SetClipNotes(t, 0, new[] { new NotaNote(pitch, 0.0, 1.0, vel) });+ var buf = new float[4096 * 2]; e.Seek(0); e.Play();+ for (int b = 0; b < 12; b++) e.RenderOffline(buf, 4096); // ~1.1 s: the whole strum has sounded+ e.StopTransport();+ int n = e.MidiEffectScope(t, 0, sc) >= 4 ? (int)sc[3] : 0;+ var r = new int[n]; for (int i = 0; i < n; i++) r[i] = (int)sc[4 + i];+ return r;+ }e.AddMidiClip(t, 0.0, 4.0);- e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 2.0, 0.9f) });- // With Keep Root on vs off the audio differs (the root note is removed).- var withRoot = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(withRoot, 12000); e.StopTransport();+ SetByName(e, t, 0, "Strum", 0f);+ Check(ChordOf(60).SequenceEqual(new[] { 60, 64, 67, 71 }), "Maj7 on C4 → C E G B");+ Check((int)sc[0] == 60, "telemetry reports the played root");+ SetByName(e, t, 0, "On 2", 0f);+ Check(ChordOf(60).SequenceEqual(new[] { 60, 64, 71 }), "a switched-off shift is dropped");+ SetByName(e, t, 0, "On 2", 1f);SetByName(e, t, 0, "Keep Root", 0f);- var noRoot = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(noRoot, 12000); e.StopTransport();- double kd = 0; for (int i = 0; i < 12000 * 2; i++) { double d = withRoot[i] - noRoot[i]; kd += d * d; }- Check(Math.Sqrt(kd / (12000 * 2)) > 0.002, "Keep Root toggle changes the output");+ Check(ChordOf(60).SequenceEqual(new[] { 64, 67, 71 }), "Keep root off drops the played note");+ SetByName(e, t, 0, "Keep Root", 1f);+ SetByName(e, t, 0, "Spread", 40f);+ Check(ChordOf(60).SequenceEqual(new[] { 60, 67, 76, 83 }), "Spread ⅓: every other shift up an octave");+ SetByName(e, t, 0, "Spread", 80f);+ Check(ChordOf(60).SequenceEqual(new[] { 60, 76, 79, 83 }), "Spread ⅔: all shifts up an octave");+ SetByName(e, t, 0, "Spread", 0f);+ SetByName(e, t, 0, "Fold", 1f); SetByName(e, t, 0, "On 3", 0f);+ Check(ChordOf(62).SequenceEqual(new[] { 62, 65, 69 }), "Fold in C major: a triad on D turns minor");+ SetByName(e, t, 0, "Fold Key", 9f); SetByName(e, t, 0, "Fold Mode", 1f);+ Check(ChordOf(64).SequenceEqual(new[] { 64, 67, 71 }), "Fold in A minor: a triad on E turns minor");+ SetByName(e, t, 0, "Fold", 0f); SetByName(e, t, 0, "On 3", 1f);+ SetByName(e, t, 0, "Vel 1", -30f);+ ChordOf(60, 100f / 127f);+ Check((int)sc[4 + 4 + 1] == 70 && (int)sc[4 + 4 + 0] == 100, $"velocity offsets add MIDI units (E at {(int)sc[9]}, root {(int)sc[8]})");+ SetByName(e, t, 0, "Vel 1", 0f);++ // Strum: the telemetry counts the notes that have sounded.+ SetByName(e, t, 0, "Strum", 100f);+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 2.0, 0.9f) });+ var sbuf = new float[1024 * 2]; e.Seek(0); e.Play();+ e.RenderOffline(sbuf, 1024); e.MidiEffectScope(t, 0, sc); int early = (int)sc[2], held = (int)sc[1];+ for (int b = 0; b < 20; b++) e.RenderOffline(sbuf, 1024);+ e.MidiEffectScope(t, 0, sc); int late = (int)sc[2];+ e.StopTransport();+ Check(held == 1 && early >= 1 && early < 4 && late == 4, $"Strum 100 ms sounds the chord low → high over time ({early} → {late} of 4, held {held})");++ // Changing the shifts while a key is held still releases what it played (no stuck notes).+ SetByName(e, t, 0, "Strum", 0f);+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 0.5, 0.9f) });+ var hb = new float[2048 * 2]; e.Seek(0); e.Play();+ e.RenderOffline(hb, 2048);+ SetByName(e, t, 0, "Voice 1", 5f); SetByName(e, t, 0, "Voice 2", 9f); SetByName(e, t, 0, "On 4", 1f); SetByName(e, t, 0, "Voice 4", -5f);+ for (int b = 0; b < 60; b++) e.RenderOffline(hb, 2048); // ~2.8 s: note off at 0.25 s, then the release tail+ e.StopTransport();+ Check(Rms(hb, 2048) < 1e-4f, $"editing shifts mid-note leaves no stuck notes (tail RMS {Rms(hb, 2048):E1})");// Strum + all voices stays finite and audible.- SetByName(e, t, 0, "Keep Root", 1f);- SetByName(e, t, 0, "Voice 3", 12f); SetByName(e, t, 0, "Strum", 40f); SetByName(e, t, 0, "Spread", 50f);+ SetByName(e, t, 0, "Strum", 40f); SetByName(e, t, 0, "Spread", 50f);+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 2.0, 0.9f) });var sb = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(sb, 12000); e.StopTransport();bool fin = true; foreach (var s in sb) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { fin = false; break; }Check(fin && Rms(sb, 12000) > 0.001f, "Strum + Spread render audible + finite");+ SetByName(e, t, 0, "Voice 3", 12f);int t2 = e.DuplicateTrack(t);- Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Voice 3") - 12f) < 1e-3, "duplicate track clones Chord params");+ Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Voice 3") - 12f) < 1e-3 && GetByName(e, t2, 0, "On 4") == 1f, "duplicate track clones Chord params");++ // A project saved before the slot switches (16 params, 0 st = off) loads with On N derived.+ {+ var w = new System.Collections.Generic.List<string>();+ var doc = ProjectService.Capture(e, new TransportState(120, 1, false, false), w);+ var md = doc.Tracks.First(x => x.MidiEffects.Count > 0).MidiEffects[0];+ var legacy = new float[16];+ legacy[0] = 3; legacy[1] = 7; legacy[2] = 0; legacy[3] = -12; legacy[7] = 1; // Voice 1,2,4 used; 3,5,6 "off"+ md.Params = legacy;+ using var e2 = new NotaEngine();+ ProjectService.Apply(doc, e2, Path.GetTempPath());+ int lt = -1;+ for (int i = 0; e2.TryGetTrackInfo(i, out var ti); i++) if (e2.TrackMidiEffectCount(ti.Id) > 0 && e2.MidiEffectKind(ti.Id, 0) == 1) { lt = ti.Id; break; }+ Check(lt > 0 && GetByName(e2, lt, 0, "On 1") == 1f && GetByName(e2, lt, 0, "On 3") == 0f && GetByName(e2, lt, 0, "On 4") == 1f+ && GetByName(e2, lt, 0, "On 5") == 0f, "legacy Chord project: 0-semitone slots load switched off");+ }++ // Factory presets: 25+, every name valid, each applies in place and renders.+ {+ var cat = new FactoryPresetCatalog();+ var mine = cat.All().Where(p => p.IsMidiEffect && p.BuiltinKind == 1).ToList();+ Check(mine.Count >= 25, $"Nota Chord ships 25+ factory presets (got {mine.Count})");+ var names = new System.Collections.Generic.HashSet<string>();+ for (int i = 0; i < pc; i++) names.Add(e.MidiEffectParamName(t, 0, i));+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !names.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();+ Check(bad.Count == 0, $"every Chord preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ SetByName(e, t, 0, "View", 1f);+ var off = new System.Collections.Generic.List<string>();+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.9f) });+ foreach (var p in mine)+ {+ if (cat.ApplyInPlace(e, p.Id, t, 0).Length != 0) { off.Add(p.DisplayName + " (apply)"); continue; }+ var pb = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(pb, 12000); e.StopTransport();+ bool ok = true; foreach (var x in pb) if (!float.IsFinite(x) || Math.Abs(x) > 8f) { ok = false; break; }+ if (!ok || Rms(pb, 12000) < 0.001f) off.Add(p.DisplayName);+ }+ Check(off.Count == 0, $"every Chord preset applies and renders{(off.Count > 0 ? " — off: " + string.Join(", ", off) : "")}");+ Check(GetByName(e, t, 0, "View") == 1f, "presets leave the card size (View) alone");+ }}// ===================== Nota Scale (MIDI kind 2) rework =====================