Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Files tab tags and filters, similar sounds, project key, loops warped on drop
Egor Khindikaynen5581a90feb70
diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.csindex 87806ead..5a75e81b 100644--- a/src/managed/Nota.App/BrowserView.cs+++ b/src/managed/Nota.App/BrowserView.cs@@ -27,6 +27,7 @@ using Avalonia.Layout;using Avalonia.Media;using Avalonia.Platform.Storage;using Nota.Application;+using Nota.Application.Samples;using Nota.Presentation;namespace Nota.App;@@ -219,6 +220,15 @@ public sealed class BrowserView : UserControl// Header filter chips (Favorites + one per tag); rebuilt from the VM's tags.private readonly Border _chipsHost;private readonly ChipStrip _chipsPanel;+ // Files tab: the sample filter strip (Loops · One-shots · BPM · Key, and "Like …" while+ // showing similar sounds). Unlike the tag strip it wraps rather than folding into "+N":+ // it holds at most five fixed chips, and BPM and Key are the point of it.+ private readonly Border _sampleChipsHost;+ private readonly WrapPanel _sampleChips;++ /// <summary>The project tempo / key, for the filter's "project" shortcuts.</summary>+ public Func<double>? ProjectTempo { get; set; }+ public Func<MusicalKey?>? ProjectKey { get; set; }private readonly Border _overflowChip;private readonly TextBlock _overflowText;@@ -333,6 +343,9 @@ public sealed class BrowserView : UserControl_chipsPanel = new ChipStrip(_overflowChip, _overflowText);_chipsHost = new Border { Margin = new Thickness(8, 0, 8, 7), Child = _chipsPanel };+ _sampleChips = new WrapPanel { ItemSpacing = 5, LineSpacing = 5 };+ _sampleChipsHost = new Border { Margin = new Thickness(8, 0, 8, 7), Child = _sampleChips, IsVisible = false };+_previewFooter = new PreviewPlayer { IsVisible = false };_previewFooter.SetContext(files: _active == FilesTab);@@ -371,7 +384,7 @@ public sealed class BrowserView : UserControlcontentHost.Children.Add(_emptyWrap);var right = new DockPanel();- var topStack = new StackPanel { Children = { headerRow, _chipsHost } };+ var topStack = new StackPanel { Children = { headerRow, _chipsHost, _sampleChipsHost } };DockPanel.SetDock(topStack, Dock.Top);DockPanel.SetDock(_statusBar, Dock.Bottom);DockPanel.SetDock(_previewFooter, Dock.Bottom);@@ -492,6 +505,13 @@ public sealed class BrowserView : UserControl// Rebuild the header chips whenever tags/favorites change (also refreshes active state).vm.LibraryChanged += RebuildChips;RebuildChips();+ vm.SampleIndexChanged += () => { if (_active == FilesTab) RefreshCounts(); };+ // A rescan (settings, a pack installed) can leave "similar" mode behind the view's back.+ vm.Samples.CollectionChanged += (_, _) =>+ {+ if (!ReferenceEquals(_chipsAnchor, vm.SimilarAnchor) || _chipsFilter != vm.SampleFilter) RebuildSampleChips();+ };+ RebuildSampleChips();RefreshCounts();}@@ -565,7 +585,10 @@ public sealed class BrowserView : UserControl{bool searching = !string.IsNullOrEmpty(_search.Text?.Trim());bool filtering = tab is 0 or 1 or 2 && _vm is not null && _vm.FilterMode != BrowserFilter.None;- if (searching || filtering) return ("No matches", "Try a different search or clear the filters.");+ bool sampleFilter = tab == FilesTab && _vm is not null && (!_vm.SampleFilter.IsEmpty || _vm.SimilarAnchor is not null);+ if (sampleFilter && _vm!.IndexProgress.Total > 0)+ return ("No matches yet", "Nota is still analysing your samples — more matches appear as it goes.");+ if (searching || filtering || sampleFilter) return ("No matches", "Try a different search or clear the filters.");return tab switch{0 => ("No instruments yet", "Nota's built-in synths plus your VST/AU plug-ins. Scan your plug-ins in Settings → Plug-ins to add more."),@@ -599,9 +622,12 @@ public sealed class BrowserView : UserControlreturn $"{bi} built-in · {Plural(pl, "plug-in")}";}int n = VisibleCount(tab);+ // Filtered, the folders on screen are only there to hold the matches: count those.+ if (tab == FilesTab && _vm.SimilarAnchor is not null || tab == FilesTab && !_vm.SampleFilter.IsEmpty)+ n = System.Linq.Enumerable.Count(_vm.Samples, s => s.Kind != BrowserItemKind.Folder);return tab switch{- 3 => Plural(n, "sample"),+ 3 => Plural(n, "sample") + AnalysingSuffix(),4 => Plural(n, "preset"),_ => Plural(n, "project"),};@@ -609,6 +635,13 @@ public sealed class BrowserView : UserControlprivate static string Plural(int n, string noun) => $"{n} {noun}{(n == 1 ? "" : "s")}";+ // " · analysing 34 %" while the library scan runs.+ private string AnalysingSuffix()+ {+ var (done, total) = _vm?.IndexProgress ?? (0, 0);+ return total > 0 ? $" · analysing {done * 100 / total}\u2009%" : "";+ }+private void SelectTab(int index){if (index == _active) return;@@ -629,6 +662,7 @@ public sealed class BrowserView : UserControlif (auditions) SyncPreview(_pages[index]);// Favorite/tag filter chips apply only to the device tabs._chipsHost.IsVisible = index is 0 or 1 or 2;+ _sampleChipsHost.IsVisible = index == FilesTab && _vm?.HasSampleIndex == true;_statusBar.IsVisible = !isMap;if (isMap) { _matchCount.Text = ""; _emptyWrap.IsVisible = false; return; }RefreshCounts();@@ -766,10 +800,12 @@ public sealed class BrowserView : UserControl};if (child) name.Classes.Add("child");- // The type, as a quiet tag on the right edge (toggleable in the ⋮ menu).- string tag = RowTag(item);+ // The type, as a quiet tag on the right edge (toggleable in the ⋮ menu). A sample's+ // tag is what the index heard — "124 · Am" — and fills in as the scan reaches it.+ bool sample = item.Kind == BrowserItemKind.Sample;+ string tag = sample ? SampleTag(item) : RowTag(item);TextBlock? tagText = null;- if (tag.Length > 0 && (_settings?.Current.BrowserShowTypeTags ?? true))+ if (sample || (tag.Length > 0 && (_settings?.Current.BrowserShowTypeTags ?? true)))tagText = new TextBlock { Text = tag, Classes = { "RowTag" }, TextTrimming = TextTrimming.CharacterEllipsis };var row = new IndexRowPanel@@ -786,12 +822,40 @@ public sealed class BrowserView : UserControl};// The row's full identity lives in the tooltip, where the tag has no room for it- // (a plug-in's format, a sample's folder).+ // (a plug-in's format, a sample's folder, tempo and key).string tip = item.Tip.Length > 0 ? item.Tip : item.Sub;ToolTip.SetTip(row, tip.Length > 0 ? $"{item.Name} · {tip}" : item.Name);+ if (sample)+ {+ void Retag(object? _, System.ComponentModel.PropertyChangedEventArgs __)+ {+ tagText!.Text = SampleTag(item);+ row.InvalidateArrange();+ }+ // Subscribe only while shown: the item outlives its rows (they are rebuilt on every+ // scroll), so a lasting handler would pin every row ever drawn.+ row.AttachedToVisualTree += (_, _) => { item.PropertyChanged -= Retag; item.PropertyChanged += Retag; tagText!.Text = SampleTag(item); };+ row.DetachedFromVisualTree += (_, _) => item.PropertyChanged -= Retag;+ row.PointerEntered += (_, _) =>+ {+ var meta = item.Sample?.Describe() ?? "";+ var parts = new List<string> { item.Name };+ if (meta.Length > 0) parts.Add(meta);+ if (tip.Length > 0) parts.Add(tip);+ ToolTip.SetTip(row, string.Join(" · ", parts));+ };+ }return row;}+ // "124 · Am", a hit's note, or (until analysed, or with nothing to say) the file type.+ private string SampleTag(BrowserItem item)+ {+ var t = item.Sample?.Tag ?? "";+ if (t.Length > 0) return t;+ return (_settings?.Current.BrowserShowTypeTags ?? true) ? RowTag(item) : "";+ }+/// <summary>Lays out one index row. A Grid cannot express the priority this row needs:/// the name is the thing being read, so it takes the space it wants first and the type/// tag lives on whatever is left — an Auto tag column would instead trim every long@@ -975,6 +1039,14 @@ public sealed class BrowserView : UserControlif (_settings is not null) { _settings.Current.BrowserFavoritesFirst = v; _settings.Save(); }RefreshCounts();}));+ if (_active == FilesTab && _settings is not null)+ {+ // What happens when a sample lands on the arrangement.+ var s = _settings;+ flyout.Items.Add(new Separator());+ flyout.Items.Add(CheckItem("Warp loops to project tempo", s.Current.SamplesWarpLoops, v => { s.Current.SamplesWarpLoops = v; s.Save(); }));+ flyout.Items.Add(CheckItem("Transpose to project key", s.Current.SamplesMatchKey, v => { s.Current.SamplesMatchKey = v; s.Save(); }));+ }flyout.Items.Add(new Separator());var editTags = new MenuItem { Header = "Edit tags…" };editTags.Click += (_, _) => EditTagsRequested?.Invoke(null);@@ -1151,6 +1223,110 @@ public sealed class BrowserView : UserControlif (flyout.Items.Count > 0) flyout.ShowAt(_overflowChip);}+ // --- Files: sample filter chips ------------------------------------------++ private BrowserItem? _chipsAnchor; // the state the chips were last drawn for+ private SampleFilter? _chipsFilter;++ private void RebuildSampleChips()+ {+ _sampleChips.Children.Clear();+ if (_vm is null || !_vm.HasSampleIndex) return;+ var f = _vm.SampleFilter;+ _chipsAnchor = _vm.SimilarAnchor;+ _chipsFilter = f;+ if (_vm.SimilarAnchor is { } anchor)+ {+ string stem = System.IO.Path.GetFileNameWithoutExtension(anchor.Name);+ if (stem.Length > 18) stem = stem[..17] + "…";+ var like = MakeChip($"Like {stem}", null, true, () => { _vm.ClearSimilar(); RebuildSampleChips(); RefreshCounts(); });+ ToolTip.SetTip(like, $"Sounds like {anchor.Name}, closest first — click to go back to all samples");+ _sampleChips.Children.Add(like);+ }+ _sampleChips.Children.Add(MakeChip("Loops", null, f.Kind == SampleKind.Loop,+ () => SetSampleFilter(f with { Kind = f.Kind == SampleKind.Loop ? SampleKind.Unknown : SampleKind.Loop })));+ _sampleChips.Children.Add(MakeChip("One-shots", null, f.Kind == SampleKind.OneShot,+ () => SetSampleFilter(f with { Kind = f.Kind == SampleKind.OneShot ? SampleKind.Unknown : SampleKind.OneShot })));+ ChipBorder? bpm = null, key = null;+ bpm = MakeChip(f.HasBpm ? f.BpmCaption + "\u2009BPM" : "BPM", null, f.HasBpm, () => ShowBpmFilter(bpm!));+ key = MakeChip(f.Key?.Long ?? "Key", null, f.Key is not null, () => ShowKeyFilter(key!));+ ToolTip.SetTip(bpm, "Filter by tempo");+ ToolTip.SetTip(key, "Filter by key — a key also shows its relative (A minor ↔ C major)");+ _sampleChips.Children.Add(bpm);+ _sampleChips.Children.Add(key);+ }++ private void SetSampleFilter(SampleFilter f)+ {+ if (_vm is null) return;+ _vm.SampleFilter = f;+ RebuildSampleChips();+ RefreshCounts();+ }++ // Min / max fields that filter as you type, plus "around the project tempo" (±5 %, what+ // warps without audible artefacts) and a reset.+ private void ShowBpmFilter(Control anchor)+ {+ if (_vm is null) return;+ var f = _vm.SampleFilter;+ var flyout = new Flyout { Placement = PlacementMode.BottomEdgeAlignedLeft };+ TextBox Field(double v, string hint) => new()+ {+ Classes = { "field" }, Width = 64, Watermark = hint, FontSize = 12,+ Text = v > 0 ? SampleInfo.FormatBpm(v) : "",+ };+ var min = Field(f.BpmMin, "min");+ var max = Field(f.BpmMax, "max");+ static double Parse(string? s)+ => double.TryParse((s ?? "").Trim().Replace(',', '.'), System.Globalization.NumberStyles.Float,+ System.Globalization.CultureInfo.InvariantCulture, out var v) && v is > 0 and < 1000 ? v : 0;+ void Apply() => SetSampleFilter(_vm.SampleFilter with { BpmMin = Parse(min.Text), BpmMax = Parse(max.Text) });+ min.TextChanged += (_, _) => Apply();+ max.TextChanged += (_, _) => Apply();+ var dash = new TextBlock { Text = "–", VerticalAlignment = VerticalAlignment.Center };+ dash.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");+ var unit = new TextBlock { Text = "BPM", Classes = { "Caption" }, VerticalAlignment = VerticalAlignment.Center };+ var fields = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { min, dash, max, unit } };++ var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };+ if (ProjectTempo?.Invoke() is > 0 and var tempo)+ {+ var near = new Button { Content = $"Project tempo ±5\u2009%", Classes = { "ghost" } };+ ToolTip.SetTip(near, $"Loops within 5\u2009% of {SampleInfo.FormatBpm(tempo)}\u2009BPM warp to it cleanly");+ near.Click += (_, _) =>+ {+ min.Text = SampleInfo.FormatBpm(Math.Floor(tempo * 0.95));+ max.Text = SampleInfo.FormatBpm(Math.Ceiling(tempo * 1.05));+ };+ actions.Children.Add(near);+ }+ var any = new Button { Content = "Any tempo", Classes = { "ghost" } };+ any.Click += (_, _) => { flyout.Hide(); SetSampleFilter(_vm.SampleFilter with { BpmMin = 0, BpmMax = 0 }); };+ actions.Children.Add(any);++ flyout.Content = new StackPanel { Spacing = 8, Margin = new Thickness(2), Children = { fields, actions } };+ flyout.ShowAt(anchor);+ }++ private void ShowKeyFilter(Control anchor)+ {+ if (_vm is null) return;+ var extras = new List<(string, MusicalKey)>();+ if (ProjectKey?.Invoke() is { } pk) extras.Add(($"Project key · {pk.Short}", pk));+ KeyPicker.Show(anchor, _vm.SampleFilter.Key, "Any key", k => SetSampleFilter(_vm.SampleFilter with { Key = k }), extras);+ }++ private async void ShowSimilar(BrowserItem item)+ {+ if (_vm is null) return;+ _statusText.Text = $"Finding sounds like {item.Name}…";+ int n = await _vm.ShowSimilarAsync(item);+ RebuildSampleChips();+ RefreshCounts();+ if (n == 0) _statusText.Text = "Couldn't analyse that sample";+ }+private void ToggleFilter(BrowserFilter mode, string tagId){if (_vm is null) return;@@ -1342,6 +1518,16 @@ public sealed class BrowserView : UserControlswitch (item.Kind){+ case BrowserItemKind.Sample when _vm?.HasSampleIndex == true:+ {+ var similar = new MenuItem { Header = "Show similar sounds" };+ similar.Click += (_, _) => ShowSimilar(item);+ var reveal = new MenuItem { Header = "Reveal in Finder" };+ reveal.Click += (_, _) => RevealRequested?.Invoke(item);+ flyout.Items.Add(similar);+ flyout.Items.Add(reveal);+ return flyout;+ }case BrowserItemKind.Sample:case BrowserItemKind.MidiFile:// A saved preset file on disk. Synthetic rows (factory presets, drum kits)diff --git a/src/managed/Nota.App/Controls/KeyPicker.cs b/src/managed/Nota.App/Controls/KeyPicker.csnew file mode 100644index 00000000..d2d9e8d2--- /dev/null+++ b/src/managed/Nota.App/Controls/KeyPicker.cs@@ -0,0 +1,68 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The 24-key picker: a MAJOR and a MINOR row of twelve segments, plus a way out ("No key"+// for the project, "Any key" for the browser filter). Shared by the transport's KEY cell+// and the Files tab's key filter so both read the same.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Layout;+using Nota.Application.Samples;++namespace Nota.App;++internal static class KeyPicker+{+ /// <summary>Opens the picker under <paramref name="anchor"/>. <paramref name="pick"/> gets the+ /// chosen key, or null for <paramref name="noneLabel"/>; <paramref name="extras"/> are+ /// shortcut buttons (label, key) shown before it — "Project key · Am".</summary>+ public static void Show(Control anchor, MusicalKey? current, string noneLabel, Action<MusicalKey?> pick,+ IReadOnlyList<(string Label, MusicalKey Key)>? extras = null)+ {+ var flyout = new Flyout { Placement = PlacementMode.BottomEdgeAlignedLeft };+ flyout.Content = Build(current, noneLabel, k => { flyout.Hide(); pick(k); }, extras);+ flyout.ShowAt(anchor);+ }++ /// <summary>The picker's content alone (what <see cref="Show"/> puts in its flyout).</summary>+ internal static Control Build(MusicalKey? current, string noneLabel, Action<MusicalKey?> choose,+ IReadOnlyList<(string Label, MusicalKey Key)>? extras = null)+ {+ var panel = new StackPanel { Spacing = 6, Margin = new Thickness(2) };+ foreach (var mode in new[] { KeyMode.Major, KeyMode.Minor })+ {+ panel.Children.Add(new TextBlock { Text = mode == KeyMode.Major ? "MAJOR" : "MINOR", Classes = { "SectionLabel" } });+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };+ for (int t = 0; t < 12; t++)+ {+ var key = new MusicalKey(t, mode);+ var b = new ToggleButton+ {+ Content = key.Short, Classes = { "seg" }, IsChecked = current == key,+ Width = 34, Padding = new Thickness(0), HorizontalContentAlignment = HorizontalAlignment.Center,+ };+ ToolTip.SetTip(b, key.Long);+ b.Click += (_, _) => choose(key);+ row.Children.Add(b);+ }+ panel.Children.Add(new Border { Classes = { "segmented" }, Child = row, HorizontalAlignment = HorizontalAlignment.Left });+ }++ var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 2, 0, 0) };+ foreach (var (label, key) in extras ?? Array.Empty<(string, MusicalKey)>())+ {+ var b = new Button { Content = label, Classes = { "ghost" } };+ b.Click += (_, _) => choose(key);+ actions.Children.Add(b);+ }+ var none = new Button { Content = noneLabel, Classes = { "ghost" } };+ none.Click += (_, _) => choose(null);+ actions.Children.Add(none);+ panel.Children.Add(actions);+ return panel;+ }+}diff --git a/src/managed/Nota.App/MainWindow.AudioImport.cs b/src/managed/Nota.App/MainWindow.AudioImport.csindex 4258db90..346ccb0b 100644--- a/src/managed/Nota.App/MainWindow.AudioImport.cs+++ b/src/managed/Nota.App/MainWindow.AudioImport.cs@@ -6,8 +6,10 @@// 1. the target track appears at once (translucent, "Processing…") with a placeholder clip;// 2. a worker decodes the file block by block — the placeholder's waveform fills in as it// goes (instantly when the analysis cache already knows the file) — then detects tempo;-// 3. back on the UI thread the decoded buffer is placed (no disk I/O) and auto-warped with-// the measured tempo, the warp cache building in small steps so the UI keeps drawing;+// 3. back on the UI thread the decoded buffer is placed (no disk I/O) and — if the sample+// index calls it a loop (or a long take with a tempo) — warped to the project tempo, and+// optionally transposed to the project key; the warp cache builds in small steps so the+// UI keeps drawing. A one-shot is never warped;// 4. the track turns opaque and is selected.using System;@@ -15,7 +17,9 @@ using System.Diagnostics;using System.Threading;using System.Threading.Tasks;using Avalonia.Threading;+using Microsoft.Extensions.DependencyInjection;using Nota.Application;+using Nota.Application.Samples;using Nota.Infrastructure;namespace Nota.App;@@ -23,6 +27,7 @@ namespace Nota.App;public partial class MainWindow{private readonly AudioAnalysisCache _analysis = new();+ private ISampleIndex SampleIndex => App.Services.GetRequiredService<ISampleIndex>();// Bumped on New/Open: an import still running belongs to the previous graph (its track id// may now name a different track), so it bows out instead of placing its clip.@@ -74,7 +79,7 @@ public partial class MainWindowtry{string? project = _projectPath;- (job, double bpm) = await Task.Run(() => DecodeImport(path, project, progress, cts.Token));+ (job, double bpm, SampleInfo? info) = await Task.Run(() => DecodeImport(path, project, progress, cts.Token));if (job is null) { _vm.StatusText = $"Failed to load {name}"; return; }if (!Alive()) { _vm.StatusText = $"Import of {name} cancelled"; return; }@@ -84,12 +89,24 @@ public partial class MainWindowplaced = true;pending.ClipPlaced = true;- if (bpm > 0)+ var settings = App.Services.GetRequiredService<ISettingsService>().Current;+ double warpBpm = WarpTempoFor(info, bpm, settings.SamplesWarpLoops);+ // Only material that plays in a key moves to it: a hit (an 808 included) would be+ // varispeeded — shorter, brighter, another sound — so one-shots keep their pitch.+ int semis = settings.SamplesMatchKey && _vm.Transport.Key is { } projectKey+ && info is { Kind: not SampleKind.OneShot, Key: { } sampleKey }+ ? sampleKey.SemitonesTo(projectKey) : 0;+ if (warpBpm > 0 || semis != 0){- // Warp with the tempo the worker measured, deferring the (heavy) stretch so it- // can be built in slices below instead of in one UI-thread block.+ // Warp with the tempo the index / worker measured, deferring the (heavy) stretch+ // so it can be built in slices below instead of in one UI-thread block. The+ // transpose rides the same deferred build (a warped clip keeps its length).Engine.SetDeferWarpBuild(true);- try { bpm = Engine.AutoWarpClipAtBpm(t, clip, bpm); }+ try+ {+ if (warpBpm > 0) warpBpm = Engine.AutoWarpClipAtBpm(t, clip, warpBpm);+ if (semis != 0) Engine.SetClipPitch(t, clip, semis);+ }finally { Engine.SetDeferWarpBuild(false); }Timeline.Refresh();await BuildImportWarpAsync(name, Alive);@@ -98,9 +115,7 @@ public partial class MainWindowTimeline.RemovePendingImport(pending);Timeline.Select(t, clip); // the finished import becomes the active track- _vm.StatusText = bpm > 0- ? string.Format(NotaNum.Culture, "Imported {0} · warped to tempo ({1:0.0} BPM)", name, bpm)- : $"Imported {name}";+ _vm.StatusText = ImportedText(name, info, warpBpm, semis);}catch (OperationCanceledException){@@ -121,15 +136,42 @@ public partial class MainWindow}}+ // The tempo to warp a dropped sample to (0 = leave it unwarped). A one-shot never warps;+ // a loop warps at the tempo the index settled (its name, or its length) unless the user+ // turned that off; a long take warps at its heard tempo, as imports always have. With no+ // index entry (the file couldn't be analysed) the worker's measured tempo decides.+ private static double WarpTempoFor(SampleInfo? info, double measured, bool warpLoops) => info switch+ {+ null => measured,+ { Kind: SampleKind.OneShot } => 0,+ { Kind: SampleKind.Loop } => warpLoops ? info.Bpm : 0,+ _ => info.Bpm,+ };++ private string ImportedText(string name, SampleInfo? info, double warpedBpm, int semis)+ {+ var parts = new System.Collections.Generic.List<string> { $"Imported {name}" };+ double project = (double)_vm!.Transport.Bpm;+ if (warpedBpm > 0)+ parts.Add(info is { Kind: SampleKind.Loop, Bpm: > 0 } && Math.Abs(info.Bpm - project) > 0.01+ ? $"loop warped {SampleInfo.FormatBpm(info.Bpm)} \u2192 {SampleInfo.FormatBpm(project)}\u2009BPM"+ : string.Format(NotaNum.Culture, "warped to tempo ({0:0.0}\u2009BPM)", warpedBpm));+ else if (info?.Kind == SampleKind.OneShot) parts.Add("one-shot, not warped");+ if (semis != 0 && _vm.Transport.Key is { } k)+ parts.Add($"transposed {(semis > 0 ? "+" : "\u2212")}{Math.Abs(semis)}\u2009st to {k.Long}");+ return string.Join(" · ", parts);+ }+// Worker thread: fingerprint + cache lookup, block-wise decode with throttled waveform- // ticks, tempo detection, cache write. Returns (null, 0) when the file can't be decoded.- private (IAudioImport? job, double bpm) DecodeImport(string path, string? project,- IProgress<ImportTick> progress, CancellationToken ct)+ // ticks, analysis (via the sample index), cache write. Returns (null, 0, null) when the+ // file can't be decoded.+ private (IAudioImport? job, double bpm, SampleInfo? info) DecodeImport(string path, string? project,+ IProgress<ImportTick> progress, CancellationToken ct){string? key = AudioAnalysisCache.Fingerprint(path);var cached = key is null ? null : _analysis.TryLoad(key, project);var job = Engine.OpenAudioImport(path);- if (job is null) return (null, 0);+ if (job is null) return (null, 0, null);try{if (cached is not null) job.SeedPeakTable(cached.PeakTable);@@ -148,16 +190,22 @@ public partial class MainWindow{ct.ThrowIfCancellationRequested();int r = job.Step(ImportBlockFrames);- if (r < 0) { job.Dispose(); return (null, 0); }+ if (r < 0) { job.Dispose(); return (null, 0, null); }if (r == 0) break;if (sinceTick.ElapsedMilliseconds >= ImportTickMs) { Report(); sinceTick.Restart(); }}total = job.TotalFrames; // a truncated file reports fewer frames once doneReport();- double bpm = cached?.Bpm ?? job.DetectTempo();+ // The library index usually knows a sample already (the Files tab scanned it); a file+ // from elsewhere is analysed now — from the buffer just decoded — and remembered.+ var index = SampleIndex;+ var info = index.Get(path);+ SampleAnalysis? measured = null;+ if (info is null && (measured = job.Analyze()) is not null) info = index.Store(path, measured);+ double bpm = cached?.Bpm ?? measured?.Bpm ?? job.DetectTempo();if (key is not null && cached is null) _analysis.Store(key, new AudioAnalysis(job.ReadPeakTable(), bpm), project);- return (job, bpm);+ return (job, bpm, info);}catch{diff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.csindex 89c2b93e..9073dab5 100644--- a/src/managed/Nota.App/MainWindow.Files.cs+++ b/src/managed/Nota.App/MainWindow.Files.cs@@ -172,6 +172,7 @@ public partial class MainWindow_vm.Transport.LoopOn = false;_vm.Transport.TimeSigNumerator = 4;_vm.Transport.TimeSigDenominator = 4;+ _vm.Transport.KeyCode = -1;_projectPath = null;_learn?.Clear(); // start with a clean MIDI-map for the new projectTimeline.ClearSections(); // …and a clean song structure@@ -228,6 +229,7 @@ public partial class MainWindow_vm.Transport.LoopOn = result.Transport.LoopOn;_vm.Transport.TimeSigNumerator = result.Transport.TimeSigNumerator;_vm.Transport.TimeSigDenominator = result.Transport.TimeSigDenominator;+ _vm.Transport.KeyCode = result.Transport.Key;_projectPath = dir;_learn?.LoadMappings(dir); // MIDI-learn mappings ride in the bundle sidecar_modular?.LoadLayout(dir); // modular-editor node/island positions (sidecar)diff --git a/src/managed/Nota.App/MainWindow.Recovery.cs b/src/managed/Nota.App/MainWindow.Recovery.csindex 17a7661d..16ea0c43 100644--- a/src/managed/Nota.App/MainWindow.Recovery.cs+++ b/src/managed/Nota.App/MainWindow.Recovery.cs@@ -26,7 +26,7 @@ public partial class MainWindowprivate TransportState TransportSnapshot()=> new((double)_vm!.Transport.Bpm, _vm.Transport.MasterVolume,_vm.Transport.MetronomeOn, _vm.Transport.LoopOn,- _vm.Transport.TimeSigNumerator, _vm.Transport.TimeSigDenominator);+ _vm.Transport.TimeSigNumerator, _vm.Transport.TimeSigDenominator, _vm.Transport.KeyCode);private void OnAutosaveTick(){diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axamlindex 66dee2bb..e42f5b11 100644--- a/src/managed/Nota.App/MainWindow.axaml+++ b/src/managed/Nota.App/MainWindow.axaml@@ -195,6 +195,14 @@</StackPanel><TextBlock Classes="CellLabel" Text="SIG" HorizontalAlignment="Center"/></StackPanel>+ <!-- Project key: loops dropped in can be transposed to it -->+ <Button x:Name="KeyChip" Classes="cell" Click="OnPickProjectKey" ToolTip.Tip="Set the project key — samples can be transposed to it">+ <StackPanel Spacing="2">+ <TextBlock x:Name="KeyLabel" Classes="Mono" Text="—" FontSize="14" LineHeight="16"+ MinWidth="30" TextAlignment="Center" HorizontalAlignment="Center" Foreground="{DynamicResource Brush.TextTertiary}"/>+ <TextBlock Classes="CellLabel" Text="KEY" HorizontalAlignment="Center"/>+ </StackPanel>+ </Button><!-- Clip snap grid: click to cycle --><Button x:Name="SnapChip" Classes="cell" Click="OnCycleSnap" ToolTip.Tip="Cycle the clip snap grid"><StackPanel Spacing="2">diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 61867573..6fabdce5 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -234,6 +234,7 @@ public partial class MainWindow : WindowmasterVol.Value = vm.Transport.MasterVolume;else if (e.PropertyName == nameof(vm.Transport.TimeSigNumerator)) tsNum.Value = vm.Transport.TimeSigNumerator;else if (e.PropertyName == nameof(vm.Transport.TimeSigDenominator)) tsDen.Value = vm.Transport.TimeSigDenominator;+ else if (e.PropertyName == nameof(vm.Transport.KeyCode)) ShowProjectKey();};var cpuGreen = (IBrush?)NotaPalette.Success;@@ -289,6 +290,11 @@ public partial class MainWindow : WindowTimeline.ClipLabels = (ClipLabelMode)Math.Clamp(vm.Settings.Current.ArrangementClipLabels, 0, 2);Timeline.ShowSections = vm.Settings.Current.ArrangementShowSections;Browser.SetViewModel(vm.Browser);+ Browser.ProjectTempo = () => (double)vm.Transport.Bpm; // the Files filter's "project" shortcuts+ Browser.ProjectKey = () => vm.Transport.Key;+ // The library index analyses on worker threads; rows pick up their tempo / key tags on the UI thread.+ App.Services.GetRequiredService<ISampleIndex>().Changed +=+ () => Avalonia.Threading.Dispatcher.UIThread.Post(vm.Browser.OnSampleIndexChanged, Avalonia.Threading.DispatcherPriority.Background);Browser.ItemActivated += OnBrowserItemActivated;Browser.Preview.Attach(vm.Engine, vm.Settings, App.Services.GetRequiredService<IPresetAudition>());Browser.Preview.StatusChanged += msg => { if (_vm is not null) _vm.StatusText = msg; };@@ -520,6 +526,24 @@ public partial class MainWindow : Window(0.25, "1/16"), (0.5, "1/8"), (1.0, "1/4"), (2.0, "1/2"), (4.0, "1 bar"),};private int _snapIndex = 2; // 1/4+ private void OnPickProjectKey(object? sender, RoutedEventArgs e)+ {+ if (_vm is null) return;+ KeyPicker.Show(KeyChip, _vm.Transport.Key, "No key", k =>+ {+ _vm.Transport.KeyCode = k?.Code ?? -1;+ _vm.StatusText = k is { } key ? $"Project key: {key.Long}" : "No project key";+ });+ }++ // The KEY cell reads "—" in tertiary ink until a key is set.+ private void ShowProjectKey()+ {+ var k = _vm?.Transport.Key;+ KeyLabel.Text = k?.Short ?? "\u2014";+ KeyLabel.BindResource(TextBlock.ForegroundProperty, k is null ? "Brush.TextTertiary" : "Brush.TextPrimary");+ }+private void OnCycleSnap(object? sender, RoutedEventArgs e){_snapIndex = (_snapIndex + 1) % SnapSteps.Length;diff --git a/src/managed/Nota.App/PreferencesWindow.Samples.cs b/src/managed/Nota.App/PreferencesWindow.Samples.csindex 642380d1..89045bba 100644--- a/src/managed/Nota.App/PreferencesWindow.Samples.cs+++ b/src/managed/Nota.App/PreferencesWindow.Samples.cs@@ -329,8 +329,11 @@ public sealed partial class PreferencesWindowtry{await _samples.InstallAsync(p, progress, job.Token);+ // Analyse the new pack first, so its tempo / key tags and filters work at once.+ if (_samples.Installed.FirstOrDefault(i => i.Id == p.Id) is { } installed)+ App.Services.GetRequiredService<ISampleIndex>().Prioritize(installed.Path);_main?.Browser.RebuildSamples();- SetStoreResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab.", sticky: false);+ SetStoreResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab, where it is being analysed for tempo and key.", sticky: false);}catch (OperationCanceledException){diff --git a/src/managed/Nota.Application/Ports/IProjectStore.cs b/src/managed/Nota.Application/Ports/IProjectStore.csindex b3201025..8cfa0c33 100644--- a/src/managed/Nota.Application/Ports/IProjectStore.cs+++ b/src/managed/Nota.Application/Ports/IProjectStore.cs@@ -4,9 +4,10 @@namespace Nota.Application;/// <summary>Transport values the App owns, passed across the persistence boundary-/// so the on-disk model stays UI-framework-free.</summary>+/// so the on-disk model stays UI-framework-free. <paramref name="Key"/> is the project key+/// as a <see cref="Samples.MusicalKey.Code"/> (−1 = none set).</summary>public readonly record struct TransportState(double Bpm, double MasterVolume, bool MetronomeOn, bool LoopOn,- int TimeSigNumerator = 4, int TimeSigDenominator = 4);+ int TimeSigNumerator = 4, int TimeSigDenominator = 4, int Key = -1);/// <summary>Outcome of loading a project: the transport to restore + any items that/// were downgraded/skipped (referential-integrity warnings).</summary>diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.csindex 81349c5f..befb38fb 100644--- a/src/managed/Nota.Application/Settings.cs+++ b/src/managed/Nota.Application/Settings.cs@@ -73,6 +73,15 @@ public sealed class Settings/// <summary>Browser player: the well shows the live spectrum instead of the waveform.</summary>public bool BrowserPreviewSpectrum { get; set; }+ // --- smart samples (Files tab ⋮ menu) ------------------------------------+ /// <summary>A loop dropped on the arrangement is warped to the project tempo from the tempo+ /// the sample index knows; a one-shot never is.</summary>+ public bool SamplesWarpLoops { get; set; } = true;+ /// <summary>A loop with a known key dropped on the arrangement is transposed to the project+ /// key (the shorter way, ±6 semitones; one-shots keep their pitch). Off by default — it+ /// changes the sound.</summary>+ public bool SamplesMatchKey { get; set; }+// --- arrangement view options (View menu) --------------------------------/// <summary>How many clips print their name on the lane: 0 every clip, 1 the head of each/// run (default — a repeated pattern then reads as one block), 2 none.</summary>diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex 5403d4ea..8c9be15d 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -65,6 +65,9 @@ public sealed class TransportDtopublic bool LoopOn { get; set; }public int TimeSigNumerator { get; set; } = 4;public int TimeSigDenominator { get; set; } = 4;+ /// <summary>The project key ("Am", "Eb"); null = none set. Loops dropped in can be+ /// transposed to it.</summary>+ public string? Key { get; set; }[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex bc32eca7..b9328857 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -65,6 +65,7 @@ public sealed class ProjectServiceLoopOn = transport.LoopOn,TimeSigNumerator = transport.TimeSigNumerator,TimeSigDenominator = transport.TimeSigDenominator,+ Key = Nota.Application.Samples.MusicalKey.FromCode(transport.Key)?.Short,},};diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectStore.csindex 0ce18177..c74925d5 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs@@ -24,7 +24,8 @@ public sealed class ProjectStore : IProjectStorevar transport = new TransportState(doc.Transport.Bpm, doc.Transport.MasterVolume,doc.Transport.MetronomeOn, doc.Transport.LoopOn,- doc.Transport.TimeSigNumerator, doc.Transport.TimeSigDenominator);+ doc.Transport.TimeSigNumerator, doc.Transport.TimeSigDenominator,+ Nota.Application.Samples.MusicalKey.Parse(doc.Transport.Key)?.Code ?? -1);return new ProjectLoadResult(transport, warnings) { MissingPlugins = MissingPlugins(doc) };}diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.csindex c4d5a9e4..4206bacf 100644--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs@@ -7,9 +7,11 @@// it (handled by MainWindow).using System.Collections.ObjectModel;+using System.ComponentModel;using System.IO;using CommunityToolkit.Mvvm.ComponentModel;using Nota.Application;+using Nota.Application.Samples;namespace Nota.Presentation;@@ -26,8 +28,25 @@ public enum BrowserItemKind/// <summary>Active library filter for the device tabs (Instr / FX / MIDI).</summary>public enum BrowserFilter { None, Favorites, Tag }-public sealed class BrowserItem+public sealed class BrowserItem : INotifyPropertyChanged{+ private SampleInfo? _sample;++ public event PropertyChangedEventHandler? PropertyChanged;++ /// <summary>What the sample index knows about a Files row (tempo, key, loop or one-shot);+ /// null until it has been analysed. Fills in live as the background scan runs.</summary>+ public SampleInfo? Sample+ {+ get => _sample;+ set+ {+ if (ReferenceEquals(_sample, value)) return;+ _sample = value;+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Sample)));+ }+ }+public required string Name { get; init; }public required BrowserItemKind Kind { get; init; }public int CatalogIndex { get; init; } = -1; // plugins@@ -91,6 +110,14 @@ public sealed partial class BrowserViewModel : ObservableObjectprivate readonly IDrumKits? _kits;private readonly ISettingsService? _settings;private readonly IBrowserLibrary? _library;+ private readonly ISampleIndex? _index;++ // Files tab: every audio leaf (for live tag updates), the sample filter, and "similar+ // sounds" mode — a flat list of the closest samples to an anchor, in place of the tree.+ private readonly List<BrowserItem> _sampleLeaves = new();+ private SampleFilter _sampleFilter = SampleFilter.Empty;+ private BrowserItem? _similarAnchor;+ private List<BrowserItem> _similarRows = new();// Full trees (top-level devices/plugins with factory-preset children); the public// Instruments/Effects collections are the flattened, filtered *visible* projection.@@ -132,8 +159,9 @@ public sealed partial class BrowserViewModel : ObservableObjectpublic BrowserViewModel(IPluginCatalog catalog, IPresetLibrary presets, IFactoryPresets factory,ISettingsService? settings = null, IBrowserLibrary? library = null,- IDrumKits? kits = null)+ IDrumKits? kits = null, ISampleIndex? sampleIndex = null){+ _index = sampleIndex;_catalog = catalog;_presets = presets;_factory = factory;@@ -523,9 +551,11 @@ public sealed partial class BrowserViewModel : ObservableObjectpublic void RebuildSamples(){_sampleTree.Clear();+ _sampleLeaves.Clear();Samples.Clear();if (_settings is null) return;var root = _settings.ResolvedSamplesFolder();+ _index?.Watch(root); // analyses whatever it doesn't know yet, in the background// Folder nodes keyed by absolute directory path (reused while placing files).var folders = new Dictionary<string, BrowserItem>(StringComparer.OrdinalIgnoreCase);@@ -537,20 +567,103 @@ public sealed partial class BrowserViewModel : ObservableObject{var dir = Path.GetDirectoryName(path) ?? root;var parentChildren = GetOrCreateFolder(root, dir, folders, out int depth);- parentChildren.Add(new BrowserItem+ var leaf = new BrowserItem{Name = Path.GetFileName(path),Kind = Nota.Application.Midi.MidiFileReader.IsMidiFile(path) ? BrowserItemKind.MidiFile : BrowserItemKind.Sample,Sub = "",Path = path,Depth = depth,- });+ };+ if (leaf.Kind == BrowserItemKind.Sample) { leaf.Sample = _index?.Get(path); _sampleLeaves.Add(leaf); }+ parentChildren.Add(leaf);}AppendKitFolders();SortSampleTree(_sampleTree);+ _similarAnchor = null; // the anchor row is gone; its list would point at stale rows+ _similarRows.Clear();RebuildSampleVisible();}+ // --- smart samples: tags, filter, similar ------------------------------------------++ /// <summary>The Files tab's sample filter ("loops · 120–128 · A minor").</summary>+ public SampleFilter SampleFilter+ {+ get => _sampleFilter;+ set { _sampleFilter = value ?? SampleFilter.Empty; RebuildSampleVisible(); }+ }++ /// <summary>The sample "similar sounds" is showing neighbours of, or null for the tree.</summary>+ public BrowserItem? SimilarAnchor => _similarAnchor;++ /// <summary>Files analysed / found by the running library scan; Total 0 when idle.</summary>+ public (int Done, int Total) IndexProgress => _index?.Progress ?? (0, 0);++ public bool HasSampleIndex => _index is not null;++ /// <summary>Raised after <see cref="OnSampleIndexChanged"/> so the view can refresh its status line.</summary>+ public event Action? SampleIndexChanged;++ /// <summary>Call on the UI thread when the index reports progress: Files rows pick up their+ /// tags in place (no list reset — the selection and scroll stay), and a filtered or+ /// "similar" list is recomputed only if its rows actually changed.</summary>+ public void OnSampleIndexChanged()+ {+ if (_index is null) return;+ foreach (var leaf in _sampleLeaves) leaf.Sample = _index.Get(leaf.Path);+ if (!_sampleFilter.IsEmpty) RebuildSampleVisible(onlyIfChanged: true);+ SampleIndexChanged?.Invoke();+ }++ /// <summary>Replaces the Files tree with the samples that sound most like+ /// <paramref name="item"/>, closest first. Analyses the anchor first if it must (off the+ /// UI thread). Returns how many were found.</summary>+ public async Task<int> ShowSimilarAsync(BrowserItem item, int count = 50)+ {+ if (_index is null || item.Kind != BrowserItemKind.Sample) return 0;+ var index = _index;+ string path = item.Path;+ var hits = await Task.Run(() => index.Similar(path, count));+ var root = _settings?.ResolvedSamplesFolder();+ _similarRows = hits.Select(h => new BrowserItem+ {+ Name = Path.GetFileName(h.Info.Path),+ Kind = BrowserItemKind.Sample,+ Sub = "",+ Tip = FolderOf(h.Info.Path, root),+ Path = h.Info.Path,+ Depth = 0,+ }).ToList();+ foreach (var r in _similarRows) r.Sample = index.Get(r.Path);+ _similarAnchor = item;+ item.Sample ??= index.Get(path);+ RebuildSampleVisible();+ return _similarRows.Count;+ }++ /// <summary>Back from "similar sounds" to the folder tree.</summary>+ public void ClearSimilar()+ {+ if (_similarAnchor is null) return;+ _similarAnchor = null;+ _similarRows.Clear();+ RebuildSampleVisible();+ }++ private static string FolderOf(string path, string? root)+ {+ var dir = Path.GetDirectoryName(path) ?? "";+ if (root is null) return dir;+ var rel = Path.GetRelativePath(root, dir);+ return rel == "." ? "" : rel.StartsWith("..", StringComparison.Ordinal) ? dir : rel;+ }++ // Files rows the sample filter lets through: audio the index has analysed and that+ // matches; a MIDI file has no tempo or key, so any filter hides it.+ private bool PassesSampleFilter(BrowserItem leaf)+ => leaf.Kind == BrowserItemKind.Sample ? _sampleFilter.Matches(leaf.Sample) : _sampleFilter.IsEmpty;+// The rendered factory kits, as a browsable folder alongside the user's own samples.// They live in Nota's data folder rather than the user's samples folder (they are// regenerable, and they should not appear in a folder the user curates), so the tree@@ -650,7 +763,21 @@ public sealed partial class BrowserViewModel : ObservableObject/// <summary>Flattens the sample folder tree into the visible <see cref="Samples"/>/// collection, honouring expand state and the Files search query.</summary>- private void RebuildSampleVisible() => RebuildTreeVisible(_sampleTree, Samples, _treeQuery[3].Trim());+ private void RebuildSampleVisible(bool onlyIfChanged = false)+ {+ string q = _treeQuery[3].Trim();+ List<BrowserItem> rows;+ if (_similarAnchor is not null)+ rows = _similarRows.Where(r => (q.Length == 0 || Matches(r, q)) && PassesSampleFilter(r)).ToList();+ else+ {+ rows = new List<BrowserItem>();+ Func<BrowserItem, bool>? leafOk = _sampleFilter.IsEmpty ? null : PassesSampleFilter;+ foreach (var node in _sampleTree) FlattenTree(node, q, ancestorMatched: false, rows, leafOk);+ }+ if (onlyIfChanged && rows.SequenceEqual(Samples)) return;+ Samples.ReplaceAll(rows);+ }/// <summary>Flattens the preset tree (category → device → preset) into <see cref="Presets"/>.</summary>private void RebuildPresetVisible() => RebuildTreeVisible(_presetTree, Presets, _treeQuery[4].Trim());@@ -660,34 +787,37 @@ public sealed partial class BrowserViewModel : ObservableObjectprivate void RebuildTreeVisible(List<BrowserItem> roots, BulkObservableCollection<BrowserItem> dst, string q){var rows = new List<BrowserItem>();- foreach (var node in roots) FlattenTree(node, q, ancestorMatched: false, rows);+ foreach (var node in roots) FlattenTree(node, q, ancestorMatched: false, rows, leafOk: null);dst.ReplaceAll(rows);}// Adds `node` (and, for folders, its visible descendants) to `dst`. Returns whether the// node ended up visible. With a query, folders auto-expand and survive only if the folder- // name or some descendant matches; a folder-name hit reveals its whole subtree.- private bool FlattenTree(BrowserItem node, string q, bool ancestorMatched, List<BrowserItem> dst)+ // name or some descendant matches; a folder-name hit reveals its whole subtree. A leaf+ // filter (the Files tab's sample filter) works like a query: folders open to show what+ // passes and drop out when nothing under them does — a folder's name alone never does.+ private bool FlattenTree(BrowserItem node, string q, bool ancestorMatched, List<BrowserItem> dst,+ Func<BrowserItem, bool>? leafOk){if (node.Kind != BrowserItemKind.Folder){- bool show = q.Length == 0 || ancestorMatched || Matches(node, q);+ bool show = (q.Length == 0 || ancestorMatched || Matches(node, q)) && (leafOk?.Invoke(node) ?? true);if (show) dst.Add(node);return show;}bool folderMatched = ancestorMatched || (q.Length > 0 && Matches(node, q));- if (q.Length == 0)+ if (q.Length == 0 && leafOk is null){dst.Add(node);if (node.IsExpanded)- foreach (var c in node.Children) FlattenTree(c, q, ancestorMatched: false, dst);+ foreach (var c in node.Children) FlattenTree(c, q, ancestorMatched: false, dst, leafOk);return true;}int mark = dst.Count;dst.Add(node); // tentative — removed below if nothing under it matches- bool any = folderMatched;+ bool any = folderMatched && leafOk is null;foreach (var c in node.Children)- any |= FlattenTree(c, q, folderMatched, dst);+ any |= FlattenTree(c, q, folderMatched, dst, leafOk);if (!any) { while (dst.Count > mark) dst.RemoveAt(dst.Count - 1); return false; }return true;}diff --git a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.csindex 146aafb0..8466bd59 100644--- a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs@@ -24,6 +24,12 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject[ObservableProperty] private decimal _bpm = 120; // decimal for NumericUpDown[ObservableProperty] private int _timeSigNumerator = 4;[ObservableProperty] private int _timeSigDenominator = 4;+ /// <summary>The project key as a <see cref="Nota.Application.Samples.MusicalKey.Code"/>+ /// (−1 = none). Managed-only: the engine has no use for it; samples dropped in are+ /// transposed to it on request.</summary>+ [ObservableProperty] private int _keyCode = -1;++ public Nota.Application.Samples.MusicalKey? Key => Nota.Application.Samples.MusicalKey.FromCode(KeyCode);[ObservableProperty] private double _masterVolume = 1.0;[ObservableProperty] private string _masterDbText = "0.0\u2009dB";[ObservableProperty] private bool _metronomeOn;diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 737900cd..25f884fb 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -8134,7 +8134,7 @@ Console.WriteLine("-- M7-6a: project save/load --");{ new Nota.Application.AutomationPoint(0, 1.5f), new Nota.Application.AutomationPoint(8, 0.5f) });var transport = new TransportState(140.0, 0.5, MetronomeOn: true, LoopOn: false,- TimeSigNumerator: 7, TimeSigDenominator: 8);+ TimeSigNumerator: 7, TimeSigDenominator: 8, Key: new Nota.Application.Samples.MusicalKey(6, Nota.Application.Samples.KeyMode.Minor).Code);var warnings = new System.Collections.Generic.List<string>();var doc = ProjectService.Capture(src, transport, warnings);Check(warnings.Count == 0, $"no warnings for a built-in-only project ({warnings.Count})");@@ -8146,6 +8146,7 @@ Console.WriteLine("-- M7-6a: project save/load --");Check(loaded.FormatVersion == ProjectService.CurrentFormatVersion, "format version round-trips");Check(Math.Abs(loaded.Transport.Bpm - 140.0) < 1e-9 && loaded.Transport.MetronomeOn, "transport round-trips");Check(loaded.Transport.TimeSigNumerator == 7 && loaded.Transport.TimeSigDenominator == 8, "time signature round-trips (7/8)");+ Check(loaded.Transport.Key == "F#m", $"project key round-trips (F# minor → \"{loaded.Transport.Key}\")");// Replay into a fresh engine and verify the live state.using var dst = new NotaEngine();