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.

88.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// M4.1-C / M7-4 + Phase 3 + the "compact index" refresh (mockup 1a): the left
// browser, an island panel with a 40px icon rail (Instr / FX / MIDI / Files /
// Preset / Proj / Map) down its left edge. Each tab shows one list of single-line
// 24px rows, sectioned into Built-in and Plug-ins with counts; a built-in row shows
// its distinctive word without the "Nota" family name, and the device
// type sits at the right edge as a quiet tag. A search box filters the active list
// live, a ⋮ button holds the view options, chips filter by favorite/tag, a status
// line counts what is on screen, and a pinned preview footer auditions the selection — a
// sample, a preset or a built-in device (list tabs, see PreviewPlayer). Double-clicking an
// item raises ItemActivated. Brushes bind via GetResourceObservable (the control is built
// during MainWindow's XAML load, before it is attached). Rows are drag sources (M7-5).

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.VisualTree;
using Nota.Application;
using Nota.Application.Input;
using Nota.Application.Samples;
using Nota.Presentation;
using Microsoft.Extensions.DependencyInjection;
using Nota.Application.Localization;

namespace Nota.App;

public sealed partial class BrowserView : UserControl
{
    // The browser drag payload. macOS's native drag session requires exactly one
    // pasteboard item per drag image, and Avalonia makes one drag image per data
    // FORMAT while only *native* formats become pasteboard items — an in-process
    // format is never native, so it always mismatches and crashes the NSDragging
    // session. So the drag carries a single native text item (pasteboard filler)
    // and the actual BrowserItem is handed off in-process via this static (the drag
    // is in-process anyway; DoDragDropAsync blocks the UI thread until drop).
    private const string DragSentinel = "nota-browser-item";
    internal static BrowserItem? CurrentDrag { get; private set; }

    /// <summary>True while a browser row is being dragged (used by drop targets).</summary>
    public static bool IsBrowserDrag => CurrentDrag is not null;

    /// <summary>True while the drag is a Modular node (spec 095): only the Modular canvas takes it.</summary>
    public static bool IsModularNodeDrag => CurrentDrag is { Kind: BrowserItemKind.ModularNode };

    /// <summary>True while the drag is an arrangement audio clip pulled out as a sample (it
    /// rides the browser payload, so every sample drop target takes it as-is).</summary>
    public static bool IsClipDrag { get; private set; }

    /// <summary>Drags <paramref name="item"/> as the browser payload from a press elsewhere in
    /// the app. Completes when it's dropped (or cancelled).</summary>
    internal static async Task DragItemAsync(PointerPressedEventArgs press, BrowserItem item, bool fromClip = false)
    {
        // Single native pasteboard item (one format → one drag image → one
        // pasteboard item: macOS is satisfied). The payload rides CurrentDrag.
        var data = new DataTransfer();
        data.Add(DataTransferItem.Create(DataFormat.Text, DragSentinel));
        CurrentDrag = item;
        IsClipDrag = fromClip;
        try { await DragDrop.DoDragDropAsync(press, data, DragDropEffects.Copy); }
        finally { CurrentDrag = null; IsClipDrag = false; }
    }

    // --- external file drops (from Finder / other programs) -----------------
    // Audio extensions Nota can import as a clip / sample; MIDI files (MidiFileReader)
    // import as MIDI clips. Anything else in an external drag is ignored.
    private static readonly HashSet<string> AudioExts = new(StringComparer.OrdinalIgnoreCase)
    { ".wav", ".wave", ".aif", ".aiff", ".flac", ".mp3", ".ogg", ".m4a", ".aac" };

    /// <summary>A drag a sample target should light up for: an internal browser row,
    /// or an external drag that carries file(s). Lenient by design — used in DragOver,
    /// where some backends don't expose the file list yet; the drop re-checks.</summary>
    public static bool IsAcceptableDrag(DragEventArgs e)
        => !DeviceDrag.IsActive   // a device card's drag carries text too, but isn't a file
           && !IsModularNodeDrag  // a Modular node goes on the Modular canvas only (spec 095)
           && (IsBrowserDrag || e.DataTransfer.Contains(DataFormat.File) || HasPathText(e.DataTransfer));

    // A drag that may name files without Avalonia's file list (#300): plain text or a
    // file manager's own URI list. The drop parses it and ignores anything else.
    private static bool HasPathText(IDataTransfer data)
        => data.Formats.Any(f => f.Equals(DataFormat.Text) || UriListFormat(f) is not null);

    private static DataFormat<byte[]>? UriListFormat(DataFormat f)
        => f is DataFormat<byte[]> b && f.Kind == DataFormatKind.Platform
           && DroppedFilePaths.UriListMimeTypes.Contains(f.Identifier) ? b : null;

    /// <summary>Local paths (files or folders) an external drag carries: Avalonia's file
    /// list, or when it has none (some sources / bridges on Linux, #300) the paths parsed
    /// from its text or URI-list formats.</summary>
    internal static List<string> ExternalPaths(DragEventArgs e)
    {
        var paths = new List<string>();
        var data = e.DataTransfer;
        if (data.Contains(DataFormat.File) && data.TryGetFiles() is { } files)
            foreach (var f in files)
                if (f.TryGetLocalPath() is { Length: > 0 } p) paths.Add(p);
        if (paths.Count > 0 || IsBrowserDrag) return paths;
        foreach (var f in data.Formats)
        {
            string? text = f.Equals(DataFormat.Text) ? data.TryGetText()
                         : UriListFormat(f) is { } b ? DroppedFilePaths.Decode(data.TryGetValue(b))
                         : null;
            if (text is null || text == DragSentinel) continue;
            foreach (var p in DroppedFilePaths.Parse(text))
                if ((File.Exists(p) || Directory.Exists(p)) && !paths.Contains(p)) paths.Add(p);
        }
        if (paths.Count == 0)
            App.Services.GetService<ILogSink>()?.Info(
                Loc.F("browser.external_drop_named_no_files", string.Join(", ", data.Formats.Select(f => $"{f.Kind}:{f.Identifier}"))));
        return paths;
    }

    /// <summary>Local paths of the audio / MIDI files carried by an external drag (empty
    /// if none / not a file drag).</summary>
    private static List<string> ExternalFiles(DragEventArgs e)
        => ExternalPaths(e).Where(p => AudioExts.Contains(System.IO.Path.GetExtension(p))
                                       || Nota.Application.Midi.MidiFileReader.IsMidiFile(p)).ToList();

    /// <summary>The items a drop should load: the internal browser item (any kind), or
    /// one synthesized Sample / MidiFile item per external file. Empty when there's nothing
    /// we can use (e.g. an unsupported external file). Callers that take one use [0].</summary>
    public static IReadOnlyList<BrowserItem> DroppedItems(DragEventArgs e)
    {
        if (CurrentDrag is { } item) return new[] { item };
        if (DeviceDrag.IsActive) return Array.Empty<BrowserItem>();   // a device card, not files
        var list = new List<BrowserItem>();
        foreach (var p in ExternalFiles(e))
            list.Add(new BrowserItem
            {
                Name = System.IO.Path.GetFileNameWithoutExtension(p),
                Kind = Nota.Application.Midi.MidiFileReader.IsMidiFile(p) ? BrowserItemKind.MidiFile : BrowserItemKind.Sample,
                Path = p,
            });
        return list;
    }

    private BrowserItem? _pressedItem;
    private Point _pressPoint;
    private PointerPressedEventArgs? _pressArgs;

    // Rail icons come from the shared Glyph set (one 16-unit grid, one stroke), so they keep
    // the same weight next to each other. A local Foreground would outrank the rail's
    // active/inactive styles, so RailIcon only sets one where no style paints it.
    private static Glyph RailIcon(GlyphKind kind, double size, string? inkToken = null)
    {
        var g = new Glyph(kind, size);
        if (inkToken is not null) g.BindResource(Glyph.ForegroundProperty, inkToken);
        return g;
    }

    private const int TabCount = 10;  // Instr / FX / MIDI / Files / Preset / Proj / Map / History / Track / Modular
    private const int EffectsTab = 1; // Audio effects
    private const int FilesTab = 3;   // samples: the player auditions the file
    private const int PresetsTab = 4; // Instr / FX / MIDI / Files / Presets carry the player
    private const int MapTab = 6;     // MIDI-learn mappings — hosts a MidiMapView, not a list
    private const int HistoryTab = 7; // the open project's versions — hosts a HistoryView
    private const int InspectorTab = 8; // the selected track's settings — hosts a TrackInspectorView
    // Modular-only nodes (spec 095): a flat list on the rail after MIDI effects, shown only
    // while Modular is the view. The index is last so the others keep theirs.
    private const int ModularTab = 9;
    private readonly BrowserTabMemory _tabMemory = new(0, ModularTab);
    private static bool IsCustomTab(int index) => index is MapTab or HistoryTab or InspectorTab;
    private const double RowH = 30;   // single-line index row (style guide: browser rows 30)
    private const double GroupRowH = 30;

    private readonly ListBox[] _pages;
    private readonly Border[] _tabs;
    private readonly ObservableCollection<BrowserItem>[] _filtered;
    private readonly IReadOnlyList<BrowserItem>?[] _sources = new IReadOnlyList<BrowserItem>?[TabCount];
    private readonly ContentControl _content = new();
    private int _active = -1;
    private BrowserViewModel? _vm;
    private ISettingsService? _settings;
    private MidiMapView? _midiMap;
    private HistoryView? _historyView;
    private Control? _trackInspector;

    // Collapsed: only the icon rail shows; clicking an icon unfolds the browser on that tab.
    private bool _collapsed;
    private readonly Control _body;          // everything right of the rail
    private readonly Border _railDivider;
    private readonly Border _collapseBtn;

    /// <summary>Raised when the browser folds to its rail or unfolds (the host resizes its column).</summary>
    public event Action<bool>? CollapsedChanged;
    public bool IsCollapsed => _collapsed;

