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
Add generative clip tools to the piano roll
Egor Khindikaynen3651ab926db4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2cab9b30..a0eb324a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,28 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Clip tools — generative writing and rewriting in the piano roll.** A **Tools** rail+ opens beside the roll with fifteen tools. Six **generators** write notes: *Rhythm*+ (a pattern weighted toward the strong beats, with density, variation and accent),+ *Seed* (reads the clip's own intervals, note lengths and onset spacing, then writes a+ fresh take in the same voice), *Stacks* (grows every note into a chord — 3rds, 4ths,+ 5ths, octaves or clusters, voiced close / open / drop 2 / spread / power), *Euclidean*+ (hits spread as evenly as the steps allow, with rotation and a second Euclidean ride+ picking the accents), *Melodic Steps* (a step sequencer in scale degrees with a contour)+ and *Shape* (a curve traced across the clip). Nine **transformations** rewrite them:+ *Arpeggiate*, *Connect* (runs that walk to the next pitch, carved out of the source note+ when the part is legato), *Ornament* (grace notes, trills, mordents, turns, flams and+ rolls), *Quantize* (with swing and humanize), *Recombine* (pulls pitch and rhythm apart+ and puts them back together differently, in phrase-sized chunks), *Span*, *Strum*,+ *Time Warp* and *Velocity Shaper*.+- **Every change is previewed before you commit to it.** Turning a knob re-runs the tool,+ shows the result in the roll and streams it to the engine, so a generator is audible+ while you shape it. **Apply** keeps it as one undo step; **Revert** drops it without+ leaving anything in the history. A selection scopes a tool to those notes and carries+ the rest of the clip through untouched; output can replace what it was given or be added+ on top. Every tool is seeded, so a result is repeatable and "New seed" re-rolls it — and+ the ones that think in pitch follow the roll's **Set Scale** key, so what they write+ stays in key.- **Ten factory kits for the Drum Rack.** *Volta* (warm analog boom), *Kompakt* (punchyanalog house), *Micron* (small vintage rhythm box), *Linnwood* (80s PCM machine, gatedsnare), *Atelier* (acoustic studio kit), *Cellar* (dusty vinyl break), *Neon* (moderndiff --git a/FEATURES.md b/FEATURES.mdindex 9036c0e7..59795d5b 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -135,6 +135,21 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).- A MIDI clip trimmed in the arrangement mutes note tails at its boundary.- Live edits (moving a note, changing its length) reach the engine immediately, and awhole drag is a single undo step.+- **Clip tools (generate and transform)**: a **Tools** rail beside the piano roll with+ fifteen tools that write or rewrite notes. Six **generators** — *Rhythm* (a pattern that+ leans on the strong beats), *Seed* (learns the clip's own intervals and rhythm, then+ writes a new take in the same voice), *Stacks* (grows each note into a voiced chord),+ *Euclidean*, *Melodic Steps* and *Shape* — and nine **transformations** — *Arpeggiate*,+ *Connect*, *Ornament*, *Quantize*, *Recombine*, *Span*, *Strum*, *Time Warp* and+ *Velocity Shaper*.+ - Every knob move is **previewed in the roll and in the engine** — you hear the result+ before deciding — and **Apply** keeps it as a single undo step. Backing out leaves no+ trace in the history.+ - A selection scopes the tool to those notes; with nothing selected it works the whole+ clip. Output can **replace** what it was given or be **added** on top.+ - Everything is **seeded**, so a result is repeatable and "New seed" re-rolls it.+ - Tools that think in pitch follow the roll's **Set Scale** key, so what they write+ stays in key.- **Pattern (step sequencer)**: on a Drum Rack track the detail panel gains a **Pattern**tab between Devices and Clip — a drum-machine grid with one row per loaded pad. Click astep to place a hit, shift-click for an accent, drag across the grid to paint, and usediff --git a/src/managed/Nota.App/ClipEditorView.cs b/src/managed/Nota.App/ClipEditorView.csindex ff3e47bc..4d895d3f 100644--- a/src/managed/Nota.App/ClipEditorView.cs+++ b/src/managed/Nota.App/ClipEditorView.cs@@ -32,7 +32,8 @@ public sealed class ClipEditorView : UserControlprivate readonly ContentControl _rightHost;private readonly EnvPanel? _envPanel;private readonly ClipPropsView _props;- private Border _notesTab = null!, _envTab = null!;+ private readonly MidiToolsView _tools;+ private Border _notesTab = null!, _envTab = null!, _toolsChip = null!;public ClipEditorView(PianoRollView roll, string clipName, double startBeat,IAudioEngine? engine = null, int trackId = -1, int clipIndex = -1, double lengthBeats = 4)@@ -43,11 +44,16 @@ public sealed class ClipEditorView : UserControlif (engine is not null && trackId > 0 && clipIndex >= 0)_envPanel = new EnvPanel(engine, trackId, clipIndex, lengthBeats);- var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };+ // Props rail | editor | clip-tools rail. The tools rail is a toggle rather than a+ // tab because its whole point is watching the roll change while you turn a knob.+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };_props = new ClipPropsView(roll, clipName, startBeat);grid.Children.Add(_props);Grid.SetColumn(_rightHost, 1);grid.Children.Add(_rightHost);+ _tools = new MidiToolsView(roll) { IsVisible = false };+ Grid.SetColumn(_tools, 2);+ grid.Children.Add(_tools);var header = TabsHeader();DockPanel.SetDock(header, Dock.Top);@@ -73,6 +79,18 @@ public sealed class ClipEditorView : UserControl_rightHost.Content = envelopes ? _envPanel : Roll;PaintTab(_notesTab, !envelopes);PaintTab(_envTab, envelopes);+ if (envelopes && _tools.IsVisible) ToggleTools();+ }++ /// <summary>Shows or hides the clip-tools rail. Hiding drops the tool's preview, so+ /// walking away from a half-tweaked generator leaves the clip as it was.</summary>+ private void ToggleTools()+ {+ bool show = !_tools.IsVisible;+ if (show && _rightHost.Content != Roll) ShowTab(false);+ _tools.IsVisible = show;+ SetChip(_toolsChip, "Tools", show);+ _tools.SetActive(show);}private static void PaintTab(Border tab, bool active)@@ -93,13 +111,20 @@ public sealed class ClipEditorView : UserControlPaintTab(_notesTab, true);PaintTab(_envTab, false);var tabs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { _notesTab, _envTab } };- var scale = ScaleControls();- DockPanel.SetDock(scale, Dock.Right);+ _toolsChip = Chip();+ SetChip(_toolsChip, "Tools", false);+ _toolsChip.PointerPressed += (_, e) => { e.Handled = true; ToggleTools(); };+ var right = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center,+ Children = { ScaleControls(), _toolsChip },+ };+ DockPanel.SetDock(right, Dock.Right);return new Border{Height = 30, Background = Panel, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1),Padding = new Thickness(10, 0),- Child = new DockPanel { LastChildFill = true, Children = { scale, tabs } },+ Child = new DockPanel { LastChildFill = true, Children = { right, tabs } },};}diff --git a/src/managed/Nota.App/MidiToolsView.cs b/src/managed/Nota.App/MidiToolsView.csnew file mode 100644index 00000000..4730135e--- /dev/null+++ b/src/managed/Nota.App/MidiToolsView.cs@@ -0,0 +1,531 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The clip-tools rail on the right of the piano roll: a Generate / Transform+// picker, a parameter list built from the tool's own descriptor (no per-tool+// panel), and the seed / blend / apply row. Every knob move re-runs the tool and+// previews the result in the roll — audible, undo-free — so Apply is a decision+// the user has already heard.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using Nota.Application.Midi;++namespace Nota.App;++public sealed class MidiToolsView : UserControl+{+ private static IBrush Panel => NotaPalette.SurfaceCard;+ private static IBrush Sunken => NotaPalette.BgSunken;+ private static IBrush Raised => NotaPalette.SurfaceRaised;+ private static IBrush BorderDef => NotaPalette.BorderDefault;+ private static IBrush BorderStrong => NotaPalette.BorderStrong;+ private static IBrush Brass => NotaPalette.Accent;+ private static IBrush AccentBright => NotaPalette.AccentBright;+ private static IBrush AccentSubtle => NotaPalette.AccentSubtle;+ private static IBrush TextPrimary => NotaPalette.TextPrimary;+ private static IBrush TextSecondary => NotaPalette.TextSecondary;+ private static IBrush TextTertiary => NotaPalette.TextTertiary;++ public const double RailWidth = 236;++ private readonly PianoRollView _roll;+ private readonly Dictionary<string, MidiToolSettings> _settings = new(StringComparer.Ordinal);++ private readonly StackPanel _toolList = new() { Spacing = 2 };+ private readonly StackPanel _paramList = new() { Spacing = 5 };+ private readonly TextBlock _blurb;+ private readonly TextBlock _scopeText;+ private readonly TextBlock _seedText;+ private readonly TextBlock _resultText;+ private Border _generateTab = null!, _transformTab = null!;+ private Border _replaceChip = null!, _addChip = null!;+ private Border? _applyButton;++ private MidiToolKind _kind = MidiToolKind.Generate;+ private MidiTool? _tool;+ private MidiToolBlend _blend = MidiToolBlend.Replace;+ private int _seed = 1;++ // The clip as it stood before the preview, plus the selection the tool is scoped to.+ private List<NotaNote> _source = new();+ private HashSet<int> _scope = new();+ private bool _suppressResync;++ public MidiToolsView(PianoRollView roll)+ {+ _roll = roll;+ Width = RailWidth;+ Background = Panel;+ BorderBrush = BorderDef;+ BorderThickness = new Thickness(1, 0, 0, 0);++ _blurb = new TextBlock { FontSize = 9, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap, MinHeight = 24 };+ _scopeText = new TextBlock { FontSize = 9, Foreground = TextSecondary, TextWrapping = TextWrapping.Wrap };+ _resultText = Mono("—");+ _resultText.Foreground = TextTertiary;+ _seedText = Mono("1");++ var body = new StackPanel { Spacing = 9, Margin = new Thickness(10) };+ body.Children.Add(KindTabs());+ body.Children.Add(new Border+ {+ Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5),+ Padding = new Thickness(3), MaxHeight = 236,+ Child = new ScrollViewer { Content = _toolList, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled },+ });+ body.Children.Add(_blurb);+ body.Children.Add(Rule());+ body.Children.Add(Section("PARAMETERS", _paramList));+ body.Children.Add(Rule());+ body.Children.Add(SeedRow());+ body.Children.Add(Section("OUTPUT", new StackPanel { Spacing = 5, Children = { BlendRow(), _scopeText, ResultRow() } }));+ body.Children.Add(ActionRow());++ Content = new ScrollViewer+ {+ Content = body,+ HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,+ VerticalScrollBarVisibility = ScrollBarVisibility.Auto,+ };++ RebuildToolList();+ RebuildParams();+ _roll.Changed += OnRollChanged;+ // A preview must not outlive the rail: switching clips replaces the whole editor,+ // and the engine is still holding the previewed notes with nothing in undo to get+ // back from them.+ DetachedFromVisualTree += (_, _) => _roll.CancelPreview();+ Resync();+ }++ /// <summary>Called by the clip editor when the rail is shown or hidden. Hiding drops any+ /// preview, so a tool the user walked away from never silently sticks.</summary>+ public void SetActive(bool active)+ {+ if (active) { Resync(); Preview(); }+ else _roll.CancelPreview();+ }++ // --- state ------------------------------------------------------------++ private void OnRollChanged()+ {+ // ShowPreview raises Changed too; re-reading then would capture the preview as the+ // source and the tool would compound on its own output.+ if (_suppressResync || _roll.Previewing) return;+ Resync();+ }++ /// <summary>Re-reads the clip and the selection as the working set for the next run.</summary>+ private void Resync()+ {+ _source = new List<NotaNote>(_roll.SourceNotes);+ _scope = new HashSet<int>(_roll.SelectionIndices.Where(i => i >= 0 && i < _source.Count));+ _scopeText.Text = _scope.Count > 0+ ? $"Scope · {_scope.Count} selected note{(_scope.Count == 1 ? "" : "s")}"+ : $"Scope · whole clip ({_source.Count} note{(_source.Count == 1 ? "" : "s")})";+ }++ private MidiToolContext Context() => new()+ {+ LengthBeats = _roll.LengthBeats,+ Grid = _roll.Grid,+ ScaleOn = _roll.ScaleOn,+ ScaleRoot = _roll.ScaleRoot,+ ScaleMask = MidiScales.MaskAt(_roll.ScaleIndex),+ Seed = _seed,+ };++ private MidiToolSettings SettingsFor(MidiTool tool)+ {+ if (!_settings.TryGetValue(tool.Id, out var s)) _settings[tool.Id] = s = tool.NewSettings();+ return s;+ }++ private void Preview()+ {+ if (_tool is null) { _roll.CancelPreview(); return; }+ var result = MidiToolRunner.Apply(_tool, _source, _scope, SettingsFor(_tool), Context(), _blend);+ _suppressResync = true;+ _roll.ShowPreview(result);+ _suppressResync = false;+ int delta = result.Count - _source.Count;+ _resultText.Text = $"{result.Count} notes ({delta:+0;-0;\u00b10})";+ _resultText.Foreground = delta == 0 ? TextTertiary : AccentBright;+ PaintApply();+ }++ private void Apply()+ {+ if (_tool is null || !_roll.Previewing) return;+ _suppressResync = true;+ _roll.ApplyPreview();+ _suppressResync = false;+ Resync();+ // Deliberately no re-preview: the applied result is the new source, so running the+ // tool again here would show it applied twice before the user asked for anything.+ // The next knob move (or New seed) arms a fresh preview from the new source.+ _resultText.Text = $"{_source.Count} notes · applied";+ _resultText.Foreground = TextSecondary;+ PaintApply();+ }++ private void Revert()+ {+ _roll.CancelPreview();+ Resync();+ _resultText.Text = "—";+ _resultText.Foreground = TextTertiary;+ PaintApply();+ }++ /// <summary>Apply reads as available only while something is actually pending.</summary>+ private void PaintApply()+ {+ if (_applyButton is null) return;+ bool pending = _roll.Previewing;+ _applyButton.Opacity = pending ? 1 : 0.45;+ _applyButton.Cursor = new Cursor(pending ? StandardCursorType.Hand : StandardCursorType.Arrow);+ }++ private void SelectTool(MidiTool? tool)+ {+ _roll.CancelPreview();+ Resync();+ _tool = tool;+ _blurb.Text = tool?.Blurb ?? "";+ RebuildToolList();+ RebuildParams();+ Preview();+ }++ // --- tool list --------------------------------------------------------++ private Control KindTabs()+ {+ _generateTab = KindTab("Generate", MidiToolKind.Generate);+ _transformTab = KindTab("Transform", MidiToolKind.Transform);+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };+ g.Children.Add(_generateTab);+ Grid.SetColumn(_transformTab, 1);+ g.Children.Add(_transformTab);+ return g;+ }++ private Border KindTab(string label, MidiToolKind kind)+ {+ var t = new TextBlock { Text = label, FontSize = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border+ {+ Height = 24, CornerRadius = new CornerRadius(5), BorderThickness = new Thickness(1),+ Cursor = new Cursor(StandardCursorType.Hand), Child = t, Tag = kind,+ };+ b.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ if (_kind == kind) return;+ _kind = kind;+ PaintKindTabs();+ SelectTool(null);+ };+ return b;+ }++ private void PaintKindTabs()+ {+ foreach (var b in new[] { _generateTab, _transformTab })+ {+ bool active = (MidiToolKind)b.Tag! == _kind;+ b.Background = active ? AccentSubtle : Raised;+ b.BorderBrush = active ? Brass : BorderStrong;+ ((TextBlock)b.Child!).Foreground = active ? AccentBright : TextSecondary;+ }+ }++ private void RebuildToolList()+ {+ PaintKindTabs();+ _toolList.Children.Clear();+ foreach (var tool in MidiToolCatalog.All.Where(t => t.Kind == _kind))+ {+ bool active = _tool?.Id == tool.Id;+ var text = new TextBlock+ {+ Text = tool.Name, FontSize = 11, VerticalAlignment = VerticalAlignment.Center,+ Foreground = active ? AccentBright : TextPrimary, Margin = new Thickness(8, 0, 0, 0),+ };+ var row = new Border+ {+ Height = 24, CornerRadius = new CornerRadius(4),+ Background = active ? AccentSubtle : Brushes.Transparent,+ BorderBrush = active ? Brass : Brushes.Transparent, BorderThickness = new Thickness(1),+ Cursor = new Cursor(StandardCursorType.Hand), Child = text,+ };+ var captured = tool;+ row.PointerPressed += (_, e) => { e.Handled = true; SelectTool(captured); };+ _toolList.Children.Add(row);+ }+ }++ // --- parameter rail ---------------------------------------------------++ private void RebuildParams()+ {+ _paramList.Children.Clear();+ if (_tool is null)+ {+ _paramList.Children.Add(new TextBlock { Text = "Pick a tool.", FontSize = 9, Foreground = TextTertiary });+ return;+ }+ var settings = SettingsFor(_tool);+ foreach (var p in _tool.Params) _paramList.Children.Add(ParamRow(p, settings));+ }++ private Control ParamRow(MidiToolParam p, MidiToolSettings settings)+ {+ var value = Mono(p.Display(settings[p.Id]));+ value.Foreground = TextSecondary;+ value.HorizontalAlignment = HorizontalAlignment.Right;+ value.Margin = new Thickness(0);++ Control control;+ switch (p.Kind)+ {+ case MidiParamKind.Choice:+ {+ value.Text = p.Display(settings[p.Id]) + " \u25be";+ var chip = Chip(value);+ chip.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ var flyout = new MenuFlyout();+ for (int i = 0; i < (p.Choices?.Length ?? 0); i++)+ {+ int idx = i;+ var item = new MenuItem { Header = p.Choices![i] };+ if (Math.Abs(settings[p.Id] - i) < 0.5) item.Icon = new TextBlock { Text = "·", Foreground = AccentBright };+ item.Click += (_, _) =>+ {+ settings.Set(p.Id, idx);+ value.Text = p.Display(settings[p.Id]) + " \u25be";+ Preview();+ };+ flyout.Items.Add(item);+ }+ flyout.ShowAt(chip);+ };+ // The chip already carries the read-out, so the row is label + chip.+ return TwoColumn(p.Name, chip);+ }++ case MidiParamKind.Toggle:+ {+ var chip = Chip(value);+ void Paint()+ {+ bool on = settings.Flag(p.Id);+ chip.Background = on ? AccentSubtle : Raised;+ chip.BorderBrush = on ? Brass : BorderStrong;+ value.Foreground = on ? AccentBright : TextSecondary;+ value.Text = p.Display(settings[p.Id]);+ }+ Paint();+ chip.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ settings.Set(p.Id, settings.Flag(p.Id) ? 0 : 1);+ Paint();+ Preview();+ };+ return TwoColumn(p.Name, chip);+ }++ default:+ {+ double span = Math.Max(1e-9, p.Max - p.Min);+ var fader = new MiniFader((settings[p.Id] - p.Min) / span, 1.0)+ {+ Accent = true,+ Default = (p.Default - p.Min) / span,+ VerticalAlignment = VerticalAlignment.Center,+ };+ fader.ValueChanged += v =>+ {+ double raw = p.Min + v * span;+ if (p.Kind is MidiParamKind.Int or MidiParamKind.Note) raw = Math.Round(raw);+ if (Math.Abs(raw - settings[p.Id]) < 1e-9) return;+ settings.Set(p.Id, raw);+ value.Text = p.Display(settings[p.Id]);+ Preview();+ };+ control = fader;+ break;+ }+ }++ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("72,*,50"), ColumnSpacing = 6, Height = 16 };+ grid.Children.Add(new TextBlock { Text = p.Name, FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center });+ Grid.SetColumn(control, 1); grid.Children.Add(control);+ Grid.SetColumn(value, 2); value.VerticalAlignment = VerticalAlignment.Center; grid.Children.Add(value);+ return grid;+ }++ private static Control TwoColumn(string label, Control control)+ {+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("72,*"), ColumnSpacing = 6 };+ grid.Children.Add(new TextBlock { Text = label, FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center });+ Grid.SetColumn(control, 1); grid.Children.Add(control);+ return grid;+ }++ // --- seed / blend / actions -------------------------------------------++ private Control SeedRow()+ {+ var box = FieldBox(22);+ _seedText.Text = _seed.ToString();+ box.Child = _seedText;++ var reroll = TextChip("New seed");+ reroll.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ _seed = Random.Shared.Next(1, 9999);+ _seedText.Text = _seed.ToString();+ Preview();+ };++ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6 };+ grid.Children.Add(box);+ Grid.SetColumn(reroll, 1); grid.Children.Add(reroll);+ return Section("SEED", grid);+ }++ private Control BlendRow()+ {+ _replaceChip = TextChip("Replace");+ _addChip = TextChip("Add");+ void Paint()+ {+ foreach (var (chip, blend) in new[] { (_replaceChip, MidiToolBlend.Replace), (_addChip, MidiToolBlend.Add) })+ {+ bool active = _blend == blend;+ chip.Background = active ? AccentSubtle : Raised;+ chip.BorderBrush = active ? Brass : BorderStrong;+ ((TextBlock)chip.Child!).Foreground = active ? AccentBright : TextSecondary;+ }+ }+ _replaceChip.PointerPressed += (_, e) => { e.Handled = true; _blend = MidiToolBlend.Replace; Paint(); Preview(); };+ _addChip.PointerPressed += (_, e) => { e.Handled = true; _blend = MidiToolBlend.Add; Paint(); Preview(); };+ Paint();++ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };+ grid.Children.Add(_replaceChip);+ Grid.SetColumn(_addChip, 1); grid.Children.Add(_addChip);+ return grid;+ }++ private Control ResultRow()+ {+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6 };+ grid.Children.Add(new TextBlock { Text = "Result", FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center });+ _resultText.HorizontalAlignment = HorizontalAlignment.Right;+ _resultText.Margin = new Thickness(0);+ Grid.SetColumn(_resultText, 1); grid.Children.Add(_resultText);+ return grid;+ }++ private Control ActionRow()+ {+ var apply = new Border+ {+ Height = 26, Background = AccentSubtle, BorderBrush = Brass, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5),+ Cursor = new Cursor(StandardCursorType.Hand),+ Child = new TextBlock { Text = "Apply", FontSize = 11, Foreground = AccentBright, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },+ };+ apply.PointerPressed += (_, e) => { e.Handled = true; Apply(); };+ _applyButton = apply;+ PaintApply();++ var revert = TextChip("Revert");+ revert.Height = 26;+ revert.PointerPressed += (_, e) => { e.Handled = true; Revert(); };++ var reset = TextChip("Defaults");+ reset.Height = 26;+ reset.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ if (_tool is null) return;+ SettingsFor(_tool).Reset();+ RebuildParams();+ Preview();+ };++ var top = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };+ top.Children.Add(revert);+ Grid.SetColumn(reset, 1); top.Children.Add(reset);++ return new StackPanel+ {+ Spacing = 6, Margin = new Thickness(0, 2, 0, 6),+ Children =+ {+ apply, top,+ new TextBlock+ {+ Text = "Every change is previewed in the roll — Apply keeps it as one undo step.",+ FontSize = 9, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap,+ },+ },+ };+ }++ // --- helpers ----------------------------------------------------------++ private static TextBlock Mono(string text)+ {+ var t = new TextBlock { Text = text, FontSize = 10, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(7, 0, 0, 0) };+ t.BindResource(FontFamilyProperty, "Font.Mono");+ return t;+ }++ private static Control Section(string title, Control content) => new StackPanel+ {+ Spacing = 5,+ Children =+ {+ new TextBlock { Text = title, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = TextTertiary },+ content,+ },+ };++ private static Control Rule() => new Border { Height = 1, Background = BorderDef };++ private static Border FieldBox(double h) => new()+ {+ Height = h, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5),+ };++ private static Border Chip(Control child) => new()+ {+ Height = 20, Background = Raised, BorderBrush = BorderStrong, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5),+ Cursor = new Cursor(StandardCursorType.Hand), Child = child, Padding = new Thickness(0, 0, 6, 0),+ };++ private static Border TextChip(string text) => new()+ {+ Height = 22, Background = Raised, BorderBrush = BorderStrong, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5),+ Cursor = new Cursor(StandardCursorType.Hand), Padding = new Thickness(8, 0),+ Child = new TextBlock { Text = text, FontSize = 10, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },+ };+}diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex e8f992f5..1c342cd9 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -21,6 +21,7 @@ using Avalonia.Layout;using Avalonia.Media;using Avalonia.Threading;using Nota.Application;+using Nota.Application.Midi;namespace Nota.App;@@ -64,14 +65,11 @@ public sealed class PianoRollView : UserControl// --- musical scale overlay ("Set Scale") ----------------// Session-global (static seed) so the chosen key/scale persists as you move// between clips, like a global scale setting. Off by default → chromatic, no- // dimming. Masks mirror the engine's Nota Scale device (src/MidiScale.h).- public static readonly string[] KeyNames =- { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };- public static readonly string[] ScaleNames =- { "Major", "Natural Minor", "Harmonic Minor", "Dorian", "Phrygian",- "Lydian", "Mixolydian", "Pentatonic Major", "Pentatonic Minor", "Chromatic" };- private static readonly ushort[] ScaleMasks =- { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };+ // dimming. The key/scale tables are shared with the clip tools and the engine's+ // Nota Scale device (src/MidiScale.h) — see MidiScales.+ public static string[] KeyNames => MidiScales.KeyNames;+ public static string[] ScaleNames => MidiScales.Names;+ private static ushort[] ScaleMasks => MidiScales.Masks;private static bool s_scaleOn;private static int s_root;@@ -307,6 +305,7 @@ public sealed class PianoRollView : UserControlpublic void SetNotes(IEnumerable<NotaNote> notes, double lengthBeats){+ _previewBackup = null;_notes.Clear();_notes.AddRange(notes);_lengthBeats = Math.Max(1, lengthBeats);@@ -387,7 +386,7 @@ public sealed class PianoRollView : UserControl_selection.Clear();for (int k = 0; k < copies.Count; k++) _selection.Add(baseIdx + k);Invalidate();- Commit?.Invoke(_notes);+ CommitNotes();Changed?.Invoke();return true;}@@ -400,11 +399,99 @@ public sealed class PianoRollView : UserControlif (i >= 0 && i < _notes.Count) _notes.RemoveAt(i);_selection.Clear();Invalidate();- Commit?.Invoke(_notes);+ CommitNotes();Changed?.Invoke();return true;}+ // --- clip-tool preview -------------------------------------------------------+ // A tool's result is shown in the roll and streamed to the engine with no undo+ // checkpoint, exactly like a note drag, so the knobs are audible while they move.+ // The clip's own notes are held here until the preview is applied or dropped.+ private List<NotaNote>? _previewBackup;++ public bool Previewing => _previewBackup is not null;++ /// <summary>The clip's notes ignoring any preview in flight — what a tool reads.</summary>+ public IReadOnlyList<NotaNote> SourceNotes => _previewBackup ?? _notes;++ /// <summary>Indices into <see cref="SourceNotes"/> that are selected. Only meaningful+ /// while no preview is running, which is when a tool captures its working set.</summary>+ public IReadOnlyCollection<int> SelectionIndices => _selection;++ /// <summary>Puts a tool's result on screen and in the engine without touching undo.</summary>+ public void ShowPreview(IReadOnlyList<NotaNote> notes)+ {+ _previewBackup ??= new List<NotaNote>(_notes);+ _notes.Clear();+ _notes.AddRange(notes);+ _selection.Clear();+ EnsureNotesVisible();+ Invalidate();+ CommitLive?.Invoke(_notes);+ Changed?.Invoke();+ }++ /// <summary>Centres the pitch range when not one note is on screen — which is what a+ /// generator writing into a different register leaves behind. A preview you cannot see+ /// is worse than no preview; scrolling only when nothing is visible keeps the view put+ /// for every ordinary edit.</summary>+ public void EnsureNotesVisible()+ {+ if (_notes.Count == 0) return;+ double vh = _bodyScroll.Viewport.Height;+ if (vh <= 0) { _pendingCenter = true; return; }+ double top = _bodyScroll.Offset.Y, bottom = top + vh;+ foreach (var n in _notes)+ {+ double y = (MaxPitch - n.Pitch) * RowH;+ if (y >= top && y + RowH <= bottom) return;+ }+ _pendingVOffset = CenterOffsetForNotes();+ ApplyPendingVOffset();+ }++ /// <summary>Drops the preview and puts the clip back, again without an undo entry —+ /// so a tool the user backed out of leaves no trace in the history.</summary>+ public void CancelPreview()+ {+ if (_previewBackup is null) return;+ _notes.Clear();+ _notes.AddRange(_previewBackup);+ _previewBackup = null;+ _selection.Clear();+ Invalidate();+ CommitLive?.Invoke(_notes);+ Changed?.Invoke();+ }++ /// <summary>Keeps the previewed notes as one undoable edit.</summary>+ public void ApplyPreview()+ {+ if (_previewBackup is null) return;+ var original = _previewBackup;+ _selection.Clear();+ Invalidate();+ // A commit checkpoints whatever the engine currently holds — and the live stream+ // has already put the preview there, so committing straight away would make undo+ // land on the preview. Rewind the engine to the clip's own notes first (no undo+ // step of its own), then commit, so the one entry points at the original.+ CommitLive?.Invoke(original);+ CommitNotes();+ Changed?.Invoke();+ }++ /// <summary>Pushes a note set as one undoable edit. Any clip-tool preview in flight is+ /// superseded — the notes on screen become the clip's own and the tools rail re-reads+ /// them on the next <see cref="Changed"/>. Without this, quantizing (or drawing a note)+ /// while a generator previewed would leave the rail holding a baseline it could later+ /// revert the clip to.</summary>+ private void CommitNotes(IReadOnlyList<NotaNote>? notes = null)+ {+ _previewBackup = null;+ Commit?.Invoke(notes ?? _notes);+ }+public void Quantize(double strength){for (int i = 0; i < _notes.Count; i++)@@ -415,7 +502,7 @@ public sealed class PianoRollView : UserControl_notes[i] = n;}Invalidate();- Commit?.Invoke(_notes);+ CommitNotes();Changed?.Invoke();}@@ -428,7 +515,7 @@ public sealed class PianoRollView : UserControl_notes[i] = n;}Invalidate();- Commit?.Invoke(_notes);+ CommitNotes();Changed?.Invoke();}@@ -478,7 +565,7 @@ public sealed class PianoRollView : UserControlif (_notes.Count == baseIdx) return false;_selection.Clear();for (int k = baseIdx; k < _notes.Count; k++) _selection.Add(k);- Invalidate(); Commit?.Invoke(_notes); Changed?.Invoke();+ Invalidate(); CommitNotes(); Changed?.Invoke();return true;}@@ -507,7 +594,7 @@ public sealed class PianoRollView : UserControlif (maxP + dp > MaxPitch) dp = MaxPitch - maxP;if (Math.Abs(db) < 1e-9 && dp == 0) return false;foreach (int i in sel) { var n = _notes[i]; n.StartBeat += db; n.Pitch += dp; _notes[i] = n; }- Invalidate(); Commit?.Invoke(_notes); Changed?.Invoke();+ Invalidate(); CommitNotes(); Changed?.Invoke();if (dp != 0) EnsurePitchVisible(dp > 0 ? maxP + dp : minP + dp);return true;}@@ -829,7 +916,7 @@ public sealed class PianoRollView : UserControl_o._notes.Add(nt);_o._selection.Clear(); _o._selection.Add(_o._notes.Count - 1);}- _o.Invalidate(); _o.Commit?.Invoke(_o._notes); _o.Changed?.Invoke();+ _o.Invalidate(); _o.CommitNotes(); _o.Changed?.Invoke();e.Handled = true;return;}@@ -929,7 +1016,7 @@ public sealed class PianoRollView : UserControlprivate void PushLive(){if (_o.CommitLive is null) return; // no live path wired (e.g. session) → commit on release- if (!_liveStarted) { _liveStarted = true; _o.Commit?.Invoke(_preDrag); }+ if (!_liveStarted) { _liveStarted = true; _o.CommitNotes(_preDrag); }_o.CommitLive(_o._notes);}@@ -977,7 +1064,7 @@ public sealed class PianoRollView : UserControl// Live path: undo was seeded on the first move; push the final state (no undo).// No live path (session): fall back to a single committing push.if (_o.CommitLive is not null && _liveStarted) _o.CommitLive(_o._notes);- else _o.Commit?.Invoke(_o._notes);+ else _o.CommitNotes();}_liveStarted = false;_cursorKind = 0; Cursor = ArrowCursor; // re-evaluated on the next hover@@ -1168,7 +1255,7 @@ public sealed class PianoRollView : UserControlprotected override void OnPointerReleased(PointerReleasedEventArgs e){- if (_drag) { _drag = false; _o.Commit?.Invoke(_o._notes); _o.Changed?.Invoke(); }+ if (_drag) { _drag = false; _o.CommitNotes(); _o.Changed?.Invoke(); }}private void Apply(double y)diff --git a/src/managed/Nota.Application/Midi/MidiGenerators.cs b/src/managed/Nota.Application/Midi/MidiGenerators.csnew file mode 100644index 00000000..af55d41f--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiGenerators.cs@@ -0,0 +1,413 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The six clip generators. Unlike the transformations these write notes rather+// than rewrite them; Stacks and Seed still read the input as source material, so+// every generator takes the same signature. The clip's length is the canvas —+// a generator fills it and stops.++namespace Nota.Application.Midi;++using U = MidiToolUtil;++public static class MidiGenerators+{+ // -------------------------------------------------------------------- Rhythm++ public static MidiTool Rhythm { get; } = new(+ "rhythm", "Rhythm", MidiToolKind.Generate,+ "Lays down a pattern that leans on the strong beats, as densely as you ask.",+ new[]+ {+ MidiToolParam.Rate("rate", "Rate"),+ MidiToolParam.Int("steps", "Pattern", 1, 32, 16, " st"),+ MidiToolParam.Percent("density", "Density", 0.5),+ MidiToolParam.Percent("variation", "Variation", 0.15),+ MidiToolParam.Note("pitch", "Pitch", 36),+ MidiToolParam.Float("gate", "Gate", 0.05, 2.0, 0.5, "×"),+ MidiToolParam.Percent("accent", "Accent", 0.45),+ MidiToolParam.Percent("velocity", "Velocity", 0.85),+ },+ RunRhythm);++ private static List<NotaNote> RunRhythm(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ double rate = s.RateBeats("rate");+ int steps = s.Int("steps");+ double density = s["density"], variation = s["variation"], gate = s["gate"];+ double accent = s["accent"], velocity = s["velocity"];+ int pitch = s.Int("pitch");+ var rng = U.Rng(ctx, "rhythm");++ // One pass to settle the base bar, then tile it — variation re-rolls individual+ // steps on each repeat so the loop breathes without losing its shape.+ var basePattern = new bool[steps];+ for (int i = 0; i < steps; i++) basePattern[i] = Hit(i, steps, density, rng);+ // Anything but a near-empty pattern lands on the downbeat — a rhythm that skips+ // beat one reads as a mistake however the dice fell.+ if (density >= 0.2) basePattern[0] = true;++ var outp = new List<NotaNote>();+ int total = (int)Math.Ceiling(ctx.LengthBeats / rate);+ for (int i = 0; i < total; i++)+ {+ int slot = U.Mod(i, steps);+ bool hit = basePattern[slot];+ if (i >= steps && variation > 0 && rng.NextDouble() < variation) hit = Hit(slot, steps, density, rng);+ if (!hit) continue;+ double m = Metric(slot, steps);+ double vel = velocity * (1 - accent * (1 - m));+ outp.Add(U.Note(pitch, i * rate, rate * gate, vel));+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ private static bool Hit(int i, int steps, double density, Random rng)+ {+ if (density <= 0) return false;+ double m = Metric(i, steps);+ // Low density only survives on strong beats; high density flattens the bias.+ return rng.NextDouble() < Math.Min(1.0, density * 1.35 * Math.Pow(m, 2.0 - 1.6 * density));+ }++ /// <summary>Metric strength of a step: 1 on the downbeat, falling off as the step lands+ /// on ever finer subdivisions. This is what keeps a sparse pattern musical.</summary>+ private static double Metric(int i, int steps)+ {+ if (i == 0) return 1.0;+ for (int d = 2; d <= 32; d *= 2)+ {+ double slot = steps / (double)d;+ if (slot < 1) break;+ if (Math.Abs(i % slot) < 1e-9) return Math.Max(0.15, 1.0 - Math.Log2(d) * 0.17);+ }+ return 0.12;+ }++ // ---------------------------------------------------------------------- Seed++ public static MidiTool Seed { get; } = new(+ "seed", "Seed", MidiToolKind.Generate,+ "Learns the clip's intervals and rhythm, then writes a new take in the same voice.",+ new[]+ {+ MidiToolParam.Percent("pitchvar", "Pitch Var", 0.5),+ MidiToolParam.Percent("rhythmvar", "Rhythm Var", 0.4),+ MidiToolParam.Float("density", "Density", 0.25, 2.5, 1.0, "×"),+ MidiToolParam.Int("range", "Range", 0, 24, 12, " st"),+ MidiToolParam.Toggle("scale", "In Scale", true),+ MidiToolParam.Percent("velocity", "Vel Var", 0.2),+ },+ RunSeed);++ private static List<NotaNote> RunSeed(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ var src = U.Sorted(input);+ if (src.Count < 2) return new List<NotaNote>(src);++ double pitchVar = s["pitchvar"], rhythmVar = s["rhythmvar"], density = s["density"];+ double velVar = s["velocity"];+ int range = s.Int("range");+ bool inScale = s.Flag("scale");+ var rng = U.Rng(ctx, "seed");++ // The clip's own vocabulary: which intervals it steps by, how long notes are, and+ // how far apart onsets fall. Drawing from these is what keeps the take in character.+ var intervals = new List<int>();+ var gaps = new List<double>();+ var lengths = new List<double>();+ for (int i = 1; i < src.Count; i++)+ {+ intervals.Add(src[i].Pitch - src[i - 1].Pitch);+ double g = src[i].StartBeat - src[i - 1].StartBeat;+ if (g > 1e-6) gaps.Add(g);+ }+ foreach (var n in src) lengths.Add(n.LengthBeats);+ if (gaps.Count == 0) gaps.Add(ctx.Grid);++ int low = src.Min(n => n.Pitch), high = src.Max(n => n.Pitch);+ int centre = (low + high) / 2;+ int lo = range > 0 ? centre - range : low;+ int hi = range > 0 ? centre + range : high;++ var outp = new List<NotaNote>();+ int pitch = src[0].Pitch;+ double t = src[0].StartBeat;+ int step = 0;++ while (t < ctx.LengthBeats - 1e-6)+ {+ double vel = src[step % src.Count].Velocity;+ if (velVar > 0) vel = Math.Clamp(vel + (rng.NextDouble() * 2 - 1) * velVar, 0.05, 1.0);++ double len = rng.NextDouble() < rhythmVar+ ? lengths[rng.Next(lengths.Count)]+ : src[step % src.Count].LengthBeats;++ int outPitch = inScale ? ctx.Snap(pitch) : pitch;+ outp.Add(U.Note(outPitch, t, len * (1.0 / Math.Max(0.25, density)), vel));++ // Step: either replay the source's next move, or draw a fresh one from the pool.+ int interval = rng.NextDouble() < pitchVar+ ? intervals[rng.Next(intervals.Count)]+ : intervals[step % intervals.Count];+ pitch += interval;+ // Fold back inside the range instead of clamping, which would flatten the line.+ while (pitch > hi) pitch -= 12;+ while (pitch < lo) pitch += 12;++ double gap = rng.NextDouble() < rhythmVar+ ? gaps[rng.Next(gaps.Count)]+ : gaps[step % gaps.Count];+ t += Math.Max(U.MinLength, gap / density);+ step++;+ if (step > 4096) break;+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ // -------------------------------------------------------------------- Stacks++ private static readonly string[] StackIntervals = { "3rds", "4ths", "5ths", "Octaves", "Cluster" };+ private static readonly string[] StackVoicings = { "Close", "Open", "Drop 2", "Spread", "Power" };++ public static MidiTool Stacks { get; } = new(+ "stacks", "Stacks", MidiToolKind.Generate,+ "Grows every note into a chord, voiced the way you would play it.",+ new[]+ {+ MidiToolParam.Int("voices", "Voices", 1, 5, 2),+ MidiToolParam.Choice("interval", "Interval", StackIntervals, 0),+ MidiToolParam.Choice("voicing", "Voicing", StackVoicings, 0),+ MidiToolParam.Int("spread", "Spread", 0, 3, 0, " oct"),+ MidiToolParam.Float("falloff", "Vel Falloff", 0, 1, 0.15, "×"),+ MidiToolParam.Toggle("scale", "In Scale", true),+ },+ RunStacks);++ private static List<NotaNote> RunStacks(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int voices = s.Int("voices"), intervalMode = s.Int("interval"), voicing = s.Int("voicing");+ int spread = s.Int("spread");+ double falloff = s["falloff"];+ bool inScale = s.Flag("scale") && ctx.ScaleOn;+ var degrees = ctx.Degrees;++ // Diatonic stacking walks the scale a fixed number of degrees per voice. With no+ // scale to walk, a uniform semitone step would stack augmented triads out of+ // "3rds", so chromatic mode follows a chord-tone table instead.+ int degStep = intervalMode switch { 0 => 2, 1 => 3, 2 => 4, 3 => degrees.Length, _ => 1 };+ int[] semiStack = intervalMode switch+ {+ 0 => new[] { 0, 4, 7, 11, 14, 17 }, // triad into the seventh and ninth+ 1 => new[] { 0, 5, 10, 15, 20, 25 },+ 2 => new[] { 0, 7, 14, 21, 28, 35 },+ 3 => new[] { 0, 12, 24, 36, 48, 60 },+ _ => new[] { 0, 1, 2, 3, 4, 5 },+ };++ var outp = new List<NotaNote>();+ foreach (var root in U.Sorted(input))+ {+ var stack = new List<int> { root.Pitch };+ for (int v = 1; v <= voices; v++)+ {+ int p = inScale+ ? MidiScales.PitchAtDegree(degrees, ctx.ScaleRoot,+ MidiScales.DegreeOfPitch(degrees, ctx.ScaleRoot, root.Pitch) + degStep * v, 0)+ : root.Pitch + semiStack[Math.Min(v, semiStack.Length - 1)];+ stack.Add(p + 12 * spread * v);+ }++ switch (voicing)+ {+ case 1: // Open — lift every other voice an octave+ for (int i = 1; i < stack.Count; i += 2) stack[i] += 12;+ break;+ case 2: // Drop 2 — the second voice from the top falls an octave+ if (stack.Count >= 2) stack[^2] -= 12;+ break;+ case 3: // Spread — fan the stack out an octave per voice+ for (int i = 0; i < stack.Count; i++) stack[i] += 12 * i;+ break;+ case 4: // Power — root, fifth, octave only+ stack = new List<int> { root.Pitch, root.Pitch + 7, root.Pitch + 12 }+ .Take(Math.Max(2, voices + 1)).ToList();+ break;+ }++ for (int i = 0; i < stack.Count; i++)+ outp.Add(U.Note(stack[i], root.StartBeat, root.LengthBeats, root.Velocity * (1 - falloff * i / Math.Max(1, stack.Count - 1.0))));+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ // ----------------------------------------------------------------- Euclidean++ public static MidiTool Euclidean { get; } = new(+ "euclidean", "Euclidean", MidiToolKind.Generate,+ "Spreads a number of hits as evenly as a number of steps allows.",+ new[]+ {+ MidiToolParam.Int("steps", "Steps", 1, 32, 16),+ MidiToolParam.Int("pulses", "Pulses", 0, 32, 5),+ MidiToolParam.Int("rotation", "Rotate", -31, 31, 0),+ MidiToolParam.Rate("rate", "Rate"),+ MidiToolParam.Note("pitch", "Pitch", 36),+ MidiToolParam.Float("gate", "Gate", 0.05, 2.0, 0.5, "×"),+ MidiToolParam.Percent("velocity", "Velocity", 0.85),+ MidiToolParam.Int("accents", "Accents", 0, 32, 0),+ MidiToolParam.Percent("accentvel", "Accent Vel", 1.0),+ },+ RunEuclidean);++ private static List<NotaNote> RunEuclidean(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int steps = s.Int("steps");+ int pulses = Math.Min(s.Int("pulses"), steps);+ int rotation = s.Int("rotation");+ double rate = s.RateBeats("rate"), gate = s["gate"];+ int pitch = s.Int("pitch");+ double velocity = s["velocity"], accentVel = s["accentvel"];+ int accents = Math.Min(s.Int("accents"), pulses);++ var pattern = U.Euclid(steps, pulses, rotation);+ // A second Euclidean ride over the hits themselves picks which ones land hard.+ var accentPattern = accents > 0 ? U.Euclid(Math.Max(1, pulses), accents, 0) : Array.Empty<bool>();++ var outp = new List<NotaNote>();+ int total = (int)Math.Ceiling(ctx.LengthBeats / rate);+ int hitIndex = 0;+ for (int i = 0; i < total; i++)+ {+ if (!pattern[U.Mod(i, steps)]) continue;+ bool accent = accentPattern.Length > 0 && accentPattern[U.Mod(hitIndex, accentPattern.Length)];+ outp.Add(U.Note(pitch, i * rate, rate * gate, accent ? accentVel : velocity));+ hitIndex++;+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ // ------------------------------------------------------------- Melodic Steps++ private static readonly string[] Contours =+ { "Up", "Down", "Arch", "Valley", "Zigzag", "Random Walk", "Random" };++ public static MidiTool MelodicSteps { get; } = new(+ "melodicsteps", "Melodic Steps", MidiToolKind.Generate,+ "A step sequencer in scale degrees — pick a contour and a span, get a line.",+ new[]+ {+ MidiToolParam.Int("steps", "Steps", 1, 32, 8),+ MidiToolParam.Rate("rate", "Rate", 3),+ MidiToolParam.Choice("contour", "Contour", Contours, 2),+ MidiToolParam.Int("range", "Range", 1, 21, 7, " deg"),+ MidiToolParam.Note("root", "Root", 60),+ MidiToolParam.Percent("density", "Density", 0.85),+ MidiToolParam.Float("gate", "Gate", 0.05, 2.0, 0.9, "×"),+ MidiToolParam.Percent("velocity", "Velocity", 0.8),+ MidiToolParam.Percent("velvar", "Vel Var", 0.15),+ },+ RunMelodicSteps);++ private static List<NotaNote> RunMelodicSteps(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int steps = s.Int("steps"), range = s.Int("range"), contour = s.Int("contour");+ double rate = s.RateBeats("rate"), gate = s["gate"];+ double density = s["density"], velocity = s["velocity"], velVar = s["velvar"];+ int rootNote = s.Int("root");+ var rng = U.Rng(ctx, "melodicsteps");+ var degrees = ctx.Degrees;+ int baseDegree = MidiScales.DegreeOfPitch(degrees, ctx.ScaleRoot, rootNote);++ // Settle the degree sequence once so the pattern repeats rather than wanders off.+ var seq = new int[steps];+ int walk = 0;+ for (int i = 0; i < steps; i++)+ {+ double f = steps == 1 ? 0 : i / (double)(steps - 1);+ seq[i] = contour switch+ {+ 0 => (int)Math.Round(f * range),+ 1 => (int)Math.Round((1 - f) * range),+ 2 => (int)Math.Round(Math.Sin(f * Math.PI) * range),+ 3 => (int)Math.Round((1 - Math.Sin(f * Math.PI)) * range),+ 4 => i % 2 == 0 ? 0 : range,+ 5 => walk = Math.Clamp(walk + rng.Next(-2, 3), 0, range),+ _ => rng.Next(0, range + 1),+ };+ }+ var rests = new bool[steps];+ for (int i = 0; i < steps; i++) rests[i] = rng.NextDouble() > density;++ var outp = new List<NotaNote>();+ int total = (int)Math.Ceiling(ctx.LengthBeats / rate);+ for (int i = 0; i < total; i++)+ {+ int slot = U.Mod(i, steps);+ if (rests[slot]) continue;+ int pitch = MidiScales.PitchAtDegree(degrees, ctx.ScaleRoot, baseDegree + seq[slot], 0);+ double vel = velocity + (velVar > 0 ? (rng.NextDouble() * 2 - 1) * velVar : 0);+ outp.Add(U.Note(pitch, i * rate, rate * gate, vel));+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ // --------------------------------------------------------------------- Shape++ private static readonly string[] Shapes =+ { "Ramp Up", "Ramp Down", "Sine", "Triangle", "Exponential", "Logarithmic", "S-Curve", "Square", "Random Walk" };++ public static MidiTool Shape { get; } = new(+ "shape", "Shape", MidiToolKind.Generate,+ "Traces a curve across the clip and drops a note wherever it passes a step.",+ new[]+ {+ MidiToolParam.Choice("shape", "Shape", Shapes, 2),+ MidiToolParam.Rate("rate", "Rate", 4),+ MidiToolParam.Int("range", "Range", 1, 36, 12, " st"),+ MidiToolParam.Note("root", "Root", 60),+ MidiToolParam.Float("cycles", "Cycles", 0.25, 8, 1, "×"),+ MidiToolParam.Float("phase", "Phase", 0, 1, 0, ""),+ MidiToolParam.Float("gate", "Gate", 0.05, 2.0, 0.9, "×"),+ MidiToolParam.Percent("velocity", "Velocity", 0.8),+ MidiToolParam.Toggle("velfollow", "Vel Follows", false),+ MidiToolParam.Toggle("scale", "In Scale", true),+ },+ RunShape);++ private static List<NotaNote> RunShape(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int shape = s.Int("shape"), range = s.Int("range"), rootNote = s.Int("root");+ double rate = s.RateBeats("rate"), cycles = s["cycles"], phase = s["phase"];+ double gate = s["gate"], velocity = s["velocity"];+ bool velFollow = s.Flag("velfollow"), inScale = s.Flag("scale");+ var rng = U.Rng(ctx, "shape");++ var outp = new List<NotaNote>();+ int total = (int)Math.Ceiling(ctx.LengthBeats / rate);+ double walk = 0.5;++ for (int i = 0; i < total; i++)+ {+ double t = (i / (double)Math.Max(1, total) * cycles + phase) % 1.0;+ double unit = shape switch+ {+ 0 => t,+ 1 => 1 - t,+ 2 => 0.5 + 0.5 * Math.Sin(t * Math.PI * 2),+ 3 => 1 - Math.Abs(t * 2 - 1),+ 4 => Math.Pow(t, 2.5),+ 5 => Math.Pow(t, 1 / 2.5),+ 6 => U.SCurve(t, 1.0),+ 7 => t < 0.5 ? 0 : 1,+ _ => walk = Math.Clamp(walk + (rng.NextDouble() - 0.5) * 0.4, 0, 1),+ };+ int pitch = rootNote + (int)Math.Round(unit * range);+ if (inScale) pitch = ctx.Snap(pitch);+ double vel = velFollow ? 0.25 + unit * 0.75 : velocity;+ outp.Add(U.Note(pitch, i * rate, rate * gate, vel));+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }+}diff --git a/src/managed/Nota.Application/Midi/MidiScales.cs b/src/managed/Nota.Application/Midi/MidiScales.csnew file mode 100644index 00000000..6a9f8a0e--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiScales.cs@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The scale vocabulary shared by the piano roll's scale overlay, the Nota Scale+// MIDI device (src/MidiScale.h) and the clip tools. A mask is 12 bits; bit i set+// means "i semitones above the root is in the scale".++namespace Nota.Application.Midi;++public static class MidiScales+{+ public static readonly string[] KeyNames =+ { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };++ public static readonly string[] Names =+ { "Major", "Natural Minor", "Harmonic Minor", "Dorian", "Phrygian",+ "Lydian", "Mixolydian", "Pentatonic Major", "Pentatonic Minor", "Chromatic" };++ public static readonly ushort[] Masks =+ { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };++ public const ushort Chromatic = 4095;++ public static ushort MaskAt(int index) =>+ index >= 0 && index < Masks.Length ? Masks[index] : Chromatic;++ /// <summary>Semitone offsets of the mask, ascending — the scale's degrees.</summary>+ public static int[] Degrees(ushort mask)+ {+ var d = new List<int>(12);+ for (int i = 0; i < 12; i++) if ((mask & (1 << i)) != 0) d.Add(i);+ if (d.Count == 0) d.Add(0);+ return d.ToArray();+ }++ public static bool Contains(ushort mask, int root, int pitch)+ {+ int pc = (((pitch - root) % 12) + 12) % 12;+ return (mask & (1 << pc)) != 0;+ }++ /// <summary>Nearest in-scale pitch. <paramref name="prefer"/> > 0 searches upward+ /// first, < 0 downward first, 0 takes whichever is closer (ties go up).</summary>+ public static int Snap(ushort mask, int root, int pitch, int prefer = 0)+ {+ if (mask == Chromatic || Contains(mask, root, pitch)) return pitch;+ for (int d = 1; d <= 12; d++)+ {+ int up = pitch + d, down = pitch - d;+ bool upOk = up <= 127 && Contains(mask, root, up);+ bool downOk = down >= 0 && Contains(mask, root, down);+ if (prefer >= 0 && upOk) return up;+ if (downOk && (prefer <= 0 || !upOk)) return down;+ if (upOk) return up;+ }+ return pitch;+ }++ /// <summary>Walks <paramref name="degree"/> scale steps from the root (degree 0 = the+ /// root in octave <paramref name="octave"/>). Negative degrees walk down; the octave+ /// wraps automatically, so degree 7 of a 7-note scale is the root an octave up.</summary>+ public static int PitchAtDegree(int[] degrees, int root, int degree, int octave)+ {+ int n = degrees.Length;+ int oct = (int)Math.Floor(degree / (double)n);+ int idx = degree - oct * n;+ return root + degrees[idx] + 12 * (octave + oct);+ }++ /// <summary>Inverse of <see cref="PitchAtDegree"/>: the scale-step index of a pitch+ /// relative to <paramref name="root"/> in octave 0, snapping off-scale pitches down.</summary>+ public static int DegreeOfPitch(int[] degrees, int root, int pitch)+ {+ int rel = pitch - root;+ int oct = (int)Math.Floor(rel / 12.0);+ int pc = rel - oct * 12;+ int best = 0;+ for (int i = 0; i < degrees.Length; i++) if (degrees[i] <= pc) best = i;+ return oct * degrees.Length + best;+ }+}diff --git a/src/managed/Nota.Application/Midi/MidiTool.cs b/src/managed/Nota.Application/Midi/MidiTool.csnew file mode 100644index 00000000..0af8ec1c--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiTool.cs@@ -0,0 +1,165 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The clip-tool contract. A tool is a pure function+// (input notes, settings, context) -> output notes, described well enough that the+// UI can build its whole parameter rail from the descriptor — no per-tool panel.+// Everything is deterministic: the only randomness comes from the Seed in the+// context, so the same settings always give the same notes.++namespace Nota.Application.Midi;++public enum MidiToolKind+{+ /// <summary>Rewrites the notes it is given.</summary>+ Transform,+ /// <summary>Produces notes; may read the input as source material.</summary>+ Generate,+}++public enum MidiParamKind { Float, Int, Choice, Toggle, Note }++/// <summary>One knob on a tool. <see cref="Id"/> is the stable key used by settings and+/// presets; <see cref="Name"/> is what the rail shows.</summary>+public sealed record MidiToolParam(+ string Id,+ string Name,+ MidiParamKind Kind,+ double Min,+ double Max,+ double Default,+ string[]? Choices = null,+ string Unit = "",+ string Format = "0.##")+{+ public static MidiToolParam Float(string id, string name, double min, double max, double def, string unit = "", string format = "0.##")+ => new(id, name, MidiParamKind.Float, min, max, def, null, unit, format);++ public static MidiToolParam Int(string id, string name, int min, int max, int def, string unit = "")+ => new(id, name, MidiParamKind.Int, min, max, def, null, unit, "0");++ public static MidiToolParam Percent(string id, string name, double def)+ => new(id, name, MidiParamKind.Float, 0, 1, def, null, "%", "0");++ public static MidiToolParam Choice(string id, string name, string[] choices, int def)+ => new(id, name, MidiParamKind.Choice, 0, choices.Length - 1, def, choices);++ public static MidiToolParam Toggle(string id, string name, bool def)+ => new(id, name, MidiParamKind.Toggle, 0, 1, def ? 1 : 0);++ /// <summary>A MIDI pitch, shown by name (C3) rather than as a number.</summary>+ public static MidiToolParam Note(string id, string name, int def)+ => new(id, name, MidiParamKind.Note, 0, 127, def);++ /// <summary>A note-division picker; the stored value indexes <see cref="MidiRates.Labels"/>.</summary>+ public static MidiToolParam Rate(string id, string name, int def = MidiRates.Sixteenth)+ => new(id, name, MidiParamKind.Choice, 0, MidiRates.Labels.Length - 1, def, MidiRates.Labels);++ public string Display(double v) => Kind switch+ {+ MidiParamKind.Toggle => v >= 0.5 ? "On" : "Off",+ MidiParamKind.Choice => Choices is { Length: > 0 }+ ? Choices[Math.Clamp((int)Math.Round(v), 0, Choices.Length - 1)]+ : "",+ MidiParamKind.Note => NoteName((int)Math.Round(v)),+ MidiParamKind.Int => $"{(int)Math.Round(v)}{Unit}",+ _ => Unit == "%"+ ? $"{v * 100:0}%"+ : $"{v.ToString(Format, System.Globalization.CultureInfo.InvariantCulture)}{Unit}",+ };++ public static string NoteName(int pitch)+ {+ int p = Math.Clamp(pitch, 0, 127);+ return $"{MidiScales.KeyNames[p % 12]}{p / 12 - 1}";+ }+}++/// <summary>Note divisions in beats (one beat = a 1/4 note), mirroring the piano roll's+/// grid picker so "Rate" reads the same everywhere.</summary>+public static class MidiRates+{+ public const int Sixteenth = 4;++ public static readonly string[] Labels =+ { "1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/4T", "1/8T", "1/16T", "1/8.", "1/16." };++ public static readonly double[] Beats =+ { 4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 2.0 / 3, 1.0 / 3, 1.0 / 6, 0.75, 0.375 };++ public static double At(double index) =>+ Beats[Math.Clamp((int)Math.Round(index), 0, Beats.Length - 1)];+}++/// <summary>Musical surroundings a tool works inside: how long the clip is, what the+/// editor's grid is set to, the key the user picked, and the seed that makes every+/// random choice repeatable.</summary>+public sealed class MidiToolContext+{+ public double LengthBeats { get; init; } = 4;+ public double Grid { get; init; } = 0.25;+ public bool ScaleOn { get; init; }+ public int ScaleRoot { get; init; }+ public ushort ScaleMask { get; init; } = MidiScales.Chromatic;+ public int Seed { get; init; }++ /// <summary>The mask to write notes through — chromatic when the overlay is off, so a+ /// tool's "in scale" option is a no-op rather than a surprise.</summary>+ public ushort Mask => ScaleOn ? ScaleMask : MidiScales.Chromatic;++ public int[] Degrees => MidiScales.Degrees(Mask);++ public int Snap(int pitch, int prefer = 0) => MidiScales.Snap(Mask, ScaleRoot, pitch, prefer);+}++/// <summary>Parameter values for one tool, keyed by <see cref="MidiToolParam.Id"/>.+/// Missing keys fall back to the descriptor's default, so a tool can gain a parameter+/// without invalidating stored settings.</summary>+public sealed class MidiToolSettings+{+ private readonly Dictionary<string, double> _values = new(StringComparer.Ordinal);+ private readonly IReadOnlyList<MidiToolParam> _params;++ public MidiToolSettings(IReadOnlyList<MidiToolParam> parameters)+ {+ _params = parameters;+ foreach (var p in parameters) _values[p.Id] = p.Default;+ }++ public double this[string id] => _values.TryGetValue(id, out var v) ? v : Default(id);+ public int Int(string id) => (int)Math.Round(this[id]);+ public bool Flag(string id) => this[id] >= 0.5;+ /// <summary>A "Rate"-style parameter resolved to beats.</summary>+ public double RateBeats(string id) => MidiRates.At(this[id]);++ public void Set(string id, double value)+ {+ var p = Find(id);+ _values[id] = p is null ? value : Math.Clamp(value, p.Min, p.Max);+ }++ public void Reset()+ {+ foreach (var p in _params) _values[p.Id] = p.Default;+ }++ private MidiToolParam? Find(string id)+ {+ foreach (var p in _params) if (p.Id == id) return p;+ return null;+ }++ private double Default(string id) => Find(id)?.Default ?? 0;+}++/// <summary>A clip tool: its identity, its knobs, and the pure function that runs it.</summary>+public sealed record MidiTool(+ string Id,+ string Name,+ MidiToolKind Kind,+ string Blurb,+ IReadOnlyList<MidiToolParam> Params,+ Func<IReadOnlyList<NotaNote>, MidiToolSettings, MidiToolContext, List<NotaNote>> Run)+{+ public MidiToolSettings NewSettings() => new(Params);+}diff --git a/src/managed/Nota.Application/Midi/MidiToolCatalog.cs b/src/managed/Nota.Application/Midi/MidiToolCatalog.csnew file mode 100644index 00000000..ae2dc872--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiToolCatalog.cs@@ -0,0 +1,79 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The registry every clip-tool surface reads: the piano roll's Tools rail, and+// anything else that wants to run a tool (MCP, tests). Adding a tool means adding+// it to All — nothing else in the app enumerates them.++namespace Nota.Application.Midi;++public static class MidiToolCatalog+{+ public static IReadOnlyList<MidiTool> All { get; } = new[]+ {+ // Generators first: they are what you reach for on an empty clip.+ MidiGenerators.Rhythm,+ MidiGenerators.Seed,+ MidiGenerators.Stacks,+ MidiGenerators.Euclidean,+ MidiGenerators.MelodicSteps,+ MidiGenerators.Shape,++ MidiTransforms.Arpeggiate,+ MidiTransforms.Connect,+ MidiTransforms.Ornament,+ MidiTransforms.Quantize,+ MidiTransforms.Recombine,+ MidiTransforms.Span,+ MidiTransforms.Strum,+ MidiTransforms.TimeWarp,+ MidiTransforms.VelocityShaper,+ };++ public static IEnumerable<MidiTool> Generators => All.Where(t => t.Kind == MidiToolKind.Generate);+ public static IEnumerable<MidiTool> Transforms => All.Where(t => t.Kind == MidiToolKind.Transform);++ public static MidiTool? Find(string id) => All.FirstOrDefault(t => t.Id == id);+}++/// <summary>How a tool's output meets the notes already in the clip.</summary>+public enum MidiToolBlend+{+ /// <summary>The tool's output stands in for whatever it was given.</summary>+ Replace,+ /// <summary>The tool's output is layered on top of the untouched clip.</summary>+ Add,+}++/// <summary>Runs a tool over a clip, honouring the selection as the working scope: with a+/// selection the tool sees only those notes and the rest of the clip is carried through+/// untouched, without one it sees everything. This is the single place that decides what+/// "apply" means, so the UI, MCP and tests can't drift on it.</summary>+public static class MidiToolRunner+{+ public static List<NotaNote> Apply(+ MidiTool tool,+ IReadOnlyList<NotaNote> clip,+ IReadOnlyCollection<int>? selection,+ MidiToolSettings settings,+ MidiToolContext ctx,+ MidiToolBlend blend = MidiToolBlend.Replace)+ {+ var scoped = new List<NotaNote>();+ var untouched = new List<NotaNote>();+ bool hasSelection = selection is { Count: > 0 };++ for (int i = 0; i < clip.Count; i++)+ {+ if (!hasSelection || selection!.Contains(i)) scoped.Add(clip[i]);+ else untouched.Add(clip[i]);+ }++ var produced = tool.Run(scoped, settings, ctx);++ var result = new List<NotaNote>(untouched);+ if (blend == MidiToolBlend.Add) result.AddRange(scoped);+ result.AddRange(produced);+ return MidiToolUtil.Deoverlap(MidiToolUtil.Tidy(result, ctx.LengthBeats));+ }+}diff --git a/src/managed/Nota.Application/Midi/MidiToolUtil.cs b/src/managed/Nota.Application/Midi/MidiToolUtil.csnew file mode 100644index 00000000..50c16a70--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiToolUtil.cs@@ -0,0 +1,158 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Shared machinery for the clip tools: chord grouping, note hygiene (sort, clamp,+// de-overlap), and the shaping curves the time/velocity tools draw through.++namespace Nota.Application.Midi;++public static class MidiToolUtil+{+ /// <summary>Notes starting within this many beats of each other count as one chord.</summary>+ public const double ChordTolerance = 1.0 / 64;++ public const double MinLength = 1.0 / 64;++ public static List<NotaNote> Sorted(IEnumerable<NotaNote> notes)+ {+ var list = new List<NotaNote>(notes);+ list.Sort(static (a, b) =>+ {+ int c = a.StartBeat.CompareTo(b.StartBeat);+ return c != 0 ? c : a.Pitch.CompareTo(b.Pitch);+ });+ return list;+ }++ public static NotaNote Note(int pitch, double start, double length, double velocity) => new(+ Math.Clamp(pitch, 0, 127),+ start,+ Math.Max(MinLength, length),+ (float)Math.Clamp(velocity, 0.01, 1.0));++ /// <summary>Drops notes that start past the clip, trims those that overrun it, and+ /// clamps pitch and velocity. Every tool ends with this so nothing has to be careful.</summary>+ public static List<NotaNote> Tidy(IEnumerable<NotaNote> notes, double lengthBeats)+ {+ var outp = new List<NotaNote>();+ foreach (var n in notes)+ {+ double start = Math.Max(0, n.StartBeat);+ if (start >= lengthBeats - 1e-9) continue;+ double len = Math.Min(Math.Max(MinLength, n.LengthBeats), lengthBeats - start);+ outp.Add(Note(n.Pitch, start, len, n.Velocity));+ }+ return Sorted(outp);+ }++ /// <summary>Removes exact duplicates (same pitch at the same instant) and shortens a+ /// note that runs into the next one on the same pitch, which is what a MIDI stream+ /// needs to stay unambiguous.</summary>+ public static List<NotaNote> Deoverlap(List<NotaNote> notes)+ {+ var sorted = Sorted(notes);+ var byPitch = new Dictionary<int, int>(); // pitch -> index of the last note kept+ var result = new List<NotaNote>(sorted.Count);+ foreach (var n in sorted)+ {+ if (byPitch.TryGetValue(n.Pitch, out int prev))+ {+ var p = result[prev];+ if (Math.Abs(p.StartBeat - n.StartBeat) < 1e-6) continue; // duplicate+ double maxLen = n.StartBeat - p.StartBeat;+ if (p.LengthBeats > maxLen) { p.LengthBeats = Math.Max(MinLength, maxLen); result[prev] = p; }+ }+ result.Add(n);+ byPitch[n.Pitch] = result.Count - 1;+ }+ return result;+ }++ /// <summary>Groups notes into chords by start time. Each group is ascending by pitch.</summary>+ public static List<List<NotaNote>> Chords(IReadOnlyList<NotaNote> notes, double tolerance = ChordTolerance)+ {+ var groups = new List<List<NotaNote>>();+ var sorted = Sorted(notes);+ foreach (var n in sorted)+ {+ if (groups.Count > 0 && n.StartBeat - groups[^1][0].StartBeat <= tolerance) groups[^1].Add(n);+ else groups.Add(new List<NotaNote> { n });+ }+ foreach (var g in groups) g.Sort(static (a, b) => a.Pitch.CompareTo(b.Pitch));+ return groups;+ }++ /// <summary>A seed that varies per tool so two tools on the same clip seed don't draw+ /// the same sequence.</summary>+ public static Random Rng(MidiToolContext ctx, string salt)+ {+ unchecked+ {+ int h = ctx.Seed * 397;+ foreach (char c in salt) h = h * 31 + c;+ return new Random(h);+ }+ }++ /// <summary>Bends 0..1 through a tension curve. <paramref name="tension"/> 0 is linear,+ /// +1 pushes everything late (ease-in), -1 pulls it early (ease-out).</summary>+ public static double Bend(double t, double tension)+ {+ t = Math.Clamp(t, 0, 1);+ if (Math.Abs(tension) < 1e-6) return t;+ double k = 1 + Math.Abs(tension) * 3;+ return tension > 0 ? Math.Pow(t, k) : 1 - Math.Pow(1 - t, k);+ }++ /// <summary>A symmetric S-curve on 0..1; <paramref name="amount"/> 0 is linear.</summary>+ public static double SCurve(double t, double amount)+ {+ t = Math.Clamp(t, 0, 1);+ double s = t * t * (3 - 2 * t);+ return t + (s - t) * Math.Clamp(amount, -1, 1);+ }++ public static int Mod(int a, int n) => ((a % n) + n) % n;++ public static double Lerp(double a, double b, double t) => a + (b - a) * t;++ /// <summary>Fisher-Yates over a fraction of the list: <paramref name="amount"/> 1 fully+ /// shuffles, 0 leaves it alone, and values between swap that share of the positions —+ /// which is what makes "a bit more random" a usable knob.</summary>+ public static void PartialShuffle<T>(IList<T> items, double amount, Random rng)+ {+ amount = Math.Clamp(amount, 0, 1);+ if (items.Count < 2 || amount <= 0) return;+ for (int i = items.Count - 1; i > 0; i--)+ {+ if (rng.NextDouble() > amount) continue;+ int j = rng.Next(i + 1);+ (items[i], items[j]) = (items[j], items[i]);+ }+ }++ /// <summary>Bjorklund's algorithm: spreads <paramref name="pulses"/> hits as evenly as+ /// possible over <paramref name="steps"/> slots, then rotates the result.</summary>+ public static bool[] Euclid(int steps, int pulses, int rotation)+ {+ steps = Math.Max(1, steps);+ pulses = Math.Clamp(pulses, 0, steps);+ var pattern = new bool[steps];+ if (pulses == 0) return pattern;+ if (pulses == steps) { Array.Fill(pattern, true); return Rotate(pattern, rotation); }++ // Bjorklund's distribution, in closed form: step i is a hit when it opens a new+ // group. Hits the downbeat first, which is what makes it usable as a rhythm.+ for (int i = 0; i < steps; i++) pattern[i] = i * pulses % steps < pulses;+ return Rotate(pattern, rotation);+ }++ public static bool[] Rotate(bool[] pattern, int by)+ {+ int n = pattern.Length;+ if (n == 0) return pattern;+ var outp = new bool[n];+ for (int i = 0; i < n; i++) outp[i] = pattern[Mod(i + by, n)];+ return outp;+ }+}diff --git a/src/managed/Nota.Application/Midi/MidiTransforms.cs b/src/managed/Nota.Application/Midi/MidiTransforms.csnew file mode 100644index 00000000..3d739b07--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiTransforms.cs@@ -0,0 +1,687 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The nine clip transformations. Each is a pure function over the notes it is+// handed — no clip, track or engine awareness — so they are equally usable on a+// selection, a whole clip, or from a test.++namespace Nota.Application.Midi;++using U = MidiToolUtil;++public static class MidiTransforms+{+ // ---------------------------------------------------------------- Arpeggiate++ private static readonly string[] ArpStyles =+ { "Up", "Down", "Up-Down", "Down-Up", "Converge", "Diverge", "Random", "Chord" };++ public static MidiTool Arpeggiate { get; } = new(+ "arpeggiate", "Arpeggiate", MidiToolKind.Transform,+ "Breaks chords into a running sequence.",+ new[]+ {+ MidiToolParam.Rate("rate", "Rate"),+ MidiToolParam.Choice("style", "Style", ArpStyles, 0),+ MidiToolParam.Int("octaves", "Octaves", 1, 4, 1),+ MidiToolParam.Float("gate", "Gate", 0.05, 2.0, 0.9, "×"),+ MidiToolParam.Int("distance", "Distance", -12, 12, 12, " st"),+ MidiToolParam.Float("decay", "Vel Decay", -1, 1, 0, "×"),+ },+ RunArpeggiate);++ private static List<NotaNote> RunArpeggiate(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ double rate = s.RateBeats("rate");+ int style = s.Int("style");+ int octaves = s.Int("octaves");+ double gate = s["gate"];+ int distance = s.Int("distance");+ double decay = s["decay"];+ var rng = U.Rng(ctx, "arp");++ var chords = U.Chords(input);+ var outp = new List<NotaNote>();++ for (int c = 0; c < chords.Count; c++)+ {+ var chord = chords[c];+ double start = chord[0].StartBeat;+ double end = chord.Max(n => n.StartBeat + n.LengthBeats);+ if (c + 1 < chords.Count) end = Math.Min(end, chords[c + 1][0].StartBeat);+ if (end - start < rate * 0.5) end = start + rate; // a stab still gets one step++ // Extend the chord across the octave range before ordering it.+ var pitches = new List<int>();+ foreach (int o in Enumerable.Range(0, octaves))+ foreach (var n in chord) pitches.Add(n.Pitch + o * distance);+ var seq = OrderArp(pitches, style, rng);+ if (seq.Count == 0) continue;++ double vel = chord.Average(n => (double)n.Velocity);+ int step = 0;+ for (double t = start; t < end - 1e-6; t += rate, step++)+ {+ double fade = 1 - decay * (end - start <= rate ? 0 : (t - start) / (end - start));+ double len = rate * gate;+ if (style == 7) // Chord — every pitch of this step's cycle together+ {+ int cycle = U.Mod(step, Math.Max(1, octaves));+ foreach (var n in chord) outp.Add(U.Note(n.Pitch + cycle * distance, t, len, vel * fade));+ }+ else outp.Add(U.Note(seq[U.Mod(step, seq.Count)], t, len, vel * fade));+ }+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ private static List<int> OrderArp(List<int> pitches, int style, Random rng)+ {+ var up = pitches.Distinct().OrderBy(p => p).ToList();+ if (up.Count == 0) return up;+ switch (style)+ {+ case 1: up.Reverse(); return up;+ case 2: // Up-Down, endpoints played once+ {+ var r = new List<int>(up);+ for (int i = up.Count - 2; i >= 1; i--) r.Add(up[i]);+ return r;+ }+ case 3:+ {+ var down = Enumerable.Reverse(up).ToList();+ var r = new List<int>(down);+ for (int i = 1; i < up.Count - 1; i++) r.Add(up[i]);+ return r;+ }+ case 4: // Converge — outside in+ {+ var r = new List<int>();+ for (int lo = 0, hi = up.Count - 1; lo <= hi; lo++, hi--)+ {+ r.Add(up[lo]);+ if (lo != hi) r.Add(up[hi]);+ }+ return r;+ }+ case 5: // Diverge — inside out+ {+ var conv = OrderArp(pitches, 4, rng);+ conv.Reverse();+ return conv;+ }+ case 6:+ {+ var r = new List<int>(up);+ U.PartialShuffle(r, 1.0, rng);+ return r;+ }+ default: return up;+ }+ }++ // ------------------------------------------------------------------- Connect++ private static readonly string[] ConnectModes = { "Chromatic", "In scale" };++ public static MidiTool Connect { get; } = new(+ "connect", "Connect", MidiToolKind.Transform,+ "Fills the gaps between notes with runs that walk to the next pitch.",+ new[]+ {+ MidiToolParam.Rate("rate", "Rate", 5),+ MidiToolParam.Choice("mode", "Steps", ConnectModes, 1),+ MidiToolParam.Percent("fill", "Fill", 0.5),+ MidiToolParam.Float("gate", "Gate", 0.1, 1.5, 0.9, "×"),+ MidiToolParam.Float("velocity", "Velocity", 0.1, 1.5, 0.7, "×"),+ MidiToolParam.Int("maxsteps", "Max Steps", 1, 16, 4),+ },+ RunConnect);++ private static List<NotaNote> RunConnect(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ double rate = s.RateBeats("rate");+ bool inScale = s.Int("mode") == 1;+ double fill = s["fill"], gate = s["gate"], velScale = s["velocity"];+ int maxSteps = s.Int("maxsteps");+ var degrees = ctx.Degrees;++ var outp = U.Sorted(input);+ // Connect the top voice — a run under a sustained chord reads as a fill, not a mess.+ var line = new List<int>(); // indices into outp+ var chords = U.Chords(outp);+ foreach (var g in chords)+ line.Add(outp.FindIndex(n => n.Pitch == g[^1].Pitch && Math.Abs(n.StartBeat - g[^1].StartBeat) < 1e-9));++ var runs = new List<NotaNote>();+ for (int i = 0; i + 1 < line.Count; i++)+ {+ if (line[i] < 0 || line[i + 1] < 0) continue;+ var a = outp[line[i]];+ var b = outp[line[i + 1]];+ if (a.Pitch == b.Pitch) continue;++ // The run may eat into the source note as well as the silence after it, but+ // never all of it — one rate of the original always survives.+ double available = b.StartBeat - (a.StartBeat + rate);+ if (available < rate * 0.999) continue;+ int steps = Math.Min(maxSteps, (int)Math.Floor(available * Math.Clamp(fill, 0, 1) / rate + 1e-6));+ if (steps <= 0) continue;++ double runStart = b.StartBeat - steps * rate;+ if (a.StartBeat + a.LengthBeats > runStart)+ {+ a.LengthBeats = Math.Max(U.MinLength, runStart - a.StartBeat);+ outp[line[i]] = a;+ }++ for (int k = 0; k < steps; k++)+ {+ double f = (k + 1.0) / (steps + 1.0);+ int pitch;+ if (inScale)+ {+ int da = MidiScales.DegreeOfPitch(degrees, ctx.ScaleRoot, a.Pitch);+ int db = MidiScales.DegreeOfPitch(degrees, ctx.ScaleRoot, b.Pitch);+ pitch = MidiScales.PitchAtDegree(degrees, ctx.ScaleRoot, (int)Math.Round(U.Lerp(da, db, f)), 0);+ }+ else pitch = (int)Math.Round(U.Lerp(a.Pitch, b.Pitch, f));+ // A run that arrives on the target early gives the landing away; step past it.+ if (pitch == b.Pitch) pitch += Math.Sign(a.Pitch - b.Pitch);+ runs.Add(U.Note(pitch, runStart + k * rate, rate * gate, a.Velocity * velScale));+ }+ }+ outp.AddRange(runs);+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ // ------------------------------------------------------------------ Ornament++ private static readonly string[] OrnamentTypes =+ { "Grace", "Trill", "Mordent", "Turn", "Flam", "Roll" };++ public static MidiTool Ornament { get; } = new(+ "ornament", "Ornament", MidiToolKind.Transform,+ "Decorates notes with grace notes, trills and rolls.",+ new[]+ {+ MidiToolParam.Choice("type", "Type", OrnamentTypes, 0),+ MidiToolParam.Rate("rate", "Rate", 5),+ MidiToolParam.Percent("chance", "Chance", 1.0),+ MidiToolParam.Int("interval", "Interval", -4, 4, 1, " deg"),+ MidiToolParam.Float("velocity", "Velocity", 0.1, 1.5, 0.75, "×"),+ MidiToolParam.Toggle("scale", "In Scale", true),+ },+ RunOrnament);++ private static List<NotaNote> RunOrnament(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int type = s.Int("type");+ double rate = s.RateBeats("rate");+ double chance = s["chance"], velScale = s["velocity"];+ int interval = s.Int("interval");+ bool inScale = s.Flag("scale");+ var rng = U.Rng(ctx, "ornament");+ var degrees = ctx.Degrees;++ int Aux(int pitch, int steps)+ {+ if (!inScale) return pitch + steps;+ int d = MidiScales.DegreeOfPitch(degrees, ctx.ScaleRoot, pitch);+ return MidiScales.PitchAtDegree(degrees, ctx.ScaleRoot, d + steps, 0);+ }++ var outp = new List<NotaNote>();+ foreach (var n in U.Sorted(input))+ {+ if (rng.NextDouble() > chance) { outp.Add(n); continue; }+ int aux = Aux(n.Pitch, interval == 0 ? 1 : interval);+ double len = n.LengthBeats;+ double step = Math.Min(rate, len / 2);+ double vel = n.Velocity * velScale;++ switch (type)+ {+ case 0: // Grace — a flick into the note, stealing a sliver off the front+ outp.Add(U.Note(aux, n.StartBeat, step, vel));+ outp.Add(U.Note(n.Pitch, n.StartBeat + step, len - step, n.Velocity));+ break;++ case 1: // Trill — alternate for the note's whole length+ {+ int k = 0;+ for (double t = n.StartBeat; t < n.StartBeat + len - 1e-6; t += step, k++)+ outp.Add(U.Note(k % 2 == 0 ? n.Pitch : aux,+ t, Math.Min(step, n.StartBeat + len - t),+ k % 2 == 0 ? n.Velocity : vel));+ break;+ }++ case 2: // Mordent — main, aux, main+ outp.Add(U.Note(n.Pitch, n.StartBeat, step, n.Velocity));+ outp.Add(U.Note(aux, n.StartBeat + step, step, vel));+ outp.Add(U.Note(n.Pitch, n.StartBeat + step * 2, Math.Max(U.MinLength, len - step * 2), n.Velocity));+ break;++ case 3: // Turn — upper, main, lower, main+ {+ int upper = Aux(n.Pitch, Math.Abs(interval) == 0 ? 1 : Math.Abs(interval));+ int lower = Aux(n.Pitch, -(Math.Abs(interval) == 0 ? 1 : Math.Abs(interval)));+ double q = Math.Min(step, len / 4);+ outp.Add(U.Note(upper, n.StartBeat, q, vel));+ outp.Add(U.Note(n.Pitch, n.StartBeat + q, q, n.Velocity));+ outp.Add(U.Note(lower, n.StartBeat + q * 2, q, vel));+ outp.Add(U.Note(n.Pitch, n.StartBeat + q * 3, Math.Max(U.MinLength, len - q * 3), n.Velocity));+ break;+ }++ case 4: // Flam — a ghost a hair ahead, the main note untouched+ outp.Add(U.Note(n.Pitch, Math.Max(0, n.StartBeat - step * 0.5), step * 0.5, vel * 0.6));+ outp.Add(n);+ break;++ default: // Roll — ratchet the same pitch across the note+ for (double t = n.StartBeat; t < n.StartBeat + len - 1e-6; t += step)+ outp.Add(U.Note(n.Pitch, t, Math.Min(step, n.StartBeat + len - t) * 0.9,+ U.Lerp(n.Velocity, vel, (t - n.StartBeat) / Math.Max(1e-6, len))));+ break;+ }+ }+ return U.Deoverlap(U.Tidy(outp, ctx.LengthBeats));+ }++ // ------------------------------------------------------------------ Quantize++ public static MidiTool Quantize { get; } = new(+ "quantize", "Quantize", MidiToolKind.Transform,+ "Pulls notes onto the grid, with swing and a strength short of rigid.",+ new[]+ {+ MidiToolParam.Rate("rate", "Grid"),+ MidiToolParam.Percent("amount", "Amount", 1.0),+ MidiToolParam.Float("swing", "Swing", -0.75, 0.75, 0, "×"),+ MidiToolParam.Toggle("ends", "Quantize Ends", false),+ MidiToolParam.Float("humanize", "Humanize", 0, 0.25, 0, " b"),+ },+ RunQuantize);++ private static List<NotaNote> RunQuantize(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ double grid = s.RateBeats("rate");+ double amount = s["amount"], swing = s["swing"], humanize = s["humanize"];+ bool ends = s.Flag("ends");+ var rng = U.Rng(ctx, "quantize");++ // Swing pushes every second grid slot late by a fraction of the slot.+ double Target(double beat)+ {+ double idx = Math.Round(beat / grid);+ double t = idx * grid;+ if (Math.Abs(swing) > 1e-6 && U.Mod((int)idx, 2) == 1) t += grid * 0.5 * swing;+ return t;+ }++ var outp = new List<NotaNote>();+ foreach (var n in input)+ {+ var q = n;+ double target = Target(n.StartBeat);+ q.StartBeat = n.StartBeat + (target - n.StartBeat) * amount;+ if (humanize > 0) q.StartBeat += (rng.NextDouble() * 2 - 1) * humanize;+ if (ends)+ {+ double endTarget = Target(n.StartBeat + n.LengthBeats);+ double end = (n.StartBeat + n.LengthBeats) + (endTarget - (n.StartBeat + n.LengthBeats)) * amount;+ q.LengthBeats = Math.Max(U.MinLength, end - q.StartBeat);+ }+ outp.Add(q);+ }+ return U.Tidy(outp, ctx.LengthBeats);+ }++ // ----------------------------------------------------------------- Recombine++ private static readonly string[] RecombineModes =+ { "Shuffle Pitch", "Shuffle Rhythm", "Shuffle Both", "Rotate Pitch", "Reverse Pitch", "Mirror Pitch", "Reverse Time" };++ public static MidiTool Recombine { get; } = new(+ "recombine", "Recombine", MidiToolKind.Transform,+ "Pulls pitch and rhythm apart and puts them back together differently.",+ new[]+ {+ MidiToolParam.Choice("mode", "Mode", RecombineModes, 0),+ MidiToolParam.Percent("amount", "Amount", 0.6),+ MidiToolParam.Int("rotate", "Rotate", -16, 16, 1),+ MidiToolParam.Int("chunk", "Chunk", 1, 8, 1),+ },+ RunRecombine);++ private static List<NotaNote> RunRecombine(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int mode = s.Int("mode");+ double amount = s["amount"];+ int rotate = s.Int("rotate"), chunk = Math.Max(1, s.Int("chunk"));+ var rng = U.Rng(ctx, "recombine");++ var notes = U.Sorted(input);+ if (notes.Count < 2) return notes;++ // Chunking shuffles phrases instead of single notes, which keeps motifs intact.+ var pitchChunks = Chunked(notes.Select(n => n.Pitch).ToList(), chunk);+ var pitches = notes.Select(n => n.Pitch).ToList();++ switch (mode)+ {+ case 0:+ U.PartialShuffle(pitchChunks, amount, rng);+ pitches = pitchChunks.SelectMany(x => x).ToList();+ break;+ case 1:+ {+ var slots = Chunked(notes.Select(n => (n.StartBeat, n.LengthBeats)).ToList(), chunk);+ U.PartialShuffle(slots, amount, rng);+ var flat = slots.SelectMany(x => x).ToList();+ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ n.StartBeat = flat[i].StartBeat;+ n.LengthBeats = flat[i].LengthBeats;+ notes[i] = n;+ }+ return U.Deoverlap(U.Tidy(notes, ctx.LengthBeats));+ }+ case 2:+ {+ U.PartialShuffle(pitchChunks, amount, rng);+ pitches = pitchChunks.SelectMany(x => x).ToList();+ var slots = Chunked(notes.Select(n => (n.StartBeat, n.LengthBeats)).ToList(), chunk);+ U.PartialShuffle(slots, amount, rng);+ var flat = slots.SelectMany(x => x).ToList();+ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ n.Pitch = pitches[i];+ n.StartBeat = flat[i].StartBeat;+ n.LengthBeats = flat[i].LengthBeats;+ notes[i] = n;+ }+ return U.Deoverlap(U.Tidy(notes, ctx.LengthBeats));+ }+ case 3:+ pitches = Enumerable.Range(0, pitches.Count).Select(i => pitches[U.Mod(i + rotate, pitches.Count)]).ToList();+ break;+ case 4:+ pitches.Reverse();+ break;+ case 5: // Mirror — invert around the average pitch, snapped back into key+ {+ double axis = pitches.Average();+ pitches = pitches.Select(p => ctx.Snap((int)Math.Round(2 * axis - p))).ToList();+ break;+ }+ default: // Reverse Time — the phrase played backwards in place+ {+ double lo = notes.Min(n => n.StartBeat);+ double hi = notes.Max(n => n.StartBeat + n.LengthBeats);+ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ n.StartBeat = lo + hi - (n.StartBeat + n.LengthBeats);+ notes[i] = n;+ }+ return U.Deoverlap(U.Tidy(notes, ctx.LengthBeats));+ }+ }++ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ n.Pitch = pitches[i];+ notes[i] = n;+ }+ return U.Deoverlap(U.Tidy(notes, ctx.LengthBeats));+ }++ private static List<List<T>> Chunked<T>(List<T> items, int size)+ {+ var outp = new List<List<T>>();+ for (int i = 0; i < items.Count; i += size)+ outp.Add(items.GetRange(i, Math.Min(size, items.Count - i)));+ return outp;+ }++ // ---------------------------------------------------------------------- Span++ private static readonly string[] SpanModes = { "To Next Note", "Scale Length", "Fixed" };++ public static MidiTool Span { get; } = new(+ "span", "Span", MidiToolKind.Transform,+ "Rewrites note lengths — from staccato through legato to overlapping.",+ new[]+ {+ MidiToolParam.Choice("mode", "Mode", SpanModes, 0),+ MidiToolParam.Float("amount", "Amount", 0.05, 2.0, 1.0, "×"),+ MidiToolParam.Float("fixed", "Length", 0.03125, 8.0, 0.25, " b"),+ MidiToolParam.Float("min", "Min", 0.015625, 2.0, 0.0625, " b"),+ MidiToolParam.Toggle("perpitch", "Per Pitch", false),+ },+ RunSpan);++ private static List<NotaNote> RunSpan(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int mode = s.Int("mode");+ double amount = s["amount"], fixedLen = s["fixed"], min = s["min"];+ bool perPitch = s.Flag("perpitch");++ var notes = U.Sorted(input);+ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ double len = mode switch+ {+ 1 => n.LengthBeats * amount,+ 2 => fixedLen * amount,+ _ => NextStart(notes, i, perPitch, ctx.LengthBeats) is var next && next > n.StartBeat+ ? (next - n.StartBeat) * amount+ : n.LengthBeats * amount,+ };+ n.LengthBeats = Math.Max(min, len);+ notes[i] = n;+ }+ return U.Tidy(notes, ctx.LengthBeats);+ }++ private static double NextStart(List<NotaNote> notes, int i, bool perPitch, double clipLen)+ {+ for (int j = i + 1; j < notes.Count; j++)+ {+ if (notes[j].StartBeat <= notes[i].StartBeat + 1e-9) continue;+ if (perPitch && notes[j].Pitch != notes[i].Pitch) continue;+ return notes[j].StartBeat;+ }+ return clipLen;+ }++ // --------------------------------------------------------------------- Strum++ private static readonly string[] StrumDirections = { "Up", "Down", "Alternate", "Centre Out", "Random" };++ public static MidiTool Strum { get; } = new(+ "strum", "Strum", MidiToolKind.Transform,+ "Rolls the notes of a chord out in time instead of hitting them together.",+ new[]+ {+ MidiToolParam.Float("amount", "Amount", 0, 1.0, 0.125, " b"),+ MidiToolParam.Choice("direction", "Direction", StrumDirections, 0),+ MidiToolParam.Float("tension", "Tension", -1, 1, 0, ""),+ MidiToolParam.Float("velslope", "Vel Slope", -1, 1, 0, ""),+ MidiToolParam.Toggle("keepend", "Keep Ends", true),+ },+ RunStrum);++ private static List<NotaNote> RunStrum(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ double amount = s["amount"], tension = s["tension"], velSlope = s["velslope"];+ int direction = s.Int("direction");+ bool keepEnd = s.Flag("keepend");+ var rng = U.Rng(ctx, "strum");++ var outp = new List<NotaNote>();+ var chords = U.Chords(input);+ for (int c = 0; c < chords.Count; c++)+ {+ var chord = chords[c];+ int n = chord.Count;+ if (n < 2) { outp.AddRange(chord); continue; }++ var order = Enumerable.Range(0, n).ToList();+ bool down = direction == 1 || (direction == 2 && c % 2 == 1);+ if (down) order.Reverse();+ if (direction == 3) order = order.OrderBy(i => Math.Abs(i - (n - 1) / 2.0)).ToList();+ if (direction == 4) U.PartialShuffle(order, 1.0, rng);++ for (int k = 0; k < n; k++)+ {+ var note = chord[order[k]];+ double f = U.Bend(k / (double)(n - 1), tension);+ double offset = amount * f;+ double end = note.StartBeat + note.LengthBeats;+ note.StartBeat += offset;+ note.LengthBeats = keepEnd+ ? Math.Max(U.MinLength, end - note.StartBeat)+ : note.LengthBeats;+ note.Velocity = (float)Math.Clamp(note.Velocity * (1 + velSlope * (f - 0.5) * 2), 0.01, 1.0);+ outp.Add(note);+ }+ }+ return U.Tidy(outp, ctx.LengthBeats);+ }++ // ----------------------------------------------------------------- Time Warp++ private static readonly string[] WarpShapes = { "Curve", "S-Curve", "Sine", "Swing", "Snap to Grid" };++ public static MidiTool TimeWarp { get; } = new(+ "timewarp", "Time Warp", MidiToolKind.Transform,+ "Bends the time axis so a phrase accelerates, drags or breathes.",+ new[]+ {+ MidiToolParam.Choice("shape", "Shape", WarpShapes, 0),+ MidiToolParam.Float("curve", "Curve", -1, 1, 0.4, ""),+ MidiToolParam.Percent("amount", "Amount", 1.0),+ MidiToolParam.Int("cycles", "Cycles", 1, 8, 1),+ MidiToolParam.Toggle("lengths", "Warp Lengths", true),+ },+ RunTimeWarp);++ private static List<NotaNote> RunTimeWarp(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int shape = s.Int("shape");+ double curve = s["curve"], amount = s["amount"];+ int cycles = s.Int("cycles");+ bool warpLengths = s.Flag("lengths");++ var notes = U.Sorted(input);+ if (notes.Count == 0) return notes;+ double lo = notes.Min(n => n.StartBeat);+ double hi = Math.Max(lo + 1e-6, notes.Max(n => n.StartBeat + n.LengthBeats));+ double span = hi - lo;++ double Warp(double t)+ {+ t = Math.Clamp(t, 0, 1);+ double w = shape switch+ {+ 0 => U.Bend(t, curve),+ 1 => U.SCurve(t, curve),+ 2 => t + Math.Sin(t * Math.PI * 2 * cycles) / (Math.PI * 2 * cycles) * curve,+ 3 => SwingWarp(t, curve, cycles),+ _ => Math.Round(t * span / Math.Max(1e-6, ctx.Grid)) * ctx.Grid / span,+ };+ return U.Lerp(t, Math.Clamp(w, 0, 1), amount);+ }++ // Stretch each note by how far its own span moved apart, so a note sitting in a+ // squeezed region shortens and one in a stretched region opens up. Measuring the+ // span rather than the slope at the start matters: the slope is zero at the head+ // of a power curve, which would crush every note on the downbeat to nothing.+ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ double t0 = (n.StartBeat - lo) / span;+ double t1 = (n.StartBeat + n.LengthBeats - lo) / span;+ double w0 = Warp(t0);+ if (warpLengths)+ {+ double stretched = (Warp(Math.Min(1, t1)) - w0) * span;+ n.LengthBeats = Math.Max(U.MinLength, stretched > 1e-6 ? stretched : n.LengthBeats * 0.25);+ }+ n.StartBeat = lo + w0 * span;+ notes[i] = n;+ }+ return U.Deoverlap(U.Tidy(notes, ctx.LengthBeats));+ }++ private static double SwingWarp(double t, double curve, int cycles)+ {+ // Delay the back half of every cycle — the same shape a swing grid has.+ double period = 1.0 / Math.Max(1, cycles * 2);+ int slot = (int)Math.Floor(t / period);+ double frac = t / period - slot;+ double shift = slot % 2 == 1 ? 0 : curve * 0.5;+ return Math.Clamp((slot + frac + shift * (1 - frac)) * period, 0, 1);+ }++ // ----------------------------------------------------------- Velocity Shaper++ private static readonly string[] VelShapes =+ { "Ramp Up", "Ramp Down", "Sine", "Triangle", "Random", "Accent", "Flatten" };++ public static MidiTool VelocityShaper { get; } = new(+ "velshaper", "Velocity Shaper", MidiToolKind.Transform,+ "Draws a curve through the velocities instead of editing them one by one.",+ new[]+ {+ MidiToolParam.Choice("shape", "Shape", VelShapes, 2),+ MidiToolParam.Rate("period", "Period", 0),+ MidiToolParam.Percent("depth", "Depth", 0.35),+ MidiToolParam.Percent("centre", "Centre", 0.7),+ MidiToolParam.Float("phase", "Phase", 0, 1, 0, ""),+ MidiToolParam.Percent("random", "Random", 0),+ MidiToolParam.Percent("blend", "Blend", 1.0),+ },+ RunVelocityShaper);++ private static List<NotaNote> RunVelocityShaper(IReadOnlyList<NotaNote> input, MidiToolSettings s, MidiToolContext ctx)+ {+ int shape = s.Int("shape");+ double period = s.RateBeats("period");+ double depth = s["depth"], centre = s["centre"], phase = s["phase"], random = s["random"], blend = s["blend"];+ var rng = U.Rng(ctx, "velshaper");++ var notes = U.Sorted(input);++ for (int i = 0; i < notes.Count; i++)+ {+ var n = notes[i];+ double cycle = n.StartBeat / period;+ double t = (cycle - Math.Floor(cycle) + phase) % 1.0;+ double unit = shape switch+ {+ 0 => t,+ 1 => 1 - t,+ 2 => 0.5 + 0.5 * Math.Sin(t * Math.PI * 2),+ 3 => 1 - Math.Abs(t * 2 - 1),+ 4 => rng.NextDouble(),+ 5 => t < 1e-6 ? 1.0 : 0.35, // the downbeat of each period lands hard+ _ => 0.5,+ };+ double shaped = Math.Clamp(centre + (unit - 0.5) * depth * 2, 0.01, 1.0);+ if (random > 0) shaped = Math.Clamp(shaped + (rng.NextDouble() * 2 - 1) * random * 0.5, 0.01, 1.0);+ n.Velocity = (float)Math.Clamp(U.Lerp(n.Velocity, shaped, blend), 0.01, 1.0);+ notes[i] = n;+ }+ return U.Tidy(notes, ctx.LengthBeats);+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 60ada3c8..5dc9c847 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -7062,5 +7062,75 @@ Console.WriteLine("-- MCP tools --");Check(e.IsTrackFrozen(t), "setFreezeState re-freezes the track from a saved blob");}+// --- clip tools: every generator and transformation stays inside the clip ---------+{+ Console.WriteLine("-- clip tools (generate / transform) --");+ var toolCtx = new Nota.Application.Midi.MidiToolContext+ {+ LengthBeats = 4, Grid = 0.25, ScaleOn = true, ScaleRoot = 0,+ ScaleMask = Nota.Application.Midi.MidiScales.MaskAt(0), Seed = 11,+ };+ var toolSrc = new[]+ {+ new Nota.Application.NotaNote(60, 0.0, 2.0, 0.8f),+ new Nota.Application.NotaNote(64, 0.0, 2.0, 0.8f),+ new Nota.Application.NotaNote(67, 0.0, 2.0, 0.8f),+ new Nota.Application.NotaNote(62, 2.0, 1.0, 0.7f),+ new Nota.Application.NotaNote(71, 3.0, 1.0, 0.9f),+ };++ int bad = 0, empties = 0, nondet = 0;+ foreach (var tool in Nota.Application.Midi.MidiToolCatalog.All)+ {+ // Each parameter pinned to each end of its range, plus the defaults.+ var cases = new List<Nota.Application.Midi.MidiToolSettings> { tool.NewSettings() };+ foreach (var prm in tool.Params)+ foreach (double v in new[] { prm.Min, prm.Max })+ {+ var st = tool.NewSettings();+ st.Set(prm.Id, v);+ cases.Add(st);+ }++ foreach (var st in cases)+ {+ var r = Nota.Application.Midi.MidiToolRunner.Apply(tool, toolSrc, null, st, toolCtx);+ foreach (var n in r)+ if (n.Pitch is < 0 or > 127 || n.Velocity is <= 0 or > 1 || n.LengthBeats <= 0+ || n.StartBeat < -1e-9 || n.StartBeat + n.LengthBeats > toolCtx.LengthBeats + 1e-6)+ { bad++; Console.WriteLine($" {tool.Id}: illegal note {n.Pitch} @ {n.StartBeat}+{n.LengthBeats} v{n.Velocity}"); break; }+ }++ // A transformation with nothing to work on must not invent notes.+ if (tool.Kind == Nota.Application.Midi.MidiToolKind.Transform &&+ Nota.Application.Midi.MidiToolRunner.Apply(tool, Array.Empty<Nota.Application.NotaNote>(), null, tool.NewSettings(), toolCtx).Count != 0)+ empties++;++ // The seed is the only source of randomness, so a re-run must be identical.+ var a = Nota.Application.Midi.MidiToolRunner.Apply(tool, toolSrc, null, tool.NewSettings(), toolCtx);+ var b = Nota.Application.Midi.MidiToolRunner.Apply(tool, toolSrc, null, tool.NewSettings(), toolCtx);+ if (a.Count != b.Count) { nondet++; continue; }+ for (int i = 0; i < a.Count; i++)+ if (a[i].Pitch != b[i].Pitch || Math.Abs(a[i].StartBeat - b[i].StartBeat) > 1e-9) { nondet++; break; }+ }+ Check(Nota.Application.Midi.MidiToolCatalog.All.Count == 15, $"catalog holds 15 tools (got {Nota.Application.Midi.MidiToolCatalog.All.Count})");+ Check(bad == 0, $"every tool stays inside the clip at every parameter extreme ({bad} bad)");+ Check(empties == 0, $"no transformation invents notes from an empty clip ({empties} did)");+ Check(nondet == 0, $"every tool is deterministic for a given seed ({nondet} were not)");++ // A generated result survives the round trip through the engine.+ using var te = new NotaEngine();+ int tt = te.AddInstrumentTrack();+ int tc = te.AddMidiClip(tt, 0, 4);+ te.SetClipNotes(tt, tc, toolSrc);+ var arp = Nota.Application.Midi.MidiToolRunner.Apply(+ Nota.Application.Midi.MidiTransforms.Arpeggiate, te.GetClipNotes(tt, tc), null,+ Nota.Application.Midi.MidiTransforms.Arpeggiate.NewSettings(), toolCtx);+ Check(arp.Count > toolSrc.Length, $"Arpeggiate breaks the chord up ({toolSrc.Length} -> {arp.Count} notes)");+ te.SetClipNotes(tt, tc, arp.ToArray());+ Check(te.GetClipNotes(tt, tc).Length == arp.Count, "the generated notes round-trip through the engine");+ Check(te.Undo() && te.GetClipNotes(tt, tc).Length == toolSrc.Length, "applying a tool is one undo step");+}+Console.WriteLine(failures == 0 ? "SMOKE TEST PASSED" : $"SMOKE TEST FAILED ({failures})");return failures == 0 ? 0 : 1;