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.

28.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// The track inspector (specs/060, #186): the browser's Track inspector tab, showing the track
// the Devices panel shows — name, mute / solo / arm, record input + monitor or MIDI from,
// colour, row height and freeze — so those settings have a home besides the track menu. Every
// control calls what the header and the menu call, so undo and arming behave the same.
// Changes made elsewhere (header, menu, undo, keys) are picked up while the tab is on screen:
// a snapshot of what it shows — including every record-input and MIDI-from choice — is taken four
// times a second and the panel rebuilt when it differs. While freeze or export has suspended
// engine polling, the timer does not read the engine: that job owns it on another thread.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using Nota.Application;
using Nota.Application.Articulations;
using Nota.Application.Localization;

namespace Nota.App;

internal sealed class TrackInspectorView : UserControl
{
    private static readonly (string Label, double Height)[] Heights =
    {
        (Loc.T("common.compact"), ArrangementView.CompactRowHeight), (Loc.T("track_inspector.standard"), ArrangementView.StandardRowHeight), (Loc.T("track_inspector.large"), ArrangementView.LargeRowHeight),
    };

    private readonly IAudioEngine _engine;
    private readonly ArrangementView _timeline;
    private readonly Func<int, IReadOnlyList<FreezeEntry>> _freezeEntries;
    private readonly Func<bool> _engineSuspended;
    private readonly DispatcherTimer _poll = new() { Interval = TimeSpan.FromMilliseconds(250) };
    private int _trackId = -1;
    private string _shown = "";
    private TextBox? _nameBox;
    private TextBox? _offsetBox;   // the MIDI offset being typed (specs/085) must survive the poll too

    public TrackInspectorView(IAudioEngine engine, ArrangementView timeline, Func<int, IReadOnlyList<FreezeEntry>> freezeEntries,
        Func<bool> engineSuspended)
    {
        _engine = engine;
        _timeline = timeline;
        _freezeEntries = freezeEntries;
        _engineSuspended = engineSuspended;
        _poll.Tick += (_, _) => Poll();
        Rebuild();
    }

    /// <summary>Rebuilds the shown track's page (the Cue key appears or goes — specs/089).</summary>
    public void Reload() => Rebuild();