    private readonly TextBox _search;
    private readonly TextBlock _matchCount;
    private readonly Border _searchWrap;
    private readonly Border _optionsBtn;

    // Centered empty-state message shown over a tab whose list is empty.
    private readonly TextBlock _emptyText = new();
    private readonly Border _emptyWrap;

    // Pinned preview footer + the status line under it.
    private readonly PreviewPlayer _previewFooter;   // sample / preset auditioner — list tabs
    // The player stays hidden until the user works a list (click, arrow keys) and hides
    // again once a row is dragged or double-clicked onto the project.
    private bool _previewShown;
    private bool _listPointerDown;   // a single click is in progress on a list row
    private readonly Border _statusBar;
    private readonly TextBlock _statusText;

    /// <summary>A row double-clicked (or opened from its menu), with the keys held — ⌥ asks
    /// an instrument for a new track instead of the selected one.</summary>
    public event Action<BrowserItem, KeyModifiers>? ItemActivated;
    /// <summary>The Files tab's sample player (status messages ride its StatusChanged).</summary>
    public PreviewPlayer Preview => _previewFooter;
    /// <summary>Reveal a sample / folder / project in the system file manager.</summary>
    public event Action<BrowserItem>? RevealRequested;

    /// <summary>Map a sample folder into Nota Mosaic presets (the auto-multisample preview).</summary>
    public event Action<BrowserItem>? CreateMultisampleRequested;
    /// <summary>Delete a project bundle (moves to Trash after confirmation).</summary>
    public event Action<BrowserItem>? DeleteProjectRequested;
    /// <summary>Delete a saved preset file (moves to Trash after confirmation).</summary>
    public event Action<BrowserItem>? DeletePresetRequested;
    /// <summary>Open the user presets folder in the OS file manager (a Presets tab folder row).</summary>
    public event Action? OpenPresetsFolderRequested;
    /// <summary>Open the tag editor. Item null = manage all tags; non-null = create a tag
    /// and assign it to that device.</summary>
    public event Action<BrowserItem?>? EditTagsRequested;

    // 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 Border _categoryChipsHost;   // device tabs: one chip per category (spec 013)
    private readonly WrapPanel _categoryChips;
    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;

    public BrowserView()
    {
        MinWidth = 160; // stretches to fill its (resizable) grid column

        var template = BuildItemTemplate();
        _pages = new ListBox[TabCount];
        _filtered = new ObservableCollection<BrowserItem>[TabCount];
        for (int i = 0; i < _pages.Length; i++)
        {
            _filtered[i] = new ObservableCollection<BrowserItem>();
            _pages[i] = NewList(template);
            _pages[i].ItemsSource = _filtered[i];
            HookActivation(_pages[i]);
        }

        _tabs = new[]
        {
            RailTab(0, Loc.T("common.instruments"), GlyphKind.Keyboard),
            RailTab(1, Loc.T("browser.audio_effects_2"), GlyphKind.Sliders),
            RailTab(2, Loc.T("browser.midi_effects_2"), GlyphKind.Midi),
            RailTab(3, Loc.T("browser.files"), GlyphKind.Folder),
            RailTab(4, Loc.T("browser.presets"), GlyphKind.Bookmark),
            RailTab(5, Loc.T("browser.projects"), GlyphKind.Doc),
            RailTab(6, Loc.T("browser.midi_map"), GlyphKind.Map),
            RailTab(7, Loc.T("browser.history"), GlyphKind.History),
            RailTab(InspectorTab, Loc.T("browser.track_inspector"), GlyphKind.Track),
            RailTab(ModularTab, Loc.T("browser.modular"), GlyphKind.PatchCable),
        };
        _tabs[ModularTab].IsVisible = false;   // Modular view only (SetModularContext)
        _sources[ModularTab] = ModularBrowserItems.Build(Nota.Application.Palette.ModularCatalog.All);
        // A hairline above Files, Map and the inspector: devices · library · mappings · track.
        foreach (int i in new[] { 3, 6, InspectorTab })
        {
            _tabs[i].BorderThickness = new Thickness(0, 1, 0, 0);
            _tabs[i].BindResource(Border.BorderBrushProperty, "Brush.BorderDefault");
        }
        var tabStack = new StackPanel { Margin = new Thickness(0, 5, 0, 0) };
        foreach (int i in new[] { 0, 1, 2, ModularTab, 3, 4, 5, 6, 7, InspectorTab }) tabStack.Children.Add(_tabs[i]);
        _collapseBtn = RailButton(GlyphKind.Sidebar, Loc.T("browser.collapse_browser"), () => SetCollapsed(!_collapsed, persist: true));
        _collapseBtn.Margin = new Thickness(0, 0, 0, 6);
        var rail = new DockPanel { Width = 40 };
        DockPanel.SetDock(_collapseBtn, Dock.Bottom);
        rail.Children.Add(_collapseBtn);
        // A short window scrolls the tabs under the fold key instead of drawing them over it.
        rail.Children.Add(new ScrollViewer
        {
            Content = tabStack,
            VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,
            HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
        });

        // --- Search (style guide): 30 high, corner 7, the well; a 16px icon, the placeholder in
        // ink 3, the match count on the right in ink 3; an orange edge while typing ---
        _search = new TextBox
        {
            Watermark = Loc.T("browser.search"),
            BorderThickness = new Thickness(0),
            Background = Brushes.Transparent,
            FontSize = NotaType.Body,
            Padding = new Thickness(0),
            VerticalContentAlignment = VerticalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            Classes = { "search" },
        };
        _search.TextChanged += (_, _) => { ApplyFilter(_active); };
        _search.GotFocus += (_, _) => _searchWrap!.BindResource(Border.BorderBrushProperty, "Brush.Accent");
        _search.LostFocus += (_, _) => _searchWrap!.BorderBrush = Brushes.Transparent;
        // Esc leaves the search (the query stays) so the keyboard goes back to the app.
        _search.KeyDown += (_, e) =>
        {
            if (e.Key != Key.Escape) return;
            TopLevel.GetTopLevel(_search)?.FocusManager?.Focus(null);
            e.Handled = true;
        };
        _matchCount = new TextBlock
        {
            FontSize = NotaType.Caption,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(6, 0, 0, 0),
        };
        _matchCount.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");
        var searchIcon = RailIcon(GlyphKind.Search, 16, "Brush.TextTertiary");
        searchIcon.VerticalAlignment = VerticalAlignment.Center;
        searchIcon.Margin = new Thickness(0, 0, 8, 0);
        var searchGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };
        searchGrid.Children.Add(searchIcon);
        Grid.SetColumn(_search, 1);
        searchGrid.Children.Add(_search);
        Grid.SetColumn(_matchCount, 2);
        searchGrid.Children.Add(_matchCount);
        _searchWrap = new Border
        {
            Height = NotaSize.Search,
            CornerRadius = NotaRadius.Group,
            BorderThickness = new Thickness(1),
            BorderBrush = Brushes.Transparent,
            Padding = new Thickness(9, 0, 10, 0),
            Child = searchGrid,
        };
        _searchWrap.BindResource(Border.BackgroundProperty, "Brush.Well");

        // Sort & view options — the row's shape, sectioning and tag management.
        _optionsBtn = BuildOptionsButton();

        var headerRow = new Grid
        {
            ColumnDefinitions = new ColumnDefinitions("*,Auto"),
            Margin = new Thickness(8, 8, 8, 6),
        };
        headerRow.Children.Add(_searchWrap);
        Grid.SetColumn(_optionsBtn, 1);
        headerRow.Children.Add(_optionsBtn);

        // Filter chips (Favorites + tags). Populated from the VM in SetViewModel and
        // shown only on the device tabs (Instr / FX / MIDI). One line: the chips that
        // don't fit collapse into a "+N" that opens the rest.
        _overflowText = new TextBlock { FontSize = NotaType.Body, VerticalAlignment = VerticalAlignment.Center };
        _overflowText.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");
        _overflowChip = new Border
        {
            Height = NotaSize.Chip, CornerRadius = NotaRadius.Group, Padding = new Thickness(10, 0),
            Cursor = new Cursor(StandardCursorType.Hand),
            Child = _overflowText,
        };
        _overflowChip.BindResource(Border.BackgroundProperty, "Brush.Well");
        _overflowChip.PointerPressed += (_, e) => { ShowOverflowChips(); e.Handled = true; };
        _chipsPanel = new ChipStrip(_overflowChip, _overflowText);
        _chipsHost = new Border { Margin = new Thickness(8, 0, 8, 8), Child = _chipsPanel };

        _sampleChips = new WrapPanel { ItemSpacing = 6, LineSpacing = 6 };
        _sampleChipsHost = new Border { Margin = new Thickness(8, 0, 8, 8), Child = _sampleChips, IsVisible = false };
        // Category chips wrap rather than overflow into "+N": they are the main way to narrow
        // a device tab, so every one stays in sight.
        _categoryChips = new WrapPanel { ItemSpacing = 6, LineSpacing = 6 };
        _categoryChipsHost = new Border { Margin = new Thickness(8, 0, 8, 8), Child = _categoryChips, IsVisible = false };

        _previewFooter = new PreviewPlayer { IsVisible = false };
        _previewFooter.SetContext(files: _active == FilesTab);

        // Status line: what the active tab is showing, counted.
        _statusText = new TextBlock { FontSize = NotaType.Caption, VerticalAlignment = VerticalAlignment.Center };
        _statusText.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");
        _statusBar = new Border
        {
            Height = 30,
            Padding = new Thickness(12, 0),
            BorderThickness = new Thickness(0, 1, 0, 0),
            Child = _statusText,
        };
        _statusBar.BindResource(Border.BackgroundProperty, "Brush.Panel");
        _statusBar.BindResource(Border.BorderBrushProperty, "Brush.BorderDefault");

