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.

40.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// Detail · Devices — built-in Nota Pentad editor (instrument kind 14), a build of the
// "Nota Pentad" mockup (700×260) on the same frame as Monolith: an always-visible WHEELS
// column (pitch / mod), a centre tabbed panel (Oscillators / Filter · Amp / Poly Mod), a
// right tabbed panel (Mixer / Output / Voices — the voice setup: polyphony, allocation,
// oversampling, vintage seed …). The five-voice activity strip
// and the mixer's sum read the instrument's scope telemetry. Every control is a plugin-param,
// so automation / MIDI learn / presets / persistence come for free. BodyOnly — the shared
// shell draws the header (name / preset / A-B / meter).

using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using Nota.Application;
using static Nota.App.DeviceCardKit;
using Nota.Application.Localization;

namespace Nota.App;

internal sealed class PentadInstrumentCard : IInstrumentCard
{
    private const int ScEnvTele = 24;   // Pentad::ScEnvTele: the envelopes' stage and progress (#531)
    private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
    private static readonly IBrush Border2 = NotaPalette.BorderDefault;
    private static readonly IBrush BorderIn = NotaPalette.GraphBorder;
    private static readonly IBrush Inset = NotaPalette.BgSunken;
    private static readonly IBrush TabBg = NotaPalette.SurfaceCard;
    private static readonly IBrush Amber = NotaPalette.Accent;
    private static readonly IBrush TealC = DeviceCardKit.ModInk;
    private static readonly IBrush TxtC = NotaPalette.TextPrimary;
    private static readonly IBrush Txt2 = NotaPalette.TextSecondary;
    private static readonly IBrush MutedC = NotaPalette.TextTertiary;
    private static readonly IBrush DimC = NotaPalette.TextDisabled;
    private static readonly IBrush Handle = NotaPalette.TextSecondary;
    private static readonly IBrush OffPill = NotaPalette.SurfaceRaised;

    private static readonly string[] Feet = { "32′", "16′", "8′", "4′" };
    private static readonly string[] SyncNames = { "8 bar", "4 bar", "2 bar", "1 bar", "1/2", "1/4.", "1/4", "1/8.", "1/4T", "1/8", "1/8T", "1/16", "1/16T", "1/32" };

    public bool BodyOnly => true;
    public string Subtitle => "Analog poly";

    public string? VoiceLabel(IAudioEngine engine, int trackId, int active)
    {
        int n = engine.PluginParamCount(trackId, -1);
        for (int i = 0; i < n; i++)
            if (engine.PluginParamId(trackId, -1, i) == "polyphony")
                return $"{Math.Max(0, active)}/{Poly(engine.PluginParamGet(trackId, -1, i))}";
        return null;
    }

    private static int Poly(float v) => v < 0.25f ? 5 : v < 0.75f ? 10 : 16;