    /// <summary>Shows this track (≤ 0: none).</summary>
    public void Show(int trackId)
    {
        if (trackId == _trackId) return;
        _trackId = trackId;
        Rebuild();
    }

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        Rebuild();
        _poll.Start();
    }

    protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
    {
        _poll.Stop();
        base.OnDetachedFromVisualTree(e);
    }

    private void Poll()
    {
        // Freeze and export run on a worker and replace the session when they finish. The
        // progress dialog keeps this timer running, so leave the engine alone until the job
        // is done (the same SuspendEnginePolling the playhead clock honours).
        if (_engineSuspended()) return;
        // A folded browser keeps the tab attached but hidden; a name being typed must not be
        // swept away by a rebuild.
        if (!IsEffectivelyVisible || _nameBox?.IsFocused == true || _offsetBox?.IsFocused == true) return;
        if (Snapshot() != _shown) Rebuild();
    }

    private bool IsMaster => _trackId > 0 && _trackId == _engine.MasterTrackId;

    private bool TryInfo(out NotaTrackInfo info)
    {
        for (int i = 0; i < _engine.TrackCount; i++)
            if (_engine.TryGetTrackInfo(i, out info) && info.Id == _trackId) return true;
        info = default;
        return false;
    }

    private static bool IsAudio(in NotaTrackInfo ti) => !ti.IsInstrument && !ti.IsReturn && !ti.IsGroup;

    // Everything the panel shows, as one string: a difference means something changed elsewhere.
    private string Snapshot()
    {
        if (IsMaster) return "master|" + _engine.GetTrackName(_trackId);
        if (_trackId <= 0 || !TryInfo(out var ti)) return "none";
        int id = ti.Id;
        var sb = new StringBuilder();
        sb.Append(ti.IsInstrument).Append(ti.IsReturn).Append(ti.IsGroup).Append('|')
          .Append(TrackNames.Of(_engine, ti)).Append('|')
          .Append(_engine.GetTrackColorIndex(id)).Append(',').Append(ArrangementView.EffectiveColorIndex(_engine, id)).Append('|')
          .Append(ti.Muted).Append(ti.Soloed).Append(ti.Armed).Append('|')
          .Append(_timeline.TrackRowHeight(id)).Append('|');
        if (IsAudio(ti))
        {
            var pick = RecordInputPick.Of(_engine, id);
            sb.Append(pick).Append(_engine.GetTrackMonitor(id));
            if (pick.Source > 0) sb.Append(TrackNames.Of(_engine, pick.Source));
            foreach (var c in _timeline.RecordInputChoices(id))
                sb.Append('|').Append(c.Pick.Source).Append(':').Append(c.Pick.Input.First).Append('.').Append(c.Pick.Input.Width).Append('=').Append(c.Label);
        }
        if (ti.IsInstrument)
        {
            int src = _engine.GetTrackMidiSource(id);
            sb.Append(src);
            if (src > 0) sb.Append(TrackNames.Of(_engine, src));
            foreach (var c in _timeline.MidiSourceChoices(id))
                sb.Append('|').Append(c.Id).Append('=').Append(c.Name);
            // The articulation map (specs/085): an undo, the MCP or another view can change it.
            var map = _engine.GetTrackArticulationMapJson(id);
            sb.Append("|art:").Append(map?.Length ?? -1).Append(':').Append(map?.GetHashCode() ?? 0)
              .Append("|off:").Append(_engine.GetTrackMidiOffsetMs(id));
        }
        foreach (var f in _freezeEntries(id)) sb.Append('|').Append(f.Label).Append(f.Switch);
        return sb.ToString();
    }

    private void Rebuild()
    {
        if (_engineSuspended()) return;
        _shown = Snapshot();
        _nameBox = null;
        _offsetBox = null;
        var s = new StackPanel { Spacing = 18, Margin = new Thickness(12, 12, 12, 16) };
        if (IsMaster) BuildMaster(s);
        else if (_trackId > 0 && TryInfo(out var ti)) BuildTrack(s, ti);
        else
        {
            Content = new TextBlock
            {
                Text = Loc.T("track_inspector.no_track_selected"), FontSize = 11, Foreground = NotaPalette.TextTertiary,
                HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
            };
            return;
        }
        Content = new ScrollViewer { Content = s, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };
    }

    // ---- sections -----------------------------------------------------------------------

    private void BuildMaster(StackPanel s)
    {
        string name = _engine.GetTrackName(_trackId) is { Length: > 0 } m ? m : Loc.T("common.master");
        s.Children.Add(Title(NotaPalette.Master, name, "MASTER"));
        s.Children.Add(Note(Loc.T("track_inspector.every_track_ends_up_here")));
    }

    private void BuildTrack(StackPanel s, NotaTrackInfo ti)
    {
        int id = ti.Id;
        bool audio = IsAudio(ti);
        bool frozen = (audio || ti.IsInstrument) && _engine.IsTrackFrozen(id);
        string kind = ti.IsReturn ? Loc.T("common.return") : ti.IsGroup ? Loc.T("common.group") : ti.IsInstrument ? Loc.T("track_inspector.midi_track") : Loc.T("track_inspector.audio_track");
        s.Children.Add(Title(ArrangementView.TrackBrush(ArrangementView.EffectiveColorIndex(_engine, id)), TrackNames.Of(_engine, ti),
            NotaText.Label(frozen ? Loc.F("track_inspector.frozen", kind) : kind)));

        s.Children.Add(Section(Loc.T("track_inspector.name"), NameBox(ti)));

        var state = new UniformGrid { Rows = 1, Columns = 3, ColumnSpacing = 6 };
        state.Children.Add(Toggle(Loc.T("common.mute"), ti.Muted != 0, NotaPalette.Mute, Loc.T("track_inspector.mute_the_track"),
            (on, _) => { _engine.SetTrackMute(id, on); Edited(); }));
        if (!ti.IsReturn)
            state.Children.Add(Toggle(Loc.T("common.solo"), ti.Soloed != 0, NotaPalette.Solo, Loc.T("track_inspector.solo_the_track"),
                (on, _) => { _engine.SetTrackSolo(id, on); Edited(); }));
        if (audio || ti.IsInstrument)
            state.Children.Add(Toggle(Loc.T("track_inspector.arm"), ti.Armed != 0, NotaPalette.Record, TrackArming.Tip,
                (on, mods) => { TrackArming.Set(_engine, id, on, mods); Edited(); }));
        if (CueKey.Shown(_engine))   // Cue (specs/089)
            state.Children.Add(CueKey.Create(_engine, id, 0, 24, NotaRadius.Field, out _, Edited));
        state.Columns = state.Children.Count;
        s.Children.Add(state);

        if (audio) s.Children.Add(Section(Loc.T("common.input"), InputRows(id)));
        if (ti.IsInstrument) s.Children.Add(Section(Loc.T("common.input"), MidiInputRows(id)));
        if (ti.IsInstrument) s.Children.Add(Section(Loc.T("articulations.inspector.head"), ArticulationsBody(id)));

        s.Children.Add(Section(Loc.T("track_inspector.color"), Swatches(id)));

        if (!ti.IsReturn)
        {
            double h = _timeline.TrackRowHeight(id);
            int chosen = Array.FindIndex(Heights, p => Math.Abs(p.Height - h) < 0.5);
            s.Children.Add(Section(Loc.T("track_inspector.height"), SessionView.Segmented(Heights.Select(p => p.Label).ToList(), chosen,
                i => { _timeline.SetTrackHeights(new[] { id }, Heights[i].Height); Rebuild(); })));
        }

        var freeze = _freezeEntries(id);
        if (freeze.Count > 0) s.Children.Add(Section(Loc.T("common.freeze"), FreezeButtons(freeze)));
    }

    // Enter or leaving the box renames; Esc puts the name back. An empty name returns the
    // track to its automatic one (the instrument's, "Audio 3"…).
    private Control NameBox(NotaTrackInfo ti)
    {
        int id = ti.Id;
        string shown = TrackNames.Of(_engine, ti);
        var box = new TextBox { Text = shown, FontSize = 11, Height = NotaSize.Shell, MinHeight = 0, VerticalContentAlignment = VerticalAlignment.Center };
        // Leaving the box also happens when a rebuild (another track selected) drops it, so the
        // rename and the redraw it causes wait for the rebuild to finish.
        void Commit()
        {
            string text = (box.Text ?? "").Trim();
            if (text == shown) return;
            Dispatcher.UIThread.Post(() =>
            {
                _engine.SetTrackName(id, text);
                _timeline.RefreshAfterTrackEdit();
                Rebuild();
            });
        }
        box.KeyDown += (_, e) =>
        {
            if (e.Key is not (Key.Enter or Key.Escape)) return;
            if (e.Key == Key.Escape) box.Text = shown;
            e.Handled = true;
            TopLevel.GetTopLevel(box)?.FocusManager?.Focus(null);
        };
        box.LostFocus += (_, _) => Commit();
        _nameBox = box;
        return box;
    }

    private Control InputRows(int id)
    {
        var choices = _timeline.RecordInputChoices(id);
        var cur = RecordInputPick.Of(_engine, id);
        int sel = choices.FindIndex(c => c.Pick.Matches(cur));
        string label = sel >= 0 ? choices[sel].Label : choices[0].Label;
        var rows = new StackPanel { Spacing = 8 };
        rows.Children.Add(SessionView.Row(Loc.T("common.record_input"), SessionView.Chip(label, false, a =>
            SessionView.Pick(a, choices.Select(c => (c.Pick, c.Label)), p => p.Matches(cur),
                p => { p.ApplyTo(_engine, id); Edited(); }))));

        // Master can't be monitored (it would feed back), as on the header's monitor chip.
        bool canMonitor = cur.Source != -1;
        bool monitor = _engine.GetTrackMonitor(id);
        var chip = SessionView.Chip(monitor ? "On" : Loc.T("common.off"), monitor, _ => { _engine.SetTrackMonitor(id, !monitor); Edited(); });
        chip.IsEnabled = canMonitor;
        ToolTip.SetTip(chip, canMonitor ? Loc.T("track_inspector.hear_the_input_live_through") : Loc.T("track_inspector.master_cant_be_monitored_it"));
        rows.Children.Add(SessionView.Row(Loc.T("track_inspector.monitor_input"), chip));
        return rows;
    }

    // MIDI input (specs/086): device, channel, then MIDI from.
    private Control MidiInputRows(int id)
    {
        var cur = _engine.GetTrackMidiInput(id);
        var devices = MidiInputPick.Devices(_engine, id);
        string devLabel = devices.Find(d => d.Uid == cur.Uid).Label ?? Loc.T("midi_input.all_inputs");
        var rows = new StackPanel { Spacing = 8 };
        var devChip = SessionView.Chip(devLabel, false, a =>
            SessionView.Pick(a, devices.Select(d => (d.Uid, d.Label)), u => u == cur.Uid,
                u => { _engine.SetTrackMidiInput(id, u, cur.Channel); Edited(); }));
        ToolTip.SetTip(devChip, Loc.T("midi_input.tooltip"));
        rows.Children.Add(SessionView.Row(Loc.T("midi_input.menu"), devChip));
        var channels = MidiInputPick.Channels();
        string chLabel = cur.Channel > 0 ? channels[cur.Channel].Label : channels[0].Label;
        rows.Children.Add(SessionView.Row(Loc.T("midi_input.channel"), SessionView.Chip(chLabel, false, a =>
            SessionView.Pick(a, channels.Select(c => (c.Channel, c.Label)), c => c == cur.Channel,
                c => { _engine.SetTrackMidiInput(id, cur.Uid, c); Edited(); }))));
        if (MidiInputPick.MpeWarning(_engine, id))
            rows.Children.Add(Note(Loc.T("midi_input.mpe_warning")));
        rows.Children.Add(MidiFromRow(id));
        return rows;
    }

    private Control MidiFromRow(int id)
    {
        int cur = _engine.GetTrackMidiSource(id);
        var choices = new List<(int Id, string Name)> { (-1, Loc.T("common.none")) };
        choices.AddRange(_timeline.MidiSourceChoices(id));
        string label = choices.FirstOrDefault(c => c.Id == cur).Name ?? Loc.T("common.none");
        var chip = SessionView.Chip(label, false, a =>
            SessionView.Pick(a, choices.Select(c => (c.Id, c.Name)), v => v == cur, v => { _engine.SetTrackMidiSource(id, v); Edited(); }));
        ToolTip.SetTip(chip, Loc.T("track_inspector.play_another_instrument_tracks_midi"));
        return SessionView.Row(Loc.T("track_inspector.midi_from"), chip);
    }

    // ---- articulations (specs/085, US1) -------------------------------------------------------

    private static IArticulationLibrary? Library => App.Services?.GetService(typeof(IArticulationLibrary)) as IArticulationLibrary;

    // The track's map (name and size, a pick from the library), Import… and Remove. Files dropped
    // from Explorer onto the section import like the picker does: decided by content, previewed first.
    private Control ArticulationsBody(int id)
    {
        var map = ArticulationMapAssignment.Read(_engine, id);
        var rows = new StackPanel { Spacing = 8 };

        var lib = Library;
        var saved = lib?.List() ?? (IReadOnlyList<ArticulationMap>)Array.Empty<ArticulationMap>();
        var choices = new List<(string Id, string Name)> { ("", Loc.T("common.none")) };
        choices.AddRange(saved.Select(m => (m.Id, m.Name)));
        if (map is not null && saved.All(m => m.Id != map.Id)) choices.Insert(1, (map.Id, map.Name));   // the project's own copy
        var chip = SessionView.Chip(map?.Name ?? Loc.T("common.none"), false, a =>
            SessionView.Pick(a, choices, v => v == (map?.Id ?? ""), v =>
            {
                if (v.Length == 0) { if (map is not null) _engine.ClearTrackArticulationMap(id); }
                else if (v != map?.Id && lib?.Get(v) is { } chosen) ArticulationMapAssignment.Assign(_engine, id, chosen);
                Edited();
            }));
        ToolTip.SetTip(chip, Loc.T("articulations.inspector.map_tip"));
        rows.Children.Add(SessionView.Row(Loc.T("articulations.inspector.map"), chip));
        if (map is not null) rows.Children.Add(Note(ArticulationText.Count(map)));
        rows.Children.Add(SessionView.Row(Loc.T("articulations.inspector.midi_offset"), MidiOffsetBox(id)));
        // FR-018: what each articulation with an offset of its own adds up to on this track.
        if (map is not null)
        {
            double trackMs = _engine.GetTrackMidiOffsetMs(id);
            foreach (var (name, total) in ArticulationText.EffectiveOffsets(map, trackMs))
                rows.Children.Add(Note(Loc.F("articulations.inspector.effective", name, OffsetText(total), OffsetText(trackMs), OffsetText(total - trackMs))));
        }

        var import = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Content = Loc.T("articulations.inspector.import") };
        ToolTip.SetTip(import, Loc.T("articulations.inspector.import_tip"));
        import.Click += async (_, _) => await PickAndImport(id);
        var buttons = new WrapPanel { Orientation = Orientation.Horizontal, Children = { import } };
        var manage = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(6, 0, 0, 0), Content = Loc.T("articulations.inspector.edit_maps") };
        ToolTip.SetTip(manage, Loc.T("articulations.inspector.edit_maps_tip"));
        manage.Click += (_, _) =>
            ((Avalonia.Application.Current?.ApplicationLifetime as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime)?.MainWindow as MainWindow)?.ShowArticulationMaps();
        buttons.Children.Add(manage);
        if (map is not null)
        {
            var remove = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(6, 0, 0, 0), Content = Loc.T("articulations.inspector.remove") };
            ToolTip.SetTip(remove, Loc.T("articulations.inspector.remove_tip"));
            remove.Click += (_, _) => { _engine.ClearTrackArticulationMap(id); Edited(); };
            buttons.Children.Add(remove);
        }
        rows.Children.Add(buttons);
        rows.Children.Add(Note(Loc.T("articulations.inspector.drop_hint")));

        var host = new Border
        {
            Child = rows, Padding = new Thickness(6), Margin = new Thickness(-6), CornerRadius = NotaRadius.Field,
            BorderThickness = new Thickness(1), BorderBrush = Brushes.Transparent, Background = Brushes.Transparent,
        };
        HookArticulationDrop(host, id);
        return host;
    }

    // The track's MIDI playback offset (specs/085, T052): typed in milliseconds ("−80", "-80 ms",
    // "−0.08 s"), shown in the display culture. Enter or leaving the box sets it (one undo step);
    // Esc puts it back; text that isn't a time is ignored.
    private const double OffsetRangeMs = 2000;
    private static string OffsetText(double ms) => NotaNum.Unit(Math.Round(ms), "0", "ms");

    private Control MidiOffsetBox(int id)
    {
        double cur = _engine.GetTrackMidiOffsetMs(id);
        string shown = OffsetText(cur);
        var box = new TextBox
        {
            Text = shown, FontSize = 11, Height = NotaSize.Shell, MinHeight = 0, Width = 96,
            VerticalContentAlignment = VerticalAlignment.Center, HorizontalContentAlignment = HorizontalAlignment.Right,
        };
        ToolTip.SetTip(box, Loc.T("articulations.inspector.midi_offset_tip"));
        void Commit()
        {
            string text = (box.Text ?? "").Trim();
            if (text == shown) return;
            double? pos = ValueText.Solve(text, shown, p => OffsetText(-OffsetRangeMs + 2 * OffsetRangeMs * p));
            if (pos is not double p) { box.Text = shown; return; }
            double ms = Math.Round(-OffsetRangeMs + 2 * OffsetRangeMs * p);
            Dispatcher.UIThread.Post(() =>   // after a rebuild that dropped the box has finished, like the name
            {
                if (ms != cur) _engine.SetTrackMidiOffsetMs(id, ms);
                Edited();
            });
        }
        box.KeyDown += (_, e) =>
        {
            if (e.Key is not (Key.Enter or Key.Escape)) return;
            if (e.Key == Key.Escape) box.Text = shown;
            e.Handled = true;
            TopLevel.GetTopLevel(box)?.FocusManager?.Focus(null);
        };
        box.LostFocus += (_, _) => Commit();
        _offsetBox = box;
        return box;
    }

    private async System.Threading.Tasks.Task PickAndImport(int id)
    {
        if (TopLevel.GetTopLevel(this) is not { } top) return;
        var files = await top.PickFilesAsync(new FilePickerOpenOptions
        {
            Title = Loc.T("articulations.preview.title"),
            AllowMultiple = false,
            FileTypeFilter = new[]
            {
                new FilePickerFileType(Loc.T("articulations.inspector.file_type")) { Patterns = ArticulationImport.PickerExtensions.Select(x => "*" + x).ToArray() },
                new FilePickerFileType(Loc.T("articulations.inspector.all_files")) { Patterns = new[] { "*" } },
            },
        });
        if (files.Count > 0 && files[0].TryGetLocalPath() is { Length: > 0 } path) await ImportFromFile(id, path);
    }

    // Import → preview → (accepted) keep in the library and give the track. The file is only read.
    private async System.Threading.Tasks.Task ImportFromFile(int id, string path)
    {
        if (TopLevel.GetTopLevel(this) is not Window owner) return;
        var result = ArticulationImport.ImportFile(path);
        bool ok = await new ArticulationImportPreview(System.IO.Path.GetFileName(path), result).ShowDialog<bool>(owner);
        if (!ok || result.Map is not { } map) return;
        try { Library?.Save(map); }
        catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or ArgumentException)
        {
            // Still assign it: the project keeps its own copy. Say the library didn't take it.
            await new ConfirmWindow(Loc.T("articulations.preview.title"), Loc.F("articulations.inspector.library_failed", ex.Message), Loc.T("common.close"), null).ShowDialog<bool>(owner);
        }
        if (!ArticulationMapAssignment.Assign(_engine, id, map))
            await new ConfirmWindow(Loc.T("articulations.preview.title"), Loc.T("articulations.inspector.assign_failed"), Loc.T("common.close"), null).ShowDialog<bool>(owner);
        Edited();
    }

    // Explorer → section. A drag is accepted on sight (reading files at drag-over would stall the
    // pointer); the drop takes the first file and decides by its content, like the picker.
    private void HookArticulationDrop(Border target, int id)
    {
        DragDrop.SetAllowDrop(target, true);
        void Glow(bool on) => target.BorderBrush = on ? NotaPalette.Accent : Brushes.Transparent;
        DragDrop.AddDragOverHandler(target, (_, e) =>
        {
            if (BrowserView.CurrentDrag is not null || !BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.None; return; }
            e.DragEffects = DragDropEffects.Copy;
            e.Handled = true;
            Glow(true);
        });
        DragDrop.AddDragLeaveHandler(target, (_, _) => Glow(false));
        DragDrop.AddDropHandler(target, (_, e) =>
        {
            Glow(false);
            if (BrowserView.CurrentDrag is not null) return;
            var file = BrowserView.ExternalPaths(e).FirstOrDefault(System.IO.File.Exists);
            if (file is null) return;
            e.Handled = true;
            Dispatcher.UIThread.Post(() => _ = ImportFromFile(id, file));   // after the drop returns: the dialog is modal
        });
    }

    // The track palette — each base in its normal, light and dark shade — and Auto, the
    // stored colour ringed, as in the track menu.
    private Control Swatches(int id)
    {
        int current = _engine.GetTrackColorIndex(id);
        int bases = ArrangementView.PaletteBases, shades = ArrangementView.PaletteShades;
        var grid = new UniformGrid { Columns = bases };
        for (int shade = 0; shade < shades; shade++)
            for (int b = 0; b < bases; b++)
            {
                int idx = b * shades + shade;
                grid.Children.Add(Swatch(ArrangementView.TrackBrush(idx), idx == current, () => _timeline.SetTrackColours(new[] { id }, idx)));
            }
        var auto = SessionView.Chip(Loc.T("common.auto"), current == -1, _ => _timeline.SetTrackColours(new[] { id }, -1));
        ToolTip.SetTip(auto, Loc.T("track_inspector.the_colour_the_tracks_position"));
        auto.HorizontalAlignment = HorizontalAlignment.Left;
        return new StackPanel { Spacing = 6, Children = { grid, auto } };
    }

    private Control Swatch(IBrush fill, bool on, Action pick)
    {
        var sw = new Border
        {
            Height = 18, Margin = new Thickness(2), CornerRadius = NotaRadius.Cell, Background = fill,
            BorderBrush = on ? NotaPalette.TextPrimary : Brushes.Transparent, BorderThickness = new Thickness(on ? 1.5 : 0),
            Cursor = new Cursor(StandardCursorType.Hand),
        };
        sw.PointerPressed += (_, e) =>
        {
            if (!e.GetCurrentPoint(sw).Properties.IsLeftButtonPressed) return;
            e.Handled = true;
            pick();
            Rebuild();
        };
        return sw;
    }

    private Control FreezeButtons(IReadOnlyList<FreezeEntry> entries)
    {
        var wrap = new WrapPanel { Orientation = Orientation.Horizontal };
        foreach (var f in entries)
        {
            var ink = f.Danger ? NotaPalette.Danger : NotaPalette.TextPrimary;
            string text = f.Switch is { } on ? $"{f.Label} · {(on ? "on" : "off")}" : f.Label;
            var content = new StackPanel
            {
                Orientation = Orientation.Horizontal, Spacing = 6,
                Children = { new Glyph(f.Icon, 12) { Foreground = ink, VerticalAlignment = VerticalAlignment.Center },
                             new TextBlock { Text = text, FontSize = 11, FontWeight = FontWeight.Medium, Foreground = ink, VerticalAlignment = VerticalAlignment.Center } },
            };
            var b = new Button { Height = NotaSize.Shell, Padding = new Thickness(10, 0), Margin = new Thickness(0, 0, 6, 6), Content = content };
            var run = f.Run;
            b.Click += (_, _) => run();
            wrap.Children.Add(b);
        }
        return wrap;
    }

    // ---- pieces -------------------------------------------------------------------------

    private void Edited()
    {
        _timeline.RefreshAfterTrackEdit();
        Rebuild();
    }

    private static Control Title(IBrush color, string title, string sub)
    {
        var dot = new Border { Width = 10, Height = 10, CornerRadius = NotaRadius.Field, Background = color, VerticalAlignment = VerticalAlignment.Center };
        var name = new TextBlock
        {
            Text = title, FontSize = 15, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary,
            TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center,
        };
        var head = new DockPanel { Children = { dot, name } };
        DockPanel.SetDock(dot, Dock.Left);
        dot.Margin = new Thickness(0, 0, 8, 0);
        var s = ClipEditorKit.Mono(sub, 10, NotaPalette.TextTertiary);
        s.TextTrimming = TextTrimming.CharacterEllipsis;
        return new StackPanel { Spacing = 4, Children = { head, s } };
    }

    private static Control Section(string head, Control body)
        => new StackPanel { Spacing = 8, Children = { SessionView.SectionHead(head), body } };

    private static TextBlock Note(string text) => new()
    {
        Text = text, FontSize = 11, LineHeight = 16, Foreground = NotaPalette.TextTertiary, TextWrapping = TextWrapping.Wrap,
    };

    // A worded state key (Mute / Solo / Arm), filled in its colour while on — the header's
    // chips at inspector size.
    private static Control Toggle(string text, bool on, SolidColorBrush fill, string tip, Action<bool, KeyModifiers> set)
    {
        var tb = new TextBlock
        {
            Text = text, FontSize = 10, FontWeight = FontWeight.SemiBold,
            HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
            Foreground = on ? NotaPalette.InkOn(fill) : NotaPalette.TextSecondary,
        };
        var chip = new Border
        {
            Height = 22, CornerRadius = NotaRadius.Field, BorderThickness = new Thickness(1), Child = tb,
            Background = on ? fill : NotaPalette.SurfaceRaised, BorderBrush = on ? fill : NotaPalette.Seam,
            Cursor = new Cursor(StandardCursorType.Hand),
        };
        ToolTip.SetTip(chip, tip);
        chip.PointerPressed += (_, e) =>
        {
            if (!e.GetCurrentPoint(chip).Properties.IsLeftButtonPressed) return;
            e.Handled = true;
            set(!on, e.KeyModifiers);
        };
        return chip;
    }
}