        // Empty-state message, centered over the list when a tab has nothing to show.
        _emptyText.FontSize = 10;
        _emptyText.TextWrapping = TextWrapping.Wrap;
        _emptyText.TextAlignment = TextAlignment.Center;
        _emptyText.LineHeight = 16;
        _emptyText.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");
        _emptyWrap = new Border
        {
            IsHitTestVisible = true,   // so the one-line empty state can offer its how-to as a tooltip
            IsVisible = false,
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            MaxWidth = 240,
            Padding = new Thickness(20, 0),
            Child = _emptyText,
        };
        var contentHost = new Grid();
        contentHost.Children.Add(_content);
        contentHost.Children.Add(_emptyWrap);

        var right = new DockPanel();
        var topStack = new StackPanel { Children = { headerRow, BuildFilesBars(), BuildProjectsBar(), _categoryChipsHost, _chipsHost, _sampleChipsHost } };
        DockPanel.SetDock(topStack, Dock.Top);
        DockPanel.SetDock(_statusBar, Dock.Bottom);
        DockPanel.SetDock(_previewFooter, Dock.Bottom);
        right.Children.Add(topStack);
        right.Children.Add(_statusBar);
        right.Children.Add(_previewFooter);
        right.Children.Add(contentHost);

        var railDivider = _railDivider = new Border { BorderThickness = new Thickness(0, 0, 1, 0), Child = rail };
        railDivider.BindResource(Border.BackgroundProperty, "Brush.SurfaceDeep");   // style guide: the left rail is deep
        railDivider.BindResource(Border.BorderBrushProperty, "Brush.BorderDefault");
        _body = right;

        var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
        Grid.SetColumn(railDivider, 0);
        Grid.SetColumn(right, 1);
        grid.Children.Add(railDivider);
        grid.Children.Add(right);

        // A docked panel: square, no frame of its own — it meets the canvas on the seam the
        // shell grid draws. ClipToBounds keeps the full-bleed rows inside it.
        var outer = new Border
        {
            BorderThickness = new Thickness(0),
            ClipToBounds = true,
            Child = grid,
        };
        outer.BindResource(Border.CornerRadiusProperty, "Radius.Docked");
        outer.BindResource(Border.BackgroundProperty, "Brush.Panel");
        outer.BindResource(Border.BorderBrushProperty, "Brush.BorderDefault");
        Content = outer;