    public Control Build(DeviceCardContext ctx)
    {
        var engine = ctx.Engine;
        int track = ctx.TrackId;
        int pc = engine.PluginParamCount(track, -1);
        var idx = new Dictionary<string, int>();
        for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;
        float G(string id) => idx.TryGetValue(id, out var i) ? engine.PluginParamGet(track, -1, i) : 0f;
        int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;
        (int, string) P(string id) => (I(id), id);
        bool On(string id) => G(id) > 0.5f;
        // A discrete edit (click) is one automation gesture, so it records while the transport does.
        void SetP(string id, float v)
        {
            if (I(id) is not (var i and >= 0)) return;
            engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id);
            engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f));
            engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id);
        }

        var readouts = new List<Action>();
        var scope = new float[32];
        var filtCurve = new PentadFilterCurve { Spectrum = new FilterSpectrum(engine, track) };
        var fEnvView = new VoltEnv(engine, track) { MinHeight = 50 };
        var aEnvView = new VoltEnv(engine, track) { MinHeight = 50 };
        var envScale = new EnvTimeScale();
        var voiceStrips = new List<PentadVoiceStrip>();
        var sumBar = new PentadLevelBar { Height = 4, VerticalAlignment = VerticalAlignment.Center };
        var sumTxt = MonoText("", 8, TxtC);
        int scN = 0;

        void Refresh()
        {
            filtCurve.Set(G("cutoff"), G("reso"), On("lowcomp")); filtCurve.InvalidateVisual();
            fEnvView.Refresh();
            scN = engine.InstrumentScope(track, scope);
            if (scN >= ScEnvTele + 4)
            {
                fEnvView.SetPlay((int)scope[ScEnvTele], scope[ScEnvTele + 1]);
                aEnvView.SetPlay((int)scope[ScEnvTele + 2], scope[ScEnvTele + 3]);
            }
            if (scN >= 24)
            {
                int poly = (int)scope[0];
                foreach (var vs in voiceStrips) vs.Set(poly, scope.AsSpan(8, 16));
                sumBar.SetLinear(scope[4] * 0.6);
                sumTxt.Text = scope[4] > 1e-4 ? $"{20 * Math.Log10(scope[4] * 0.6):0.0}" : "−∞";
            }
            foreach (var a in readouts) a();
        }

        // ---- small builders --------------------------------------------------------
        static TextBlock Lbl(string t, double fs, IBrush c, FontWeight w = FontWeight.SemiBold)
            => new() { Text = NotaText.Label(t), FontSize = fs, FontWeight = w, Foreground = c, VerticalAlignment = VerticalAlignment.Center };
        static TextBlock Caps(string t) => new() { Text = NotaText.Label(t), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Medium, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center };
        static TextBlock MonoText(string t, double fs, IBrush c)
        { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Measure"); return tb; }
        static StackPanel Row(double sp, params Control[] cs)
        { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }
        static Control Docked(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
        static Control Col(Control c, int col) { Grid.SetColumn(c, col); return c; }
        static Border Divider(Control child, double top = 5) => new() { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, top, 0, 0), Child = child };

        Control K(string id, string name, Func<float, string> fmt, bool mod = false, double sz = Knob.SizeSecondary, double cw = 40, bool inline = false)
            => InstrumentControls.InstKnob(ctx, idx, id, name, Refresh, fmt, sz, cw, mod ? TealC : null, inline);

        // On/off pill toggle backed by a param (> 0.5 = on).
        Control Toggle(string id, string label, List<Action>? into = null)
        {
            var wrap = Switch(label, () => On(id), () => { SetP(id, On(id) ? 0f : 1f); Refresh(); }, out var sync);
            (into ?? readouts).Add(sync);
            if (I(id) is var pi and >= 0) MidiLearn.Bind(wrap, MidiTarget.PluginParam(track, -1, pi), label.Length > 0 ? label : id);
            return wrap;
        }

        // Segmented chips. values[i] is written on click; the lit chip is the nearest value.
        Control Chips(string id, string[] names, float[]? values = null, List<Action>? into = null, double fs = 7)
        {
            var vals = values ?? BuildValues(names.Length);
            var seg = DeviceCardKit.Segments(names, () => DeviceCardKit.NearestExact(G(id), vals), iv => { SetP(id, vals[iv]); Refresh(); }, out var sync);
            (into ?? readouts).Add(sync);
            if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), id);
            return seg;
        }
        static float[] BuildValues(int n) { var v = new float[n]; for (int i = 0; i < n; i++) v[i] = n > 1 ? i / (float)(n - 1) : 0f; return v; }

        // Waveform on/off chip (the P5's independent, summable wave switches).
        Control WaveChip(string id, int wave, double w = 22, double h = 16)
        {
            var ic = new PentadWaveIcon(wave) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
            var b = new Border { Width = w, Height = h, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Cell, Cursor = new Cursor(StandardCursorType.Hand), Child = ic };
            void Hi() { bool on = On(id); b.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent; b.BorderBrush = on ? NotaPalette.BorderBrass : NotaPalette.BorderStrong; ic.Stroke = on ? NotaPalette.AccentHover : MutedC; ic.InvalidateVisual(); }
            b.PointerPressed += (_, e) => { SetP(id, On(id) ? 0f : 1f); Refresh(); e.Handled = true; };
            readouts.Add(Hi); Hi();
            if (I(id) is var pi and >= 0) MidiLearn.Bind(b, MidiTarget.PluginParam(track, -1, pi), id);
            return b;
        }

        // Horizontal fill slider bound to a param; `dim` greys it out (inactive route).
        Control HSlider(string id, Func<double, string> fmt, double valW = 24, Func<bool>? dim = null, List<Action>? into = null)
        {
            int pi = I(id);
            var row = DeviceCardKit.SliderRow("", () => G(id), n => { if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)n); Refresh(); }, () => fmt(G(id)), out var sync,
                begin: () => { if (pi >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); },
                end: () => { if (pi >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); },
                reset: pi >= 0 ? () => { SetP(id, engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,
                dim: dim, valueWidth: valW);
            (into ?? readouts).Add(sync);
            if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), id);
            return row;
        }
        // Label + slider on one grid row.
        Control SliderRow(string label, string id, Func<double, string> fmt, double labW = 38, double valW = 24, Func<bool>? dim = null, List<Action>? into = null)
        {
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions($"{labW},*"), VerticalAlignment = VerticalAlignment.Center };
            var cap = Caps(label);
            if (label.StartsWith("AT ")) cap.Text = "AT" + NotaText.Label(label)[2..];   // aftertouch: an acronym Label would lowercase
            g.Children.Add(cap); g.Children.Add(Col(HSlider(id, fmt, valW, dim, into), 1));
            return g;
        }

        // Vertical wheel bound to a param (pitch springs back to centre).
        Control VWheel(string id, string name, Func<double, string> fmt, IBrush lit, bool spring)
        {
            int pi = I(id);
            IBrush grad = NotaPalette.BgSunken;
            var bar = new Border { Width = 16, Background = grad, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Group, VerticalAlignment = VerticalAlignment.Stretch };
            var mark = new Border { Height = 2, Width = 12, Background = lit, CornerRadius = NotaRadius.Fine };
            var lay = new Canvas { Width = 16 };
            lay.Children.Add(mark); Canvas.SetLeft(mark, 2);
            var host = new Panel { Width = 16, VerticalAlignment = VerticalAlignment.Stretch, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Children = { bar, lay } };
            bool drag = false; DispatcherTimer? springT = null;
            void Vis(double v) { double h = host.Bounds.Height; if (h <= 0) h = 90; Canvas.SetTop(mark, (1 - v) * (h - 2)); }
            void From(PointerEventArgs e) { double h = host.Bounds.Height; double v = h > 0 ? Math.Clamp(1 - e.GetPosition(host).Y / h, 0, 1) : 0.5; if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)v); Vis(v); Refresh(); }
            void Spring()
            {
                springT?.Stop();
                springT = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(16) };
                springT.Tick += (_, _) =>
                {
                    double v = G(id); v += (0.5 - v) * 0.32;
                    if (Math.Abs(v - 0.5) < 0.002) { v = 0.5; springT!.Stop(); }
                    if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)v); Vis(v); Refresh();
                };
                springT.Start();
            }
            host.PointerPressed += (_, e) => { springT?.Stop(); drag = true; if (pi >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); e.Pointer.Capture(host); From(e); };
            host.PointerMoved += (_, e) => { if (drag) From(e); };
            void EndDrag() { drag = false; if (pi >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); if (spring) Spring(); }
            host.PointerReleased += (_, e) => { if (drag) { EndDrag(); e.Pointer.Capture(null); } };
            host.PointerCaptureLost += (_, _) => { if (drag) EndDrag(); };
            host.SizeChanged += (_, _) => Vis(G(id));
            var nm = new TextBlock { Text = NotaText.Label(name), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Medium, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center };
            readouts.Add(() => { if (!drag) Vis(G(id)); bool moved = Math.Abs(G(id) - (spring ? 0.5f : 0f)) > 0.01f; nm.Foreground = moved ? TxtC : MutedC; });
            var col = new DockPanel { HorizontalAlignment = HorizontalAlignment.Center };
            DockPanel.SetDock(nm, Avalonia.Controls.Dock.Bottom);
            col.Children.Add(nm); col.Children.Add(host);
            if (pi >= 0) MidiLearn.Bind(col, MidiTarget.PluginParam(track, -1, pi), name);
            return col;
        }

        // ---- formatters -------------------------------------------------------------
        static double Exp(double lo, double hi, double v) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
        static string Time(double s) => s >= 1 ? $"{s:0.0}\u2009s" : s >= 0.0995 ? $"{s * 1000:0}\u2009ms" : $"{s * 1000:0.#}\u2009ms";
        string Glide(double v) => v < 0.002 ? "off" : Time(Exp(0.005, 10, v));
        string HzFmt(double hz) => hz >= 1000 ? $"{hz / 1000:0.00}k" : $"{hz:0}";
        string Cut(float v) => HzFmt(20 * Math.Pow(1000, v));
        static string Pct(double v) => $"{v * 100:0}\u2009%";
        static string Tenths(double v) => $"{v * 10:0.0}";
        string LfoRate(float v) => On("lfosync") ? SyncNames[Math.Clamp((int)Math.Round(v * 13), 0, 13)] : $"{Exp(0.05, 20, v):0.0#}\u2009Hz";
        string VolDb(float v) { double g = 2 * v * v; return g <= 1e-4 ? "−∞" : $"{20 * Math.Log10(g):0.0}\u2009dB"; }
        int BendSt() => 1 + Math.Clamp((int)Math.Round(G("bendrange") * 11), 0, 11);

        // ======================================================================
        // LEFT — wheels
        // ======================================================================
        var bendTxt = MonoText("", 7, TxtC); var modTxt = MonoText("", 7, MutedC);
        bendTxt.HorizontalAlignment = HorizontalAlignment.Center; modTxt.HorizontalAlignment = HorizontalAlignment.Center;
        readouts.Add(() => { bendTxt.Text = $"±{BendSt()}\u2009st"; modTxt.Text = $"{G("modwheel") * 100:0}\u2009%"; modTxt.Foreground = G("modwheel") > 0.01f ? TxtC : MutedC; });
        var wheelsBody = new DockPanel { LastChildFill = true };
        var wTitle = Caps("WHEELS"); wTitle.HorizontalAlignment = HorizontalAlignment.Center; wTitle.Margin = new Thickness(0, 0, 0, 4);
        wheelsBody.Children.Add(Docked(wTitle, Avalonia.Controls.Dock.Top));
        wheelsBody.Children.Add(Docked(modTxt, Avalonia.Controls.Dock.Bottom));
        wheelsBody.Children.Add(Docked(bendTxt, Avalonia.Controls.Dock.Bottom));
        wheelsBody.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 0, 0, 3), Children = {
            VWheel("bend", "PITCH", v => "", NotaPalette.VizInk, spring: true),
            VWheel("modwheel", "MOD", v => "", NotaPalette.VizInk, spring: false) } });
        var wheels = new RuleSection { Width = 56, Padding = new Thickness(0, 5), Child = wheelsBody };
        DockPanel.SetDock(wheels, Avalonia.Controls.Dock.Left);

        // ======================================================================
        // CENTRE — Oscillators
        // ======================================================================
        const string OscCols = "18,40,40,40,*,62";
        Control Cell(Control c, int col, HorizontalAlignment ha = HorizontalAlignment.Center) { c.HorizontalAlignment = ha; c.VerticalAlignment = VerticalAlignment.Center; return Col(new Panel { Children = { c } }, col); }
        Control OscRow(string o)
        {
            bool isA = o == "a";
            string p = "o" + o;
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions(OscCols) };
            g.Children.Add(Cell(Lbl(isA ? "A" : "B", 10, TxtC, FontWeight.SemiBold), 0, HorizontalAlignment.Left));
            g.Children.Add(Cell(K($"{p}oct", "", v => Feet[Math.Clamp((int)Math.Round(v * 3), 0, 3)], false, Knob.SizeInline, 40, true), 1));
            g.Children.Add(Cell(K($"{p}semi", "", v => { int s = (int)Math.Round((v - 0.5f) * 24); return s == 0 ? "0\u2009st" : $"{s:+0;−0}\u2009st"; }, false, Knob.SizeInline, 40, true), 2));
            g.Children.Add(Cell(K($"{p}fine", "", v => { double c = (v - 0.5) * 100; return Math.Abs(c) < 0.5 ? "0\u2009c" : $"{c:+0;−0}\u2009c"; }, false, Knob.SizeInline, 40, true), 3));
            var chips = isA ? Row(3, WaveChip("oasaw", 0), WaveChip("oapulse", 1)) : Row(3, WaveChip("obsaw", 0), WaveChip("obtri", 2), WaveChip("obpulse", 1));
            var pw = HSlider($"{p}pw", v => Pct(v), 30, () => !On($"{p}pulse"));
            pw.Width = 110;
            g.Children.Add(Cell(Row(6, chips, pw), 4));
            Control opts = isA ? Toggle("oasync", "Sync")
                : new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { Toggle("oblofreq", "Lo freq"), Toggle("obkbd", "Kbd") } };
            g.Children.Add(Cell(opts, 5, HorizontalAlignment.Right));
            return new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Child = g };
        }
        Control OscTab()
        {
            var hdr = new Grid { ColumnDefinitions = new ColumnDefinitions(OscCols), Height = 13 };
            string[] h = { "OSC", "OCT", "SEMI", "FINE", Loc.T("device.pentad.shape_pulse_width_caps"), "OPTIONS" };
            for (int i = 0; i < h.Length; i++)
            {
                var t = new TextBlock { Text = NotaText.Label(h[i]), FontSize = 7, FontWeight = FontWeight.Medium, Foreground = DimC, VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = i == 0 ? HorizontalAlignment.Left : i == h.Length - 1 ? HorizontalAlignment.Right : HorizontalAlignment.Center };
                hdr.Children.Add(Col(t, i));
            }
            // bottom row: glide · voice mode · voices
            var glide = Row(4, K("glide", "GLIDE", v => Glide(v), false, Knob.SizeSecondary, 44), Chips("glidemode", new[] { "Off", "On", "Leg" }));
            var mode = Row(6, Caps("MODE"), Chips("voicemode", new[] { "Poly", "Uni", "Mono" }));
            var strip = new PentadVoiceStrip { Width = 84, Height = 14 }; voiceStrips.Add(strip);
            var voices = Row(6, Caps("VOICES"), strip);
            var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), ColumnSpacing = 14, Height = 50 };
            bottom.Children.Add(glide); bottom.Children.Add(Col(mode, 1)); bottom.Children.Add(Col(voices, 3));
            var rows = new Grid { RowDefinitions = new RowDefinitions("*,*") };
            var rb = OscRow("b"); Grid.SetRow(rb, 1);
            rows.Children.Add(OscRow("a")); rows.Children.Add(rb);
            return new DockPanel { LastChildFill = true, Margin = new Thickness(6, 0, 6, 2), Children = {
                Docked(hdr, Avalonia.Controls.Dock.Top),
                Docked(new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 2, 0, 0), Child = bottom }, Avalonia.Controls.Dock.Bottom),
                rows } };
        }

        // ======================================================================
        // CENTRE — Filter · Amp
        // ======================================================================
        Control FilterPanel()
        {
            filtCurve.Changed = (c, r) =>
            {
                if (I("cutoff") is var ci and >= 0) engine.PluginParamSet(track, -1, ci, (float)c);
                if (I("reso") is var ri and >= 0) engine.PluginParamSet(track, -1, ri, (float)r);
                Refresh();
            };
            filtCurve.DragStarted += () => { engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, "cutoff"); engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, "reso"); };
            filtCurve.DragEnded += () => { engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, "cutoff"); engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, "reso"); };
            var graph = new Border { Margin = new Thickness(0, 3, 0, 3), Child = filtCurve };
            var keyPct = MonoText("", 7, Txt2);
            readouts.Add(() => keyPct.Text = Pct(G("keytrk")));
            keyPct.HorizontalAlignment = HorizontalAlignment.Center;
            var key = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { Caps("KEYTRACK"), Chips("keytrk", new[] { "0", "½", "1" }), keyPct } };
            // The graph takes the whole height; the knobs sit in a column to its right, as on
            // Nota Volt (#531).
            var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), RowDefinitions = new RowDefinitions("Auto,Auto"), RowSpacing = 4 };
            knobs.Children.Add(K("cutoff", "CUTOFF", Cut, false, Knob.SizeSecondary, 48));
            knobs.Children.Add(Col(K("reso", "RESO", v => Tenths(v), false, Knob.SizeSecondary, 48), 1));
            var envK = K("fenvamt", "ENVELOPE", v => Tenths(v), true, Knob.SizeSecondary, 48); Grid.SetRow(envK, 1); knobs.Children.Add(envK);
            Grid.SetRow(key, 1); knobs.Children.Add(Col(key, 1));
            var left = new DockPanel { LastChildFill = true, Children = { Docked(Caps("FILTER"), Avalonia.Controls.Dock.Top), graph } };
            var side = new Border { Width = 112, VerticalAlignment = VerticalAlignment.Center, Child = knobs };
            var body = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8, Children = { left, Col(side, 1) } };
            return new Border { Width = 196, BorderBrush = BorderIn, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(7, 4), Child = body };
        }
        // The two envelopes side by side on one time scale (#531): drag the curve, bend decay and
        // release by their diamonds, Lin / Exp in each header; Release sits in the tab bar.
        double RelSec(float v) => On("releaseon") ? EnvPanel.ExpMap(v, 0.002, 15.0) : 0.004;
        Control EnvTab()
        {
            Control Cell(string id, string label, string learn, Func<float, string> fmt) => K(id, label, fmt, false, Knob.SizeInline, 40);
            Control Seg(string id, string[] names) => Chips(id, names);
            var fe = EnvPanel.Build(fEnvView, new EnvPanel.Spec("FILTER ENV", new[] { "fattack", "fdecay", "fsustain", "frelease" },
                new[] { "fdcurve", "frcurve", "fenvexp" }, (0.0005, 10.0), (0.002, 15.0), (0.002, 15.0)), P, Cell, Seg, null, envScale);
            var ae = EnvPanel.Build(aEnvView, new EnvPanel.Spec("AMP ENV", new[] { "aattack", "adecay", "asustain", "arelease" },
                new[] { "adcurve", "arcurve", "aenvexp" }, (0.0005, 10.0), (0.002, 15.0), (0.002, 15.0)), P, Cell, Seg, null, envScale);
            fEnvView.Seconds = WithRelease(fEnvView.Seconds!);
            aEnvView.Seconds = WithRelease(aEnvView.Seconds!);
            Func<int, double, double> WithRelease(Func<int, double, double> f) => (k, n) => k == 3 ? RelSec((float)n) : f(k, n);
            var aeHost = new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(7, 0, 0, 0), Child = ae };
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 7, Margin = new Thickness(7, 4) };
            g.Children.Add(fe); g.Children.Add(Col(aeHost, 1));
            return g;
        }
        // The filter on its own tab, across the whole panel.
        Control FilterTab()
        {
            var f = (Border)FilterPanel();
            f.Width = double.NaN; f.BorderThickness = new Thickness(0);
            return f;
        }

        // ======================================================================
        // CENTRE — Poly Mod · LFO · Wheel Mod
        // ======================================================================
        string Dests()
        {
            var d = new List<string>();
            if (On("pmfreqa")) d.Add("Freq A"); if (On("pmpwa")) d.Add("PW A"); if (On("pmfilter")) d.Add("Filter");
            return d.Count == 0 ? Loc.T("device.pentad.no_dest") : string.Join(" + ", d);
        }
        int ActiveRoutes()
        {
            int dn = (On("pmfreqa") ? 1 : 0) + (On("pmpwa") ? 1 : 0) + (On("pmfilter") ? 1 : 0);
            return dn * ((G("pmenv") > 0.001f ? 1 : 0) + (G("pmoscb") > 0.001f ? 1 : 0));
        }
        Control RouteRow(string src, string id, bool isPm, Func<string> dest, string? dimWhenZeroOf = null)
        {
            var srcT = new TextBlock { Text = src, FontSize = 8, Foreground = TxtC, Width = 58, VerticalAlignment = VerticalAlignment.Center };
            var destT = new TextBlock { FontSize = 8, Foreground = TxtC, Width = 84, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
            bool Dim() => G(id) < 0.001f || (isPm && !On("pmfreqa") && !On("pmpwa") && !On("pmfilter"));
            readouts.Add(() => { destT.Text = dest(); bool d = Dim(); srcT.Foreground = d ? Txt2 : TxtC; destT.Foreground = d ? Txt2 : TxtC; });
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*"), ColumnSpacing = 6, Height = 18 };
            g.Children.Add(srcT);
            g.Children.Add(Col(new TextBlock { Text = "→", FontSize = 8, Foreground = DimC, VerticalAlignment = VerticalAlignment.Center }, 1));
            g.Children.Add(Col(destT, 2));
            g.Children.Add(Col(HSlider(id, v => Tenths(v), 26, Dim), 3));
            return g;
        }
        Control PolyModTab()
        {
            var dests = Row(12, Caps("DEST"), Toggle("pmfreqa", "Osc A freq"), Toggle("pmpwa", "Osc A PW"), Toggle("pmfilter", "Filter cutoff"));
            dests.Height = 18;
            var vel = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 12, Height = 18, Children = {
                SliderRow("VEL → AMP", "velamp", v => Pct(v), 52, 30),
                Col(SliderRow("VEL → FILT", "velfilt", v => Pct(v), 52, 30), 1) } };
            var at = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 12, Height = 18, Children = {
                SliderRow("AT → cut", "atcutoff", v => Pct(v), 52, 30),
                Col(SliderRow("AT → LFO", "atlfo", v => Pct(v), 52, 30), 1) } };
            var routes = new StackPanel { Spacing = 1, Children = {
                RouteRow("Filter env", "pmenv", true, Dests),
                RouteRow("Osc B", "pmoscb", true, Dests),
                dests, vel, at } };

            // LFO
            var lfoWaves = Row(2, WaveChip("lfotri", 2, 20, 14), WaveChip("lfosaw", 0, 20, 14), WaveChip("lfosquare", 3, 20, 14));
            var lfo = new StackPanel { Spacing = 2, Children = {
                Caps("LFO"),
                Row(4, K("lforate", "RATE", LfoRate, false, Knob.SizeSecondary, 38), K("lfoamt", "AMOUNT", v => Pct(v), true, Knob.SizeSecondary, 38),
                    new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { lfoWaves, Chips("lfosync", new[] { "Free", "Sync" }) } }) } };
            // Wheel mod
            var wmGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), RowDefinitions = new RowDefinitions("Auto,Auto"), RowSpacing = 3, ColumnSpacing = 6 };
            void W(string id, string l, int r, int c) { var t = Toggle(id, l); Grid.SetRow(t, r); Grid.SetColumn(t, c); wmGrid.Children.Add(t); }
            W("wmfreqa", "Freq A", 0, 0); W("wmfreqb", "Freq B", 0, 1); W("wmfilter", "Filter", 0, 2);
            W("wmpwa", "PW A", 1, 0); W("wmpwb", "PW B", 1, 1);
            var mixRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), ColumnSpacing = 5, Children = {
                Caps("SOURCE"), Col(Lbl("LFO", 7, DimC, FontWeight.Normal), 1), Col(HSlider("wmmix", v => Pct(v), 26), 2), Col(Lbl("NOISE", 7, DimC, FontWeight.Normal), 3) } };
            var wm = new StackPanel { Spacing = 3, Children = { Caps(Loc.T("device.pentad.wheel_mod_destinations_caps")), wmGrid, mixRow } };
            var wmBox = new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(10, 0, 0, 0), Child = wm };
            var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 10, Children = { lfo, Col(wmBox, 1) } };

            return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 3, 8, 2), Children = {
                Docked(Caps(Loc.T("device.pentad.poly_mod_source_destination_caps")), Avalonia.Controls.Dock.Top),
                Docked(Divider(bottom, 4), Avalonia.Controls.Dock.Bottom),
                new Border { Padding = new Thickness(0, 2, 0, 0), Child = routes } } };
        }

        // ======================================================================
        // RIGHT — Mixer / Output
        // ======================================================================
        Control MixRow(string onId, string lvlId, string name)
        {
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,34,*"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
            g.Children.Add(Toggle(onId, ""));
            g.Children.Add(Col(Caps(name), 1));
            g.Children.Add(Col(HSlider(lvlId, v => Tenths(v), 20, () => !On(onId)), 2));
            return g;
        }
        Control MixerTab()
        {
            bool UniOff() => G("voicemode") < 0.25f && G("unison") < 0.25f;
            var noiseType = Chips("noisecolor", new[] { "White", "Pink" }); noiseType.Margin = new Thickness(24, 0, 0, 0);
            var uni = Row(6, new TextBlock { Text = "Unison", FontSize = 7, FontWeight = FontWeight.Medium, Foreground = MutedC, Width = 38, VerticalAlignment = VerticalAlignment.Center }, Chips("unison", new[] { "Off", "×2", "×5" }));
            var det = SliderRow("DETUNE", "unidetune", v => $"{v * 50:0}\u2009c", 38, 26, UniOff);
            var sum = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, Children = { Caps("SUM"), Col(sumBar, 1), Col(sumTxt, 2) } };
            var g = new Grid { RowDefinitions = new RowDefinitions("*,*,*,*,Auto,*,*,*") };
            Control[] rows = { MixRow("mixaon", "mixa", "OSC A"), MixRow("mixbon", "mixb", "OSC B"), MixRow("mixnoiseon", "mixnoise", "NOISE"), noiseType,
                new Border { Height = 1, Background = BorderIn, Margin = new Thickness(0, 3) }, uni, det, sum };
            for (int r = 0; r < rows.Length; r++) { rows[r].VerticalAlignment = r == 4 ? VerticalAlignment.Center : VerticalAlignment.Center; Grid.SetRow(rows[r], r); g.Children.Add(rows[r]); }
            return new Border { Padding = new Thickness(6, 4), Child = g };
        }
        Control OutputTab()
        {
            // Volume alone, centred — the track meter already shows the level.
            var top = K("volume", "VOLUME", VolDb, false, Knob.SizeMain, 54);
            top.HorizontalAlignment = HorizontalAlignment.Center;
            var bend = Row(6, new TextBlock { Text = "Bend", FontSize = 7, FontWeight = FontWeight.Medium, Foreground = MutedC, Width = 38, VerticalAlignment = VerticalAlignment.Center },
                Chips("bendrange", new[] { "2", "5", "7", "12" }, new[] { 1 / 11f, 4 / 11f, 6 / 11f, 1f }), Lbl("st", 7, MutedC, FontWeight.Normal));
            // Velocity → filter: a quick switch over the Velocity Filter amount (0 ↔ 50 %).
            var velF = Switch("Vel → filter", () => G("velfilt") > 0.001f, () => { SetP("velfilt", G("velfilt") > 0.001f ? 0f : 0.5f); Refresh(); }, out var velSync);
            readouts.Add(velSync);
            var body = new DockPanel { LastChildFill = false, Children = {
                Docked(top, Avalonia.Controls.Dock.Top),
                Docked(Divider(new StackPanel { Spacing = 6, Children = { SliderRow("SPREAD", "spread", v => Pct(v), 38, 30), bend, velF } }), Avalonia.Controls.Dock.Top) } };
            ((Control)body.Children[1]).Margin = new Thickness(0, 6, 0, 0);
            return new Border { Padding = new Thickness(6, 4), Child = body };
        }
        // The voice setup (what the status strip's Voice flyout held): one compact row per
        // setting, label left, control right, spread over the panel's height.
        Control VoicesTab()
        {
            var seedTxt = MonoText("", 8, TxtC);
            readouts.Add(() => seedTxt.Text = $"#{(int)Math.Round(G("seed") * 16777215):X6}");
            var rr = new Border { Padding = new Thickness(5, 1), CornerRadius = NotaRadius.Cell, Background = OffPill, Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = "Re-roll", FontSize = 8, Foreground = TxtC } };
            ToolTip.SetTip(rr, Loc.T("device.pentad.re_roll_the_vintage_seed"));
            rr.PointerPressed += (_, e) => { SetP("seed", (float)Random.Shared.NextDouble()); Refresh(); e.Handled = true; };
            var tune = HSlider("tune", v => { double c = (v - 0.5) * 200; return Math.Abs(c) < 0.5 ? "0\u2009c" : $"{c:+0;−0}\u2009c"; }, 30);
            var at = HSlider("aftertouch", v => Pct(v), 30);
            (string Label, Control C, bool Fill)[] rows =
            {
                ("VOICES", Chips("polyphony", new[] { "5", "10", "16" }), false),
                ("ALLOCATION", Chips("alloc", new[] { "Rotate", "Oldest" }), false),
                ("GLIDE", Chips("glidemode", new[] { "Off", "On", "Legato" }), false),
                ("RELEASE", Toggle("releaseon", "Release switch"), false),
                ("OVERSAMPLE", Chips("oversample", new[] { "×2", "×4" }), false),
                ("BASS COMP", Toggle("lowcomp", Loc.T("device.pentad.restore_lows_at_high_q")), false),
                ("NOISE FLOOR", Toggle("noisefloor", "−100\u2009dBFS hiss"), false),
                ("SEED", Row(6, seedTxt, rr), false),
                ("TUNE", tune, true),
                ("AFTERTOUCH", at, true),
            };
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("62,*"), ColumnSpacing = 4 };
            for (int r = 0; r < rows.Length; r++)
            {
                g.RowDefinitions.Add(new RowDefinition(GridLength.Star));
                var cap = Caps(rows[r].Label); Grid.SetRow(cap, r); g.Children.Add(cap);
                var c = rows[r].C;
                c.HorizontalAlignment = rows[r].Fill ? HorizontalAlignment.Stretch : HorizontalAlignment.Left;
                c.VerticalAlignment = VerticalAlignment.Center;
                Grid.SetRow(c, r); Grid.SetColumn(c, 1); g.Children.Add(c);
            }
            return new Border { Padding = new Thickness(6, 3), Child = g };
        }

        // ======================================================================
        // Tab frames + extras
        // ======================================================================
        var centreHost = new ContentControl();
        var rightHost = new ContentControl();
        var extrasHost = new ContentControl { VerticalAlignment = VerticalAlignment.Center };
        var tabBodies = new Control?[4]; var rightBodies = new Control?[3];
        int centreTab = 0;

        // Drift slider + seed re-roll (Oscillators tab bar)
        var reroll = new Border { Padding = new Thickness(3, 0), CornerRadius = NotaRadius.Cell, Background = OffPill, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
            Child = new Glyph(GlyphKind.Cycle, 9) { Foreground = Txt2 } };
        ToolTip.SetTip(reroll, Loc.T("device.pentad.re_roll_the_vintage_seed"));
        reroll.PointerPressed += (_, e) => { SetP("seed", (float)Random.Shared.NextDouble()); Refresh(); e.Handled = true; };
        var driftSl = HSlider("drift", v => $"{v * 100:0}\u2009%", 22); driftSl.Width = 76;
        Control[] extras = {
            Row(5, Caps("DRIFT"), driftSl, reroll),
            MonoText("4-pole LP · 24\u2009dB/oct", 7, MutedC),
            Toggle("releaseon", "Release"),
            MonoText("", 7, MutedC) };
        readouts.Add(() => { if (extras[3] is TextBlock t) { int n = ActiveRoutes(); t.Text = Loc.Plural("device.pentad.per_voice_active_routes", n); } });

        Control CentreBody(int t) => tabBodies[t] ??= t switch { 1 => FilterTab(), 2 => EnvTab(), 3 => PolyModTab(), _ => OscTab() };
        Control RightBody(int t) => rightBodies[t] ??= t switch { 1 => OutputTab(), 2 => VoicesTab(), _ => MixerTab() };

        var centre = TabFrame(new[] { "Oscillators", "Filter", Loc.T("device.pentad.env_tab"), "Poly Mod" }, centreHost, CentreBody, false, t => { centreTab = t; extrasHost.Content = extras[t]; Refresh(); }, extrasHost);
        var rightFrame = TabFrame(new[] { "Mixer", "Output", Loc.T("device.pentad.voices_tab") }, rightHost, RightBody, true, null, null);
        var right = new RuleSection { Width = 186, Child = rightFrame };
        DockPanel.SetDock(right, Avalonia.Controls.Dock.Right);
        var centreBox = new RuleSection { Margin = new Thickness(5, 0), Child = centre };

        // ---- assemble ---------------------------------------------------------------
        var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { wheels, right, centreBox } };
        var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceCard, Children = { bodyRow } };

        ctx.SetInstLiveViz(Refresh);
        Refresh();
        return root;

        // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
        Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
        {
            int sel = 0; var btns = new Border[tabs.Length];
            void Hi()
            {
                for (int i = 0; i < tabs.Length; i++)
                {
                    bool on = i == sel;
                    btns[i].Background = on ? TabBg : Brushes.Transparent; btns[i].BorderBrush = on ? Amber : Brushes.Transparent;
                    var tb = (TextBlock)btns[i].Child!; tb.Foreground = on ? NotaPalette.TextPrimary : MutedC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
                }
            }
            var bar = centered ? (Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
            for (int i = 0; i < tabs.Length; i++)
            {
                int iv = i;
                var b = new Border { Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
                    Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center } };
                b.PointerPressed += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };
                btns[i] = b; bar.Children.Add(b);
            }
            var barDock = new DockPanel { Height = 20, LastChildFill = centered };
            if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Avalonia.Controls.Dock.Right); barDock.Children.Add(ex); }
            if (!centered) DockPanel.SetDock(bar, Avalonia.Controls.Dock.Left);
            barDock.Children.Add(bar);
            var barBorder = new Border { BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };
            DockPanel.SetDock(barBorder, Avalonia.Controls.Dock.Top);
            Hi(); host.Content = body(sel); changed?.Invoke(sel);
            return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
        }
    }
}