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.

(fix) Mosaic pack presets expand in the browser; preset drops load in place

Egor Khindikaynen2dc0e6eb1201
diff --git a/.specify/bugs/mosaic-packs-expand/assessment.md b/.specify/bugs/mosaic-packs-expand/assessment.md
new file mode 100644
index 00000000..05f19537
--- /dev/null
+++ b/.specify/bugs/mosaic-packs-expand/assessment.md
@@ -0,0 +1,79 @@
+# Bug Assessment: Mosaic → Packs → a pack won't expand in the browser
+
+- **Slug**: mosaic-packs-expand
+- **Created**: 2026-10-11
+- **Source**: pasted text
+- **Verdict**: valid
+- **Severity**: high
+
+## Report (verbatim or summarized)
+
+> Загруженные паки в браузере отображаются в Mosaic -> Packs, но их либо нельзя развернуть,
+> или разворачивается, но не отображаются пресеты. И перетащить соответственно тоже нельзя.
+
+## Symptom
+
+In the Instruments tab, Nota Mosaic → Packs expands and lists the installed packs, but clicking a
+pack's disclosure triangle does nothing visible: its presets never appear, so none can be dragged
+onto a track. Expected: the pack expands to its presets, which drag like any other preset.
+
+## Reproduction
+
+1. Install at least one sample pack (Settings → Downloads) so Mosaic generates pack presets.
+2. Browser → Instruments → expand Nota Mosaic → expand Packs: the packs are listed.
+3. Click a pack's disclosure triangle (or the row): no presets appear.
+4. (Collapsing and re-expanding Packs then shows the pack open — its state did flip, the list
+ simply was never rebuilt.)
+
+## Suspected Code Paths
+
+- `src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs:424` `DeviceTabOf()` — decides
+ which device tab to re-flatten after a toggle, but only checks a device's **direct** children
+ (`d.Children.Contains(item)`). A pack folder is a grandchild (Mosaic → Packs → pack), so it
+ returns -1.
+- `src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs:399` `ToggleExpand()` — with -1 it
+ falls into the Files/Presets branch: flips `IsExpanded`, records the path in `_expandedTreeKeys`,
+ rebuilds the Files and Presets lists — but never `RebuildVisible(0)`, so the Instruments list
+ is stale.
+- `src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs:317-333` — builds the 3-level
+ Packs tree (the only device-tab tree deeper than two levels); `AddPresetRows` (`:500`) already
+ recurses correctly, so rendering is fine once rebuilt.
+- `src/managed/Nota.App/BrowserView.cs:1186` `OnRowPressed` — drag is generic for `Preset` rows;
+ nothing pack-specific blocks it. Drag fails only because the rows are never visible.
+
+## Root Cause Hypothesis
+
+`DeviceTabOf` assumes device-tab folders are at most one level deep. The Mosaic Packs tree added
+a second folder level, so toggling a pack is misrouted to the Files/Presets refresh and the
+Instruments list never re-flattens. Confidence: high.
+
+## Proposed Remediation
+
+**Preferred**: make `DeviceTabOf` search the whole subtree of each device (a recursive
+`Contains` over `Children`), so any nested folder on a device tab returns its tab and
+`ToggleExpand` calls `RebuildVisible(tab)`. Small, local, no API change.
+
+**Alternatives**:
+- Give `BrowserItem` a tab / owner field set at build time — avoids the tree walk but touches
+ every place that constructs device-tab items.
+
+**Files likely to change**:
+- `src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs`
+- `tests/Nota.SmokeTest/` (a browser test, via `BrowserTestSupport.cs`)
+
+**Tests to add or update**:
+- Build a `BrowserViewModel` with a fake `IMosaicPacks` returning two presets in one folder;
+ expand Mosaic → Packs → the pack via `ToggleExpand` and assert both preset rows appear in
+ `Instruments`; collapse and assert they're gone.
+
+## Risks & Considerations
+
+- Folder expansion on device tabs is not persisted across `Rebuild()` (they are all collapsed
+ there), unlike Files folders; after the fix pack folders also won't land in `_expandedTreeKeys`
+ — consistent with the other device-tab folders.
+- Side note (not this bug): `MosaicLibrary.Presets()` parses every preset file on each browser
+ `Rebuild()`; with many packs this could become slow.
+
+## Open Questions
+
+- None.
diff --git a/.specify/bugs/mosaic-packs-expand/fix.md b/.specify/bugs/mosaic-packs-expand/fix.md
new file mode 100644
index 00000000..1f472a73
--- /dev/null
+++ b/.specify/bugs/mosaic-packs-expand/fix.md
@@ -0,0 +1,53 @@
+# Bug Fix: Mosaic → Packs → a pack won't expand in the browser
+
+- **Slug**: mosaic-packs-expand
+- **Fixed**: 2026-10-11
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+`BrowserViewModel.DeviceTabOf` now searches a device's whole subtree, so toggling a nested
+folder (Nota Mosaic → Packs → a pack) re-flattens the Instruments list and the pack's presets
+appear (and can be dragged).
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs` | modified | `DeviceTabOf` uses a recursive `Holds(node, item)` instead of `d.Children.Contains(item)` |
+| `tests/Nota.SmokeTest/BrowserTestSupport.cs` | added | `FakeMosaicPacks` — a fixed `IMosaicPacks` list for browser tests |
+| `tests/Nota.SmokeTest/MosaicTests.cs` | added test | `BrowserPacks()` run from `MosaicTests.Run()` |
+
+## Diff Highlights
+
+```csharp
+if (_instrTree.Any(d => Holds(d, item))) return 0;
+...
+private static bool Holds(BrowserItem node, BrowserItem item)
+ => node.Children.Any(c => c == item || Holds(c, item));
+```
+
+## Tests Added or Updated
+
+- `MosaicTests.BrowserPacks` — "a Mosaic pack expands to its presets in the browser": expands
+ Nota Mosaic → Packs → pack via `ToggleExpand` and checks both preset rows are in `Instruments`.
+- `MosaicTests.BrowserPacks` — "a Mosaic pack collapses again".
+
+## Local Verification
+
+- `dotnet run --project tests/Nota.SmokeTest -c Release` → `SMOKE TEST PASSED` (full run).
+- With the old `DeviceTabOf` restored temporarily: `[FAIL] a Mosaic pack expands to its presets
+ in the browser`, `SMOKE TEST FAILED` — the test pins the bug. Fix restored afterwards.
+- Not checked in the running app (drag of the now-visible rows uses the generic preset drag path).
+
+## Deviations from Assessment
+
+None.
+
+## Follow-ups
+
+- `MosaicLibrary.Presets()` parses every pack preset on each browser `Rebuild()` — watch with
+ many packs.
+- Dropping a pack preset on an existing instrument track still adds a track — that is
+ `preset-drop-new-track`.
diff --git a/.specify/bugs/mosaic-packs-expand/test.md b/.specify/bugs/mosaic-packs-expand/test.md
new file mode 100644
index 00000000..f0016129
--- /dev/null
+++ b/.specify/bugs/mosaic-packs-expand/test.md
@@ -0,0 +1,55 @@
+# Bug Verification: Mosaic → Packs → a pack won't expand in the browser
+
+- **Slug**: mosaic-packs-expand
+- **Tested**: 2026-10-11
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+The reproduction no longer reproduces in the real `MainWindow` (headless Avalonia, real app
+services, a Mosaic pack on disk). Clicking the pack's disclosure triangle shows its presets, and
+clicking it again hides them. Those presets drop onto the arrangement through the window's real
+drop handler. No regressions from the change.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (post-fix) | `/tmp/packsharness` (`NOTA_DATA_DIR=/tmp/packsharness/data dotnet run`) | pass | Real `MainWindow` + `BrowserView`; two presets saved via `IMosaicPacks.Save` into "Test Pack"; synthetic `PointerPressed` on the disclosure triangles of Nota Mosaic → Packs → Test Pack |
+| Presets are draggable payload | same harness, `MainWindow.OnArrangementDrop` (reflected) with the pack rows | pass | A pack preset on empty space makes a Mosaic track |
+| New tests | `dotnet run --project tests/Nota.SmokeTest -c Release` | pass | "a Mosaic pack expands to its presets in the browser", "a Mosaic pack collapses again" |
+| Test pins the bug | same, with the old `DeviceTabOf` (during `/speckit-bug-fix`) | pass | The expand check failed on the old code |
+| Regression suite | full smoke test | pass (1 unrelated) | Only `Nota Consort stress` timing failed; it is a DSP benchmark this fix doesn't touch, and it varied between runs |
+| Lint / type-check | `dotnet build` (via the smoke run) | pass | No new warnings in changed files |
+
+## Output Excerpts
+
+```
+packs root: /tmp/packsharness/data/presets/Mosaic Packs
+[PASS] Nota Mosaic → Packs row is shown
+[PASS] Packs → Test Pack row is shown
+[PASS] clicking the pack's triangle shows its presets (Grand, Upright)
+[PASS] clicking it again collapses the pack
+[PASS] a pack preset dropped on empty space makes a Mosaic track (status: Applied preset Grand)
+HARNESS PASSED
+```
+
+Screenshot: `/tmp/packsharness/shots/packs-expanded.png`. It shows Nota Mosaic → Packs → Test Pack
+→ Grand, Upright.
+
+## Residual Risks
+
+- The OS drag gesture itself (`DragDrop.DoDragDropAsync`) can't run headless. The drop was fed to
+ `OnArrangementDrop` directly. The drag start in `BrowserView.OnRowPressed` is generic for
+ `Preset` rows and unchanged.
+- Not clicked by hand in the running app on a display.
+- The harness used a generated pack, not a real downloaded pack. The tree built from it is the
+ same.
+
+## Recommendation
+
+Close the bug. The fix is verified in the real window, and the remaining gap (the native drag
+gesture) is code this fix doesn't touch. A quick manual expand-and-drag in the app before the
+release is still worth doing.
diff --git a/.specify/bugs/preset-drop-new-track/assessment.md b/.specify/bugs/preset-drop-new-track/assessment.md
new file mode 100644
index 00000000..8824091f
--- /dev/null
+++ b/.specify/bugs/preset-drop-new-track/assessment.md
@@ -0,0 +1,95 @@
+# Bug Assessment: Dropping an instrument preset on an instrument track adds a new track
+
+- **Slug**: preset-drop-new-track
+- **Created**: 2026-10-11
+- **Source**: pasted text
+- **Verdict**: valid (behaviour as coded; the user expects in-place replacement)
+- **Severity**: medium
+
+## Report (verbatim or summarized)
+
+> перемещаешь пресет из браузера на аранжировку, добавляется инструмент с пресетом. Потом
+> перещаешь другой пресет на ту же дорожку, добавляется новая дорожка (а хотелось бы чтобы на
+> старой обновлялся)
+
+## Symptom
+
+Dragging an instrument preset onto an existing instrument track in the arrangement always
+creates a new track. Expected: the preset loads into that track's instrument (swapping the
+instrument if it is a different kind), as dropping a bare instrument already does.
+
+## Reproduction
+
+1. Drag any instrument preset (e.g. a Nota Mosaic factory preset) to empty arrangement space →
+ a new track with that preset.
+2. Drag another instrument preset onto that same track's lane.
+3. A second track is created; the first is unchanged.
+
+## Suspected Code Paths
+
+- `src/managed/Nota.Presentation/DeviceInsertService.cs:176` `DropOnArrangement()` — bare
+ instruments try `TryReplaceInstrument` first; presets go to `RouteToTrack`.
+- `src/managed/Nota.Presentation/DeviceInsertService.cs:307` `RouteToTrack()` — calls
+ `ApplyPreset(item, new InsertTarget(trackId))`, i.e. `InPlace = false`.
+- `src/managed/Nota.Presentation/DeviceInsertService.cs:358` `ApplyPresetCore()` — the in-place
+ branch exists but only for **factory** presets with `target.InPlace` (the command palette,
+ `PaletteProviders.cs:196`). Otherwise `_factory.Apply` / `_presets.ApplyFromFile` →
+ `PresetService.Apply` (`Nota.Infrastructure/Persistence/PresetService.cs:172`), whose
+ `builtin-instrument` / `plugin-instrument` cases always add a track.
+- File-based instrument presets (user presets, Mosaic pack presets) have no in-place path in the
+ insert service at all; `IPresetStore` only has `ApplyFromFile`.
+ `PresetService.ApplyInPlace` (`:298`) and `IMosaicPacks.ApplyInPlace` exist and are used by the
+ device card's preset picker.
+
+## Root Cause Hypothesis
+
+Design gap rather than a regression: the arrangement drop never asks for in-place application,
+and only factory presets could do it anyway. Confidence: high.
+
+## Proposed Remediation
+
+**Preferred**:
+1. In `DropOnArrangement`, route instrument presets with `InPlace: true` when the drop target is
+ a plain instrument track (`CanReplaceInstrument`); otherwise keep today's new-track behaviour
+ (empty space, audio / group / return tracks, racks).
+2. Extend the in-place branch of `ApplyPresetCore` to file presets: add
+ `IPresetStore.ApplyInPlaceFromFile(engine, path, trackId)` (in `PresetStore`) that loads the
+ document and, for `builtin-instrument`, swaps the track's built-in instrument if the kind
+ differs then calls `PresetService.ApplyInPlace`; for `plugin-instrument`, sets the track's
+ instrument plugin then restores its state. It reports whether the instrument was swapped so the
+ result carries `InstrumentReplaced` (card state reset). Effect presets and kits are unchanged.
+3. Keep `PresetLanded` populated so the card's preset label updates.
+
+**Alternatives**:
+- Only fix factory presets (one-line `InPlace: true`) — leaves Mosaic pack and user presets
+ still spawning tracks, which is exactly the pack workflow from `mosaic-packs-expand`.
+- A modifier key (e.g. ⌥-drop) to force a new track — could be added later; the default should
+ match bare-instrument drops.
+
+**Files likely to change**:
+- `src/managed/Nota.Presentation/DeviceInsertService.cs`
+- `src/managed/Nota.Application/Ports/IPresetStore.cs`
+- `src/managed/Nota.Infrastructure/Persistence/PresetStore.cs` (+ `PresetService.cs` helper)
+- `tests/Nota.SmokeTest/` (insertion test)
+
+**Tests to add or update**:
+- Factory instrument preset dropped on an instrument track of the same kind → track count
+ unchanged, preset params applied.
+- Preset of a different built-in kind → same track, `TrackInstrumentKind` switched.
+- Mosaic pack / user file preset → same track, Mosaic program set.
+- Preset dropped on empty space / an audio track → still creates a new track.
+
+## Risks & Considerations
+
+- Behaviour change: users who relied on "drop preset = new track" lose it on instrument lanes;
+ dropping below the last track still creates one.
+- Swapping the instrument kind discards the old instrument's state — same as a bare-instrument
+ drop today, and one undo step (`Group`).
+- Session view drops (`OnSessionDrop`) and Devices-panel drops route separately; decide whether
+ they should match (Devices panel probably yes).
+- Racks (kinds 3/4) excluded by `CanReplaceInstrument` — a preset there keeps making a new track.
+
+## Open Questions
+
+- Should the Session view and Devices panel drops get the same in-place behaviour?
+ [NEEDS CLARIFICATION]
diff --git a/.specify/bugs/preset-drop-new-track/fix.md b/.specify/bugs/preset-drop-new-track/fix.md
new file mode 100644
index 00000000..0bbf1073
--- /dev/null
+++ b/.specify/bugs/preset-drop-new-track/fix.md
@@ -0,0 +1,73 @@
+# Bug Fix: Dropping an instrument preset on an instrument track adds a new track
+
+- **Slug**: preset-drop-new-track
+- **Fixed**: 2026-10-11
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+An instrument preset dropped on a plain instrument track in the arrangement now loads into that
+track's instrument (swapping the instrument when the preset is for another one) instead of
+starting a new track. This works for factory presets and for preset files — user presets and
+Nota Mosaic pack presets. Drops on empty space, audio / group / return tracks and racks still
+start a track.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/managed/Nota.Presentation/DeviceInsertService.cs` | modified | `DropOnArrangement` applies presets with `InPlace: true`; `ApplyPresetCore` gains an in-place branch for preset files |
+| `src/managed/Nota.Application/Ports/IPresetStore.cs` | modified | new `ApplyInstrumentInPlace(engine, path, trackId, out swapped)` |
+| `src/managed/Nota.Infrastructure/Persistence/PresetStore.cs` | modified | implements it: swaps the built-in / plug-in instrument if needed, then `PresetService.ApplyInPlace` |
+| `tests/Nota.SmokeTest/PaletteTests.cs` | added test | `PresetDrops()`; relabelled the existing "dropped one starts its own track" check |
+
+## Diff Highlights
+
+```csharp
+// DropOnArrangement
+if (item.Kind == BrowserItemKind.Preset) return ApplyPreset(item, new InsertTarget(trackId, Beat: beat, InPlace: true));
+
+// ApplyPresetCore, after the factory in-place branch
+if (fp is null && !target.NewTrack && target.InPlace && CanReplaceInstrument(t)
+ && _presets?.ApplyInstrumentInPlace(_engine, item.Path, t, out bool fileSwapped) is { } fw)
+ return new InsertResult { ..., InstrumentReplaced = fileSwapped, PresetLanded = (t, PresetChain.Instrument, -1, item.Name, "") };
+```
+
+`ApplyInstrumentInPlace` returns null for non-instrument files (effect presets), so those keep
+going through `ApplyFromFile` unchanged. Kits are handled before this and are unaffected.
+
+## Tests Added or Updated
+
+- `PaletteTests.PresetDrops` — "a factory preset dropped on an instrument track loads there; a
+ second one replaces it" (track count unchanged, kind switched Volt → Aurora, effects kept).
+- `PaletteTests.PresetDrops` — "a preset file dropped on an instrument track swaps its instrument
+ in place" (a user preset saved from a Volt, dropped on the Aurora track).
+- `PaletteTests.PresetDrops` — "a preset dropped on empty space still starts a track".
+- `PaletteTests.EngineChecks` — existing check relabelled "…while one not asked in place still
+ starts its own track" (`ApplyPreset` without `InPlace` is unchanged).
+
+## Local Verification
+
+- `dotnet run --project tests/Nota.SmokeTest -c Release` → all new checks `[PASS]`.
+ The run ended `SMOKE TEST FAILED (1)`: `Nota Consort stress … per 128-frame block (budget 2,90 ms)`
+ — a DSP timing benchmark this change doesn't touch. It passed in an earlier run this session,
+ and another run failed 4 timing checks, so it is load-dependent. Unrelated to this fix.
+- The Mosaic pack path is not tested on its own here: a pack preset is a `builtin-instrument`
+ `.notapreset` that goes through the same `PresetService.ApplyInPlace` (→ `LoadMosaicProgram`),
+ which `MosaicTests` already checks ("a pack preset loads into a Mosaic").
+- Not checked in the running app.
+
+## Deviations from Assessment
+
+- The assessment's open question (Session view / Devices panel drops) is not addressed: only the
+ arrangement drop changed. The Devices panel (`Insert` → `InsertCore` → `ApplyPreset` without
+ `InPlace`) still creates a track for an instrument preset.
+- Swapping to Nota Rhythm through a preset doesn't load the default kit the way a bare
+ instrument drop does (`TryReplaceInstrument`). Same as the palette's existing factory
+ in-place path.
+
+## Follow-ups
+
+- Decide on Devices panel / Session view drops (pass `InPlace: true` there too).
+- CHANGELOG `[Unreleased]` entry under Fixed: both bugs are user-visible.
diff --git a/.specify/bugs/preset-drop-new-track/test.md b/.specify/bugs/preset-drop-new-track/test.md
new file mode 100644
index 00000000..45826fb2
--- /dev/null
+++ b/.specify/bugs/preset-drop-new-track/test.md
@@ -0,0 +1,48 @@
+# Bug Verification: Dropping an instrument preset on an instrument track adds a new track
+
+- **Slug**: preset-drop-new-track
+- **Tested**: 2026-10-11
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+The reproduction from the assessment (drop a preset → a track; drop another on that track) was run
+through `MainWindow`'s real arrangement drop handler. The second drop now loads into the existing
+track, with no new track, across pack, factory and cross-instrument presets. A drop on empty space
+still creates a track.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (post-fix) | `/tmp/packsharness`, `MainWindow.OnArrangementDrop` (reflected) | pass | Pack preset "Grand" on empty space → Mosaic track; "Upright" on that track → same track count, program now "Upright" |
+| Cross-instrument | same harness | pass | Factory Volt preset on the Mosaic track → Volt in place; pack preset → back to Mosaic in place |
+| New tests | `dotnet run --project tests/Nota.SmokeTest -c Release` | pass | `PaletteTests.PresetDrops`: factory twice, user preset file of another kind, empty space |
+| Regression suite | full smoke test | pass (1 unrelated) | Only `Nota Consort stress` timing failed; unrelated DSP benchmark, varied between runs |
+| Lint / type-check | `dotnet build` (via the smoke run) | pass | |
+
+## Output Excerpts
+
+```
+[PASS] a pack preset dropped on empty space makes a Mosaic track (status: Applied preset Grand)
+[PASS] a second pack preset dropped on that track adds no track (status: Applied preset Upright)
+[PASS] …and the track's Mosaic program is now 'Upright'
+[PASS] a factory Volt preset dropped on it swaps to Volt in place (status: Applied preset Warm Pad)
+[PASS] and a pack preset swaps it back to Mosaic (status: Applied preset Grand)
+HARNESS PASSED
+```
+
+## Residual Risks
+
+- The native drag gesture is not exercised headless (see `mosaic-packs-expand/test.md`).
+- Devices panel and Session view drops still create a track for an instrument preset. The fix
+ deliberately left them out, and the assessment's open question is still open.
+- A plug-in instrument preset dropped in place was not exercised (no plug-ins in the isolated data
+ dir). The code path is `SetTrackInstrumentPlugin` + `ApplyState`.
+
+## Recommendation
+
+Close the bug for the arrangement. Decide separately whether the Devices panel and Session view
+drops should behave the same way.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 48b0543b..b86ac0e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,16 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
+### Fixed
+- **Sample-pack presets open in the browser:** under Nota Mosaic → Packs, a pack wouldn't
+ expand, so its presets couldn't be seen or dragged. Packs now expand to their presets like
+ any other preset folder.
+- **A preset dropped on an instrument track loads there:** dragging a second instrument
+ preset onto a track in the Arrangement used to add another track. It now loads into that
+ track's instrument and switches the instrument if the preset is for a different one. This
+ works for factory presets, your own presets and sample-pack presets, and the track's effects
+ stay. A preset dropped on empty space still starts a new track.
+
## [0.51.2] — 2026-10-11
### Highlights
diff --git a/src/managed/Nota.Application/Ports/IPresetStore.cs b/src/managed/Nota.Application/Ports/IPresetStore.cs
index 94a19901..5558eb11 100644
--- a/src/managed/Nota.Application/Ports/IPresetStore.cs
+++ b/src/managed/Nota.Application/Ports/IPresetStore.cs
@@ -11,6 +11,11 @@ public interface IPresetStore
/// string ("" = clean).</summary>
string ApplyFromFile(IAudioEngine engine, string path, int targetTrackId);
+ /// <summary>Loads an instrument preset file into a track's instrument in place, swapping
+ /// the instrument first when the preset is for another one (<paramref name="swapped"/>).
+ /// Null — nothing done — when the file isn't an instrument preset; else a warning ("" = clean).</summary>
+ string? ApplyInstrumentInPlace(IAudioEngine engine, string path, int trackId, out bool swapped);
+
/// <summary>Captures a track's device/instrument as a preset and saves it to
/// <paramref name="folder"/>. Returns false if there was nothing to capture
/// (e.g. the built-in synth has no state).</summary>
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs b/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs
index b9c41221..01240e3f 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs
@@ -12,6 +12,36 @@ public sealed class PresetStore : IPresetStore
return PresetService.Apply(doc, engine, targetTrackId);
}
+ public string? ApplyInstrumentInPlace(IAudioEngine engine, string path, int trackId, out bool swapped)
+ {
+ swapped = false;
+ PresetDocument doc;
+ try { doc = PresetService.Load(path); }
+ catch { return null; } // ApplyFromFile reports it
+ switch (doc.Type)
+ {
+ case "builtin-instrument":
+ if (engine.TrackInstrumentKind(trackId) != doc.BuiltinKind || engine.TrackInstrumentPluginId(trackId).Length > 0)
+ {
+ if (!engine.SetTrackBuiltinInstrument(trackId, doc.BuiltinKind)) return $"Couldn't load {doc.DisplayName}.";
+ swapped = true;
+ }
+ break;
+ case "plugin-instrument":
+ if (engine.TrackInstrumentPluginId(trackId) != doc.PluginId)
+ {
+ int idx = NotaEngine.PluginIndexOfId(doc.PluginId);
+ if (idx < 0) return $"Plugin not installed: {doc.PluginId}";
+ engine.SetTrackInstrumentPlugin(trackId, idx);
+ swapped = true;
+ }
+ break;
+ default:
+ return null;
+ }
+ return PresetService.ApplyInPlace(doc, engine, trackId, -1);
+ }
+
public bool Save(IAudioEngine engine, int trackId, int deviceIndex, string displayName, string folder)
{
var doc = PresetService.Capture(engine, trackId, deviceIndex, displayName);
diff --git a/src/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.cs
index bf01b74e..e852d82f 100644
--- a/src/managed/Nota.Presentation/DeviceInsertService.cs
+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs
@@ -184,6 +184,8 @@ public sealed class DeviceInsertService
return t > 0 ? new InsertResult { Ok = true, TrackId = t, CreatedTrack = true, Status = $"Added {item.Name} (track {t})" }
: InsertResult.Fail($"Couldn't load {item.Name}.");
});
+ // A preset on a plain instrument track loads into its instrument, like a bare instrument.
+ if (item.Kind == BrowserItemKind.Preset) return ApplyPreset(item, new InsertTarget(trackId, Beat: beat, InPlace: true));
return Group(() => RouteToTrack(item, trackId));
}
@@ -379,6 +381,15 @@ public sealed class DeviceInsertService
PresetLanded = (t, PresetChain.Instrument, -1, item.Name, factoryId),
};
}
+ // …and a preset file (a user preset, a Mosaic pack preset) the same way.
+ if (fp is null && !target.NewTrack && target.InPlace && CanReplaceInstrument(t)
+ && _presets?.ApplyInstrumentInPlace(_engine, item.Path, t, out bool fileSwapped) is { } fw)
+ return new InsertResult
+ {
+ Ok = fw.Length == 0, TrackId = t, InstrumentReplaced = fileSwapped, ShowDevices = true,
+ Status = fw.Length > 0 ? fw : $"Applied preset {item.Name}",
+ PresetLanded = (t, PresetChain.Instrument, -1, item.Name, ""),
+ };
// Apply doesn't say where the preset landed, so diff the chain around it: a new track
// (instrument preset) or one more device / MIDI effect on the target (appended last).
diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
index 086092af..6ab92ac2 100644
--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
@@ -421,15 +421,19 @@ public sealed partial class BrowserViewModel : ObservableObject
}
// The device tab (0 Instr / 1 FX / 2 MIDI) a preset category folder belongs to, or -1.
+ // Folders nest (Nota Mosaic → Packs → a pack), so the whole subtree is searched.
private int DeviceTabOf(BrowserItem item)
{
if (item.Kind != BrowserItemKind.Folder) return -1;
- if (_instrTree.Any(d => d.Children.Contains(item))) return 0;
- if (_fxTree.Any(d => d.Children.Contains(item))) return 1;
- if (_midiTree.Any(d => d.Children.Contains(item))) return 2;
+ if (_instrTree.Any(d => Holds(d, item))) return 0;
+ if (_fxTree.Any(d => Holds(d, item))) return 1;
+ if (_midiTree.Any(d => Holds(d, item))) return 2;
return -1;
}
+ private static bool Holds(BrowserItem node, BrowserItem item)
+ => node.Children.Any(c => c == item || Holds(c, item));
+
/// <summary>Sets the live search query for a tree tab (0 = Instruments, 1 = FX,
/// 2 = MIDI, 3 = Files, 4 = Presets) and refreshes its visible list.</summary>
public void FilterTree(int tab, string query)
diff --git a/tests/Nota.SmokeTest/BrowserTestSupport.cs b/tests/Nota.SmokeTest/BrowserTestSupport.cs
index 63ed4982..ffed6a7f 100644
--- a/tests/Nota.SmokeTest/BrowserTestSupport.cs
+++ b/tests/Nota.SmokeTest/BrowserTestSupport.cs
@@ -25,3 +25,18 @@ internal sealed class EmptyPresetLibrary : IPresetLibrary
{
public IReadOnlyList<PresetInfo> List(string folder) => Array.Empty<PresetInfo>();
}
+
+/// <summary>A fixed list of Mosaic pack presets, for the browser's Nota Mosaic → Packs tree.</summary>
+internal sealed class FakeMosaicPacks(params MosaicPackPreset[] presets) : IMosaicPacks
+{
+ public string Root => "";
+ public IReadOnlyList<MosaicPackPreset> Presets() => presets;
+ public event Action? Changed { add { } remove { } }
+ public Task<int> ScanAsync(CancellationToken ct = default) => Task.FromResult(0);
+ public string Save(Nota.Application.Mosaic.MosaicProgram program, string name, string folder, IReadOnlyDictionary<string, float>? param = null) => "";
+ public string ApplyInPlace(IAudioEngine engine, string path, int trackId) => "";
+ public Nota.Application.Mosaic.MosaicProgram? Read(string path) => null;
+ public string ToRef(string path) => path;
+ public string? Resolve(string reference) => null;
+ public double? DetectNote(string path) => null;
+}
diff --git a/tests/Nota.SmokeTest/MosaicTests.cs b/tests/Nota.SmokeTest/MosaicTests.cs
index d0052afe..c6aab006 100644
--- a/tests/Nota.SmokeTest/MosaicTests.cs
+++ b/tests/Nota.SmokeTest/MosaicTests.cs
@@ -97,6 +97,33 @@ internal static class MosaicTests
Directory.CreateDirectory(dir);
try { foreach (var r in RunIn(dir)) yield return r; }
finally { try { Directory.Delete(dir, true); } catch { } }
+ foreach (var r in BrowserPacks()) yield return r;
+ }
+
+ // The browser's Nota Mosaic → Packs → a pack: three folder levels deep, and a pack must
+ // expand to its presets on the Instruments tab (bug mosaic-packs-expand).
+ private static IEnumerable<(bool, string)> BrowserPacks()
+ {
+ var packs = new FakeMosaicPacks(
+ new MosaicPackPreset("/p/Osiris/Grand.notapreset", "Grand", "Osiris", "sfz"),
+ new MosaicPackPreset("/p/Osiris/Upright.notapreset", "Upright", "Osiris", "files"));
+ var vm = new Nota.Presentation.BrowserViewModel(new EmptyPluginCatalog(), new EmptyPresetLibrary(),
+ new FactoryPresetCatalog(), mosaic: packs);
+ var rows = vm.Instruments;
+ var mosaic = rows.FirstOrDefault(r => r.BuiltinKind == MosaicModel.Kind && r.Depth == 0);
+ if (mosaic is null) { yield return (false, "browser lists Nota Mosaic"); yield break; }
+ vm.ToggleExpand(mosaic);
+ var packsRow = rows.FirstOrDefault(r => r.Name == "Packs" && r.Kind == Nota.Presentation.BrowserItemKind.Folder);
+ if (packsRow is null) { yield return (false, "Nota Mosaic → Packs is listed"); yield break; }
+ vm.ToggleExpand(packsRow);
+ var pack = rows.FirstOrDefault(r => r.Name == "Osiris" && r.Kind == Nota.Presentation.BrowserItemKind.Folder);
+ if (pack is null) { yield return (false, "Packs lists the pack"); yield break; }
+ vm.ToggleExpand(pack);
+ yield return (rows.Any(r => r.Path == "/p/Osiris/Grand.notapreset") && rows.Any(r => r.Path == "/p/Osiris/Upright.notapreset"),
+ "a Mosaic pack expands to its presets in the browser");
+ vm.ToggleExpand(pack);
+ yield return (!rows.Any(r => r.Path.StartsWith("/p/Osiris/", StringComparison.Ordinal)),
+ "a Mosaic pack collapses again");
}
private static IEnumerable<(bool, string)> RunIn(string dir)
diff --git a/tests/Nota.SmokeTest/PaletteTests.cs b/tests/Nota.SmokeTest/PaletteTests.cs
index dc8f757f..911b65e5 100644
--- a/tests/Nota.SmokeTest/PaletteTests.cs
+++ b/tests/Nota.SmokeTest/PaletteTests.cs
@@ -262,7 +262,47 @@ internal static class PaletteTests
yield return (pr.Ok && eng.TrackCount == count0 && eng.TrackInstrumentKind(k) == 5 && Chain(k) == "0,3",
"an instrument preset loads in place, swapping the instrument (palette)");
var dropped = svc.ApplyPreset(presetRow, new InsertTarget(k));
- yield return (dropped.CreatedTrack, "…while a dropped one still starts its own track");
+ yield return (dropped.CreatedTrack, "…while one not asked in place still starts its own track");
+
+ foreach (var x in PresetDrops(eng, factory, volt, aurora, Track, Chain)) yield return x;
+ }
+
+ // Dropping a preset on the arrangement (bug preset-drop-new-track): on a plain instrument
+ // track it loads into that track's instrument — factory or file preset, same kind or not;
+ // on empty space it still starts a track.
+ private static IEnumerable<(bool, string)> PresetDrops(NotaEngine eng, FactoryPresetCatalog factory,
+ BrowserItem volt, BrowserItem aurora, Func<int> track, Func<int, string> chain)
+ {
+ string dir = Path.Combine(Path.GetTempPath(), "nota-preset-drop-" + Environment.ProcessId);
+ Directory.CreateDirectory(dir);
+ try
+ {
+ var store = new PresetStore();
+ var svc = new DeviceInsertService(eng, factory, store, null);
+ BrowserItem Row(FactoryPresetInfo p) => new() { Name = p.DisplayName, Kind = BrowserItemKind.Preset, Path = "factory:" + p.Id };
+ var auroraPresets = factory.All().Where(p => p.IsInstrument && p.BuiltinKind == 5).ToList();
+
+ int t = track(); int n0 = eng.TrackCount;
+ var r1 = svc.DropOnArrangement(Row(auroraPresets[0]), t, 0);
+ var r2 = svc.DropOnArrangement(Row(auroraPresets[1]), t, 0);
+ yield return (r1.Ok && r2.Ok && !r1.CreatedTrack && !r2.CreatedTrack && eng.TrackCount == n0
+ && eng.TrackInstrumentKind(t) == 5 && chain(t) == "0,3" && r1.InstrumentReplaced && !r2.InstrumentReplaced,
+ "a factory preset dropped on an instrument track loads there; a second one replaces it");
+
+ // A user preset file of another instrument: saved from a Volt, dropped on the Aurora track.
+ int v = svc.CreateInstrumentTrack(volt, 0);
+ store.Save(eng, v, -1, "Drop Test", dir);
+ string file = Directory.EnumerateFiles(dir, "*" + PresetService.Extension).First();
+ var userRow = new BrowserItem { Name = "Drop Test", Kind = BrowserItemKind.Preset, Path = file };
+ int n1 = eng.TrackCount;
+ var r3 = svc.DropOnArrangement(userRow, t, 0);
+ yield return (r3.Ok && !r3.CreatedTrack && r3.InstrumentReplaced && eng.TrackCount == n1 && eng.TrackInstrumentKind(t) == 6 && chain(t) == "0,3",
+ $"a preset file dropped on an instrument track swaps its instrument in place ({r3.Status})");
+
+ var r4 = svc.DropOnArrangement(Row(auroraPresets[0]), -1, 8);
+ yield return (r4.CreatedTrack && eng.TrackCount == n1 + 1, "a preset dropped on empty space still starts a track");
+ }
+ finally { try { Directory.Delete(dir, true); } catch { } }
}
// Source checks: the menu names only catalog commands, every command has a handler, and