        SelectTab(0);
    }

    /// <summary>Give the browser the MIDI-learn service so the Map tab can show/edit mappings.</summary>
    public void SetMidiLearn(MidiLearnService learn)
    {
        _midiMap = new MidiMapView(learn);
        if (_active == MapTab) _content.Content = _midiMap;
    }

    /// <summary>Give the browser the project's History tab.</summary>
    internal void SetHistory(HistoryView view)
    {
        _historyView = view;
        if (_active == HistoryTab) _content.Content = view;
    }

    /// <summary>Give the browser the track inspector tab (specs/060).</summary>
    internal void SetTrackInspector(Control view)
    {
        _trackInspector = view;
        if (_active == InspectorTab) _content.Content = view;
    }

    /// <summary>Reveal the MIDI-mappings tab (called when learn mode is armed).</summary>
    public void ShowMidiMap() { SelectTab(MapTab); SetCollapsed(false, persist: true); }
    /// <summary>Opens the History tab (the project's versions).</summary>
    public void ShowHistory() { SelectTab(HistoryTab); SetCollapsed(false, persist: true); }
    /// <summary>Unfolds the browser on Audio effects with the keyboard in its search, ready to
    /// type (the device chain's "+", #97).</summary>
    public void FocusEffectSearch()
    {
        SelectTab(EffectsTab);
        SetCollapsed(false, persist: true);
        // The search row was hidden while folded: focus it once it is laid out again.
        Avalonia.Threading.Dispatcher.UIThread.Post(() => { _search.Focus(); _search.SelectAll(); }, Avalonia.Threading.DispatcherPriority.Input);
    }

    /// <summary>Fold the browser down to its icon rail, or unfold it.</summary>
    public void SetCollapsed(bool collapsed, bool persist)
    {
        if (collapsed == _collapsed) return;
        _collapsed = collapsed;
        _body.IsVisible = !collapsed;
        MinWidth = collapsed ? 0 : 160;
        // Folded, the rail is the whole island — its divider would double the outer border.
        _railDivider.BorderThickness = new Thickness(0, 0, collapsed ? 0 : 1, 0);
        // Nothing is open while folded, so no tab is marked active.
        for (int i = 0; i < _tabs.Length; i++)
            _tabs[i].Classes.Set("active", !collapsed && i == _active);
        ToolTip.SetTip(_collapseBtn, collapsed ? Loc.T("browser.expand_browser") : Loc.T("browser.collapse_browser"));
        if (persist && _settings is not null)
        {
            _settings.Current.BrowserCollapsed = collapsed;
            _settings.Save();
        }
        CollapsedChanged?.Invoke(collapsed);
    }

    /// <summary>Modular became (or stopped being) the view (spec 095): the Modular tab joins or
    /// leaves the rail, and the browser shows the tab last picked in that context — the
    /// Modular tab the first time.</summary>
    public void SetModularContext(bool inModular)
    {
        if (inModular == _tabMemory.InModular) return;
        _tabs[ModularTab].IsVisible = inModular;
        int tab = inModular ? _tabMemory.Enter() : _tabMemory.Leave();
        SelectTab(tab);
    }

    /// <summary>Persist the view options (the ⋮ menu) across sessions. Optional: without it
    /// the browser still works, it just forgets the toggles on quit.</summary>
    public void SetSettings(ISettingsService settings)
    {
        _settings = settings;
        SetCollapsed(settings.Current.BrowserCollapsed, persist: false);
        if (_vm is null) return;
        _vm.GroupBySource = settings.Current.BrowserGroupBySource;
        _vm.FavoritesFirst = settings.Current.BrowserFavoritesFirst;
        RefreshRows();
        RebuildCategoryChips();
    }

    public void SetViewModel(BrowserViewModel vm)
    {
        _vm = vm;
        if (_settings is not null)
        {
            vm.GroupBySource = _settings.Current.BrowserGroupBySource;
            vm.FavoritesFirst = _settings.Current.BrowserFavoritesFirst;
        }
        // Tree tabs (Instruments / FX / MIDI / Files / Presets) bind straight to the VM's
        // flattened visible collections; the VM owns their filtering + expand/collapse.
        _pages[0].ItemsSource = vm.Instruments;
        _pages[1].ItemsSource = vm.Effects;
        _pages[2].ItemsSource = vm.MidiEffects;
        _pages[3].ItemsSource = vm.Samples;
        _pages[4].ItemsSource = vm.Presets;
        for (int i = 0; i <= 4; i++)
        {
            int idx = i;
            VisibleOf(idx)!.CollectionChanged += (_, _) => { if (_active == idx) RefreshCounts(); };
        }

        // Flat tabs (Projects) keep the view-side substring filter.
        var cols = new ObservableCollection<BrowserItem>?[] { null, null, null, null, null, vm.Projects };
        for (int i = 5; i < cols.Length; i++)
        {
            int idx = i;
            _sources[idx] = cols[idx];
            cols[idx]!.CollectionChanged += (_, _) => ApplyFilter(idx);
            ApplyFilter(idx);
        }
        for (int i = 0; i <= 4; i++) ApplyFilter(i);

        // Rebuild the header chips whenever tags/favorites change (also refreshes active state).
        vm.LibraryChanged += RebuildChips;
        RebuildChips();
        // A plug-in rescan can add or remove the Other chip.
        vm.DevicesRebuilt += RebuildCategoryChips;
        RebuildCategoryChips();
        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();
        HookBrowse(vm);
        HookProjects(vm);
        RefreshCounts();
    }

    private ObservableCollection<BrowserItem>? VisibleOf(int tab) => tab switch
    {
        0 => _vm?.Instruments,
        1 => _vm?.Effects,
        2 => _vm?.MidiEffects,
        3 => _vm is null ? null : _vm.BrowseMode ? _vm.BrowseItems : _vm.Samples,
        4 => _vm?.Presets,
        _ => null,
    };

    private void ApplyFilter(int index)
    {
        if (index < 0 || index >= _filtered.Length) return;
        // Tree tabs (devices + Files + Presets): the VM re-filters + flattens into its collections.
        if (index is >= 0 and <= 4)
        {
            _vm?.FilterTree(index, _search.Text?.Trim() ?? "");
            if (index == _active) RefreshCounts();
            return;
        }
        var src = _sources[index];
        var dst = _filtered[index];
        dst.Clear();
        if (src is not null)
        {
            string q = _search.Text?.Trim() ?? "";
            foreach (var it in src)
            {
                if (index == ModularTab) { if (ModularBrowserItems.Matches(it, q)) dst.Add(it); continue; }
                if (q.Length == 0
                    || it.Name.Contains(q, StringComparison.OrdinalIgnoreCase)
                    || it.Sub.Contains(q, StringComparison.OrdinalIgnoreCase))
                    dst.Add(it);
            }
        }
        if (index == _active) RefreshCounts();
    }

    // Re-flatten the visible lists (after a view option changed) without touching the query.
    private void RefreshRows()
    {
        if (_vm is null) return;
        for (int i = 0; i <= 4; i++) _vm.FilterTree(i, _search.Text?.Trim() ?? "");
        RefreshCounts();
    }

    // The search-box match count, the status line and the empty state all describe the
    // same thing — what the active tab is showing — so they refresh together.
    private void RefreshCounts()
    {
        if (_active < 0 || IsCustomTab(_active)) return;
        _matchCount.Text = VisibleCount(_active).ToString();
        _statusText.Text = StatusFor(_active);
        UpdateEmptyState();
    }

    // Show the centered empty-state message when the active tab has nothing to display.
    private void UpdateEmptyState()
    {
        if (_active < 0) return;
        bool empty = VisibleCount(_active) == 0;
        _emptyWrap.IsVisible = empty;
        if (empty) { var (line, detail) = EmptyMessage(_active); _emptyText.Text = line; ToolTip.SetTip(_emptyText, detail); }
    }

    // Empty state (almanac § States): one line in Ink 5, centred, no illustration and no
    // call to action. The how-to that used to follow it lives in the tooltip.
    private (string Line, string Detail) EmptyMessage(int tab)
    {
        bool searching = !string.IsNullOrEmpty(_search.Text?.Trim());
        bool filtering = tab is 0 or 1 or 2 && _vm is not null
                         && (_vm.FilterMode != BrowserFilter.None || _vm.CategoryFilter(tab).Length > 0);
        bool sampleFilter = tab == FilesTab && _vm is not null && (!_vm.SampleFilter.IsEmpty || _vm.SimilarAnchor is not null);
        if (sampleFilter && _vm!.IndexProgress.Total > 0)
            return (Loc.T("browser.no_matches_yet"), Loc.T("browser.nota_is_still_analysing_your"));
        if (tab == FilesTab && BrowseOn && !searching)
            return _vm!.BrowseState == BrowseListState.Unreadable
                ? (Loc.T("browser.folder_unreadable"), "")
                : (Loc.T("browser.folder_empty"), "");
        if (searching || filtering || sampleFilter) return (Loc.T("browser.no_matches"), Loc.T("browser.try_a_different_search_or"));
        return tab switch
        {
            0 => (Loc.T("browser.no_instruments_yet"), Loc.T("browser.notas_built_in_synths_plus")),
            1 => (Loc.T("browser.no_audio_effects_yet"), Loc.T("browser.notas_built_in_effects_plus")),
            2 => (Loc.T("browser.no_midi_effects_yet"), Loc.T("browser.arpeggiator_chord_scale_and_more")),
            3 => (Loc.T("browser.no_samples_yet"), Loc.T("browser.add_audio_files_to_your")),
            4 => (Loc.T("browser.no_presets_yet"), Loc.T("browser.right_click_a_device_header")),
            _ => (Loc.T("browser.no_projects_yet"), MenuKit.Keys(Loc.T("browser.save_a_project_s_into"))),
        };
    }

    // Rows the user can actually act on — section headers are chrome, not matches.
    private int VisibleCount(int index)
    {
        var src = VisibleOf(index) ?? (IReadOnlyList<BrowserItem>)_filtered[index];
        int n = 0;
        foreach (var it in src) if (!it.IsGroup) n++;
        return n;
    }

    // "13 instruments · 10 built-in · 3 plug-ins" — the device tabs split by source, the
    // library tabs just counted. Everything here counts what is on screen, filters included.
    private string StatusFor(int tab)
    {
        if (_vm is null) return "";
        if (tab is 0 or 1 or 2)
        {
            var (bi, pl) = _vm.VisibleDeviceCounts(tab);
            // The total is already in the search box, so spend the line on the split — it is
            // the thing the sections exist to show, and it fits a narrow panel.
            return Loc.F("browser.built_in", bi, Loc.Plural("browser.plug_ins", pl));
        }
        int n = VisibleCount(tab);
        // Filtered, the folders on screen are only there to hold the matches: count those.
        if (tab == FilesTab && BrowseOn)
            return Loc.Plural("browser.samples", System.Linq.Enumerable.Count(_vm.BrowseItems, s => s.Kind is BrowserItemKind.Sample or BrowserItemKind.MidiFile));
        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 => Loc.Plural("browser.samples", n) + AnalysingSuffix(),
            4 => Loc.Plural("browser.presets_n", n),
            ModularTab => Loc.Plural("browser.nodes_n", n),
            _ => Loc.Plural("browser.projects_n", n),
        };
    }

    // " · analysing 34 %" while the library scan runs.
    private string AnalysingSuffix()
    {
        var (done, total) = _vm?.IndexProgress ?? (0, 0);
        return total > 0 ? Loc.F("browser.analysing", done * 100 / total) : "";
    }

    private void SelectTab(int index)
    {
        if (index == _active) return;
        _active = index;
        _tabMemory.Picked(index);
        for (int i = 0; i < _tabs.Length; i++)
            _tabs[i].Classes.Set("active", !_collapsed && i == index);
        // The MIDI-map, History and inspector tabs host bespoke views, not a filtered item list.
        bool isMap = IsCustomTab(index);
        _content.Content = index switch
        {
            MapTab => _midiMap,
            HistoryTab => _historyView,
            InspectorTab => _trackInspector,
            _ => _pages[index],
        };
        if (index == HistoryTab) _historyView?.Refresh();
        _searchWrap.IsVisible = !isMap;
        _optionsBtn.IsVisible = !isMap;
        // The auditioner follows the list tabs: samples in Files, presets and built-in devices
        // in Instr / FX / MIDI / Presets. It picks up the new tab's selection.
        bool auditions = index <= PresetsTab;
        UpdatePreviewVisibility();
        _previewFooter.SetContext(files: index == FilesTab);
        if (auditions) SyncPreview(_pages[index]);
        // Favorite/tag filter chips apply only to the device tabs.
        _chipsHost.IsVisible = index is 0 or 1 or 2;
        RebuildCategoryChips();
        UpdateFilesBars();
        UpdateProjectsBar();
        if (index == FilesTab) _vm?.RefreshSampleAvailability();   // a drive plugged in or pulled out meanwhile
        _statusBar.IsVisible = !isMap;
        if (isMap) { _matchCount.Text = ""; _emptyWrap.IsVisible = false; return; }
        // The shared search box may have changed on another tab (#342).
        if (index <= PresetsTab) _vm?.ShowTab(index, _search.Text?.Trim() ?? "");
        else ApplyFilter(index);
        RefreshCounts();
    }

    private Border RailTab(int index, string caption, GlyphKind iconKind)
    {
        // Icon-only rail; the caption survives as a tooltip. A 16px icon in a 28px key, with
        // the soft tint and a 2 × 14 orange tick at the rail's edge when it is the current page.
        var icon = RailIcon(iconKind, 16);
        icon.HorizontalAlignment = HorizontalAlignment.Center;
        icon.VerticalAlignment = VerticalAlignment.Center;
        var bar = new Border { Classes = { "RailBar" } };
        var inner = new Grid();
        inner.Children.Add(new Border { Classes = { "RailKey" }, Child = icon });
        inner.Children.Add(bar);
        var tab = new Border { Classes = { "RailTab" }, Child = inner };
        ToolTip.SetTip(tab, caption);
        tab.PointerPressed += (_, _) =>
        {
            SelectTab(index);
            SetCollapsed(false, persist: true);   // a click on the folded rail opens that tab
        };
        return tab;
    }

    // A rail-styled action (not a tab): the same 28px key and hover, never marked active.
    private static Border RailButton(GlyphKind iconKind, string caption, Action onClick)
    {
        var icon = RailIcon(iconKind, 16);
        icon.HorizontalAlignment = HorizontalAlignment.Center;
        icon.VerticalAlignment = VerticalAlignment.Center;
        var btn = new Border { Classes = { "RailTab" }, Child = new Border { Classes = { "RailKey" }, Child = icon } };
        ToolTip.SetTip(btn, caption);
        btn.PointerPressed += (_, e) =>
        {
            if (!e.GetCurrentPoint(btn).Properties.IsLeftButtonPressed) return;
            onClick();
            e.Handled = true;
        };
        return btn;
    }

    // --- rows ----------------------------------------------------------------

    private IDataTemplate BuildItemTemplate() => new FuncDataTemplate<BrowserItem>((item, _) =>
    {
        if (item is null) return new Control();
        return item.IsGroup ? GroupRow(item) : item.Kind == BrowserItemKind.Project ? ProjectRow(item) : IndexRow(item);
    }, supportsRecycling: false);

    // A section header: caption, a hairline filling the gap, and the section's count.
    private Control GroupRow(BrowserItem item)
    {
        // Device tabs' BUILT-IN / PLUG-INS headers fold their section on click (#230); a
        // header without a key (other tabs) stays plain chrome.
        bool foldable = item.Path.Length > 0;
        var label = new TextBlock
        {
            Text = NotaText.Label(item.Name),
            Classes = { "GroupLabel" },
            VerticalAlignment = VerticalAlignment.Center,
        };
        var head = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Margin = new Thickness(foldable ? 6 : 10, 0, 0, 0) };
        if (foldable)
        {
            var caret = new Glyph(item.IsExpanded ? GlyphKind.CaretDown : GlyphKind.CaretRight, 10) { VerticalAlignment = VerticalAlignment.Center };
            caret.BindResource(Glyph.ForegroundProperty, "Brush.TextTertiary");
            head.Children.Add(caret);
        }
        head.Children.Add(label);
        var rule = new Border { Height = 1, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 8, 0) };
        rule.BindResource(Border.BackgroundProperty, "Brush.Rule");
        var count = new TextBlock
        {
            Text = item.GroupCount.ToString(),
            FontSize = NotaType.Caption,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 12, 0),
        };
        count.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");

        var grid = new Grid { Height = GroupRowH, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), Background = Brushes.Transparent };
        grid.Children.Add(head);
        Grid.SetColumn(rule, 1);
        grid.Children.Add(rule);
        Grid.SetColumn(count, 2);
        grid.Children.Add(count);
        if (foldable)
        {
            grid.Cursor = new Cursor(StandardCursorType.Hand);
            ToolTip.SetTip(grid, item.IsExpanded ? Loc.T("browser.collapse") : Loc.T("browser.expand"));
            grid.PointerPressed += (_, e) =>
            {
                if (!e.GetCurrentPoint(grid).Properties.IsLeftButtonPressed) return;
                e.Handled = true;
                _vm?.ToggleSection(item);
            };
        }
        return grid;
    }

    // One index row: [brass edge][caret][Nota][name] … [★][tag dots][type tag].
    private Control IndexRow(BrowserItem item)
    {
        bool child = item.Depth > 0;

        var edge = new Border { Classes = { "RowEdge" } };

        // Disclosure triangle for parents with children; a spacer otherwise, so leaf rows
        // and child rows keep their names aligned.
        Control disclosure;
        if (item.HasChildren)
        {
            var tri = RailIcon(item.IsExpanded ? GlyphKind.CaretDown : GlyphKind.CaretRight, 12, "Brush.TextTertiary");
            var hit = new Border
            {
                Width = 14, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
                Child = tri,
            };
            hit.PointerPressed += (_, e) => { _vm?.ToggleExpand(item); e.Handled = true; };
            disclosure = hit;
        }
        else
        {
            disclosure = new Border { Width = 14 };
        }

        // The Downloaded folder (installed sample packs) carries the Downloads arrow.
        Control? icon = null;
        if (item.IsDownloads)
        {
            icon = RailIcon(GlyphKind.Downloads, 13, "Brush.TextSecondary");
        }
        // The Files browse view (spec 092): every row says what it is — folder, drive, audio,
        // MIDI or another file — since folders open with a click rather than a caret.
        else if (IsBrowseRow(item))
        {
            var kind = item.IsVolume ? GlyphKind.Drive
                     : item.Kind switch
                     {
                         BrowserItemKind.Folder => GlyphKind.Folder,
                         BrowserItemKind.Sample => GlyphKind.AudioFile,
                         BrowserItemKind.MidiFile => GlyphKind.Midi,
                         _ => GlyphKind.Doc,
                     };
            icon = RailIcon(kind, 14, item.Kind switch
            {
                BrowserItemKind.Folder => "Brush.TextSecondary",
                BrowserItemKind.OtherFile => "Brush.TextDisabled",
                _ => "Brush.TextTertiary",
            });
        }

        // A built-in row shows its distinctive word only ("Aurora", not "Nota Aurora"): the
        // family name would repeat down the whole list. Search still matches the full name.
        var name = new TextBlock
        {
            // Files and folders keep their real names ("Nota Samples" is a folder, not a device).
            // (The factory kits' node is Nota's own and keeps its short name.)
            Text = item.Prefix.Length > 0 && (item.Sub == "factory" || item.Kind is not (BrowserItemKind.Folder or BrowserItemKind.Sample or BrowserItemKind.MidiFile))
                ? item.ShortName : item.Name,
            Classes = { "RowName" },
            TextTrimming = TextTrimming.CharacterEllipsis,
        };
        if (child || item.Size is not null) name.Classes.Add("child");
        if (item.Unavailable) name.Classes.Add("unavailable");
        // The selected clip's source file (spec 092, #581): an orange edge and name.
        void MarkLocated() { edge.Classes.Set("located", item.Located); name.Classes.Set("located", item.Located); }
        MarkLocated();

        // 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 browseFile = item.Size is not null;
        bool sample = item.Kind == BrowserItemKind.Sample && !browseFile;
        string tag = browseFile ? Extension(item) : sample ? SampleTag(item) : item.Kind == BrowserItemKind.MidiFile ? RowTag(item) : Capital(RowTag(item));
        TextBlock? tagText = null;
        if (sample || browseFile || (tag.Length > 0 && (_settings?.Current.BrowserShowTypeTags ?? true)))
            tagText = new TextBlock { Text = tag, Classes = { "RowTag" }, TextTrimming = TextTrimming.CharacterEllipsis };
        TextBlock? sizeText = item.Size is { } bytes
            ? new TextBlock { Text = FileSize(bytes), Classes = { "RowTag" }, TextAlignment = TextAlignment.Right }
            : null;

        var row = new IndexRowPanel
        {
            Height = RowH,
            Indent = 6 + item.Depth * 12,
            Edge = edge,
            Disclosure = disclosure,
            Icon = icon,
            Name2 = name,
            Markers = BuildRowMarkers(item),   // brass ★ + tag colour dots
            Tag2 = tagText,
            Size2 = sizeText,
        };
        // A file Nota can't add stays in the list, in the disabled ink (spec 092).
        if (item.Kind == BrowserItemKind.OtherFile)
        {
            name.Classes.Add("inert");
            tagText?.Classes.Add("inert");
            sizeText?.Classes.Add("inert");
        }

        // 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, tempo and key).
        string tip = item.Tip.Length > 0 ? item.Tip : item.Sub;
        ToolTip.SetTip(row, tip.Length > 0 ? $"{item.Name} · {tip}" : item.Name);
        // Every other file row still follows Locate's mark as the selected clip changes.
        if (!sample && item.Kind is BrowserItemKind.Sample or BrowserItemKind.MidiFile)
        {
            void Relocate(object? _, System.ComponentModel.PropertyChangedEventArgs e)
            {
                if (e.PropertyName == nameof(BrowserItem.Located)) MarkLocated();
            }
            row.AttachedToVisualTree += (_, _) => { item.PropertyChanged -= Relocate; item.PropertyChanged += Relocate; MarkLocated(); };
            row.DetachedFromVisualTree += (_, _) => item.PropertyChanged -= Relocate;
        }
        if (sample)
        {
            void Retag(object? _, System.ComponentModel.PropertyChangedEventArgs e)
            {
                if (e.PropertyName == nameof(BrowserItem.Located)) { MarkLocated(); return; }
                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); MarkLocated(); };
            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;
    }

    // A browse row (spec 092): a listed folder / drive / file of the browse view.
    private static bool IsBrowseRow(BrowserItem item)
        => item.Size is not null || item.IsVolume
           || item.Kind == BrowserItemKind.Folder && !item.HasChildren && item.PlaceIndex < 0 && item.Path.Length > 0
              && System.IO.Path.IsPathRooted(item.Path) && item.Sub != "factory";

    private static string Extension(BrowserItem item)
        => System.IO.Path.GetExtension(item.Path).TrimStart('.').ToLowerInvariant();

    // "820 KB", "12.4 MB" — the browse view's size column.
    private static string FileSize(long bytes)
    {
        const double K = 1024;
        if (bytes < K) return Loc.F("browser.size_b", bytes);
        if (bytes < K * K) return Loc.F("browser.size_kb", Math.Round(bytes / K).ToString("0", NotaNum.Culture));
        if (bytes < K * K * K) return Loc.F("browser.size_mb", (bytes / (K * K)).ToString(bytes < 10 * K * K ? "0.0" : "0", NotaNum.Culture));
        return Loc.F("browser.size_gb", (bytes / (K * K * K)).ToString("0.0", NotaNum.Culture));
    }

    // "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
    /// device name to keep "paraphonic synth" whole.</summary>
    private sealed class IndexRowPanel : Panel
    {
        private const double Gutter = 9;   // right margin, clear of the scrollbar
        private const double Gap = 5;

        public double Indent { get; init; }
        public Border Edge { get; init; } = null!;
        public Control Disclosure { get; init; } = null!;
        public Control? Icon { get; init; }
        public TextBlock Name2 { get; init; } = null!;
        public Control? Markers { get; init; }
        public TextBlock? Tag2 { get; init; }
        /// <summary>The browse view's size column: fixed width, so sizes line up.</summary>
        public TextBlock? Size2 { get; init; }
        private const double SizeW = 54;

        protected override Size MeasureOverride(Size availableSize)
        {
            Build();
            foreach (var c in Children) c.Measure(Size.Infinity);
            return new Size(0, Height);
        }

        private bool _built;
        private void Build()
        {
            if (_built) return;
            _built = true;
            Children.Add(Edge);
            Children.Add(Disclosure);
            if (Icon is not null) Children.Add(Icon);
            Children.Add(Name2);
            if (Markers is not null) Children.Add(Markers);
            if (Tag2 is not null) Children.Add(Tag2);
            if (Size2 is not null) Children.Add(Size2);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            double h = finalSize.Height;
            void Place(Control c, double x, double w)
                => c.Arrange(new Rect(x, (h - c.DesiredSize.Height) / 2, w, c.DesiredSize.Height));

            Edge.Arrange(new Rect(0, 0, Edge.Width, h));
            Disclosure.Arrange(new Rect(Indent, 0, Disclosure.DesiredSize.Width, h));

            double left = Indent + Disclosure.DesiredSize.Width + 3;
            if (Icon is not null)
            {
                Place(Icon, left, Icon.DesiredSize.Width);
                left += Icon.DesiredSize.Width + Gap;
            }

            double right = Math.Max(left, finalSize.Width - Gutter);
            if (Size2 is not null)
            {
                Size2.Arrange(new Rect(right - SizeW, (h - Size2.DesiredSize.Height) / 2, SizeW, Size2.DesiredSize.Height));
                right = Math.Max(left, right - SizeW - 8);
            }
            double markersW = Markers?.DesiredSize.Width ?? 0;
            double avail = Math.Max(0, right - left - (markersW > 0 ? markersW + 6 : 0));

            // The name first, then the tag on what survives — so a long name trims at the
            // row's edge instead of being squeezed by a secondary label.
            double nameW = Math.Min(Name2.DesiredSize.Width, avail);
            double tagW = 0;
            if (Tag2 is not null)
                tagW = Math.Min(Tag2.DesiredSize.Width, Math.Max(0, avail - nameW - 6));
            Place(Name2, left, nameW);

            double x = right;
            if (Tag2 is not null) { x -= tagW; Place(Tag2, x, tagW); if (tagW > 0) x -= 6; }
            if (Markers is not null) { x -= markersW; Place(Markers, x, markersW); }
            return finalSize;
        }
    }

    // The right-edge tag: what kind of thing the row is, in as few words as possible.
    // Nothing for rows whose indent already says it (presets under a device, folders).
    // Tags read in sentence case ("Wavetable synth", "Built-in"); a file extension stays as it is.
    private static string Capital(string s)
        => s.Length > 0 && char.IsLower(s[0]) ? char.ToUpperInvariant(s[0]) + s[1..] : s;

    private static string RowTag(BrowserItem it) => it.Kind switch
    {
        BrowserItemKind.Folder => "",
        BrowserItemKind.Preset => it.Depth > 0 ? "" : it.Sub,
        BrowserItemKind.Sample or BrowserItemKind.MidiFile => System.IO.Path.GetExtension(it.Path).TrimStart('.').ToLowerInvariant(),
        // A column of "project" down a tab that is only projects says nothing.
        BrowserItemKind.Project => "",
        _ => it.Sub,
    };

    // A small trailing strip of markers for a device row: a brass ★ when favorited, then up
    // to three tag-colour dots. Null for non-device rows (presets / samples / folders / projects).
    private Control? BuildRowMarkers(BrowserItem item)
    {
        if (_vm is null || item.LibraryKey.Length == 0) return null;
        bool fav = _vm.IsFavorite(item);
        var tags = _vm.TagsFor(item);
        if (!fav && tags.Count == 0) return null;

        var strip = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Spacing = 3,
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(6, 0, 0, 0),
        };
        if (fav)
        {
            var star = RailIcon(GlyphKind.StarFilled, 12, "Brush.Accent");
            strip.Children.Add(star);
        }
        int shown = 0;
        foreach (var t in tags)
        {
            if (shown++ >= 3) break;
            strip.Children.Add(new Ellipse
            {
                Width = 6, Height = 6, VerticalAlignment = VerticalAlignment.Center,
                Fill = BrushFromHex(t.Color),
            });
        }
        return strip;
    }

    private static IBrush BrushFromHex(string hex)
    {
        // A tag colour comes from the library, not the palette — Ink() re-tints it for the
        // active theme instead of painting a graphite-tuned hue onto paper.
        try { return NotaPalette.Ink(hex); }
        catch { return NotaPalette.TextTertiary; }
    }

    // --- view options ---------------------------------------------------------

    private Border BuildOptionsButton()
    {
        // An icon button (style guide): 28, corner 7, no fill at rest, the well on hover.
        var icon = RailIcon(GlyphKind.Options, 16, "Brush.TextSecondary");
        icon.HorizontalAlignment = HorizontalAlignment.Center;
        icon.VerticalAlignment = VerticalAlignment.Center;
        var btn = new Border
        {
            Width = NotaSize.Icon, Height = NotaSize.Icon,
            Margin = new Thickness(4, 0, 0, 0),
            CornerRadius = NotaRadius.Group,
            Background = Brushes.Transparent,
            Cursor = new Cursor(StandardCursorType.Hand),
            Child = icon,
        };
        btn.PointerEntered += (_, _) => btn.BindResource(Border.BackgroundProperty, "Brush.Well");
        btn.PointerExited += (_, _) => btn.Background = Brushes.Transparent;
        ToolTip.SetTip(btn, Loc.T("browser.sort_and_view"));
        btn.PointerPressed += (_, e) => { ShowOptionsMenu(btn); e.Handled = true; };
        return btn;
    }

    private void ShowOptionsMenu(Control anchor)
    {
        var flyout = new MenuFlyout();
        flyout.Items.Add(CheckItem(Loc.T("browser.show_type_tags"), _settings?.Current.BrowserShowTypeTags ?? true, v =>
        {
            if (_settings is null) return;
            _settings.Current.BrowserShowTypeTags = v;
            _settings.Save();
            RefreshRows();
        }));
        flyout.Items.Add(CheckItem(Loc.T("browser.category_chips"), CategoryChipsOn, v =>
        {
            if (_settings is not null) { _settings.Current.BrowserCategoryChips = v; _settings.Save(); }
            // A hidden chip must not keep narrowing the list.
            if (!v && _vm is not null) for (int t = 0; t < 3; t++) _vm.SetCategoryFilter(t, "");
            RebuildCategoryChips();
            RefreshCounts();
        }));
        flyout.Items.Add(CheckItem(Loc.T("browser.group_by_source"), _vm?.GroupBySource ?? true, v =>
        {
            if (_vm is not null) _vm.GroupBySource = v;
            if (_settings is not null) { _settings.Current.BrowserGroupBySource = v; _settings.Save(); }
            RefreshCounts();
        }));
        flyout.Items.Add(CheckItem(Loc.T("browser.favorites_first"), _vm?.FavoritesFirst ?? true, v =>
        {
            if (_vm is not null) _vm.FavoritesFirst = v;
            if (_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(Loc.T("browser.warp_loops_to_project_tempo"), s.Current.SamplesWarpLoops, v => { s.Current.SamplesWarpLoops = v; s.Save(); }));
            flyout.Items.Add(CheckItem(Loc.T("browser.transpose_to_project_key"), s.Current.SamplesMatchKey, v => { s.Current.SamplesMatchKey = v; s.Save(); }));
        }
        flyout.Items.Add(new Separator());
        var editTags = new MenuItem { Header = Loc.T("browser.edit_tags") };
        editTags.Click += (_, _) => EditTagsRequested?.Invoke(null);
        flyout.Items.Add(editTags);
        flyout.ShowAt(anchor);
    }

    // A checkable row, drawn the same way the tag menu marks assignment (a leading ✓ or
    // its width in blanks) so the two menus read alike.
    private static MenuItem CheckItem(string label, bool on, Action<bool> set)
    {
        var mi = new MenuItem { Header = label, ToggleType = MenuItemToggleType.CheckBox, IsChecked = on };
        mi.Click += (_, _) => set(!on);
        return mi;
    }

    private void ShowPreview(bool shown)
    {
        _previewShown = shown;
        UpdatePreviewVisibility();
    }

    private void UpdatePreviewVisibility() => _previewFooter.IsVisible = _previewShown && _active <= PresetsTab;

    // A row left the browser for the project: stop its audition and put the player away.
    private void DismissPreview()
    {
        _listPointerDown = false;
        _previewFooter.StopPlayback();
        ShowPreview(false);
    }

    // Hands the player a list's selection and the row below it (which the player pre-renders,
    // so arrowing down plays at once).
    private void SyncPreview(ListBox list)
    {
        var item = list.SelectedItem as BrowserItem;
        BrowserItem? next = null;
        if (item is not null && list.ItemsSource is System.Collections.IList rows)
        {
            int i = rows.IndexOf(item);
            for (int j = i + 1; i >= 0 && j < rows.Count; j++)
                if (rows[j] is BrowserItem { IsGroup: false } r && r.Kind is not (BrowserItemKind.Folder or BrowserItemKind.OtherFile)) { next = r; break; }
        }
        _previewFooter.SetItem(item, next);
    }

    private ListBox NewList(IDataTemplate itemTemplate) => new()
    {
        Classes = { "browser" },
        Padding = new Thickness(0, 0, 0, 6),
        ItemTemplate = itemTemplate,
    };

    /// <summary>A Return pressed on the Modular tab's list with a node selected adds it
    /// (spec 095): the window's transport keys leave that Return to the list.</summary>
    public bool TakesReturn(object? source)
        => source is Visual v && _active == ModularTab
           && _pages[ModularTab].SelectedItem is BrowserItem { Kind: BrowserItemKind.ModularNode }
           && (v == _pages[ModularTab] || v.GetVisualAncestors().Contains(_pages[ModularTab]));

    private void HookActivation(ListBox list)
    {
        // Enter / Return on a Modular node adds it, as a double-click does (spec 095).
        list.KeyDown += (_, e) =>
        {
            if (e.Key is not (Key.Enter or Key.Return) || e.KeyModifiers != KeyModifiers.None) return;
            if (list.SelectedItem is not BrowserItem { Kind: BrowserItemKind.ModularNode } node) return;
            ItemActivated?.Invoke(node, e.KeyModifiers);
            e.Handled = true;
        };
        list.DoubleTapped += (_, e) =>
        {
            if (list.SelectedItem is not BrowserItem { IsGroup: false } item) return;
            if (item.Kind == BrowserItemKind.OtherFile) return;   // listed, but nothing Nota can open
            // Folders (sample dirs, preset categories) are navigation: double-click opens them.
            // In Browse a single click already opened it; a second open would go one deeper.
            if (item.Kind == BrowserItemKind.Folder && list == _pages[FilesTab] && BrowseOn) return;
            else if (item.Kind == BrowserItemKind.Folder) _vm?.ToggleExpand(item);
            else { DismissPreview(); ItemActivated?.Invoke(item, e.KeyModifiers); }
        };
        list.SelectionChanged += (_, _) =>
        {
            // Section headers are chrome: never let one become the selection.
            if (list.SelectedItem is BrowserItem { IsGroup: true }) { list.SelectedItem = null; return; }
            if (_suppressPreview) return;   // Locate selects a row without auditioning it
            if (_active <= PresetsTab && list == _pages[_active])
            {
                SyncPreview(list);
                // Keyboard navigation reveals at once; a click waits for release, so a row
                // pressed only to be dragged away doesn't flash the player.
                if (!_listPointerDown) ShowPreview(true);
            }
        };
        list.AddHandler(InputElement.PointerPressedEvent, (object? _, PointerPressedEventArgs e) =>
                _listPointerDown = e.ClickCount < 2 && e.GetCurrentPoint(list).Properties.IsLeftButtonPressed,
            RoutingStrategies.Tunnel, handledEventsToo: true);
        // Drag source (M7-5): start a copy-drag when the pointer leaves the row.
        // Must use handledEventsToo — ListBoxItem marks PointerPressed as Handled for
        // selection, so a plain `+=` (handled=false) never fires and the drag never
        // starts (no drag cursor). AddHandler with handledEventsToo:true still runs.
        list.AddHandler(InputElement.PointerPressedEvent, OnRowPressed, RoutingStrategies.Bubble, handledEventsToo: true);
        list.AddHandler(InputElement.PointerMovedEvent, OnRowMoved, RoutingStrategies.Bubble, handledEventsToo: true);
        list.AddHandler(InputElement.PointerReleasedEvent,
            (object? _, PointerReleasedEventArgs e) =>
            {
                // A Browse folder opens on a click (contracts/ui.md), released on the row it was pressed on.
                if (_pressedFolder is { } folder && list == _pages[FilesTab] && BrowseOn
                    && (e.Source as StyledElement)?.DataContext == folder && !folder.Unavailable)
                    _vm?.BrowseTo(folder.Path);
                _pressedFolder = null;
                _pressedItem = null; _pressArgs = null;
                if (_listPointerDown && _active <= PresetsTab && list == _pages[_active]) ShowPreview(true);
                _listPointerDown = false;
            },
            RoutingStrategies.Bubble, handledEventsToo: true);
        // Right-click / context menu: favorites + tags on device rows, reveal on files,
        // open / reveal / delete on projects.
        list.ContextRequested += (_, e) => ShowContextMenu(list, e);
    }

    private BrowserItem? _pressedFolder;   // a Browse folder row pressed; opens on release

    private void OnRowPressed(object? sender, PointerPressedEventArgs e)
    {
        _pressedItem = null;
        _pressArgs = null;
        _pressedFolder = null;
        if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
        if (InButton(e.Source as StyledElement)) return;          // preview button etc.
        var item = (e.Source as StyledElement)?.DataContext as BrowserItem;
        if (item is { Kind: BrowserItemKind.Folder, IsGroup: false } && e.ClickCount == 1 && BrowseOn && IsBrowseRow(item))
            _pressedFolder = item;
        // Projects, folders and section headers aren't draggable (folders are navigation,
        // not payload; headers are chrome).
        if (item is null || item.IsGroup || item.Kind is BrowserItemKind.Project or BrowserItemKind.Folder or BrowserItemKind.OtherFile) return;
        _pressedItem = item;
        _pressPoint = e.GetPosition(this);
        _pressArgs = e;   // DoDragDropAsync needs the PointerPressed args
    }

    // Once the pointer moves past the threshold, start the drag with the stored
    // press args (DoDragDropAsync requires PointerPressedEventArgs).
    private async void OnRowMoved(object? sender, PointerEventArgs e)
    {
        if (_pressedItem is null || _pressArgs is null) return;
        if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) { _pressedItem = null; _pressArgs = null; return; }
        var p = e.GetPosition(this);
        if (Math.Abs(p.X - _pressPoint.X) < 4 && Math.Abs(p.Y - _pressPoint.Y) < 4) return;

        var item = _pressedItem;
        var args = _pressArgs;
        _pressedItem = null; _pressArgs = null; // start the drag once
        DismissPreview();
        await DragItemAsync(args, item);
    }

    private static bool InButton(StyledElement? el)
    {
        for (var c = el; c is not null; c = c.Parent)
            if (c is Button) return true;
        return false;
    }

    // --- header filter chips -------------------------------------------------

    private void RebuildChips()
    {
        _chipsPanel.ClearChips();   // the "+N" is a permanent child, not one of the chips
        if (_vm is null) return;
        _chipsPanel.Children.Add(MakeChip(Loc.T("browser.favorites"), null,
            _vm.FilterMode == BrowserFilter.Favorites, () => ToggleFilter(BrowserFilter.Favorites, "")));
        foreach (var t in _vm.Tags)
        {
            var tag = t;
            bool active = _vm.FilterMode == BrowserFilter.Tag && _vm.FilterTagId == tag.Id;
            _chipsPanel.Children.Add(MakeChip(tag.Title, tag.Color, active, () => ToggleFilter(BrowserFilter.Tag, tag.Id)));
        }
        _chipsPanel.InvalidateMeasure();
    }

    private bool CategoryChipsOn => _settings?.Current.BrowserCategoryChips ?? true;

    // The active device tab's category chips (spec 013): one per category in the tab's order,
    // Other last when something lands there. One pick at a time: a click picks, a click on
    // the picked chip clears, a click on another switches. Each tab keeps its own pick.
    private void RebuildCategoryChips()
    {
        _categoryChips.Children.Clear();
        bool show = _vm is not null && _active is 0 or 1 or 2 && CategoryChipsOn;
        _categoryChipsHost.IsVisible = show;
        if (!show) return;
        int tab = _active;
        string picked = _vm!.CategoryFilter(tab);
        foreach (var name in _vm.CategoriesOn(tab))
        {
            var category = name;
            bool active = picked == category;
            _categoryChips.Children.Add(MakeChip(DeviceCategories.Display(category), null, active, () =>
            {
                _vm.SetCategoryFilter(tab, active ? "" : category);
                RebuildCategoryChips();
                RefreshCounts();
            }));
        }
    }

    // The chips that didn't fit on the line, offered as a menu off the "+N".
    private void ShowOverflowChips()
    {
        if (_vm is null) return;
        var flyout = new MenuFlyout();
        foreach (var item in _chipsPanel.Hidden)
        {
            var chip = item;
            var mi = new MenuItem { Header = chip.Label, ToggleType = MenuItemToggleType.CheckBox, IsChecked = chip.Active };
            if (chip.ColorHex is not null) MenuKit.SetTrailing(mi, MenuKit.Swatch(BrushFromHex(chip.ColorHex)));
            mi.Click += (_, _) => chip.OnClick();
            flyout.Items.Add(mi);
        }
        if (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(Loc.F("browser.like", stem), null, true, () => { _vm.ClearSimilar(); RebuildSampleChips(); RefreshCounts(); });
            ToolTip.SetTip(like, Loc.F("browser.sounds_like_closest_first_click", anchor.Name));
            _sampleChips.Children.Add(like);
        }
        _sampleChips.Children.Add(MakeChip(Loc.T("browser.loops"), null, f.Kind == SampleKind.Loop,
            () => SetSampleFilter(f with { Kind = f.Kind == SampleKind.Loop ? SampleKind.Unknown : SampleKind.Loop })));
        _sampleChips.Children.Add(MakeChip(Loc.T("browser.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 ?? Loc.T("browser.key"), null, f.Key is not null, () => ShowKeyFilter(key!));
        ToolTip.SetTip(bpm, Loc.T("browser.filter_by_tempo"));
        ToolTip.SetTip(key, Loc.T("browser.filter_by_key_a_key"));
        _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 = 11,
            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 = Loc.T("browser.bpm_caps"), 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 = Loc.F("browser.project_tempo_5"), Classes = { "ghost" } };
            ToolTip.SetTip(near, Loc.F("browser.loops_within_5_of_bpm", SampleInfo.FormatBpm(tempo)));
            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 = Loc.T("browser.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((Loc.F("browser.project_key", pk.Short), pk));
        KeyPicker.Show(anchor, _vm.SampleFilter.Key, Loc.T("browser.any_key"), k => SetSampleFilter(_vm.SampleFilter with { Key = k }), extras);
    }

    private async void ShowSimilar(BrowserItem item)
    {
        if (_vm is null) return;
        _statusText.Text = Loc.F("browser.finding_sounds_like", item.Name);
        int n = await _vm.ShowSimilarAsync(item);
        RebuildSampleChips();
        RefreshCounts();
        if (n == 0) _statusText.Text = Loc.T("browser.couldnt_analyse_that_sample");
    }

    private void ToggleFilter(BrowserFilter mode, string tagId)
    {
        if (_vm is null) return;
        bool same = _vm.FilterMode == mode && (mode != BrowserFilter.Tag || _vm.FilterTagId == tagId);
        _vm.SetLibraryFilter(same ? BrowserFilter.None : mode, tagId);
        RebuildChips();
        RefreshCounts();
    }

    // A filter chip (almanac § Controls): 20 tall, pill, 9px sides, one line. A dot carries
    // the category colour in place of an icon. Engaged is a brass edge and brass text on the
    // brass wash — solid brass belongs to the one primary action in a context, not a filter.
    private ChipBorder MakeChip(string text, string? colorHex, bool active, Action onClick)
    {
        var content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center };
        if (colorHex is not null)
            content.Children.Add(new Ellipse { Width = 6, Height = 6, VerticalAlignment = VerticalAlignment.Center, Fill = BrushFromHex(colorHex) });
        // Style guide: 24 high, 10 padding, corner 7, the well, 12 in ink 2; on, the soft tint
        // with orange text (a filter is picked, not live).
        var tb = new TextBlock { Text = text, FontSize = NotaType.Body, VerticalAlignment = VerticalAlignment.Center };
        tb.BindResource(TextBlock.ForegroundProperty, active ? "Brush.AccentBright" : "Brush.TextSecondary");
        content.Children.Add(tb);

        var chip = new ChipBorder
        {
            Label = text, ColorHex = colorHex, Active = active, OnClick = onClick,
            Height = NotaSize.Chip, CornerRadius = NotaRadius.Group, Padding = new Thickness(10, 0),
            Cursor = new Cursor(StandardCursorType.Hand), Child = content,
        };
        chip.BindResource(Border.BackgroundProperty, active ? "Brush.AccentSoft" : "Brush.Well");
        chip.PointerPressed += (_, e) =>
        {
            if (!e.GetCurrentPoint(chip).Properties.IsLeftButtonPressed) return;
            onClick(); e.Handled = true;
        };
        return chip;
    }

    /// <summary>A filter chip that remembers what it stands for, so the overflow menu can
    /// offer the same choice the chip would have.</summary>
    private sealed class ChipBorder : Border
    {
        public string Label { get; init; } = "";
        public string? ColorHex { get; init; }
        public bool Active { get; init; }
        public Action OnClick { get; init; } = () => { };
    }

    /// <summary>One line of chips: lays them out left to right and collapses whatever runs
    /// off the end into a trailing "+N" (which opens the rest as a menu). A WrapPanel would
    /// grow the header instead, pushing the list down as tags are added.</summary>
    private sealed class ChipStrip : Panel
    {
        private const double Gap = 5;
        private readonly Border _overflow;
        private readonly TextBlock _overflowText;
        private readonly List<ChipBorder> _hidden = new();

        public ChipStrip(Border overflow, TextBlock overflowText)
        {
            ClipToBounds = true;
            _overflow = overflow;
            _overflowText = overflowText;
            Children.Add(overflow);
        }

        /// <summary>The chips that didn't fit, in order.</summary>
        public IReadOnlyList<ChipBorder> Hidden => _hidden;

        /// <summary>Drop every chip, keeping the overflow affordance.</summary>
        public void ClearChips()
        {
            for (int i = Children.Count - 1; i >= 0; i--)
                if (Children[i] is ChipBorder) Children.RemoveAt(i);
            _hidden.Clear();
        }

        private IEnumerable<ChipBorder> Chips
        {
            get { foreach (var c in Children) if (c is ChipBorder cb) yield return cb; }
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (var c in Children) c.Measure(Size.Infinity);
            return new Size(0, 20);   // one chip row, whatever the width
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _hidden.Clear();
            var chips = new List<ChipBorder>(Chips);

            // Park anything that doesn't fit outside the panel; ClipToBounds swallows it.
            // Toggling IsVisible from inside Arrange would re-enter layout and leave a chip
            // painted where it was last arranged.
            void Park(Control c) => c.Arrange(new Rect(finalSize.Width, 0, 0, 0));

            double total = 0;
            foreach (var c in chips) total += c.DesiredSize.Width + Gap;
            if (total - Gap <= finalSize.Width)
            {
                double x0 = 0;
                foreach (var c in chips)
                {
                    c.Arrange(new Rect(x0, 0, c.DesiredSize.Width, 20));
                    x0 += c.DesiredSize.Width + Gap;
                }
                Park(_overflow);
                return finalSize;
            }

            // Reserve the "+N" width up front so the last chip never sits under it. Its
            // widest form is the one where everything is hidden, so measure that.
            _overflowText.Text = "+" + chips.Count;
            _overflow.Measure(Size.Infinity);
            double reserve = _overflow.DesiredSize.Width + Gap;
            double x = 0;
            foreach (var c in chips)
            {
                double w = c.DesiredSize.Width;
                if (_hidden.Count == 0 && x + w + reserve <= finalSize.Width)
                {
                    c.Arrange(new Rect(x, 0, w, 20));
                    x += w + Gap;
                }
                else
                {
                    Park(c);          // once one chip is out, the rest follow it — order stays
                    _hidden.Add(c);
                }
            }
            _overflowText.Text = "+" + _hidden.Count;
            _overflow.Measure(Size.Infinity);
            _overflow.Arrange(new Rect(x, 0, _overflow.DesiredSize.Width, 20));
            return finalSize;
        }
    }

    // --- context menus -------------------------------------------------------

    private void ShowContextMenu(Control owner, ContextRequestedEventArgs e)
    {
        if (_vm is null) return;
        var item = (e.Source as StyledElement)?.DataContext as BrowserItem
                   ?? (owner as ListBox)?.SelectedItem as BrowserItem;
        if (item is null || item.IsGroup) return;
        var flyout = BuildContextMenu(item);
        if (flyout is null) return;
        flyout.ShowAt(owner, showAtPointer: true);
        e.Handled = true;
    }

    // The row's menu with the item named at the top (spec 034).
    private MenuFlyout? BuildContextMenu(BrowserItem item)
    {
        var flyout = BuildContextMenuItems(item);
        if (flyout is null || flyout.Items.Count == 0) return flyout;
        flyout.Items.Insert(0, MenuKit.Header(item.Name, null, ItemKindLabel(item)));
        flyout.Items.Insert(1, new Separator());
        return flyout;
    }

    private static string ItemKindLabel(BrowserItem item) => item.Kind switch
    {
        BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument => Loc.T("common.instrument"),
        BrowserItemKind.BuiltinEffect or BrowserItemKind.PluginEffect => Loc.T("browser.audio_effect"),
        BrowserItemKind.BuiltinMidiEffect => Loc.T("browser.midi_effect"),
        BrowserItemKind.Sample => Loc.T("common.sample"),
        BrowserItemKind.MidiFile => Loc.T("browser.midi_file"),
        BrowserItemKind.Project => Loc.T("browser.project"),
        BrowserItemKind.Preset => Loc.T("browser.preset"),
        BrowserItemKind.Folder => Loc.T("browser.folder"),
        BrowserItemKind.OtherFile => Loc.T("browser.file"),
        BrowserItemKind.ModularNode => Loc.T("browser.modular_node"),
        _ => "",
    };

    private MenuFlyout? BuildContextMenuItems(BrowserItem item)
    {
        var flyout = new MenuFlyout();

        // Device rows (Instr / FX / MIDI): favorites + tag assignment.
        if (item.LibraryKey.Length > 0 && _vm is not null)
        {
            bool fav = _vm.IsFavorite(item);
            var favItem = new MenuItem { Header = fav ? Loc.T("browser.remove_from_favorites") : Loc.T("browser.add_to_favorites") };
            favItem.Click += (_, _) => _vm.ToggleFavorite(item);
            flyout.Items.Add(favItem);

            var tagsMenu = new MenuItem { Header = Loc.T("browser.tags") };
            foreach (var t in _vm.Tags)
            {
                var tag = t;
                bool assigned = _vm.IsTagAssigned(item, tag.Id);
                var mi = new MenuItem { Header = tag.Title, ToggleType = MenuItemToggleType.CheckBox, IsChecked = assigned };
                MenuKit.SetTrailing(mi, MenuKit.Swatch(BrushFromHex(tag.Color)));
                mi.Click += (_, _) => _vm.AssignTag(item, tag.Id, !assigned);
                tagsMenu.Items.Add(mi);
            }
            if (_vm.Tags.Count > 0) tagsMenu.Items.Add(new Separator());
            var newTag = new MenuItem { Header = Loc.T("browser.new_tag") };
            newTag.Click += (_, _) => EditTagsRequested?.Invoke(item);   // create + assign to this device
            var editTags = new MenuItem { Header = Loc.T("browser.edit_tags") };
            editTags.Click += (_, _) => EditTagsRequested?.Invoke(null); // manage all
            tagsMenu.Items.Add(newTag);
            tagsMenu.Items.Add(editTags);
            flyout.Items.Add(tagsMenu);
            return flyout;
        }

        switch (item.Kind)
        {
            case BrowserItemKind.Sample when _vm?.HasSampleIndex == true:
            {
                var similar = new MenuItem { Header = Loc.T("browser.show_similar_sounds") };
                similar.Click += (_, _) => ShowSimilar(item);
                var reveal = new MenuItem { Header = MenuKit.RevealLabel };
                reveal.Click += (_, _) => RevealRequested?.Invoke(item);
                flyout.Items.Add(similar);
                flyout.Items.Add(reveal);
                flyout.Items.Add(CopyPathItem(item));
                return flyout;
            }
            // A saved preset file on disk (#234). Synthetic rows (factory presets, drum kits)
            // carry a scheme instead of a path: built in, nothing to reveal or delete.
            case BrowserItemKind.Preset when System.IO.Path.IsPathRooted(item.Path):
            {
                var reveal = new MenuItem { Header = MenuKit.RevealLabel };
                reveal.Click += (_, _) => RevealRequested?.Invoke(item);
                flyout.Items.Add(reveal);
                flyout.Items.Add(new Separator());
                flyout.Items.Add(MenuKit.Danger(Loc.T("browser.delete"), GlyphKind.Trash, () => DeletePresetRequested?.Invoke(item)));
                return flyout;
            }
            // The Presets tab's category / device rows group by what a preset holds; the files
            // all sit in the one presets folder, so every row opens that.
            case BrowserItemKind.Folder when _active == PresetsTab && item.Path.StartsWith("preset", StringComparison.Ordinal):
            {
                var reveal = new MenuItem { Header = MenuKit.RevealLabel };
                reveal.Click += (_, _) => OpenPresetsFolderRequested?.Invoke();
                flyout.Items.Add(reveal);
                return flyout;
            }
            case BrowserItemKind.Sample:
            case BrowserItemKind.MidiFile:
            case BrowserItemKind.OtherFile:
            {
                var reveal = new MenuItem { Header = MenuKit.RevealLabel };
                reveal.Click += (_, _) => RevealRequested?.Invoke(item);
                flyout.Items.Add(reveal);
                flyout.Items.Add(CopyPathItem(item));
                return flyout;
            }
            case BrowserItemKind.Folder when _active == FilesTab:   // real sample folders (preset folders are synthetic)
            {
                if (BrowseOn) AddBrowseFolderItems(flyout, item);
                if (!item.Unavailable && !item.IsVolume)
                {
                    var multi = new MenuItem { Header = Loc.T("browser.create_multisample") };
                    multi.Click += (_, _) => CreateMultisampleRequested?.Invoke(item);
                    ToolTip.SetTip(multi, Loc.T("browser.map_the_folders_samples_by"));
                    flyout.Items.Add(multi);
                }
                var reveal = new MenuItem { Header = MenuKit.RevealLabel, IsEnabled = !item.Unavailable };
                reveal.Click += (_, _) => RevealRequested?.Invoke(item);
                flyout.Items.Add(reveal);
                flyout.Items.Add(CopyPathItem(item));
                if (!BrowseOn && item.PlaceIndex >= 0) { flyout.Items.Add(new Separator()); AddPlaceItems(flyout, item); }
                return flyout;
            }
            case BrowserItemKind.Project:
            {
                var open = new MenuItem { Header = Loc.T("common.open") };
                open.Click += (_, _) => ItemActivated?.Invoke(item, KeyModifiers.None);
                var reveal = new MenuItem { Header = MenuKit.RevealLabel };
                reveal.Click += (_, _) => RevealRequested?.Invoke(item);
                var del = MenuKit.Danger(Loc.T("browser.delete"), GlyphKind.Trash, () => DeleteProjectRequested?.Invoke(item));
                flyout.Items.Add(open);
                flyout.Items.Add(reveal);
                flyout.Items.Add(new Separator());
                flyout.Items.Add(del);
                return flyout;
            }
            default:
                return null;   // preset children etc. — no menu
        }
    }
}