Skip to content

armgit / nota

Public Imported from GitHub
0

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

(feat) Devices remember their preset and show when it changed (#157) (#360)

Chris Laupamaf85798c6090d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b1b96f3..254fa556 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,13 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Devices remember their preset and show when you changed it** (#157): after you load a
+ preset, the card header keeps its name and adds a " *" as soon as a sound parameter moves
+ away from it (the tooltip says "Changed since you loaded …"); setting it back, undoing or
+ picking the preset again clears it. Card size and EQ Eight's analyzer settings don't count.
+ The name follows the device through undo, copy and paste, duplicate and moves, and is saved
+ with the project. Applying a preset or Init is now one undo step. **Save preset…** starts
+ from the loaded preset's name. MCP: `read_preset_state`.
- **A bigger, more useful Modular Scope** (#266): drag the bar under the trace to make it
taller (76–320 px), or open the Scope in its own resizable window. New controls: a time
window in milliseconds (50 ms–8 s) or, with **Sync**, in beats (1/16 to 8 bars) at the
diff --git a/FEATURES.md b/FEATURES.md
index 77cb121d..f5c648a4 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -546,7 +546,9 @@ track count and closes with Escape.
## Built-in devices
Every built-in device uses the same 700×260 shell with a shared header: on/bypass dot,
-name, subtitle, preset picker (with **Init** to return to every default), **A/B comparison** (parameter snapshots), stereo meter,
+name, subtitle, preset picker (with **Init** to return to every default; the loaded preset's name
+stays with the device, saved with the project, and shows " *" once a sound parameter changes),
+**A/B comparison** (parameter snapshots), stereo meter,
voice count (on synths), move arrows, delete, and the ⠿ drag handle. All support factory
and user presets, automation, persistence and cloning. Instrument cards (built-in, racks
and hosted plug-ins) have the same on/off switch as effects: off silences the instrument
diff --git a/specs/048-preset-state/plan.md b/specs/048-preset-state/plan.md
new file mode 100644
index 00000000..9b874312
--- /dev/null
+++ b/specs/048-preset-state/plan.md
@@ -0,0 +1,41 @@
+# Implementation Plan: Preset name and "modified" state
+
+**Branch**: `feat/preset-state` | **Spec**: [spec.md](spec.md) | **Issue**: nota-daw/nota#157
+
+## Summary
+
+Each engine device carries a **preset tag**: an index into an append-only engine table of
+{id, name, loaded values}. Index 0 = no preset (Init). Because the tag is a small integer on the
+device object, it rides the existing value-gesture undo (a new mix kind, `PresetTag`), and it is
+copied wherever the engine clones a device (copy/paste, duplicate, move to track, rack grouping).
+"Modified" is computed on demand: the device's current parameter values (the CV base where a
+parameter is modulated) against the tag's loaded values, leaving view parameters out.
+
+## Technical context
+
+- Engine (C++20): `Device`, `MidiDevice` and `Instrument` get `presetTag`; `Engine_Presets.cpp`
+ holds the table, `presetModified` and a self-test; `MixKind::PresetTag = 6` in `mixValue` /
+ `applyMix`; clone paths copy the tag.
+- C ABI: `nota_track_device_preset_tag`, `nota_track_device_set_preset_tag`,
+ `nota_preset_tag_info`, `nota_track_device_preset_modified`, `nota_engine_preset_tag_selftest`
+ (`NOTA_MIX_PRESET_TAG`). Surfaces: 0 audio effect, 1 instrument, 2 MIDI effect.
+- Managed: `IAudioEngine` tag methods; `PresetEdit.Apply` wraps a preset apply plus the tag in
+ one `MixEdit.Step` over every parameter and the tag; `PresetEdit.Tag` for presets landed from
+ the Browser (a new device or track, already inside the insert's undo group).
+- App: the device card header reads the tag (the card's own cache follows it) and shows
+ "Name \*" with a tooltip while modified, checked a few times a second from the live tick.
+ Save preset… starts from the tag's name and retags the device.
+- Persistence: `PresetTagDto { Id, Name, Loaded }` on `InstrumentDto`, `DeviceDto`,
+ `MidiDeviceDto`; format v26, no-op migration.
+- MCP: `read_preset_state`; `apply_factory_preset_in_place` tags.
+
+## Constitution check
+
+- Audio thread: untouched. Tags are authoring state read and written on the control thread;
+ the modified check runs on the UI thread through the ABI.
+- C ABI only, no new dependencies, AGPL headers on new files.
+
+## Out of scope / follow-ups
+
+- US4: rack chain devices (rack cards apply presets through their own proxies).
+- Grain / Mosaic sources loaded by a preset are not part of the undo step (as before).
diff --git a/specs/048-preset-state/spec.md b/specs/048-preset-state/spec.md
new file mode 100644
index 00000000..953e97f3
--- /dev/null
+++ b/specs/048-preset-state/spec.md
@@ -0,0 +1,135 @@
+# Feature Specification: Preset name and "modified" state
+
+**Feature Branch**: `feat/preset-state`
+
+**Created**: 2026-10-28
+
+**Status**: Implemented (US1–US3; US4 rack chains is a follow-up)
+
+**Input**: User description: "Presets: show "(modified)" after a change, and keep the preset name
+across view switches and project reload (nota-daw/nota#157)."
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - See whether a device still sounds like its preset (Priority: P1)
+
+A producer loads "Warm Pad" on Volt and turns the filter down. The header now reads
+**Warm Pad \*** so they know the sound is their edit, not the preset. They undo the change, or
+pick Warm Pad again, and the mark goes away.
+
+**Why this priority**: It is the issue's first ask; without it the preset name misleads.
+
+**Independent Test**: Apply a factory preset to a built-in instrument, turn one knob, see the
+mark; undo, see it go.
+
+**Acceptance Scenarios**:
+
+1. **Given** a device loaded from a preset, **When** any sound parameter differs from the
+ values the preset set, **Then** its header shows the preset name followed by a mark
+ (" \*") and the picker's tooltip says "Changed since you loaded <name>".
+2. **Given** a modified device, **When** the user undoes back to the preset's values, sets the
+ parameter back by hand, or re-selects the preset, **Then** the mark goes.
+3. **Given** a device, **When** only a view setting changes (card size S / L, EQ-8's analyzer
+ mode, range and peak), **Then** it is not marked modified.
+4. **Given** a device at Init (no preset applied), **Then** the header shows "Init" without a
+ mark, as today.
+5. **Given** the user applies a preset and then undoes that step, **Then** the header shows the
+ preset it had before (and its own modified state), not the undone one.
+
+---
+
+### User Story 2 - The name stays with the device (Priority: P1)
+
+The preset name and the modified state follow the device: switching to another track and back,
+copy and paste, duplicating the device or its track, moving it to another track, saving,
+closing and reopening the project.
+
+**Why this priority**: The issue reports the name being lost or wrong over time.
+
+**Independent Test**: Apply a preset, tweak it, save and reopen: "Warm Pad \*". Duplicate the
+track: the copy says the same.
+
+**Acceptance Scenarios**:
+
+1. **Given** a device with a preset, **When** the user switches tracks or views and comes back,
+ **Then** the header shows the same name and mark.
+2. **Given** a device with a preset, **When** it is copied and pasted, duplicated, its track
+ duplicated, or it is moved to another track, **Then** the new device carries the same name and
+ the same "loaded" values (so the same mark).
+3. **Given** a project saved with devices loaded from presets, **When** it is reopened, **Then**
+ each device shows its preset name and its modified state. A project saved before this change
+ opens with the names the app can still work out (a Drum Rack kit, a Mosaic program) and Init
+ otherwise.
+
+---
+
+### User Story 3 - Save a modified preset under its old name (Priority: P2)
+
+From a modified device, **Save preset…** starts with the preset's name, so the user can keep it
+or add to it ("Warm Pad 2").
+
+**Acceptance Scenarios**:
+
+1. **Given** a device loaded from "Warm Pad", **When** the user picks Save preset…, **Then** the
+ name field starts as "Warm Pad".
+2. **Given** a device saved as a user preset, **Then** the header shows that preset's name
+ without a mark.
+
+---
+
+### User Story 4 - Rack chains (Priority: P2)
+
+A chain instrument or chain effect in an Instrument Rack, Drum Rack pad or Audio Effect Rack
+keeps its preset name and mark in the rack card and its pop-out window, saved with the project.
+
+### Edge Cases
+
+- **A preset that leaves a parameter alone** (the Sampler's trim and loop points): the loaded
+ values are what the device held right after the preset applied, so those params count from
+ there.
+- **Automation or CV moving a parameter**: the live value moves, so the mark can come and go
+ during playback. The comparison reads the parameter's base (the value the user set), not the
+ modulated one, where the engine keeps both; automation lanes that overwrite a parameter do
+ count as a change.
+- **Plug-ins**: a plug-in's user preset keeps its name; the mark compares the plug-in's exposed
+ parameters with the values after loading.
+- **A deleted user preset**: the name still shows; picking another preset replaces it.
+- **Small float differences**: a parameter counts as changed when it differs by more than
+ 1/10000 of its range.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Each device (audio effect, MIDI effect, instrument, rack chain device) MUST carry a
+ preset tag: the preset's id and display name and the parameter values right after it applied.
+- **FR-002**: Applying a preset MUST set the tag in the same undo step as the parameter change;
+ undo and redo restore the tag.
+- **FR-003**: The device header MUST show "<name> \*" when any sound parameter differs from the
+ tag's values by more than 1/10000 of its range; view parameters are left out.
+- **FR-004**: Copy / paste, duplicate (device and track), move to track and rack grouping MUST
+ keep the tag.
+- **FR-005**: The tag MUST be saved per device in the project (an optional `preset` field on
+ instruments, devices and MIDI effects, format v26 with a no-op migration); older projects
+ open without tags.
+- **FR-006**: Save preset… MUST start with the tag's name; saving sets the tag to the new
+ preset.
+- **FR-007**: MCP MUST report a device's preset name and whether it is modified
+ (`read_preset_state`); applying a factory preset in place through MCP tags the device.
+
+### Key Entities
+
+- **Preset tag**: preset id, display name, loaded values (one per parameter of the device).
+
+## Success Criteria *(mandatory)*
+
+- **SC-001**: After applying a preset, changing one parameter shows the mark on the next UI
+ frame; setting it back clears it.
+- **SC-002**: A project with 50 tagged devices saves, reopens and shows the same names and marks.
+- **SC-003**: Checking the mark for every visible device costs under 0.2 ms per UI frame.
+
+## Assumptions
+
+- The mark is " \*" after the name (fits the compact header); the tooltip spells it out.
+- Init is not a preset: applying Init clears the tag.
+- #57 (getting back to Init) is unchanged.
diff --git a/specs/048-preset-state/tasks.md b/specs/048-preset-state/tasks.md
new file mode 100644
index 00000000..2c0ffccd
--- /dev/null
+++ b/specs/048-preset-state/tasks.md
@@ -0,0 +1,16 @@
+# Tasks: Preset name and "modified" state
+
+- [x] T001 Engine: preset tag on devices, MIDI effects and instruments; tag table; clone paths copy it
+- [x] T002 Engine: `MixKind::PresetTag` in mix gestures (undo / redo)
+- [x] T003 Engine: `presetModified` (tolerance 1e-4 of range, view params skipped, CV base values) + self-test
+- [x] T004 C ABI + managed interop (`IAudioEngine`, `NotaEngine.Presets.cs`)
+- [x] T005 `PresetEdit.Apply` / `Tag`: one undo step with the tag
+- [x] T006 Device card: header name from the tag, "Name \*" + tooltip while modified
+- [x] T007 Browser drops and MCP in-place apply tag the device
+- [x] T008 Save preset… starts from the tag's name and retags
+- [x] T009 Persistence: `PresetTagDto`, format v26 + migration
+- [x] T010 MCP `read_preset_state`
+- [x] T011 Smoke tests `--preset-state` (engine self-test, undo/redo, Init, copy/duplicate/move, view params, save/load, migration)
+- [x] T012 CHANGELOG, FEATURES, docs EN + RU
+- [x] T013 macOS check with before/after screenshots (Mac mini, Oct 28: all 7 hands-on checks pass; `--preset-state` 156 PASS)
+- [ ] T014 Follow-up: rack chain devices (US4)
diff --git a/src/managed/Nota.App/DeviceCardKit.cs b/src/managed/Nota.App/DeviceCardKit.cs
index 3a66b80a..2a6ce3fc 100644
--- a/src/managed/Nota.App/DeviceCardKit.cs
+++ b/src/managed/Nota.App/DeviceCardKit.cs
@@ -328,7 +328,8 @@ internal static class DeviceCardKit
// neither select nor start dragging the card. Shared by the card shell and the rack chain
// full-UI popups.
internal static Control PresetPicker(IReadOnlyList<string> presets, int cur, string current,
- Action<int> apply, Action<int> step, double nameWidth = 132, double height = 18, Action? init = null)
+ Action<int> apply, Action<int> step, double nameWidth = 132, double height = 18, Action? init = null,
+ Func<bool>? modified = null, Action<Action>? addLive = null)
{
double H = height; // 18 in a card header, 22 in the device window's title bar
var label = new TextBlock
@@ -345,6 +346,21 @@ internal static class DeviceCardKit
Child = new DockPanel { Children = { chevron, label } },
};
ToolTip.SetTip(name, "Choose a preset");
+ // A sound parameter moved away from the loaded preset (specs/048): "Name *", read live.
+ if (modified != null && !string.IsNullOrEmpty(current))
+ {
+ bool shown = false;
+ void Mark()
+ {
+ bool m = modified();
+ if (m == shown) return;
+ shown = m;
+ label.Text = m ? current + " *" : current;
+ ToolTip.SetTip(name, m ? $"Changed since you loaded {current} · choose a preset" : "Choose a preset");
+ }
+ Mark();
+ addLive?.Invoke(Mark);
+ }
name.PointerPressed += (_, e) =>
{
if (!e.GetCurrentPoint(name).Properties.IsLeftButtonPressed) return;
diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.cs
index 37e22c51..cc4c0225 100644
--- a/src/managed/Nota.App/DeviceChainView.Shell.cs
+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs
@@ -141,6 +141,22 @@ public sealed partial class DeviceChainView
Nota.Application.Editing.MixEdit.Step(_engine, () => { for (int i = 0; i < n; i++) if (i != view) SetPr(k, di, i, p[i]); }, targets.ToArray());
}
+ private static PresetSurface SurfaceOf(ChainKind k)
+ => k == ChainKind.Instrument ? PresetSurface.Instrument : k == ChainKind.Midi ? PresetSurface.MidiEffect : PresetSurface.Effect;
+
+ /// <summary>Applies a preset (or Init, <paramref name="id"/> "") as one undo step that also
+ /// tags the device with it (specs/048), so undo brings back the old sound and its name.
+ /// A preset that didn't apply (a warning back) leaves the tag as it was.</summary>
+ private string PresetStep(ChainKind k, int di, Func<string> apply, string id, string name)
+ => Nota.Application.Editing.PresetEdit.Apply(_engine, _trackId, SurfaceOf(k), di, id, name, apply);
+
+ // The modified check walks every parameter: a few times a second is plenty for a label.
+ private static Func<bool> Throttled(Func<bool> check)
+ {
+ int tick = 0; bool last = false;
+ return () => { if (tick++ % 6 == 0) last = check(); return last; };
+ }
+
internal readonly record struct ShellSpec(
string Name, string Subtitle, int DeviceIndex, int Count, bool Bypassed, bool Bypassable,
bool CanMove, bool CanDelete, int PresetKind, bool IsInstrument, double Width, ChainKind Kind,
@@ -258,8 +274,8 @@ public sealed partial class DeviceChainView
// Factory presets for this device (or the card's own list), and applying one in place.
List<(string Id, string Name)> presets;
- Action<string> applyById;
- Action? resetToInit = null; // Init isn't a preset, it's every default (#57); an own list opts in (#165)
+ Func<string, string> applyById; // each returns a warning, "" when it applied
+ Func<string>? resetToInit = null; // Init isn't a preset, it's every default (#57); an own list opts in (#165)
if (s.Presets is { } own)
{
presets = own.Items.ToList();
@@ -267,18 +283,25 @@ public sealed partial class DeviceChainView
// from the browser, or a project reopened, still names its kit.
string now = own.Current();
if (now.Length > 0 && presets.FindIndex(p => p.Id == now) is var ni and >= 0) { extra.PresetId = now; extra.Preset = presets[ni].Name; }
+ // An own list (a kit, a program) isn't a parameter change the mix undo can hold, so
+ // its pick retags the device directly: the name and the mark follow the pick.
+ var ownSurface = SurfaceOf(s.Kind);
applyById = id =>
{
string warn = own.Apply(id);
if (warn.Length > 0) StatusMessage?.Invoke(warn);
+ else _engine.SetDevicePresetTag(_trackId, ownSurface, di, "own:" + id, presets.FirstOrDefault(p => p.Id == id).Name ?? "");
Changed?.Invoke();
+ return warn;
};
if (own.Init is { } init)
resetToInit = () =>
{
string warn = init();
if (warn.Length > 0) StatusMessage?.Invoke(warn);
+ else _engine.SetDevicePresetTag(_trackId, ownSurface, di, "", "");
Changed?.Invoke();
+ return warn;
};
}
else
@@ -288,19 +311,62 @@ public sealed partial class DeviceChainView
&& (s.Kind == ChainKind.Midi ? p.IsMidiEffect : (p.IsInstrument == s.IsInstrument && !p.IsMidiEffect)))
.Select(p => (p.Id, p.DisplayName)).ToList()
: new List<(string Id, string Name)>();
- applyById = id => _factory.ApplyInPlace(_engine, id, _trackId, di);
+ applyById = id =>
+ {
+ string warn = _factory.ApplyInPlace(_engine, id, _trackId, di);
+ if (warn.Length > 0) StatusMessage?.Invoke(warn);
+ return warn;
+ };
// A device whose factory list already starts from its own "Init" preset needs no second one.
if (presets.Count > 0 && !presets.Any(p => p.Name == "Init"))
resetToInit = () =>
{
string warn = _factory.ResetInPlace(_engine, _trackId, di, s.Kind == ChainKind.Midi);
if (warn.Length > 0) StatusMessage?.Invoke(warn);
+ return warn;
};
}
+ // A factory list reads the device's own preset tag (specs/048): it follows undo, copies
+ // and saved projects, so the card only caches it.
+ bool tagged = s.Presets is null && presets.Count > 0;
+ var surface = SurfaceOf(s.Kind);
+ int tagIx = s.Utility ? -1 : _engine.DevicePresetTag(_trackId, surface, di);
+ if (tagged && tagIx >= 0)
+ {
+ var tag = _engine.PresetTagInfo(tagIx);
+ extra.PresetId = tag?.Id ?? ""; extra.Preset = tag?.Name ?? "";
+ }
+ // A card with its own list, or a plug-in with none, still names a preset the browser
+ // or Save preset… tagged it with (a user preset, a plug-in's preset file).
+ bool ownTagged = !tagged && tagIx > 0;
+ if (ownTagged && _engine.PresetTagInfo(tagIx) is { } ot)
+ {
+ int oi = ot.Id.StartsWith("own:", StringComparison.Ordinal) ? presets.FindIndex(p => "own:" + p.Id == ot.Id) : -1;
+ bool known = presets.FindIndex(p => p.Id == extra.PresetId) >= 0; // the device's own word wins
+ if (oi >= 0) { if (!known) { extra.PresetId = presets[oi].Id; extra.Preset = presets[oi].Name; } }
+ // A preset from outside the list (the browser, Save preset…) is newer than the list's
+ // pick: any later pick from the list retags the device as "own:".
+ else if (!ot.Id.StartsWith("own:", StringComparison.Ordinal)) { extra.PresetId = ot.Id; extra.Preset = ot.Name; }
+ }
int curPreset = presets.FindIndex(p => p.Id == extra.PresetId);
+ // A factory list's own "Init" entry stands for no tag.
+ if (tagged && curPreset < 0 && extra.PresetId.Length == 0) curPreset = presets.FindIndex(p => p.Name == "Init");
bool atInit = curPreset < 0 && string.IsNullOrEmpty(extra.Preset);
- void ApplyPreset(int i) { var p = presets[i]; applyById(p.Id); extra.PresetId = p.Id; extra.Preset = p.Name; Rebuild(); }
- void ApplyInit() { resetToInit!(); extra.PresetId = ""; extra.Preset = ""; Rebuild(); }
+ void ApplyPreset(int i)
+ {
+ var p = presets[i];
+ // The list's own "Init" entry is Init: no tag, no mark.
+ bool isInit = p.Name == "Init";
+ string warn = tagged ? PresetStep(s.Kind, di, () => applyById(p.Id), isInit ? "" : p.Id, isInit ? "" : p.Name) : applyById(p.Id);
+ if (warn.Length == 0) { extra.PresetId = p.Id; extra.Preset = p.Name; }
+ Rebuild();
+ }
+ void ApplyInit()
+ {
+ string warn = tagged ? PresetStep(s.Kind, di, resetToInit!, "", "") : resetToInit!();
+ if (warn.Length == 0) { extra.PresetId = ""; extra.Preset = ""; }
+ Rebuild();
+ }
void StepPreset(int dir)
{
int n = presets.Count; if (n == 0) return;
@@ -315,10 +381,12 @@ public sealed partial class DeviceChainView
// The picker has its own centre slot: the badges' live voice count changes width
// (Consort's "Duo 1/2" → "Poly 12/16") without moving it.
Control? picker = null;
- if (presets.Count > 0)
+ if (presets.Count > 0 || ownTagged)
{
picker = PresetPicker(presets.Select(p => p.Name).ToList(), curPreset, extra.Preset, ApplyPreset, StepPreset,
- nameWidth: s.Compact ? 74 : 132, init: resetToInit != null ? ApplyInit : null);
+ nameWidth: s.Compact ? 74 : 132, init: resetToInit != null ? ApplyInit : null,
+ modified: tagged || ownTagged ? Throttled(() => _engine.DevicePresetModified(_trackId, surface, di) == 1) : null,
+ addLive: _deviceLiveRefreshers.Add);
Grid.SetColumn(picker, 1); headerGrid.Children.Add(picker);
}
diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.cs
index dd255198..1da88a43 100644
--- a/src/managed/Nota.App/MainWindow.Browser.cs
+++ b/src/managed/Nota.App/MainWindow.Browser.cs
@@ -214,6 +214,10 @@ public partial class MainWindow
? Engine.MidiEffectName(trackId, PresetService.MidiEffectBase - deviceIndex)
: Engine.DeviceName(trackId, deviceIndex);
if (string.IsNullOrEmpty(label)) label = "Instrument";
+ // The preset it was loaded from is the likelier name to start from (specs/048).
+ var (surface, index) = deviceIndex <= PresetService.MidiEffectBase ? (PresetSurface.MidiEffect, PresetService.MidiEffectBase - deviceIndex)
+ : deviceIndex < 0 ? (PresetSurface.Instrument, -1) : (PresetSurface.Effect, deviceIndex);
+ if (Nota.Application.Editing.PresetEdit.Name(Engine, trackId, surface, index) is { Length: > 0 } loaded) label = loaded;
var name = await new TextPromptWindow("Save preset", "Preset name", label).ShowDialog<string?>(this);
if (string.IsNullOrEmpty(name)) return;
@@ -221,6 +225,9 @@ public partial class MainWindow
{
if (!_presets.Save(Engine, trackId, deviceIndex, name, _vm.Settings.PresetsFolder()))
{ _vm.StatusText = "Nothing to save (built-in synth has no state)."; return; }
+ // The device now holds that preset: its name, no " *".
+ Engine.SetDevicePresetTag(trackId, surface, index, "user:" + name, name);
+ _deviceChain.Refresh();
_vm.Browser.RebuildPresets();
_vm.StatusText = $"Saved preset {name}";
}
diff --git a/src/managed/Nota.Application/Editing/PresetEdit.cs b/src/managed/Nota.Application/Editing/PresetEdit.cs
new file mode 100644
index 00000000..6771ed69
--- /dev/null
+++ b/src/managed/Nota.Application/Editing/PresetEdit.cs
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Applying a preset to a device as one undo step that also tags the device with it
+// (specs/048-preset-state): undo brings back the previous sound and the previous name.
+
+using System;
+
+namespace Nota.Application.Editing;
+
+public static class PresetEdit
+{
+ /// <summary>Runs <paramref name="apply"/> (it sets the device's parameters) and tags the
+ /// device with the preset, as one undo step. <paramref name="presetId"/> "" = Init (no tag).
+ /// A preset that didn't apply (a warning back) leaves the tag as it was.
+ /// Returns what <paramref name="apply"/> returned (a warning, "" when fine).</summary>
+ public static string Apply(IAudioEngine engine, int trackId, PresetSurface surface, int index,
+ string presetId, string name, Func<string> apply)
+ {
+ int n = surface switch
+ {
+ PresetSurface.Instrument => engine.PluginParamCount(trackId, -1),
+ PresetSurface.MidiEffect => engine.MidiEffectParamCount(trackId, index),
+ _ => engine.DeviceParamCount(trackId, index),
+ };
+ var targets = new MixTarget[Math.Max(0, n) + 1];
+ for (int i = 0; i < n; i++)
+ targets[i] = surface switch
+ {
+ PresetSurface.Instrument => MixTarget.PluginParam(trackId, -1, i),
+ PresetSurface.MidiEffect => MixTarget.MidiDeviceParam(trackId, index, i),
+ _ => MixTarget.DeviceParam(trackId, index, i),
+ };
+ targets[^1] = MixTarget.PresetTag(trackId, surface, index);
+ string warn = "";
+ MixEdit.Step(engine, () =>
+ {
+ warn = apply();
+ if (warn.Length == 0) engine.SetDevicePresetTag(trackId, surface, index, presetId, name);
+ }, targets);
+ return warn;
+ }
+
+ /// <summary>Tags a device that a preset just landed on (a new track or device), as an undo step.</summary>
+ public static void Tag(IAudioEngine engine, int trackId, PresetSurface surface, int index, string presetId, string name)
+ => MixEdit.Step(engine, () => engine.SetDevicePresetTag(trackId, surface, index, presetId, name),
+ MixTarget.PresetTag(trackId, surface, index));
+
+ /// <summary>The device's preset name, "" with no tag (Init) or no such device.</summary>
+ public static string Name(IAudioEngine engine, int trackId, PresetSurface surface, int index)
+ => engine.DevicePresetTag(trackId, surface, index) is var t and > 0 ? engine.PresetTagInfo(t)?.Name ?? "" : "";
+}
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index 3c54bba5..76942902 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -308,7 +308,7 @@ public struct StereoMeasure
/// <summary>What a value gesture targets (specs/009 volume / pan, specs/016 device
/// parameters). Matches NOTA_MIX_*.</summary>
-public enum MixKind { TrackVolume = 0, TrackPan = 1, MasterVolume = 2, DeviceParam = 3, MidiDeviceParam = 4, PluginParam = 5 }
+public enum MixKind { TrackVolume = 0, TrackPan = 1, MasterVolume = 2, DeviceParam = 3, MidiDeviceParam = 4, PluginParam = 5, PresetTag = 6 }
/// <summary>One value a gesture records for undo; laid out like native NotaMixTarget.
/// <see cref="TrackId"/> is ignored for the master volume; <see cref="DeviceIndex"/> /
@@ -326,8 +326,17 @@ public readonly record struct MixTarget(MixKind Kind, int TrackId, int DeviceInd
public static MixTarget MidiDeviceParam(int trackId, int index, int paramIndex) => new(MixKind.MidiDeviceParam, trackId, index, paramIndex);
/// <summary>A normalized plugin / built-in instrument parameter (device −1 = the instrument).</summary>
public static MixTarget PluginParam(int trackId, int deviceIndex, int paramIndex) => new(MixKind.PluginParam, trackId, deviceIndex, paramIndex);
+ /// <summary>A device's preset tag (specs/048), so a preset applied in the gesture undoes with its name.</summary>
+ public static MixTarget PresetTag(int trackId, PresetSurface surface, int index) => new(MixKind.PresetTag, trackId, index, (int)surface);
}
+/// <summary>Which of a track's devices a preset tag is on (specs/048).</summary>
+public enum PresetSurface { Effect = 0, Instrument = 1, MidiEffect = 2 }
+
+/// <summary>The preset a device was loaded from: its id ("" = a user preset by path), name
+/// and the parameter values right after it applied (specs/048).</summary>
+public sealed record PresetTag(string Id, string Name, float[] Loaded);
+
/// <summary>A named span of arrangement time — Intro / Verse / Drop (specs/016). Project
/// data held by the engine: undoable, saved with the project.</summary>
public readonly record struct SectionInfo(double StartBeat, double LengthBeats, string Name);
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 4883101d..49e9bec8 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -1280,6 +1280,17 @@ public interface IAudioEngine : IDisposable
/// <summary>Scope history with time steps (specs/047): the newest entries oldest→newest, and the
/// seconds each one follows the previous by (one audio block). Returns the count.</summary>
int ModulatorScopeTimed(int trackId, int modId, float[] values, float[] dts);
+
+ // ---- preset tags (specs/048) ----
+ /// <summary>The device's preset tag: 0 none, -1 no such device.</summary>
+ int DevicePresetTag(int trackId, PresetSurface surface, int index);
+ /// <summary>Tag the device with a preset (empty id = Init, clears it). <paramref name="loaded"/>
+ /// = the values the preset left (null = what the device holds now). No undo step of its own:
+ /// set it inside a mix gesture with a <see cref="MixTarget.PresetTag"/> target.</summary>
+ int SetDevicePresetTag(int trackId, PresetSurface surface, int index, string presetId, string name, float[]? loaded = null);
+ PresetTag? PresetTagInfo(int tag);
+ /// <summary>1 when a sound parameter moved away from the preset's values, 0 when not, -1 with no tag.</summary>
+ int DevicePresetModified(int trackId, PresetSurface surface, int index);
int CvLinkAdd(int trackId, int modId, int deviceIndex, int paramIndex);
/// <summary>Cross-track link: modulator on trackId modulates a param on targetTrack (-1 = self).</summary>
int CvLinkAddTo(int trackId, int modId, int targetTrack, int deviceIndex, int paramIndex);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Presets.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Presets.cs
new file mode 100644
index 00000000..fc31ee4e
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Presets.cs
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// P/Invoke for preset tags (specs/048): see nota_engine.h "Preset tags".
+
+using System.Runtime.InteropServices;
+
+namespace Nota.Infrastructure;
+
+internal static partial class NativeMethods
+{
+ [LibraryImport(Lib, EntryPoint = "nota_track_device_preset_tag")]
+ internal static partial int DevicePresetTag(IntPtr engine, int trackId, int surface, int index);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_device_set_preset_tag", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial int DeviceSetPresetTag(IntPtr engine, int trackId, int surface, int index,
+ string? presetId, string? name, [In] float[]? baseValues, int baseCount);
+
+ [LibraryImport(Lib, EntryPoint = "nota_preset_tag_info")]
+ internal static partial int PresetTagInfo(IntPtr engine, int tag, [Out] byte[] presetId, int idCap,
+ [Out] byte[] name, int nameCap, [Out] float[]? baseValues, int baseCap);
+
+ [LibraryImport(Lib, EntryPoint = "nota_track_device_preset_modified")]
+ internal static partial int DevicePresetModified(IntPtr engine, int trackId, int surface, int index);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_preset_tag_selftest")]
+ internal static partial int PresetTagSelfTest(IntPtr engine);
+}
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Presets.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Presets.cs
new file mode 100644
index 00000000..317a7bf9
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Presets.cs
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Preset tags (specs/048): which preset a device was loaded from, and whether it still holds
+// that preset's values.
+
+using Nota.Application;
+
+namespace Nota.Infrastructure;
+
+public sealed partial class NotaEngine
+{
+ public int DevicePresetTag(int trackId, PresetSurface surface, int index)
+ { ThrowIfDisposed(); return NativeMethods.DevicePresetTag(_handle, trackId, (int)surface, index); }
+
+ public int SetDevicePresetTag(int trackId, PresetSurface surface, int index, string presetId, string name, float[]? loaded = null)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.DeviceSetPresetTag(_handle, trackId, (int)surface, index, presetId, name, loaded, loaded?.Length ?? 0);
+ }
+
+ public PresetTag? PresetTagInfo(int tag)
+ {
+ ThrowIfDisposed();
+ if (tag <= 0) return null;
+ var id = new byte[512]; var name = new byte[512];
+ int n = NativeMethods.PresetTagInfo(_handle, tag, id, id.Length, name, name.Length, null, 0);
+ if (n < 0) return null;
+ var values = new float[n];
+ if (n > 0) NativeMethods.PresetTagInfo(_handle, tag, id, id.Length, name, name.Length, values, n);
+ return new PresetTag(Utf8Z(id), Utf8Z(name), values);
+ }
+
+ public int DevicePresetModified(int trackId, PresetSurface surface, int index)
+ { ThrowIfDisposed(); return NativeMethods.DevicePresetModified(_handle, trackId, (int)surface, index); }
+
+ public bool PresetTagSelfTest() { ThrowIfDisposed(); return NativeMethods.PresetTagSelfTest(_handle) != 0; }
+
+ private static string Utf8Z(byte[] b)
+ {
+ int n = System.Array.IndexOf(b, (byte)0);
+ return System.Text.Encoding.UTF8.GetString(b, 0, n < 0 ? b.Length : n);
+ }
+}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index 0478130f..c0b5fa44 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -104,6 +104,9 @@ public static class ProjectMigrations
// chain children keep sidechain keys and CC targets in the track (specs/044). All absent
// in v24 documents, where every reference is track level — no-op.
new Migration(24, _ => { }),
+ // v25 -> v26: instruments, devices and MIDI effects gain Preset (the preset they were
+ // loaded from, specs/048). Absent in v25 documents = no preset named — no-op.
+ new Migration(25, _ => { }),
};
/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 22651fa4..395f83f9 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -304,8 +304,19 @@ public sealed class ControllerCurveDto
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
+/// <summary>The preset a device was loaded from (v26, specs/048): its id, name and the
+/// parameter values it left, so a reopened project still shows "Name *" once they moved.</summary>
+public sealed class PresetTagDto
+{
+ public string Id { get; set; } = "";
+ public string Name { get; set; } = "";
+ public float[] Loaded { get; set; } = System.Array.Empty<float>();
+}
+
public sealed class InstrumentDto
{
+ /// <summary>The preset it was loaded from (v26); null = none / Init.</summary>
+ public PresetTagDto? Preset { get; set; }
/// <summary>0 = Nota Synth, 1 = Sampler, 2 = Nota Physical, -1 = hosted plugin.</summary>
public int Kind { get; set; }
/// <summary>Set when Kind == 1 (built-in Sampler).</summary>
@@ -402,6 +413,8 @@ public sealed class WarpMarkerDto
/// param values. Persisted before the instrument in the chain.</summary>
public sealed class MidiDeviceDto
{
+ /// <summary>The preset it was loaded from (v26); null = none / Init.</summary>
+ public PresetTagDto? Preset { get; set; }
public int Kind { get; set; } // 0 = Arpeggiator
public bool Bypassed { get; set; }
public bool Folded { get; set; } // drawn as a strip in the Devices panel (v23, specs/022)
@@ -422,6 +435,8 @@ public sealed class MidiDeviceDto
public sealed class DeviceDto
{
+ /// <summary>The preset it was loaded from (v26); null = none / Init.</summary>
+ public PresetTagDto? Preset { get; set; }
/// <summary>Built-in kind: 0=EQ, 1=Compressor, 2=Reverb, 3=Delay, 4=Utility; -1 = hosted plugin.</summary>
public int BuiltinKind { get; set; }
public bool Bypassed { get; set; }
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 8d591208..3d2f3892 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -35,7 +35,7 @@ public sealed class ProjectService
/// v23 (specs/022) adds the Devices-panel fold on devices, MIDI effects and instruments.
/// v25 (specs/044) adds references into rack chains (lanes, CV links, Arp CC targets) and
/// chain children's sidechain keys / CC targets.
- public const int CurrentFormatVersion = 25;
+ public const int CurrentFormatVersion = 26;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -169,6 +169,7 @@ public sealed class ProjectService
instDto.SidechainSource = instScSrc >= 0 && idToIndex.TryGetValue(instScSrc, out var isi) ? isi : -1;
instDto.Folded = engine.DeviceFolded(ti.Id, -1);
instDto.Bypassed = engine.DeviceBypassed(ti.Id, -1);
+ instDto.Preset = CapturePresetTag(engine, ti.Id, PresetSurface.Instrument, -1);
t.Instrument = instDto;
}
@@ -187,6 +188,7 @@ public sealed class ProjectService
mdev.CcDepth = engine.MidiEffectCcDepth(ti.Id, m);
var mstate = engine.MidiEffectGetState(ti.Id, m); // the MIDI Effect Rack's structure
if (mstate.Length > 0) mdev.State = RegisterBlob(doc, mstate);
+ mdev.Preset = CapturePresetTag(engine, ti.Id, PresetSurface.MidiEffect, m);
t.MidiEffects.Add(mdev);
}
@@ -367,6 +369,17 @@ public sealed class ProjectService
// Capture a track's device chain (built-in params / plugin identity+state / rack blob,
// plus sidechain routing as a doc index). Shared by tracks and the master.
+ // A device's preset tag (specs/048): what it was loaded from and the values it left.
+ private static PresetTagDto? CapturePresetTag(IAudioEngine engine, int trackId, PresetSurface surface, int index)
+ => engine.PresetTagInfo(engine.DevicePresetTag(trackId, surface, index)) is { Id.Length: > 0 } tag
+ ? new PresetTagDto { Id = tag.Id, Name = tag.Name, Loaded = tag.Loaded } : null;
+
+ private static void ApplyPresetTag(IAudioEngine engine, int trackId, PresetSurface surface, int index, PresetTagDto? tag)
+ {
+ if (tag is { Id.Length: > 0 })
+ engine.SetDevicePresetTag(trackId, surface, index, tag.Id, tag.Name, tag.Loaded.Length > 0 ? tag.Loaded : null);
+ }
+
private static List<DeviceDto> CaptureDevices(IAudioEngine engine, int trackId, ProjectDocument doc,
Dictionary<int, int> idToIndex, List<string> warnings, string label)
{
@@ -403,6 +416,7 @@ public sealed class ProjectService
for (int p = 0; p < pc; p++) dev.Params[p] = engine.DeviceGetParam(trackId, d, p);
dev.State = RegisterBlob(doc, engine.DeviceGetState(trackId, d));
}
+ dev.Preset = CapturePresetTag(engine, trackId, PresetSurface.Effect, d);
list.Add(dev);
}
return list;
@@ -496,6 +510,7 @@ public sealed class ProjectService
}
if (d.Bypassed) engine.SetDeviceBypassed(trackId, di, true);
if (d.Folded) engine.SetDeviceFolded(trackId, di, true);
+ ApplyPresetTag(engine, trackId, PresetSurface.Effect, di, d.Preset);
if (d.SidechainSource >= 0) scDeferred.Add((trackId, di, d.SidechainSource));
engine.SetDeviceSidechainGain(trackId, di, d.SidechainGain);
engine.SetDeviceSidechainMix(trackId, di, d.SidechainMix);
@@ -660,6 +675,7 @@ public sealed class ProjectService
}
if (id > 0 && t.Instrument is { Folded: true }) engine.SetDeviceFolded(id, -1, true);
+ if (id > 0) ApplyPresetTag(engine, id, PresetSurface.Instrument, -1, t.Instrument?.Preset);
if (id > 0 && t.Instrument is { Bypassed: true })
engine.SetDeviceBypassed(id, -1, true); // the instrument card's switch is off (#148)
if (id > 0 && t.Instrument is { SidechainSource: >= 0 } insc)
@@ -704,6 +720,7 @@ public sealed class ProjectService
}
if (m.Bypassed) engine.SetMidiEffectBypassed(id, mi, true);
if (m.Folded) engine.SetMidiEffectFolded(id, mi, true);
+ ApplyPresetTag(engine, id, PresetSurface.MidiEffect, mi, m.Preset);
if ((m.CcDestDevice >= 0 || m.CcDestChain is not null) && m.CcDestParam >= 0)
{
engine.SetMidiEffectCcDest(id, mi, m.CcDestDevice, m.CcDestParam);
diff --git a/src/managed/Nota.Mcp/Tools/PresetTools.cs b/src/managed/Nota.Mcp/Tools/PresetTools.cs
index 8b2576da..fa6b777b 100644
--- a/src/managed/Nota.Mcp/Tools/PresetTools.cs
+++ b/src/managed/Nota.Mcp/Tools/PresetTools.cs
@@ -23,6 +23,7 @@ public sealed class PresetTools(
public sealed record FactoryPreset(string Id, string DisplayName, bool IsInstrument, int BuiltinKind, bool IsMidiEffect, string Category);
public sealed record UserPreset(string Path, string DisplayName, string Type);
+ public sealed record PresetState(string Id, string Name, bool Modified);
[McpServerTool(Name = "list_factory_presets"), Description(
"List the shipped factory presets (stable id, display name, whether it's an instrument or a MIDI effect, "
@@ -44,7 +45,26 @@ public sealed class PresetTools(
"Apply a factory preset onto an EXISTING instrument/device (deviceIndex -1 = the track instrument). "
+ "Returns \"\" on success or a warning.")]
public Task<string> ApplyFactoryPresetInPlace(string id, int trackId, int deviceIndex)
- => Mutate(() => _factory.ApplyInPlace(E, id, trackId, deviceIndex));
+ => Mutate(() =>
+ {
+ // One undo step that also names the device after the preset (specs/048).
+ var info = _factory.All().Where(p => p.Id == id).Take(1).ToList();
+ var surface = deviceIndex < 0 ? PresetSurface.Instrument
+ : info.Count > 0 && info[0].IsMidiEffect ? PresetSurface.MidiEffect : PresetSurface.Effect;
+ string name = info.Count > 0 ? info[0].DisplayName : id;
+ return Nota.Application.Editing.PresetEdit.Apply(E, trackId, surface, deviceIndex, id, name,
+ () => _factory.ApplyInPlace(E, id, trackId, deviceIndex));
+ });
+
+ [McpServerTool(Name = "read_preset_state"), Description(
+ "Which preset a device was loaded from and whether a sound parameter has changed since. "
+ + "deviceIndex -1 = the track instrument; midiEffect true for a MIDI effect. An empty name = Init / no preset.")]
+ public Task<PresetState> ReadPresetState(int trackId, int deviceIndex, bool midiEffect = false) => Read(() =>
+ {
+ var surface = deviceIndex < 0 ? PresetSurface.Instrument : midiEffect ? PresetSurface.MidiEffect : PresetSurface.Effect;
+ var tag = E.PresetTagInfo(E.DevicePresetTag(trackId, surface, deviceIndex));
+ return new PresetState(tag?.Id ?? "", tag?.Name ?? "", E.DevicePresetModified(trackId, surface, deviceIndex) == 1);
+ });
[McpServerTool(Name = "list_user_presets"), Description("List the user's saved presets from the app presets folder (path, display name, type).")]
public Task<UserPreset[]> ListUserPresets() => Read(() =>
diff --git a/src/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.cs
index 03f94989..cfea4b68 100644
--- a/src/managed/Nota.Presentation/DeviceInsertService.cs
+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs
@@ -57,6 +57,8 @@ public sealed record InsertResult
public (bool Midi, int Added, int Final, bool Replaced)? Placed { get; init; }
/// <summary>A preset that landed: chain, device index, its name and factory id ("" for a user preset).</summary>
public (int TrackId, PresetChain Chain, int Index, string Name, string FactoryId)? PresetLanded { get; init; }
+ /// <summary>The preset was applied in place and tagged in its own undo step already.</summary>
+ internal bool PresetTagged { get; init; }
/// <summary>The plug-in this insertion put on a track, for "Open plug-in window on insert"
/// (#250): DeviceIndex -1 is the track's instrument.</summary>
@@ -459,7 +461,29 @@ public sealed class DeviceInsertService
/// instrument track when the target asks for it in place (the palette), swaps the
/// instrument and loads the sound there; an effect preset lands on the target and, with a
/// placement, moves to the aimed slot.</summary>
- public InsertResult ApplyPreset(BrowserItem item, InsertTarget target) => Group(() => ApplyPresetCore(item, target));
+ public InsertResult ApplyPreset(BrowserItem item, InsertTarget target) => Group(() => TagLanded(ApplyPresetCore(item, target), item, target));
+
+ // The device a preset landed on carries its name from here on (specs/048), inside the
+ // same undo step. A preset file is tagged by its path.
+ private InsertResult TagLanded(InsertResult r, BrowserItem item, InsertTarget target)
+ {
+ if (r is not { Ok: true, PresetLanded: { } pl } || r.PresetTagged) return r;
+ var surface = pl.Chain switch
+ {
+ PresetChain.Instrument => PresetSurface.Instrument,
+ PresetChain.Midi => PresetSurface.MidiEffect,
+ _ => PresetSurface.Effect,
+ };
+ string id = pl.FactoryId.Length > 0 ? pl.FactoryId : "file:" + item.Path;
+ // A device the apply just made (a new track, an inserted device, a swapped instrument)
+ // takes the name with no undo step of its own: undo brings back the old graph with its
+ // devices' names as they were, and redo the new one with this name. A value step here
+ // would write the new device's empty tag over the restored one's on undo.
+ bool fresh = r.InstrumentReplaced || pl.Chain != PresetChain.Instrument || pl.TrackId != target.TrackId;
+ if (fresh) _engine.SetDevicePresetTag(pl.TrackId, surface, pl.Index, id, pl.Name);
+ else Nota.Application.Editing.PresetEdit.Tag(_engine, pl.TrackId, surface, pl.Index, id, pl.Name);
+ return r;
+ }
private InsertResult ApplyPresetCore(BrowserItem item, InsertTarget target)
{
@@ -477,23 +501,42 @@ public sealed class DeviceInsertService
if (!_engine.SetTrackBuiltinInstrument(t, f.BuiltinKind)) return InsertResult.Fail($"Couldn't load {item.Name}.");
swapped = true;
}
- string w = _factory.ApplyInPlace(_engine, factoryId, t, -1);
+ // On the same instrument the sound and the name change as one undo step, so undo
+ // brings both back (a swap restores the old instrument whole).
+ string w = swapped ? _factory.ApplyInPlace(_engine, factoryId, t, -1)
+ : InstrumentInPlace(t, factoryId, item.Name, () => _factory.ApplyInPlace(_engine, factoryId, t, -1));
if (w.Length == 0) InstrumentPresetApplied?.Invoke(t);
return new InsertResult
{
Ok = w.Length == 0, TrackId = t, InstrumentReplaced = swapped, ShowDevices = true,
Status = w.Length > 0 ? w : $"Applied preset {item.Name}",
- PresetLanded = (t, PresetChain.Instrument, -1, item.Name, factoryId),
+ PresetLanded = (t, PresetChain.Instrument, -1, item.Name, factoryId), PresetTagged = !swapped,
};
}
// …and a preset file (a user preset, a Mosaic pack preset) the same way.
+ // A built-in instrument's file preset on the same instrument is parameters only: one undo
+ // step with its name, as above.
+ if (fp is null && !target.NewTrack && target.InPlace && CanReplaceInstrument(t)
+ && _presets?.Describe(item.Path) is ("builtin-instrument", var fileKind) && fileKind == _engine.TrackInstrumentKind(t))
+ {
+ bool fileSwapped = false;
+ string sw = InstrumentInPlace(t, "file:" + item.Path, item.Name,
+ () => _presets!.ApplyInstrumentInPlace(_engine, item.Path, t, out fileSwapped) ?? "Presets are unavailable.");
+ if (sw.Length == 0) InstrumentPresetApplied?.Invoke(t);
+ return new InsertResult
+ {
+ Ok = sw.Length == 0, TrackId = t, InstrumentReplaced = fileSwapped, ShowDevices = true,
+ Status = sw.Length > 0 ? sw : $"Applied preset {item.Name}",
+ PresetLanded = (t, PresetChain.Instrument, -1, item.Name, ""), PresetTagged = !fileSwapped,
+ };
+ }
if (fp is null && !target.NewTrack && target.InPlace && CanReplaceInstrument(t)
- && _presets?.ApplyInstrumentInPlace(_engine, item.Path, t, out bool fileSwapped) is { } fw)
+ && _presets?.ApplyInstrumentInPlace(_engine, item.Path, t, out bool fileSwapped2) is { } fw)
{
if (fw.Length == 0) InstrumentPresetApplied?.Invoke(t);
return new InsertResult
{
- Ok = fw.Length == 0, TrackId = t, InstrumentReplaced = fileSwapped, ShowDevices = true,
+ Ok = fw.Length == 0, TrackId = t, InstrumentReplaced = fileSwapped2, ShowDevices = true,
Status = fw.Length > 0 ? fw : $"Applied preset {item.Name}",
PresetLanded = (t, PresetChain.Instrument, -1, item.Name, ""),
};
@@ -569,6 +612,9 @@ public sealed class DeviceInsertService
}
// One undo step per insertion (CP-25). Nests, so an outer group (a multi-item drop) holds.
+ private string InstrumentInPlace(int t, string id, string name, Func<string> apply)
+ => Nota.Application.Editing.PresetEdit.Apply(_engine, t, PresetSurface.Instrument, -1, id, name, apply);
+
private InsertResult Group(Func<InsertResult> body)
{
_engine.BeginUndoGroup();
diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txt
index b2f4e64d..eb950378 100644
--- a/src/native/nota.engine/CMakeLists.txt
+++ b/src/native/nota.engine/CMakeLists.txt
@@ -82,6 +82,7 @@ set(NOTA_ENGINE_SOURCES
src/abi/nota_engine_device.cpp
src/abi/nota_engine_automation.cpp
src/abi/nota_engine_modulation.cpp
+ src/abi/nota_engine_presets.cpp
src/abi/nota_engine_audio.cpp
src/abi/nota_engine_rack.cpp
src/abi/nota_engine_import.cpp
@@ -90,6 +91,7 @@ set(NOTA_ENGINE_SOURCES
src/engine/Engine.cpp
src/engine/Engine_Automation.cpp
src/engine/Engine_Modulation.cpp
+ src/engine/Engine_Presets.cpp
src/engine/Engine_Tracks.cpp
src/engine/Engine_Session.cpp
src/engine/Engine_Devices.cpp
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 16361d0c..b362ea40 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -935,6 +935,8 @@ NOTA_API void nota_engine_clear_undo_history(NotaEngine* engine);
#define NOTA_MIX_DEVICE_PARAM 3 /* audio effect: device_index = chain position */
#define NOTA_MIX_MIDI_DEVICE_PARAM 4 /* MIDI effect: device_index = MIDI-FX chain position */
#define NOTA_MIX_PLUGIN_PARAM 5 /* normalized 0..1; device_index -1 = the instrument */
+#define NOTA_MIX_PRESET_TAG 6 /* a device's preset tag (specs/048): device_index as the
+ * surface needs, param_index = the surface (below) */
typedef struct NotaMixTarget {
int32_t kind; /* NOTA_MIX_* */
@@ -948,6 +950,27 @@ NOTA_API int32_t nota_mix_gesture_begin(NotaEngine* engine, const NotaMixTarget*
/* Ends the gesture; unknown / already-ended handles are ignored. */
NOTA_API void nota_mix_gesture_end(NotaEngine* engine, int32_t handle);
+/* ---- Preset tags (specs/048) --------------------------------------------- */
+/* Which preset a device was loaded from: its id, display name and the parameter values right
+ * after it applied. surface: 0 audio effect (index = chain position), 1 the track's instrument
+ * (index ignored), 2 MIDI effect (index = MIDI-FX chain position). A tag is an index into an
+ * engine table, 0 = none; copies, duplicates and moves keep it, and a mix gesture with a
+ * NOTA_MIX_PRESET_TAG target makes setting it part of that undo step. Message thread only. */
+NOTA_API int32_t nota_track_device_preset_tag(const NotaEngine* engine, int32_t track_id, int32_t surface, int32_t index); /* -1 no device */
+/* Sets a new tag (an empty or null preset_id clears it: Init). base = the loaded values
+ * (base_count of them); null = the values the device holds now. Returns the tag, -1 no device. */
+NOTA_API int32_t nota_track_device_set_preset_tag(NotaEngine* engine, int32_t track_id, int32_t surface, int32_t index,
+ const char* preset_id, const char* name, const float* base, int32_t base_count);
+/* A tag's id and name (NUL-terminated, truncated to the caps) and up to base_cap loaded values;
+ * returns the number of values, -1 for no tag. */
+NOTA_API int32_t nota_preset_tag_info(const NotaEngine* engine, int32_t tag, char* preset_id, int32_t id_cap,
+ char* name, int32_t name_cap, float* base, int32_t base_cap);
+/* 1 when a sound parameter differs from the tag's values by more than 1/10000 of its range
+ * (view settings — the card size, EQ-8's analyzer — are left out; a CV-modulated parameter
+ * counts by its link base), 0 when it holds them, -1 with no tag or no device. */
+NOTA_API int32_t nota_track_device_preset_modified(const NotaEngine* engine, int32_t track_id, int32_t surface, int32_t index);
+NOTA_API int32_t nota_engine_preset_tag_selftest(NotaEngine* engine);
+
/* ---- Stereo measurements (008) ------------------------------------------- */
/* What each track, return and the master sends to the master, post-fader and post-pan,
* averaged over ~300 ms: level, where it sits (balance on the pan scale: a mono source
diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cpp
index 2927797e..8e1dbaff 100644
--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp
@@ -350,7 +350,7 @@ int32_t nota_mix_gesture_begin(NotaEngine* e, const NotaMixTarget* targets, int3
int32_t n = 0;
for (int32_t i = 0; i < count; ++i) {
const int32_t k = targets[i].kind;
- if (k < NOTA_MIX_TRACK_VOLUME || k > NOTA_MIX_PLUGIN_PARAM) continue;
+ if (k < NOTA_MIX_TRACK_VOLUME || k > NOTA_MIX_PRESET_TAG) continue;
t[n++] = {static_cast<nota::MixKind>(k), targets[i].track_id, targets[i].device_index, targets[i].param_index};
}
return n > 0 ? ENG(e)->beginMixGesture(t, n) : 0;
diff --git a/src/native/nota.engine/src/abi/nota_engine_presets.cpp b/src/native/nota.engine/src/abi/nota_engine_presets.cpp
new file mode 100644
index 00000000..6224931d
--- /dev/null
+++ b/src/native/nota.engine/src/abi/nota_engine_presets.cpp
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// C ABI — preset tags (specs/048): which preset a device was loaded from and whether it still
+// holds that preset's values. Thin wrappers over Engine_Presets.cpp.
+
+#include "nota_engine_internal.h"
+
+#include <cstring>
+
+namespace {
+void copyOut(const std::string& s, char* out, int32_t cap) {
+ if (!out || cap <= 0) return;
+ const size_t n = std::min(s.size(), static_cast<size_t>(cap - 1));
+ std::memcpy(out, s.data(), n);
+ out[n] = '\0';
+}
+} // namespace
+
+extern "C" {
+
+int32_t nota_track_device_preset_tag(const NotaEngine* e, int32_t track_id, int32_t surface, int32_t index) {
+ return e ? CENG(e)->presetTagOf(track_id, surface, index) : -1;
+}
+
+int32_t nota_track_device_set_preset_tag(NotaEngine* e, int32_t track_id, int32_t surface, int32_t index,
+ const char* preset_id, const char* name, const float* base, int32_t base_count) {
+ return e ? ENG(e)->setPresetTag(track_id, surface, index, preset_id, name, base, base_count) : -1;
+}
+
+int32_t nota_preset_tag_info(const NotaEngine* e, int32_t tag, char* preset_id, int32_t id_cap, char* name,
+ int32_t name_cap, float* base, int32_t base_cap) {
+ if (!e) return -1;
+ const auto* t = CENG(e)->presetTagData(tag);
+ if (!t) return -1;
+ copyOut(t->id, preset_id, id_cap);
+ copyOut(t->name, name, name_cap);
+ const int32_t n = static_cast<int32_t>(t->base.size());
+ if (base)
+ for (int32_t i = 0; i < n && i < base_cap; ++i) base[i] = t->base[static_cast<size_t>(i)];
+ return n;
+}
+
+int32_t nota_track_device_preset_modified(const NotaEngine* e, int32_t track_id, int32_t surface, int32_t index) {
+ return e ? CENG(e)->presetModified(track_id, surface, index) : -1;
+}
+
+int32_t nota_engine_preset_tag_selftest(NotaEngine* e) {
+ return (e && ENG(e)->presetTagSelfTest()) ? 1 : 0;
+}
+
+} // extern "C"
diff --git a/src/native/nota.engine/src/devices/Device.h b/src/native/nota.engine/src/devices/Device.h
index 419b9d20..aa6e45f2 100644
--- a/src/native/nota.engine/src/devices/Device.h
+++ b/src/native/nota.engine/src/devices/Device.h
@@ -251,9 +251,16 @@ class Device {
bool folded() const { return folded_; }
void setFolded(bool f) { folded_ = f; }
+ // The preset this device was loaded from (specs/048): an index into the engine's preset
+ // tag table, 0 = none. Message thread only; kept on the device so it follows moves,
+ // copies and undo/redo.
+ int32_t presetTag() const { return presetTag_; }
+ void setPresetTag(int32_t t) { presetTag_ = t; }
+
private:
std::atomic<bool> bypassed_{false};
bool folded_ = false;
+ int32_t presetTag_ = 0;
std::atomic<float> scGainDb_{0.0f};
std::atomic<float> scMix_{1.0f};
std::atomic<int32_t> scTapPre_{0};
diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.h
index 851be3e3..31d2d3cb 100644
--- a/src/native/nota.engine/src/devices/Instrument.h
+++ b/src/native/nota.engine/src/devices/Instrument.h
@@ -74,6 +74,9 @@ class Instrument {
// Fold (specs/022): the Devices panel draws the instrument as a narrow strip. A view flag
// saved with the project; message thread only.
bool folded = false;
+ // The preset this instrument was loaded from (specs/048): an engine preset tag index,
+ // 0 = none. Message thread only.
+ int32_t presetTag = 0;
Instrument();
virtual void controller(int32_t ctl, float value);
diff --git a/src/native/nota.engine/src/devices/MidiDevice.h b/src/native/nota.engine/src/devices/MidiDevice.h
index 3031352a..63dd32a1 100644
--- a/src/native/nota.engine/src/devices/MidiDevice.h
+++ b/src/native/nota.engine/src/devices/MidiDevice.h
@@ -121,6 +121,10 @@ class MidiDevice {
bool folded() const { return folded_; }
void setFolded(bool f) { folded_ = f; }
+ // The preset this device was loaded from (specs/048): an engine preset tag index, 0 = none.
+ int32_t presetTag() const { return presetTag_; }
+ void setPresetTag(int32_t t) { presetTag_ = t; }
+
// Map/CC routing: a device (the arpeggiator) can drive a target audio-device param
// on the same track from its per-step CC lane. destDevice = the track's audio-device
// chain index (-2 = no routing), destParam = that device's param index, depth 0..1
@@ -141,6 +145,7 @@ class MidiDevice {
private:
std::atomic<bool> bypassed_{false};
bool folded_ = false;
+ int32_t presetTag_ = 0;
};
} // namespace nota
diff --git a/src/native/nota.engine/src/devices/racks/RackCore.cpp b/src/native/nota.engine/src/devices/racks/RackCore.cpp
index a62f2039..1ce2b9da 100644
--- a/src/native/nota.engine/src/devices/racks/RackCore.cpp
+++ b/src/native/nota.engine/src/devices/racks/RackCore.cpp
@@ -165,6 +165,7 @@ bool RackCore::setChainInstrumentSample(int32_t chain, std::shared_ptr<SampleBuf
if (!sm) return false;
sm->setSampleRate(sampleRate_);
sm->setSample(std::move(buf), root, loop);
+ if (oldSm) fresh->presetTag = oldSm->presetTag; // still the preset it was loaded from (specs/048)
ns->chains[chain].instrument = std::move(fresh);
commit(ns);
return true;
diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cpp
index b04a577c..04acc62e 100644
--- a/src/native/nota.engine/src/engine/Engine.cpp
+++ b/src/native/nota.engine/src/engine/Engine.cpp
@@ -776,6 +776,12 @@ bool Engine::paramTargetExists(MixKind kind, int32_t trackId, int32_t deviceInde
}
bool Engine::mixValue(const MixTarget& t, float& v) const {
+ if (t.kind == MixKind::PresetTag) { // specs/048: the tag index, exact in a float
+ const int32_t tag = presetTagOf(t.trackId, t.paramIndex, t.deviceIndex);
+ if (tag < 0) return false;
+ v = static_cast<float>(tag);
+ return true;
+ }
if (t.kind == MixKind::MasterVolume) {
v = masterVolume();
return true;
@@ -800,6 +806,8 @@ bool Engine::mixValue(const MixTarget& t, float& v) const {
bool Engine::applyMix(const MixChange& c, bool after) {
const float v = after ? c.after : c.before;
+ if (c.kind == MixKind::PresetTag)
+ return setPresetTagIndex(c.trackId, c.paramIndex, c.deviceIndex, static_cast<int32_t>(v)); // gone: skip
if (c.kind == MixKind::MasterVolume) {
setMasterVolume(v);
return true;
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index 8bda2bd4..5d77e46c 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -1418,6 +1418,7 @@ class Engine {
static int32_t trackLatency(const Track& t);
std::shared_ptr<Instrument> cloneInstrument(const Track& src) const; // duplicateTrack helper
std::shared_ptr<Instrument> cloneInstrumentFrom(const Instrument& src) const;
+ std::shared_ptr<Instrument> cloneInstrumentBody(const Instrument& src) const;
// Copies of the automation lanes on one device of `t` (family as transferDevice; for the
// instrument, PluginParam lanes with deviceIndex < 0), in lane order.
std::vector<TrackLane> deviceLanes(const Track& t, int32_t family, int32_t index) const;
@@ -1609,6 +1610,34 @@ class Engine {
int32_t nextMixGesture_ = 1;
bool mixValue(const MixTarget& t, float& v) const; // current value; false = gone
bool paramTargetExists(MixKind kind, int32_t trackId, int32_t deviceIndex, int32_t paramIndex) const;
+
+ // ---- preset tags (specs/048, Engine_Presets.cpp) ----
+ // What preset a device was loaded from: its id, display name and the parameter values
+ // right after it applied. Devices hold an index into this append-only table (0 = none),
+ // so a tag change is a float-valued mix step and undo/redo restore it.
+ struct PresetTagData {
+ std::string id, name;
+ std::vector<float> base;
+ };
+ std::vector<PresetTagData> presetTags_ = std::vector<PresetTagData>(1);
+ // The parameter values a tag compares (a CV-modulated param's link base, not its live value).
+ bool presetSurfaceValues(int32_t trackId, int32_t surface, int32_t index, std::vector<float>& out) const;
+
+ public:
+ // surface: 0 audio effect (index = chain position), 1 the instrument (index ignored),
+ // 2 MIDI effect (index = MIDI-FX chain position).
+ int32_t presetTagOf(int32_t trackId, int32_t surface, int32_t index) const; // -1 no device
+ bool setPresetTagIndex(int32_t trackId, int32_t surface, int32_t index, int32_t tag);
+ // A new tag for the device: base = `base` (n values) or, when null, the values it holds now.
+ // Sets it (no undo step of its own: call it inside a mix gesture that targets the tag).
+ int32_t setPresetTag(int32_t trackId, int32_t surface, int32_t index, const char* id, const char* name,
+ const float* base, int32_t n);
+ const PresetTagData* presetTagData(int32_t tag) const;
+ // -1: no tag / no device; 0: the device holds its preset's values; 1: modified.
+ int32_t presetModified(int32_t trackId, int32_t surface, int32_t index) const;
+ bool presetTagSelfTest();
+
+ private:
bool applyMix(const MixChange& c, bool after); // write before/after; false = gone
static void mergeMix(std::vector<MixChange>& into, const std::vector<MixChange>& later);
static constexpr size_t kMaxUndoDepth = 128;
diff --git a/src/native/nota.engine/src/engine/EngineTypes.h b/src/native/nota.engine/src/engine/EngineTypes.h
index c37f5c9c..5d4fce67 100644
--- a/src/native/nota.engine/src/engine/EngineTypes.h
+++ b/src/native/nota.engine/src/engine/EngineTypes.h
@@ -100,7 +100,8 @@ enum class MixKind : int32_t {
MasterVolume = 2,
DeviceParam = 3,
MidiDeviceParam = 4,
- PluginParam = 5
+ PluginParam = 5,
+ PresetTag = 6 // a device's preset tag (specs/048): deviceIndex as above, paramIndex = the surface
};
struct MixTarget {
MixKind kind;
diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cpp
index 6e09eb9d..9fd86777 100644
--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp
@@ -286,6 +286,7 @@ bool Engine::mosaicSetProgram(int32_t trackId, const std::string& text, bool che
// zone edit is ready at once) — undo brings the old instrument, with its program, back.
auto fresh = std::static_pointer_cast<Mosaic>(m->clone());
fresh->setProgram(text);
+ fresh->presetTag = m->presetTag; // still the preset it was loaded from (specs/048)
auto nt = cloneTrack(*old);
nt->instrument = fresh;
republishWithTrack(trackId, nt);
@@ -334,6 +335,7 @@ bool Engine::setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::str
if (!sample || sample->empty()) return false;
auto fresh = std::static_pointer_cast<RhythmMachine>(rh->clone()); // copies params/patterns/samples
fresh->setVoiceSample(voice, sample);
+ fresh->presetTag = rh->presetTag; // still the preset it was loaded from (specs/048)
auto nt = cloneTrack(*old);
nt->instrument = fresh;
republishWithTrack(trackId, nt);
@@ -351,6 +353,7 @@ bool Engine::setTrackGrainSample(int32_t trackId, const std::string& path, int32
fresh->setSampleRate(sr);
for (int i = 0; i < gr->pluginParamCount(); ++i) fresh->pluginParamSet(i, gr->pluginParamGet(i));
fresh->setSample(sample, rootNote, false);
+ fresh->presetTag = gr->presetTag; // still the preset it was loaded from (specs/048)
auto nt = cloneTrack(*old);
nt->instrument = fresh;
republishWithTrack(trackId, nt);
@@ -406,6 +409,7 @@ bool Engine::setTrackSamplerSample(int32_t trackId, const std::string& path, int
fresh->setSampleRate(sr);
for (int i = 0; i < sm->pluginParamCount(); ++i) fresh->pluginParamSet(i, sm->pluginParamGet(i));
fresh->setSample(sample, rootNote, sm->loopEnabled());
+ fresh->presetTag = sm->presetTag; // still the preset it was loaded from (specs/048)
auto nt = cloneTrack(*old);
nt->instrument = fresh;
republishWithTrack(trackId, nt);
@@ -577,6 +581,12 @@ std::shared_ptr<Instrument> Engine::cloneInstrument(const Track& src) const {
}
std::shared_ptr<Instrument> Engine::cloneInstrumentFrom(const Instrument& src) const {
+ auto c = cloneInstrumentBody(src);
+ if (c) c->presetTag = src.presetTag; // the preset it was loaded from (specs/048)
+ return c;
+}
+
+std::shared_ptr<Instrument> Engine::cloneInstrumentBody(const Instrument& src) const {
const double sr = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;
if (auto c = src.clone()) {
c->setSampleRate(sr);
@@ -682,6 +692,7 @@ std::shared_ptr<Device> Engine::cloneDevice(const Device& src) const {
}
d->setBypassed(src.bypassed());
d->setFolded(src.folded());
+ d->setPresetTag(src.presetTag()); // the preset it was loaded from (specs/048)
d->setSidechainSourceTrackId(src.sidechainSourceTrackId()); // a keyed device keeps its key
d->setSidechainTapPre(src.sidechainTapPre());
d->setSidechainGainDb(src.sidechainGainDb());
@@ -779,6 +790,7 @@ std::shared_ptr<MidiDevice> Engine::cloneMidiDevice(const MidiDevice& src) const
d->setCcDepth(src.ccDepth());
d->setBypassed(src.bypassed());
d->setFolded(src.folded());
+ d->setPresetTag(src.presetTag()); // the preset it was loaded from (specs/048)
return d; // live state starts fresh
}
diff --git a/src/native/nota.engine/src/engine/Engine_Presets.cpp b/src/native/nota.engine/src/engine/Engine_Presets.cpp
new file mode 100644
index 00000000..666973aa
--- /dev/null
+++ b/src/native/nota.engine/src/engine/Engine_Presets.cpp
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Preset tags (specs/048): which preset a device was loaded from, and whether it still holds
+// that preset's values. A device stores an index into the engine's append-only tag table, so
+// a preset applied inside a mix gesture undoes together with its tag, and copies, moves and
+// duplicates keep it with the device object.
+
+#include "Engine.h"
+#include "../devices/Device.h"
+#include "../devices/Instrument.h"
+#include "../devices/MidiDevice.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+namespace nota {
+
+namespace {
+// View settings are not part of the sound: the card size, EQ-8's analyzer.
+bool isViewParam(const std::string& name) {
+ return name == "View" || name == "view" || name == "Analyzer" || name == "Analyzer Range" ||
+ name == "Analyzer Peak";
+}
+constexpr float kTolerance = 1e-4f; // of the param's range
+} // namespace
+
+int32_t Engine::presetTagOf(int32_t trackId, int32_t surface, int32_t index) const {
+ switch (surface) {
+ case 0:
+ if (auto* d = deviceAt(trackId, index)) return d->presetTag();
+ return -1;
+ case 1: {
+ auto t = findTrackAuthoring(trackId);
+ return t && t->instrument ? t->instrument->presetTag : -1;
+ }
+ case 2:
+ if (auto* m = midiDeviceAt(trackId, index)) return m->presetTag();
+ return -1;
+ default: return -1;
+ }
+}
+
+bool Engine::setPresetTagIndex(int32_t trackId, int32_t surface, int32_t index, int32_t tag) {
+ if (tag < 0 || tag >= static_cast<int32_t>(presetTags_.size())) return false;
+ switch (surface) {
+ case 0:
+ if (auto* d = deviceAt(trackId, index)) { d->setPresetTag(tag); return true; }
+ return false;
+ case 1: {
+ auto t = findTrackAuthoring(trackId);
+ if (!t || !t->instrument) return false;
+ t->instrument->presetTag = tag;
+ return true;
+ }
+ case 2:
+ if (auto* m = midiDeviceAt(trackId, index)) { m->setPresetTag(tag); return true; }
+ return false;
+ default: return false;
+ }
+}
+
+bool Engine::presetSurfaceValues(int32_t trackId, int32_t surface, int32_t index, std::vector<float>& out) const {
+ out.clear();
+ int32_t n = 0;
+ bool hosted = false; // a hosted plug-in effect exposes its params as plug-in params
+ switch (surface) {
+ case 0: {
+ auto* d = deviceAt(trackId, index);
+ if (!d) return false;
+ n = d->paramCount();
+ if (n == 0 && d->pluginParamCount() > 0) { n = d->pluginParamCount(); hosted = true; }
+ break;
+ }
+ case 1: { auto t = findTrackAuthoring(trackId); if (!t || !t->instrument) return false; n = pluginParamCount(trackId, -1); break; }
+ case 2: { auto* m = midiDeviceAt(trackId, index); if (!m) return false; n = m->paramCount(); break; }
+ default: return false;
+ }
+ const int32_t dev = surface == 1 ? -1 : index;
+ out.resize(static_cast<size_t>(std::max(0, n)));
+ for (int32_t p = 0; p < n; ++p) {
+ float v;
+ if (hosted) v = pluginParamGet(trackId, index, p);
+ else if (!cvBaseValue(surface, trackId, dev, p, v)) // a modulated param: its base
+ v = surface == 0 ? deviceGetParam(trackId, index, p)
+ : surface == 2 ? midiEffectGetParam(trackId, index, p)
+ : pluginParamGet(trackId, -1, p);
+ out[static_cast<size_t>(p)] = v;
+ }
+ return true;
+}
+
+int32_t Engine::setPresetTag(int32_t trackId, int32_t surface, int32_t index, const char* id, const char* name,
+ const float* base, int32_t n) {
+ if (presetTagOf(trackId, surface, index) < 0) return -1;
+ if (!id || !*id) { // Init / no preset
+ setPresetTagIndex(trackId, surface, index, 0);
+ return 0;
+ }
+ PresetTagData tag;
+ tag.id = id;
+ tag.name = name ? name : "";
+ if (base && n > 0) tag.base.assign(base, base + n);
+ else presetSurfaceValues(trackId, surface, index, tag.base);
+ presetTags_.push_back(std::move(tag));
+ const int32_t at = static_cast<int32_t>(presetTags_.size()) - 1;
+ setPresetTagIndex(trackId, surface, index, at);
+ return at;
+}
+
+const Engine::PresetTagData* Engine::presetTagData(int32_t tag) const {
+ return tag > 0 && tag < static_cast<int32_t>(presetTags_.size()) ? &presetTags_[static_cast<size_t>(tag)] : nullptr;
+}
+
+int32_t Engine::presetModified(int32_t trackId, int32_t surface, int32_t index) const {
+ const auto* tag = presetTagData(presetTagOf(trackId, surface, index));
+ if (!tag) return -1;
+ std::vector<float> now;
+ if (!presetSurfaceValues(trackId, surface, index, now)) return -1;
+ const size_t n = std::min(now.size(), tag->base.size());
+ const auto* dev = surface == 0 ? deviceAt(trackId, index) : nullptr;
+ const bool hosted = dev && dev->paramCount() == 0; // plug-in params, normalized
+ for (size_t i = 0; i < n; ++i) {
+ const auto p = static_cast<int32_t>(i);
+ std::string name;
+ float lo = 0.0f, hi = 1.0f; // instrument and plug-in params are normalized
+ if (hosted) {
+ name = pluginParamId(trackId, index, p);
+ } else if (surface == 0) {
+ const char* nm = deviceParamName(trackId, index, p);
+ name = nm ? nm : "";
+ lo = deviceParamMin(trackId, index, p);
+ hi = deviceParamMax(trackId, index, p);
+ } else if (surface == 2) {
+ const char* nm = midiEffectParamName(trackId, index, p);
+ name = nm ? nm : "";
+ lo = midiEffectParamMin(trackId, index, p);
+ hi = midiEffectParamMax(trackId, index, p);
+ } else {
+ name = pluginParamId(trackId, -1, p);
+ }
+ if (isViewParam(name)) continue;
+ const float span = std::max(1e-6f, std::fabs(hi - lo));
+ if (std::fabs(now[i] - tag->base[i]) > kTolerance * span) return 1;
+ }
+ return 0;
+}
+
+// Device-free: a tag set inside a gesture undoes and redoes with it.
+bool Engine::presetTagSelfTest() {
+ const auto t = addInstrumentTrack();
+ const int32_t d = addTrackBuiltinDevice(t, 3); // Delay
+ if (d < 0) return false;
+ const int32_t h0 = static_cast<int32_t>(presetTags_.size());
+ MixTarget tg{MixKind::PresetTag, t, d, 0};
+ const int32_t g = beginMixGesture(&tg, 1);
+ const int32_t tag = setPresetTag(t, 0, d, "factory:delay:test", "Test", nullptr, 0);
+ endMixGesture(g);
+ bool ok = tag == h0 && presetTagOf(t, 0, d) == tag && presetModified(t, 0, d) == 0;
+ const int32_t p = 6; // Feedback: a continuous param well inside its range
+ const float lo = deviceParamMin(t, d, p), hi = deviceParamMax(t, d, p);
+ deviceSetParam(t, d, p, deviceGetParam(t, d, p) > (lo + hi) * 0.5f ? lo : hi);
+ ok = ok && presetModified(t, 0, d) == 1;
+ ok = ok && undo() && presetTagOf(t, 0, d) == 0 && redo() && presetTagOf(t, 0, d) == tag;
+ removeTrack(t);
+ clearUndoHistory();
+ return ok;
+}
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cpp
index 9f57c13f..12ac4500 100644
--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp
@@ -192,6 +192,7 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {
r->shareRuntimeWith(*src); // held notes play on through the swap
r->setBypassed(src->bypassed());
r->setFolded(src->folded());
+ r->setPresetTag(src->presetTag());
fresh = r.get();
nt->midiEffects[mi] = std::move(r);
republishWithTrack(trackId, nt);
@@ -210,6 +211,7 @@ RackCore* Engine::rackForEdit(int32_t trackId, int32_t deviceIndex) {
r->forkFrom(*src);
r->setBypassed(src->bypassed());
r->setFolded(src->folded());
+ r->setPresetTag(src->presetTag());
r->setSidechainSourceTrackId(src->sidechainSourceTrackId());
r->setSidechainTapPre(src->sidechainTapPre());
r->setSidechainGainDb(src->sidechainGainDb());
@@ -230,6 +232,7 @@ static std::shared_ptr<RackInstrument> forkRackInstrument(const RackInstrument&
r->shareMonoWith(src); // held keys, the sounding note and a glide in progress play on
r->setBypassed(src.bypassed());
r->folded = src.folded;
+ r->presetTag = src.presetTag;
// Playback state the audio thread owns: relaxed atomics, carried over so a held pedal
// still releases its notes after the edit.
constexpr auto rl = std::memory_order_relaxed;
@@ -1197,6 +1200,7 @@ bool Engine::rackChainMosaicSetProgram(int32_t t, int32_t di, int32_t c, const s
// edit is ready at once) into a fork of the rack; undo brings the old one back.
auto fresh = std::static_pointer_cast<Mosaic>(m->clone());
fresh->setProgram(text);
+ fresh->presetTag = m->presetTag; // still the preset it was loaded from (specs/048)
auto* fr = rackForEdit(t, di);
return fr && fr->replaceChainInstrument(c, std::move(fresh));
}
@@ -1213,6 +1217,7 @@ bool Engine::rackChainGrainSetSample(int32_t t, int32_t di, int32_t c, const std
fresh->setSampleRate(transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0);
for (int i = 0; i < gr->pluginParamCount(); ++i) fresh->pluginParamSet(i, gr->pluginParamGet(i));
fresh->setSample(sample, rootNote, false);
+ fresh->presetTag = gr->presetTag; // still the preset it was loaded from (specs/048)
auto* fr = rackForEdit(t, di);
return fr && fr->replaceChainInstrument(c, std::move(fresh));
}
diff --git a/tests/Nota.SmokeTest/PresetStateTests.cs b/tests/Nota.SmokeTest/PresetStateTests.cs
new file mode 100644
index 00000000..8486d459
--- /dev/null
+++ b/tests/Nota.SmokeTest/PresetStateTests.cs
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Preset state (specs/048, #157): a device knows which preset it was loaded from, and says so
+// once a sound parameter moves away from it. Applying a preset is one undo step with its name;
+// copies and duplicates keep the name; a saved project reopens with it; view settings and tiny
+// float noise don't count as changes. Also runnable alone: `--preset-state`.
+
+using System.Text.Json.Nodes;
+using Nota.Application;
+using Nota.Application.Editing;
+using Nota.Infrastructure;
+using Nota.Presentation;
+
+namespace Nota.SmokeTest;
+
+internal static class PresetStateTests
+{
+ private const int Eq = 0, Delay = 3, Arp = 0;
+
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ using var eng = new NotaEngine();
+ yield return (eng.PresetTagSelfTest(), "preset: the engine self-test (tag inside a gesture undoes and redoes)");
+
+ var cat = new FactoryPresetCatalog();
+ var delays = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == Delay).Take(2).ToList();
+ var synths = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 0 && p.DisplayName != "Init").Take(1).ToList();
+ var arps = cat.All().Where(p => p.IsMidiEffect && p.BuiltinKind == Arp).Take(1).ToList();
+ yield return (delays.Count == 2 && synths.Count == 1 && arps.Count == 1, "preset: factory presets for Delay, Synth and Arpeggiator");
+ if (delays.Count < 2 || synths.Count < 1 || arps.Count < 1) yield break;
+ var (a, b) = (delays[0], delays[1]);
+
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Delay);
+ const PresetSurface Fx = PresetSurface.Effect;
+ yield return (eng.DevicePresetTag(t, Fx, d) == 0 && eng.DevicePresetModified(t, Fx, d) == -1 && PresetEdit.Name(eng, t, Fx, d) == "",
+ "preset: a new device has no preset (Init)");
+ yield return (eng.DevicePresetTag(t, Fx, 9) == -1 && eng.DevicePresetTag(9999, Fx, 0) == -1, "preset: no such device reads -1");
+
+ eng.ClearUndoHistory();
+ string w = PresetEdit.Apply(eng, t, Fx, d, a.Id, a.DisplayName, () => cat.ApplyInPlace(eng, a.Id, t, d));
+ yield return (w == "" && PresetEdit.Name(eng, t, Fx, d) == a.DisplayName && eng.DevicePresetModified(t, Fx, d) == 0,
+ $"preset: applying \"{a.DisplayName}\" names the device, unchanged");
+ var tag = eng.PresetTagInfo(eng.DevicePresetTag(t, Fx, d));
+ yield return (tag is { } tg && tg.Id == a.Id && tg.Loaded.Length == eng.DeviceParamCount(t, d), "preset: the tag keeps the id and the loaded values");
+
+ // Turning a sound knob marks it; turning it back clears it.
+ float v0 = eng.DeviceGetParam(t, d, 0), lo = eng.DeviceParamMin(t, d, 0), hi = eng.DeviceParamMax(t, d, 0);
+ float moved = v0 + (v0 < (lo + hi) / 2 ? 0.3f : -0.3f) * (hi - lo);
+ eng.DeviceSetParam(t, d, 0, moved);
+ yield return (eng.DevicePresetModified(t, Fx, d) == 1, "preset: moving a parameter marks it changed");
+ eng.DeviceSetParam(t, d, 0, v0);
+ yield return (eng.DevicePresetModified(t, Fx, d) == 0, "preset: moving it back clears the mark");
+ eng.DeviceSetParam(t, d, 0, v0 + 1e-6f * (hi - lo));
+ yield return (eng.DevicePresetModified(t, Fx, d) == 0, "preset: float noise below the tolerance isn't a change");
+ eng.DeviceSetParam(t, d, 0, v0);
+
+ // One undo step per preset, name included.
+ PresetEdit.Apply(eng, t, Fx, d, b.Id, b.DisplayName, () => cat.ApplyInPlace(eng, b.Id, t, d));
+ var afterB = Enumerable.Range(0, eng.DeviceParamCount(t, d)).Select(i => eng.DeviceGetParam(t, d, i)).ToArray();
+ yield return (PresetEdit.Name(eng, t, Fx, d) == b.DisplayName && eng.DevicePresetModified(t, Fx, d) == 0,
+ $"preset: switching to \"{b.DisplayName}\"");
+ bool u1 = eng.Undo();
+ yield return (u1 && PresetEdit.Name(eng, t, Fx, d) == a.DisplayName && eng.DevicePresetModified(t, Fx, d) == 0,
+ "preset: undo brings back the previous preset's sound and name");
+ bool u2 = eng.Undo();
+ yield return (u2 && eng.DevicePresetTag(t, Fx, d) == 0, "preset: undo again goes back to no preset");
+ bool r1 = eng.Redo() && eng.Redo();
+ var redone = Enumerable.Range(0, eng.DeviceParamCount(t, d)).Select(i => eng.DeviceGetParam(t, d, i)).ToArray();
+ yield return (r1 && PresetEdit.Name(eng, t, Fx, d) == b.DisplayName && redone.SequenceEqual(afterB),
+ "preset: redo applies both again");
+
+ // Init clears the name, as one step.
+ PresetEdit.Apply(eng, t, Fx, d, "", "", () => cat.ResetInPlace(eng, t, d, false));
+ yield return (eng.DevicePresetTag(t, Fx, d) == 0 && PresetEdit.Name(eng, t, Fx, d) == "", "preset: Init clears the name");
+ yield return (eng.Undo() && PresetEdit.Name(eng, t, Fx, d) == b.DisplayName, "preset: undoing Init brings the name back");
+
+ // A preset that doesn't apply leaves the name alone.
+ PresetEdit.Apply(eng, t, Fx, d, "no-such-id", "Nope", () => cat.ApplyInPlace(eng, "no-such-id", t, d));
+ yield return (PresetEdit.Name(eng, t, Fx, d) == b.DisplayName, "preset: an unknown preset leaves the name as it was");
+
+ // Copies keep the name and the loaded values.
+ int dup = eng.DuplicateDevice(t, d);
+ yield return (dup >= 0 && PresetEdit.Name(eng, t, Fx, dup) == b.DisplayName && eng.DevicePresetModified(t, Fx, dup) == 0,
+ "preset: a duplicate keeps the preset name");
+ eng.DeviceSetParam(t, dup, 0, moved);
+ yield return (eng.DevicePresetModified(t, Fx, dup) == 1 && eng.DevicePresetModified(t, Fx, d) == 0,
+ "preset: changing the duplicate marks only the duplicate");
+ int t2 = eng.AddAudioTrack();
+ bool pasted = eng.CopyDevice(t, d) && eng.PasteDevice(t2, -1) is var pi && pi >= 0
+ && PresetEdit.Name(eng, t2, Fx, pi) == b.DisplayName;
+ yield return (pasted, "preset: copy and paste to another track keeps the name");
+ eng.MoveDevice(t, dup, 0);
+ yield return (PresetEdit.Name(eng, t, Fx, 0) == b.DisplayName && eng.DevicePresetModified(t, Fx, 0) == 1,
+ "preset: a moved device keeps its name and its change");
+
+ // View settings aren't the sound: EQ's analyzer switch doesn't mark it.
+ int eq = eng.AddBuiltinDevice(t, Eq);
+ PresetEdit.Apply(eng, t, Fx, eq, "test:eq", "Test EQ", () => "");
+ int an = Enumerable.Range(0, eng.DeviceParamCount(t, eq)).FirstOrDefault(i => eng.DeviceParamName(t, eq, i) == "Analyzer", -1);
+ if (an >= 0) eng.DeviceSetParam(t, eq, an, eng.DeviceGetParam(t, eq, an) > 0.5f ? 0f : 1f);
+ yield return (an >= 0 && eng.DevicePresetModified(t, Fx, eq) == 0, "preset: the EQ analyzer switch is a view setting, not a change");
+
+ // The instrument and MIDI effects carry names too.
+ var s = synths[0];
+ PresetEdit.Apply(eng, t, PresetSurface.Instrument, -1, s.Id, s.DisplayName, () => cat.ApplyInPlace(eng, s.Id, t, -1));
+ yield return (PresetEdit.Name(eng, t, PresetSurface.Instrument, -1) == s.DisplayName
+ && eng.DevicePresetModified(t, PresetSurface.Instrument, -1) == 0, $"preset: the Synth takes \"{s.DisplayName}\"");
+ int view = InstrumentView.Index(eng, t);
+ if (view >= 0) eng.PluginParamSet(t, -1, view, eng.PluginParamGet(t, -1, view) > 0.5f ? 0f : 1f);
+ yield return (eng.DevicePresetModified(t, PresetSurface.Instrument, -1) == 0, "preset: the card size (view) isn't a change");
+ int sp = Enumerable.Range(0, eng.PluginParamCount(t, -1)).First(i => i != view);
+ float sv = eng.PluginParamGet(t, -1, sp);
+ eng.PluginParamSet(t, -1, sp, sv > 0.5f ? sv - 0.3f : sv + 0.3f);
+ yield return (eng.DevicePresetModified(t, PresetSurface.Instrument, -1) == 1, "preset: a Synth knob marks it changed");
+
+ var ap = arps[0];
+ int m = eng.AddMidiEffect(t, Arp);
+ PresetEdit.Apply(eng, t, PresetSurface.MidiEffect, m, ap.Id, ap.DisplayName, () => cat.ApplyInPlace(eng, ap.Id, t, m));
+ yield return (PresetEdit.Name(eng, t, PresetSurface.MidiEffect, m) == ap.DisplayName
+ && eng.DevicePresetModified(t, PresetSurface.MidiEffect, m) == 0, $"preset: the Arpeggiator takes \"{ap.DisplayName}\"");
+
+ // Save → reopen: names, ids and the changed state come back.
+ string dir = Path.Combine(Path.GetTempPath(), "nota-preset-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var doc = ProjectService.Capture(eng, new TransportState(120, 1, false, false), new List<string>());
+ ProjectService.Save(doc, dir, eng);
+ using var e2 = new NotaEngine();
+ ProjectService.Apply(ProjectService.Load(dir), e2, dir);
+ int rt = -1;
+ for (int i = 0; i < e2.TrackCount; i++)
+ if (e2.TryGetTrackInfo(i, out var ti) && ti.IsInstrument) { rt = ti.Id; break; }
+ yield return (rt > 0 && PresetEdit.Name(e2, rt, Fx, 0) == b.DisplayName && e2.DevicePresetModified(rt, Fx, 0) == 1
+ && PresetEdit.Name(e2, rt, Fx, 1) == b.DisplayName && e2.DevicePresetModified(rt, Fx, 1) == 0,
+ "preset: a reopened project keeps each effect's preset and its changed state");
+ yield return (rt > 0 && e2.PresetTagInfo(e2.DevicePresetTag(rt, Fx, 1))?.Id == b.Id, "preset: the preset id round-trips");
+ yield return (rt > 0 && PresetEdit.Name(e2, rt, PresetSurface.Instrument, -1) == s.DisplayName
+ && e2.DevicePresetModified(rt, PresetSurface.Instrument, -1) == 1,
+ "preset: the instrument reopens with its preset, still changed");
+ yield return (rt > 0 && PresetEdit.Name(e2, rt, PresetSurface.MidiEffect, 0) == ap.DisplayName
+ && e2.DevicePresetModified(rt, PresetSurface.MidiEffect, 0) == 0,
+ "preset: the MIDI effect reopens with its preset");
+ }
+ finally
+ {
+ try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { }
+ }
+
+ // A v25 project has no preset names: it migrates on and every device opens at Init.
+ var old = ProjectMigrations.Migrate(new JsonObject { ["formatVersion"] = 25 });
+ yield return (old["formatVersion"]?.GetValue<int>() == ProjectService.CurrentFormatVersion
+ && new DeviceDto().Preset is null && new InstrumentDto().Preset is null && new MidiDeviceDto().Preset is null,
+ "preset: a v25 project migrates and opens with no preset names");
+
+ foreach (var r in InPlaceDrops()) yield return r;
+ foreach (var r in ReplacedInstruments()) yield return r;
+ }
+
+ // A preset dropped (or picked in the palette) onto the same kind of instrument changes the
+ // sound in place: undo brings back the old sound together with the old name.
+ private static IEnumerable<(bool, string)> InPlaceDrops()
+ {
+ using var eng = new NotaEngine();
+ var cat = new FactoryPresetCatalog();
+ var svc = new DeviceInsertService(eng, cat, null, null);
+ var two = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 0 && p.DisplayName != "Init").Take(2).ToList();
+ if (two.Count < 2) { yield return (false, "preset: two Synth presets for the in-place drop"); yield break; }
+ int t = eng.AddInstrumentTrack();
+ eng.SetTrackBuiltinInstrument(t, 0);
+ BrowserItem Row(FactoryPresetInfo p) => new() { Name = p.DisplayName, Kind = BrowserItemKind.Preset, Path = "factory:" + p.Id };
+ float[] Sound() => Enumerable.Range(0, eng.PluginParamCount(t, -1)).Select(i => eng.PluginParamGet(t, -1, i)).ToArray();
+ const PresetSurface Ins = PresetSurface.Instrument;
+
+ var r1 = svc.ApplyPreset(Row(two[0]), new InsertTarget(t, InPlace: true));
+ var first = Sound();
+ var r2 = svc.ApplyPreset(Row(two[1]), new InsertTarget(t, InPlace: true));
+ var second = Sound();
+ yield return (r1.Ok && r2.Ok && !r2.InstrumentReplaced && PresetEdit.Name(eng, t, Ins, -1) == two[1].DisplayName
+ && eng.DevicePresetModified(t, Ins, -1) == 0 && !first.SequenceEqual(second),
+ $"preset: \"{two[1].DisplayName}\" dropped on the same instrument loads in place and names it");
+ yield return (eng.Undo() && PresetEdit.Name(eng, t, Ins, -1) == two[0].DisplayName && Sound().SequenceEqual(first),
+ "preset: undoing an in-place drop brings back the old sound and the old name together");
+ // Another kind of instrument replaces the tagged one: undo brings the old one back named.
+ var others = cat.All().Where(p => p.IsInstrument && p.BuiltinKind > 0 && p.DisplayName != "Init").Take(1).ToList();
+ if (others.Count == 0) { yield return (false, "preset: a preset for another instrument kind"); yield break; }
+ var other = others[0];
+ var r3 = svc.ApplyPreset(Row(other), new InsertTarget(t, InPlace: true));
+ bool swapped = r3.Ok && eng.TrackInstrumentKind(t) == other.BuiltinKind && PresetEdit.Name(eng, t, Ins, -1) == other.DisplayName;
+ yield return (swapped && eng.Undo() && eng.TrackInstrumentKind(t) == 0 && PresetEdit.Name(eng, t, Ins, -1) == two[0].DisplayName,
+ $"preset: undoing a swap to \"{other.DisplayName}\" brings back the old instrument with its name ({PresetEdit.Name(eng, t, Ins, -1)})");
+ yield return (eng.Redo() && eng.TrackInstrumentKind(t) == other.BuiltinKind && PresetEdit.Name(eng, t, Ins, -1) == other.DisplayName,
+ $"preset: redo brings the swap back with its name ({PresetEdit.Name(eng, t, Ins, -1)})");
+ }
+
+ // An edit that publishes a fresh instrument (a Mosaic program, a drum or Grain sample) is
+ // still the preset the old one was loaded from: the name stays, undo and redo keep it.
+ private static IEnumerable<(bool, string)> ReplacedInstruments()
+ {
+ using var eng = new NotaEngine();
+ string wav = Path.Combine(Path.GetTempPath(), $"nota-smoke-preset-{Guid.NewGuid():N}.wav");
+ WavWriter.WriteSine(wav, seconds: 0.2, freq: 330, sampleRate: 44100);
+ const PresetSurface Ins = PresetSurface.Instrument;
+ var cases = new (string Kind, Func<int> Add, Func<int, bool> Edit)[]
+ {
+ ("Mosaic", eng.AddMosaicTrack, t => eng.MosaicSetProgram(t, eng.MosaicProgram(t) + "\n")),
+ ("Rhythm", eng.AddRhythmTrack, t => eng.SetRhythmVoiceSample(t, 0, wav)),
+ ("Grain", eng.AddGrainSynthTrack, t => eng.SetTrackGrainSample(t, wav)),
+ ("Sampler", eng.AddSamplerInstrumentTrack, t => eng.SetTrackSamplerSample(t, wav)),
+ };
+ try
+ {
+ foreach (var (kind, add, edit) in cases)
+ {
+ int t = add();
+ eng.SetDevicePresetTag(t, Ins, -1, "smoke:" + kind, kind + " Preset");
+ eng.ClearUndoHistory();
+ bool edited = edit(t);
+ yield return (edited && PresetEdit.Name(eng, t, Ins, -1) == kind + " Preset",
+ $"preset: a {kind} edit that swaps in a fresh instrument keeps its name ({PresetEdit.Name(eng, t, Ins, -1)})");
+ yield return (eng.Undo() && PresetEdit.Name(eng, t, Ins, -1) == kind + " Preset"
+ && eng.Redo() && PresetEdit.Name(eng, t, Ins, -1) == kind + " Preset",
+ $"preset: undo and redo of the {kind} edit keep the name");
+ }
+ }
+ finally { try { File.Delete(wav); } catch (IOException) { } }
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 18e5428c..219b0722 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -469,6 +469,14 @@ if (args.Length >= 1 && args[0] == "--pad-warp")
Console.WriteLine(failures == 0 ? "PAD WARP PASSED" : $"PAD WARP FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Preset state alone: `--preset-state` (specs/048). Also part of the full run.
+if (args.Length >= 1 && args[0] == "--preset-state")
+{
+ Console.WriteLine("-- preset state --");
+ foreach (var (ok, label) in PresetStateTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "PRESET STATE PASSED" : $"PRESET STATE FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Device fold alone: `--fold`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--fold")
{
@@ -15183,6 +15191,8 @@ foreach (var (ok, label) in AuroraNullTests.Run()) Check(ok, label);
Console.WriteLine("-- device fold --");
foreach (var (ok, label) in DeviceFoldTests.Run()) Check(ok, label);
+Console.WriteLine("-- preset state --");
+foreach (var (ok, label) in PresetStateTests.Run()) Check(ok, label);
Console.WriteLine("-- scope view --");
foreach (var (ok, label) in ScopeViewTests.Run()) Check(ok, label);