Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Drag'n'drop track and devices improvements
Egor Khindikaynen8f78853e6102
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d997c161..59b46ce5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,9 +16,18 @@ created, and the build-and-publish run starts.Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.+### Added+- Dropping an effect from the browser onto Devices puts it where you point: between cards+ (an accent bar marks the spot) or in place of the card under the pointer (the card is+ outlined). Dropping an instrument there replaces the track's instrument. Either way it is+ one undo step.+- Effects and presets can be dropped on a return track or the master in the arrangement.+### Changed- The first time you switch to automation mode, each track that already has automationshows its first automated parameter instead of Volume.+- While dragging from the browser over the arrangement, the target track is outlined in its+ header too, and the outline stays visible over the lane's clips.### Fixed- Reordering or removing effects in Devices no longer scrambles their automation: each lanediff --git a/src/managed/Nota.App/ArrangementView.Controls.cs b/src/managed/Nota.App/ArrangementView.Controls.csindex 467adf78..430a1d94 100644--- a/src/managed/Nota.App/ArrangementView.Controls.cs+++ b/src/managed/Nota.App/ArrangementView.Controls.cs@@ -239,6 +239,14 @@ public sealed partial class ArrangementViewctx.DrawText(ft, new Point(12, my + (FooterRowH - ft.Height) / 2));}+ // Browser drag-over: the return / master the drop would land on.+ if (_o.FooterDropRow >= 0)+ {+ var r = new Rect(0, _o.FooterDropRow * FooterRowH, w, FooterRowH);+ ctx.FillRectangle(DropWash, r);+ ctx.DrawRectangle(null, DropEdgePen, r.Deflate(1));+ }+// Loop region wash (matches the scrolling lanes).if (_o._loopActive && _o._loopE > _o._loopS){diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.csindex 5095da11..11b3731c 100644--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs@@ -1042,14 +1042,10 @@ public sealed partial class ArrangementViewctx.FillRectangle(SelWash, new Rect(0, sy, w, RowH(i)));}- // Browser drag-over: glow the lane the drop would land on (future state).+ // Browser drag-over: wash the lane the drop would land on (its edge is drawn+ // last, over the clips, so a full lane still reads as the target).if (_o.DropTrackIndex >= 0 && _o.DropTrackIndex < _o._tracks.Count)- {- double dy = RowTop(_o.DropTrackIndex);- var r = new Rect(0, dy, w, RowH(_o.DropTrackIndex));- ctx.FillRectangle(DropWash, r);- ctx.DrawRectangle(null, new Pen(DropEdge, 1.5), r);- }+ ctx.FillRectangle(DropWash, new Rect(0, RowTop(_o.DropTrackIndex), w, RowH(_o.DropTrackIndex)));// Vertical grid: bars always, beats when zoomed in enough.bool showBeats = _o._pixelsPerBeat >= 12;@@ -1171,6 +1167,9 @@ public sealed partial class ArrangementViewif (ex >= 0 && ex <= w) ctx.DrawLine(MarqueePen, new Point(ex, ty), new Point(ex, ty + th));}+ if (_o.DropTrackIndex >= 0 && _o.DropTrackIndex < _o._tracks.Count)+ ctx.DrawRectangle(null, DropEdgePen, new Rect(1, RowTop(_o.DropTrackIndex) + 1, w - 2, RowH(_o.DropTrackIndex) - 2));+// Drag position tooltip (req 2.9): bar.beat of the grabbed clip's start, or the// edge being trimmed, in a small pill near the cursor.if (_drag != Drag.None)diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex 8ab0ce93..239136a7 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -176,6 +176,16 @@ public sealed partial class ArrangementView : UserControlBackground = NotaPalette.AccentBright,};+ // Browser drag-over: a ring over the target row's header — the scrolling tracks' and the+ // return/master footer's (the lanes get their own wash + edge).+ private readonly Border _headerDropRing = DropRing();+ private readonly Border _footerDropRing = DropRing();+ private static Border DropRing() => new()+ {+ IsVisible = false, IsHitTestVisible = false, Width = HeaderW,+ BorderThickness = new Thickness(2), BorderBrush = DropEdge, Background = DropWash,+ };+// Return/Master section pinned under the scrolling tracks (no scroll).private readonly Canvas _footerHeaders;private readonly FooterLaneControl _footerLanes;@@ -303,7 +313,7 @@ public sealed partial class ArrangementView : UserControl// below the tracks) so instruments/samples can be dropped anywhere.DragDrop.SetAllowDrop(scroller, true);DragDrop.AddDragOverHandler(scroller, OnLaneDragOver);- DragDrop.AddDragLeaveHandler(scroller, (_, _) => { DropTrackIndex = -1; _lanes.InvalidateVisual(); });+ DragDrop.AddDragLeaveHandler(scroller, (_, _) => SetDropTrack(-1));DragDrop.AddDropHandler(scroller, OnLaneDrop);// Right-click the empty area below the tracks → paste a copied track there (the// header cards / lanes are top-anchored, so clicks below them land on the scroller).@@ -343,6 +353,11 @@ public sealed partial class ArrangementView : UserControlGrid.SetColumn(_footerLanes, 1);_footer.Children.Add(footerHeaderPanel);_footer.Children.Add(_footerLanes);+ // Effects / presets dropped on a return or the master go on that bus.+ DragDrop.SetAllowDrop(_footer, true);+ DragDrop.AddDragOverHandler(_footer, OnFooterDragOver);+ DragDrop.AddDragLeaveHandler(_footer, (_, _) => SetFooterDropRow(-1));+ DragDrop.AddDropHandler(_footer, OnFooterDrop);// Bottom: horizontal scrollbar under the lanes.var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };@@ -993,13 +1008,67 @@ public sealed partial class ArrangementView : UserControl{bool ok = BrowserView.IsAcceptableDrag(e);e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;- int ti = ok ? RowAtY(e.GetPosition(_lanes).Y) : -1;- if (ti != DropTrackIndex) { DropTrackIndex = ti; _lanes.InvalidateVisual(); }+ SetDropTrack(ok ? RowAtY(e.GetPosition(_lanes).Y) : -1);+ }++ // Marks row ti (-1 = none) as the browser drop target: lane wash + header ring.+ private void SetDropTrack(int ti)+ {+ if (ti == DropTrackIndex) return;+ DropTrackIndex = ti;+ _lanes.InvalidateVisual();+ _headerDropRing.IsVisible = ti >= 0 && ti < _tracks.Count;+ if (!_headerDropRing.IsVisible) return;+ Canvas.SetTop(_headerDropRing, RowTop(ti));+ _headerDropRing.Height = RowHeightAt(ti);+ }++ // The return/master footer row at y: returns first, master last; -1 outside.+ private int FooterRowAt(double y)+ {+ int row = (int)Math.Floor(y / FooterRowH);+ return y >= 0 && row <= _returns.Count ? row : -1;+ }+ private int FooterRowTrackId(int row)+ => row < 0 ? -1 : row < _returns.Count ? _returns[row].Id : _engine?.MasterTrackId ?? -1;++ // Only effects and presets have a home on a bus; instruments / samples belong on tracks.+ private static bool IsBusDrop()+ => BrowserView.CurrentDrag is { Kind: BrowserItemKind.BuiltinEffect or BrowserItemKind.PluginEffect or BrowserItemKind.Preset };++ private void OnFooterDragOver(object? sender, DragEventArgs e)+ {+ bool ok = IsBusDrop();+ e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;+ SetFooterDropRow(ok ? FooterRowAt(e.GetPosition(_footerHeaders).Y) : -1);+ }++ private void OnFooterDrop(object? sender, DragEventArgs e)+ {+ int row = FooterRowAt(e.GetPosition(_footerHeaders).Y);+ SetFooterDropRow(-1);+ if (!IsBusDrop() || BrowserView.CurrentDrag is not { } item) return;+ int trackId = FooterRowTrackId(row);+ if (trackId <= 0) return;+ ItemDropped?.Invoke(item, trackId, 0);+ e.Handled = true;+ }++ internal int FooterDropRow = -1; // footer row under a browser drag (-1 none); drawn by FooterLaneControl+ private void SetFooterDropRow(int row)+ {+ if (row == FooterDropRow) return;+ FooterDropRow = row;+ _footerLanes.InvalidateVisual();+ _footerDropRing.IsVisible = row >= 0;+ if (row < 0) return;+ Canvas.SetTop(_footerDropRing, row * FooterRowH);+ _footerDropRing.Height = FooterRowH;}private void OnLaneDrop(object? sender, DragEventArgs e){- DropTrackIndex = -1; _lanes.InvalidateVisual();+ SetDropTrack(-1);var items = BrowserView.DroppedItems(e);if (items.Count == 0) return;var p = e.GetPosition(_lanes);@@ -1432,6 +1501,7 @@ public sealed partial class ArrangementView : UserControl_headers.Children.Add(card);}_headers.Children.Add(_trackDropLine); // insertion marker (kept invisible until a drag)+ _headers.Children.Add(_headerDropRing); // browser drop target (kept invisible until a drag)_headers.Height = Math.Max(RowHeight, RowsHeight);}@@ -2172,6 +2242,7 @@ public sealed partial class ArrangementView : UserControlCanvas.SetLeft(master, 0);Canvas.SetTop(master, y);_footerHeaders.Children.Add(master);+ _footerHeaders.Children.Add(_footerDropRing); // browser drop target (kept invisible until a drag)}private Control BuildSlimRow(string title, string sub, int colorIndex, int trackId, string bgKey, bool masterSpine = false)@@ -2278,6 +2349,7 @@ public sealed partial class ArrangementView : UserControl// Browser drag-over: the lane the drop would land on glows (bright accent wash + edge).private static readonly IBrush DropWash = NotaPalette.Wash(NotaPalette.AccentBright, 0x28);private static readonly IBrush DropEdge = NotaPalette.Wash(NotaPalette.AccentBright, 0xC0);+ private static readonly IPen DropEdgePen = new Pen(DropEdge, 2);internal int DropTrackIndex = -1; // -1 = no drag over; set by OnLaneDragOver, drawn by LaneControl// In-progress audio take (M-fix): audio clips only materialise on stop, so a// translucent red region grows from the take start to the playhead as feedback.diff --git a/src/managed/Nota.App/DeviceChainView.Drop.cs b/src/managed/Nota.App/DeviceChainView.Drop.csnew file mode 100644index 00000000..c3805858--- /dev/null+++ b/src/managed/Nota.App/DeviceChainView.Drop.cs@@ -0,0 +1,187 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — where a browser item dropped on the panel lands, shown before the+// drop. An audio / MIDI effect goes into its own chain: over a card's middle half it+// replaces that card (ring around it), over a card's edges or the gaps it is inserted+// there (the same accent bar the drag-reorder draws). An instrument replaces the track's+// instrument (ring around it; a rack gets a new chain instead). Anything else — samples,+// presets, external files — lights the whole panel as before.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Nota.Presentation;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++/// <summary>How a browser item dropped on the Devices panel is placed.</summary>+public enum DeviceDropMode+{+ /// <summary>The usual routing: effects append, instruments go to a rack / nowhere.</summary>+ Default,+ /// <summary>A new effect goes in at <see cref="DeviceDropTarget.Index"/> (a gap, 0..count).</summary>+ Insert,+ /// <summary>The device at <see cref="DeviceDropTarget.Index"/> (-1 = the instrument) is swapped for the new one.</summary>+ Replace,+}++/// <summary>A Devices-panel drop target. <paramref name="Midi"/>: the MIDI-effect chain, else audio effects.</summary>+public readonly record struct DeviceDropTarget(DeviceDropMode Mode, int Index, bool Midi);++public sealed partial class DeviceChainView+{+ private Control? _instrumentCard; // the instrument / rack card in _row (null on audio, return, master)++ // Hints live on a layer over the scroller so showing them never reflows the cards+ // (a reflow under the pointer would flip the target back and forth).+ private readonly Canvas _dropLayer = new() { IsHitTestVisible = false, ClipToBounds = true };+ private readonly Border _dropInsertBar = new()+ {+ Width = 3, Background = AccentBright, CornerRadius = NotaRadius.Clip, IsVisible = false,+ };+ private readonly Border _dropReplaceRing = new()+ {+ BorderBrush = AccentBright, BorderThickness = new Thickness(2), CornerRadius = NotaRadius.Body,+ Background = NotaPalette.Wash(NotaPalette.AccentBright, 0x1E), IsVisible = false,+ };++ private void HookBrowserDrop()+ {+ _dropLayer.Children.Add(_dropReplaceRing);+ _dropLayer.Children.Add(_dropInsertBar);+ DragDrop.SetAllowDrop(this, true);+ DragDrop.AddDragOverHandler(this, (_, e) =>+ {+ var (ok, _) = DropTargetAt(e, showHints: true);+ e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;+ });+ DragDrop.AddDragLeaveHandler(this, (_, _) => ClearDropHints());+ DragDrop.AddDropHandler(this, (_, e) =>+ {+ var (ok, target) = DropTargetAt(e, showHints: false);+ ClearDropHints();+ if (!ok) return;+ var items = BrowserView.DroppedItems(e);+ if (items.Count == 0) return;+ foreach (var item in items) ItemDropped?.Invoke(item, target);+ e.Handled = true;+ });+ }++ private void ClearDropHints()+ {+ _dropGlow.IsVisible = false;+ _dropInsertBar.IsVisible = false;+ _dropReplaceRing.IsVisible = false;+ }++ // Resolves the drop target under the pointer and (optionally) shows its hint.+ private (bool Ok, DeviceDropTarget Target) DropTargetAt(DragEventArgs e, bool showHints)+ {+ if (showHints) ClearDropHints();+ if (_trackId <= 0 || !BrowserView.IsAcceptableDrag(e)) return (false, default);+ double x = e.GetPosition(_row).X;+ switch (BrowserView.CurrentDrag?.Kind)+ {+ case BrowserItemKind.BuiltinInstrument:+ case BrowserItemKind.PluginInstrument:+ {+ if (_instrumentCard is null || !IsInstrumentTrack(_trackId)) return (false, default);+ if (showHints) RingOver(_instrumentCard);+ int kind = _engine.TrackInstrumentKind(_trackId);+ // A rack takes the instrument as a new chain / pad (the default routing).+ return (true, kind is 3 or 4 ? default : new DeviceDropTarget(DeviceDropMode.Replace, -1, false));+ }+ case BrowserItemKind.BuiltinEffect:+ case BrowserItemKind.PluginEffect:+ return (true, EffectTargetAt(ChainKind.Effect, x, showHints));+ case BrowserItemKind.BuiltinMidiEffect:+ if (!IsInstrumentTrack(_trackId)) return (false, default);+ return (true, EffectTargetAt(ChainKind.Midi, x, showHints));+ default:+ if (showHints) _dropGlow.IsVisible = true;+ return (true, default);+ }+ }++ // Over a card's middle half → replace it; its outer quarters and the gaps → insert.+ private DeviceDropTarget EffectTargetAt(ChainKind kind, double x, bool showHints)+ {+ var cards = DomainCards(kind);+ bool midi = kind == ChainKind.Midi;+ for (int i = 0; i < cards.Count; i++)+ {+ var b = cards[i].Bounds;+ if (x < b.X + b.Width * 0.25) { if (showHints) BarAtGap(kind, i); return new(DeviceDropMode.Insert, i, midi); }+ if (x <= b.Right - b.Width * 0.25) { if (showHints) RingOver(cards[i]); return new(DeviceDropMode.Replace, i, midi); }+ }+ if (showHints) BarAtGap(kind, cards.Count);+ return new(DeviceDropMode.Insert, cards.Count, midi);+ }++ // The insertion bar centred in the spacing before gap's card (or after the last one).+ private void BarAtGap(ChainKind kind, int gap)+ {+ var cards = DomainCards(kind);+ double half = _row.Spacing / 2;+ Rect card; // the card the bar stands beside (for its x and vertical extent)+ double x;+ if (gap < cards.Count) { card = cards[gap].Bounds; x = card.X - half; }+ else if (cards.Count > 0) { card = cards[^1].Bounds; x = card.Right + half; }+ else+ {+ // An empty chain: MIDI effects open the row; audio effects follow the MIDI+ // effects and the instrument (i.e. sit before Sends / Add device).+ int at = 0;+ if (kind == ChainKind.Effect)+ foreach (var c in _row.Children)+ if (c.Tag is DevTag { Kind: ChainKind.Midi } || ReferenceEquals(c, _instrumentCard)) at++;+ if (at >= _row.Children.Count) return;+ card = _row.Children[at].Bounds; x = card.X - half;+ }+ var top = _row.TranslatePoint(new Point(x - _dropInsertBar.Width / 2, card.Y + 6), _dropLayer);+ if (top is null) return;+ Canvas.SetLeft(_dropInsertBar, top.Value.X);+ Canvas.SetTop(_dropInsertBar, top.Value.Y);+ _dropInsertBar.Height = CardH - 12;+ _dropInsertBar.IsVisible = true;+ }++ private void RingOver(Control card)+ {+ var p = card.TranslatePoint(default, _dropLayer);+ if (p is null) return;+ Canvas.SetLeft(_dropReplaceRing, p.Value.X);+ Canvas.SetTop(_dropReplaceRing, p.Value.Y);+ _dropReplaceRing.Width = card.Bounds.Width;+ _dropReplaceRing.Height = card.Bounds.Height;+ _dropReplaceRing.IsVisible = true;+ }++ /// <summary>Puts an effect just added (appended at <paramref name="newIdx"/>) where a+ /// panel drop aimed it: into the target gap, or in place of the target card (which is+ /// removed). Keeps card extras and index-addressed state elsewhere in step. Call inside+ /// an engine undo group so the add and the placement undo together.</summary>+ internal void PlaceDroppedDevice(int newIdx, DeviceDropTarget target)+ {+ if (newIdx < 0 || target.Mode == DeviceDropMode.Default) return;+ var k = target.Midi ? ChainKind.Midi : ChainKind.Effect;+ TrackExtras().Remove(ExtraKey(k, newIdx)); // a fresh slot: drop any stale entry+ int to = Math.Clamp(target.Index, 0, newIdx);+ if (to != newIdx)+ {+ if (target.Midi) _engine.MoveMidiEffect(_trackId, newIdx, to); else _engine.MoveDevice(_trackId, newIdx, to);+ ExtrasMoved(k, newIdx, to);+ }+ if (target.Mode == DeviceDropMode.Replace && to < newIdx) // the replaced card now sits right after+ {+ if (target.Midi) _engine.RemoveMidiEffect(_trackId, to + 1); else _engine.RemoveDevice(_trackId, to + 1);+ ExtrasRemoved(k, to + 1);+ }+ _selChainKind = k; _selDeviceIndex = to;+ Rebuild(); Changed?.Invoke();+ }+}diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.csindex 913679c3..f684c66b 100644--- a/src/managed/Nota.App/DeviceChainView.cs+++ b/src/managed/Nota.App/DeviceChainView.cs@@ -63,8 +63,9 @@ public sealed partial class DeviceChainView : UserControlpublic event Action<int>? PresetSaveRequested;/// <summary>Raised when a browser item is dropped on the device panel; MainWindow- /// routes it (effect → the shown track; instrument → a rack chain / drum pad).</summary>- public event Action<BrowserItem>? ItemDropped;+ /// routes it (effect → the shown track at the target slot; instrument → replaces the+ /// track's instrument, or a rack chain / drum pad).</summary>+ public event Action<BrowserItem, DeviceDropTarget>? ItemDropped;/// <summary>A one-line message for the status bar (e.g. a kit that loaded incompletely).</summary>public event Action<string>? StatusMessage;@@ -92,24 +93,8 @@ public sealed partial class DeviceChainView : UserControlHorizontalScrollBarVisibility = ScrollBarVisibility.Auto,VerticalScrollBarVisibility = ScrollBarVisibility.Disabled,};- Content = new Panel { Children = { scroller, _dropGlow } };-- DragDrop.SetAllowDrop(this, true);- DragDrop.AddDragOverHandler(this, (_, e) =>- {- bool ok = BrowserView.IsAcceptableDrag(e);- e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;- _dropGlow.IsVisible = ok;- });- DragDrop.AddDragLeaveHandler(this, (_, _) => _dropGlow.IsVisible = false);- DragDrop.AddDropHandler(this, (_, e) =>- {- _dropGlow.IsVisible = false;- var items = BrowserView.DroppedItems(e);- if (items.Count == 0) return;- foreach (var item in items) ItemDropped?.Invoke(item);- e.Handled = true;- });+ Content = new Panel { Children = { scroller, _dropGlow, _dropLayer } };+ HookBrowserDrop();}public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; _selDeviceIndex = -1; Rebuild(); }@@ -157,6 +142,7 @@ public sealed partial class DeviceChainView : UserControlprivate void Rebuild(){_row.Children.Clear();+ _instrumentCard = null;_instLiveViz = null; _instFaders.Clear(); // rebuilt only when a built-in instrument card is shown_deviceLiveRefreshers.Clear(); // compressor GR meter/curve_rackParamRefreshers.Clear(); // rack chain param faders (macro live-follow)@@ -167,7 +153,7 @@ public sealed partial class DeviceChainView : UserControlint midiCount = _engine.TrackMidiEffectCount(_trackId);for (int i = 0; i < midiCount; i++) _row.Children.Add(MidiDeviceCard(i, midiCount));- if (IsInstrumentTrack(_trackId)) _row.Children.Add(InstrumentCard());+ if (IsInstrumentTrack(_trackId)) _row.Children.Add(_instrumentCard = InstrumentCard());int count = _engine.TrackDeviceCount(_trackId);for (int i = 0; i < count; i++) _row.Children.Add(DeviceCard(i, count));@@ -222,7 +208,7 @@ public sealed partial class DeviceChainView : UserControl() => { foreach (var r in _rackParamRefreshers) r(); },Rebuild,c => RackPresetSaveRequested?.Invoke(c),- () => _dropGlow.IsVisible = false,+ ClearDropHints,_factory);// ---- instrument / sends / add ----------------------------------------diff --git a/src/managed/Nota.App/MainWindow.Dnd.cs b/src/managed/Nota.App/MainWindow.Dnd.csindex 64ab8cb7..af154385 100644--- a/src/managed/Nota.App/MainWindow.Dnd.cs+++ b/src/managed/Nota.App/MainWindow.Dnd.cs@@ -37,14 +37,7 @@ public partial class MainWindow{// Dropped on an existing (non-rack) instrument track → swap its instrument;// otherwise add a new track. Racks/Sampler fall through to their own adds.- if (CanReplaceInstrument(trackId) && Engine.SetTrackBuiltinInstrument(trackId, item.BuiltinKind))- {- if (item.BuiltinKind == RhythmModel.Kind) _kits.LoadInto(Engine, trackId, _kits.DefaultRhythmKit, out _);- _lastInstrumentTrackId = trackId;- RefreshDeviceChainIfShowing(trackId);- _vm.StatusText = $"Changed instrument to {item.Name} (track {trackId})";- break;- }+ if (TryReplaceInstrument(item, trackId)) break;int t = item.BuiltinKind switch{4 => Engine.AddDrumRackTrack(),@@ -73,14 +66,7 @@ public partial class MainWindowcase BrowserItemKind.PluginInstrument:{// Dropped on an existing (non-rack) instrument track → swap its instrument.- if (CanReplaceInstrument(trackId))- {- Engine.SetTrackInstrumentPlugin(trackId, item.CatalogIndex);- _lastInstrumentTrackId = trackId;- RefreshDeviceChainIfShowing(trackId);- _vm.StatusText = $"Changed instrument to {item.Name} (track {trackId})";- break;- }+ if (TryReplaceInstrument(item, trackId)) break;int t = Engine.AddPluginInstrumentTrack(item.CatalogIndex);Engine.AddMidiClip(t, beat, 4.0);_lastInstrumentTrackId = t;@@ -124,10 +110,49 @@ public partial class MainWindowcatch (Exception ex) { _vm.StatusText = $"Drop failed: {ex.Message}"; }}- // A browser item dropped on the Devices panel of the shown track. Effects/presets- // go on the track; instruments dropped on an Instrument/Drum Rack become a new- // chain / pad; otherwise they belong on the arrangement.- private void OnDevicePanelDrop(BrowserItem item) => DropBrowserItem(item, _deviceChain?.TrackId ?? -1);+ // A browser item dropped on the Devices panel of the shown track. An effect lands in+ // the gap it was dropped on, or replaces the card it was dropped on; an instrument+ // replaces the track's instrument (a rack gets a new chain / pad instead). The rest —+ // presets, samples — routes as usual.+ private void OnDevicePanelDrop(BrowserItem item, DeviceDropTarget target)+ {+ int t = _deviceChain?.TrackId ?? -1;+ if (_vm is null || _deviceChain is null || t <= 0 || target.Mode == DeviceDropMode.Default)+ { DropBrowserItem(item, t); return; }+ Engine.BeginUndoGroup(); // add + move (+ remove) undo as one step+ try+ {+ switch (item.Kind)+ {+ case BrowserItemKind.BuiltinInstrument:+ case BrowserItemKind.PluginInstrument:+ if (!TryReplaceInstrument(item, t)) { DropBrowserItem(item, t); return; }+ break;+ case BrowserItemKind.BuiltinEffect:+ case BrowserItemKind.PluginEffect:+ case BrowserItemKind.BuiltinMidiEffect:+ {+ int idx = item.Kind switch+ {+ BrowserItemKind.BuiltinEffect => Engine.AddBuiltinDevice(t, item.BuiltinKind),+ BrowserItemKind.PluginEffect => Engine.AddTrackEffectPlugin(t, item.CatalogIndex),+ _ => Engine.AddMidiEffect(t, item.BuiltinKind),+ };+ if (idx < 0) { _vm.StatusText = $"Couldn't load {item.Name}."; return; }+ _deviceChain.PlaceDroppedDevice(idx, target);+ _vm.StatusText = target.Mode == DeviceDropMode.Replace+ ? $"Replaced with {item.Name}" : $"Added {item.Name} to track {t}";+ break;+ }+ default:+ DropBrowserItem(item, t);+ return;+ }+ Timeline.Refresh();+ }+ catch (Exception ex) { _vm.StatusText = $"Drop failed: {ex.Message}"; }+ finally { Engine.EndUndoGroup(); }+ }private void OnModularDrop(BrowserItem item) => DropBrowserItem(item, _modular?.TrackId ?? -1);// Adds an instrument/effect/MIDI-FX/sample/preset from the browser to a track;@@ -273,6 +298,24 @@ public partial class MainWindowif (_deviceChain?.IsVisible == true && _deviceChain.TrackId == trackId) _deviceChain.Show(trackId);}+ // Swaps a plain instrument track's instrument for a dropped browser instrument (built-in+ // or plugin). False — nothing changed — when the track can't take it in place.+ private bool TryReplaceInstrument(BrowserItem item, int trackId)+ {+ if (_vm is null || !CanReplaceInstrument(trackId)) return false;+ if (item.Kind == BrowserItemKind.BuiltinInstrument)+ {+ if (!Engine.SetTrackBuiltinInstrument(trackId, item.BuiltinKind)) return false;+ if (item.BuiltinKind == RhythmModel.Kind) _kits.LoadInto(Engine, trackId, _kits.DefaultRhythmKit, out _);+ }+ else if (item.Kind == BrowserItemKind.PluginInstrument) Engine.SetTrackInstrumentPlugin(trackId, item.CatalogIndex);+ else return false;+ _lastInstrumentTrackId = trackId;+ RefreshDeviceChainIfShowing(trackId);+ _vm.StatusText = $"Changed instrument to {item.Name} (track {trackId})";+ return true;+ }+// True when an instrument dropped on this track should replace its instrument in place rather// than spawn a new track: a plain instrument track (not audio/return/group) that isn't a rack.private bool CanReplaceInstrument(int trackId)diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 713fa6db..14ff266f 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -697,6 +697,10 @@ public interface IAudioEngine : IDisposablebool Redo();bool CanUndo { get; }bool CanRedo { get; }+ /// <summary>Opens an undo group: the edits made until the matching+ /// <see cref="EndUndoGroup"/> undo as one step. Nests.</summary>+ void BeginUndoGroup();+ void EndUndoGroup();// --- Project load (M7-6) -----------------------------------------------void Reset();diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex 111eb8b5..5ad4a217 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -147,6 +147,12 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_can_redo")]internal static partial int CanRedo(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_engine_undo_group_begin")]+ internal static partial void UndoGroupBegin(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_engine_undo_group_end")]+ internal static partial void UndoGroupEnd(IntPtr engine);+[LibraryImport(Lib, EntryPoint = "nota_engine_reset")]internal static partial void Reset(IntPtr engine);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex 3ba2c164..26bbec45 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -137,6 +137,8 @@ public sealed partial class NotaEngine : IAudioEnginepublic bool Redo() { ThrowIfDisposed(); return NativeMethods.Redo(_handle) == NativeMethods.NotaResult.Ok; }public bool CanUndo { get { ThrowIfDisposed(); return NativeMethods.CanUndo(_handle) != 0; } }public bool CanRedo { get { ThrowIfDisposed(); return NativeMethods.CanRedo(_handle) != 0; } }+ public void BeginUndoGroup() { ThrowIfDisposed(); NativeMethods.UndoGroupBegin(_handle); }+ public void EndUndoGroup() { ThrowIfDisposed(); NativeMethods.UndoGroupEnd(_handle); }// --- Project load (M7-6) -----------------------------------------------diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 2f3807b5..5354b2f2 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -552,6 +552,10 @@ NOTA_API NotaResult nota_engine_undo(NotaEngine* engine);NOTA_API NotaResult nota_engine_redo(NotaEngine* engine);NOTA_API int32_t nota_engine_can_undo(const NotaEngine* engine);NOTA_API int32_t nota_engine_can_redo(const NotaEngine* engine);+/* Undo group: the edits made between begin and end undo as ONE step (e.g. replacing a+ * device in place = add + move + remove). Nests; pair every begin with an end. */+NOTA_API void nota_engine_undo_group_begin(NotaEngine* engine);+NOTA_API void nota_engine_undo_group_end(NotaEngine* engine);/* ---- Project load (M7-6) ------------------------------------------------- *//* Clear the session to an empty project: stop transport, drop all tracks,diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cppindex 6c906ec4..935725fd 100644--- a/src/native/nota.engine/src/Engine.cpp+++ b/src/native/nota.engine/src/Engine.cpp@@ -355,10 +355,24 @@ void Engine::publishRaw(std::shared_ptr<Graph> g) {void Engine::pushUndo() {if (!authoring_) return;undoStack_.push_back(authoring_); // authoring_ is immutable after publish- if (undoStack_.size() > kMaxUndoDepth) undoStack_.erase(undoStack_.begin());+ if (undoStack_.size() > kMaxUndoDepth) {+ undoStack_.erase(undoStack_.begin());+ if (undoGroupDepth_ > 0 && undoGroupBase_ > 0) --undoGroupBase_; // keep the group's anchor+ }redoStack_.clear(); // a new edit invalidates the redo branch}+void Engine::beginUndoGroup() {+ if (undoGroupDepth_++ == 0) undoGroupBase_ = undoStack_.size();+}++void Engine::endUndoGroup() {+ if (undoGroupDepth_ <= 0 || --undoGroupDepth_ > 0) return;+ // Keep only the first checkpoint the group pushed (the pre-group state).+ if (undoStack_.size() > undoGroupBase_ + 1)+ undoStack_.erase(undoStack_.begin() + static_cast<std::ptrdiff_t>(undoGroupBase_ + 1), undoStack_.end());+}+void Engine::publish(std::shared_ptr<Graph> g) {pushUndo();publishRaw(std::move(g));@@ -420,6 +434,7 @@ void Engine::reset() {nextTrackId_ = 1;undoStack_.clear();redoStack_.clear();+ undoGroupDepth_ = 0; undoGroupBase_ = 0;}diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex fda64fc7..bf9c1f5b 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -855,6 +855,12 @@ public:bool redo();bool canUndo() const { return !undoStack_.empty(); }bool canRedo() const { return !redoStack_.empty(); }+ // Undo group: every checkpoint pushed between begin and end collapses into one undo+ // step (the state before the first edit), so a compound UI edit — e.g. swapping a+ // device in place as add + move + remove — undoes with one step. Nests; an end+ // without a begin is ignored.+ void beginUndoGroup();+ void endUndoGroup();// --- offline render (tests / export) ---void renderOffline(float* out, int32_t frames);@@ -1054,6 +1060,8 @@ private:std::vector<std::shared_ptr<Graph>> undoStack_;std::vector<std::shared_ptr<Graph>> redoStack_;static constexpr size_t kMaxUndoDepth = 128;+ int32_t undoGroupDepth_ = 0; // open beginUndoGroup() calls+ size_t undoGroupBase_ = 0; // undoStack_ size when the outermost group beganstd::atomic<float> masterVolume_{1.0f};std::atomic<float> masterPeakL_{0.0f};diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cppindex 8bb7f642..c0547dc9 100644--- a/src/native/nota.engine/src/nota_engine_core.cpp+++ b/src/native/nota.engine/src/nota_engine_core.cpp@@ -198,6 +198,8 @@ int32_t nota_engine_can_undo(const NotaEngine* e) {int32_t nota_engine_can_redo(const NotaEngine* e) {return e ? (CENG(e)->canRedo() ? 1 : 0) : 0;}+void nota_engine_undo_group_begin(NotaEngine* e) { if (e) ENG(e)->beginUndoGroup(); }+void nota_engine_undo_group_end(NotaEngine* e) { if (e) ENG(e)->endUndoGroup(); }// ---- Project reset (M7-6) -------------------------------------------------diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 36bdef9c..a077c351 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -11693,6 +11693,30 @@ Console.WriteLine("-- overwrite on drag (carve) --");// bug02: select all clips, move 1.1→2.1, then 2.1→3.1 (or →5.1). Moving the clips one by// one let an early clip land on a not-yet-moved group member and carve it (clips vanished// or got cut). The atomic group move only carves clips that stay put.+Console.WriteLine("-- undo group (device swap in place) --");+{+ // A Devices-panel drop that replaces a card is add + move + remove; in an undo group+ // it must undo (and redo) as one step.+ using var ue = new NotaEngine();+ int t = ue.AddAudioTrack();+ ue.AddBuiltinDevice(t, 0); ue.AddBuiltinDevice(t, 2); // EQ, Reverb+ string Chain() { var k = new int[ue.TrackDeviceCount(t)]; for (int i = 0; i < k.Length; i++) k[i] = ue.TrackDeviceBuiltinKind(t, i); return string.Join(",", k); }+ string before = Chain();+ ue.BeginUndoGroup();+ int n = ue.AddBuiltinDevice(t, 3); // Delay, appended+ ue.MoveDevice(t, n, 0); // → in place of the EQ …+ ue.RemoveDevice(t, 1); // … which is dropped+ ue.EndUndoGroup();+ string swapped = Chain();+ Check(swapped == "3,2", $"swap in place: Delay replaces EQ ({swapped})");+ Check(ue.Undo() && Chain() == before, $"one undo restores the chain ({Chain()} vs {before})");+ Check(ue.Redo() && Chain() == swapped, "one redo re-applies the swap");+ Check(ue.Undo() && ue.Undo() && ue.TrackDeviceCount(t) == 1, "earlier edits stay separate steps");+ ue.EndUndoGroup(); // an unmatched end is ignored+ ue.AddBuiltinDevice(t, 4);+ Check(ue.Undo() && ue.TrackDeviceCount(t) == 1, "edits after the group checkpoint normally");+}+Console.WriteLine("-- group move (no self-carve) --");{using var ge = new NotaEngine();