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.

46.2 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 Shutter body (noise gate / ducker, device kind 19), a build
// of the "Nota Shutter" mockup (700 × 260) on the Utility / Valve / Vintage frame: a centre
// panel with Signal / Envelope / Sidechain / Pattern tabs — the input and the gated output over
// the window with the threshold and the close level on it, one opening drawn from attack /
// hold / release / shape / floor, the detector's band-pass under the reduction, the rhythmic
// gate's step grid — and a right panel that follows the tab (Detector · Opening · Key · Rhythm)
// over Floor · Threshold · Return (#531 card layout; S = the Signal graph and four knobs). The pictures come from the engine (Shutter.h scopeRead), so they show what the
// gate does. Every control is a device param, so automation / MIDI learn / presets / A-B /
// persistence come for free; the window length, Live (freeze) and Reset are view / meter
// actions, not params.
// FullBleed — the shared shell draws the header (name · preset · badge · bypass).

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

namespace Nota.App;

internal sealed class ShutterDeviceBody : IDeviceBody
{
    // ── Parameter indices (must match Shutter.h) ─────────────────────────────
    private const int Threshold = 0, Return = 1, Attack = 2, Hold = 3, Release = 4, Floor = 5, Lookahead = 6, Flip = 7,
        DetHP = 8, DetLP = 9, Listen = 10, Shape = 11, Retrigger = 12, DetFilter = 13, PeakHold = 14, ExternalKey = 15;
    // Scope layout (Shutter::S_* / kTele / kHist).
    private const int S_InDb = 0, S_GateGain = 1, S_GrDb = 2, S_DetDb = 3, S_Open = 4, S_State = 5, S_OutDb = 6, S_OpenRatio = 7,
        S_TrigPerBar = 8, S_Triggers = 9, S_SampleRate = 10, S_Cpu = 11, S_Latency = 12, S_ExtKey = 13, S_KeyDb = 14,
        S_PeakGrDb = 18, S_WindowSec = 20, S_HistN = 21, kTele = 24, kHist = 128;
    // Pattern (appended params + the block after the histories).
    private const int PatTarget = 16, PatRate = 17, PatDepth = 18, PatSync = 19, PatSmooth = 20, PatSwing = 21, PatSteps = 22,
        PatLevels = 23, PatRetrig = 24, PatGated = 25, PatComplexity = 26, Step1 = 28, kMaxSteps = 32;
    private const int S_Bpm = 19;
    private const int kPatAt = kTele + 3 * kHist, P_Phase = 0, P_Step = 1, P_Value = 3, kPat = 8;
    private const int kScope = kPatAt + kPat;
    private const int H_In = kTele, H_Gate = kTele + kHist, H_Det = kTele + 2 * kHist;
    private const int A_ResetMeters = 0, A_Window = 1;

    private static readonly string[] Shapes = { "Linear", "Log", "Snap" };
    private static readonly string[] StateNames = { "closed", "attack", "open", "hold", "release" };
    private static readonly string[] WindowNames = { "250\u2009ms", "1\u2009s", "4\u2009s" };
    private static readonly string[] RateSync = { "1/4", "1/2", "1 Bar", "2 Bars", "4 Bars" };
    private static readonly string[] RateFree = { "4\u2009Hz", "2\u2009Hz", "1\u2009Hz", "0.5\u2009Hz", "0.25\u2009Hz" };
    private static readonly int[] StepCounts = { 8, 16, 32 }, LevelCounts = { 4, 8, 16 };

    // The pattern browser's shapes (steps in eighths), resampled to the grid; the arrows walk them.
    private static readonly (string Name, int[] Steps)[] Patterns =
    {
        ("Push",      new[] { 8, 0, 8, 8, 0, 8, 8, 0, 8, 0, 8, 8, 0, 8, 0, 8 }),
        ("Offbeat",   new[] { 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0 }),
        ("Trance 16", new[] { 8, 0, 8, 0, 8, 8, 0, 8, 8, 0, 8, 0, 8, 8, 0, 8 }),
        ("Stutter",   new[] { 8, 8, 8, 8, 0, 0, 0, 0, 8, 0, 8, 0, 8, 8, 0, 0 }),
        ("Halftime",  new[] { 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0, 4, 0 }),
        ("Ramp Up",   new[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 }),
        ("Chop",      new[] { 8, 0, 6, 0, 8, 3, 0, 5, 8, 0, 6, 2, 8, 0, 4, 0 }),
    };
    // Copy / Paste between every Shutter in the session.
    private static float[]? _clipboard;
    private static readonly Random Rng = new();

    public double Width => 700;
    public double WidthFor(IAudioEngine engine, int trackId, int deviceIndex) => CardLayout.WidthFor(engine, trackId, deviceIndex, Width);
    public Control? HeaderAccessory(DeviceCardContext ctx, int deviceIndex) => CardLayout.SizeToggle(ctx, deviceIndex);
    public bool FullBleed => true;
    public string? Subtitle => "Gate";

    public Control Build(DeviceCardContext ctx, int index)
    {
        var engine = ctx.Engine;
        int track = ctx.TrackId, di = index;
        float P(int p) => engine.DeviceGetParam(track, di, p);
        void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
        void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
        void Raw(int p, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1));
        // A discrete edit (a click) is one automation gesture, so it records while the transport does.
        void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
        void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
        double Def(int p) => engine.DeviceParamDefault(track, di, p);
        bool On(int p) => P(p) >= 0.5f;
        int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1);

        var readouts = new List<Action>();
        void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
        // A typeable value for a graph handle (⌥-click it, specs/035).
        ValueField F(int p, string name, Func<double, string> fmt) => ValueEntry.DeviceParam(engine, track, di, p, name, fmt, RefreshAll);
        var scope = new float[kScope];
        var frozen = new float[kScope];
        int scN = 0;
        bool live = true;
        double Sc(int i) => scN > i ? scope[i] : 0;
        float[] Hist() => live ? scope : frozen;

        // ---- units ----------------------------------------------------------------
        static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
        static string MsF(double ms) => ms >= 100 ? NotaNum.F($"{ms:0}\u2009ms") : ms >= 10 ? NotaNum.F($"{ms:0.0}\u2009ms") : NotaNum.F($"{ms:0.0#}\u2009ms");
        static string MsN(double ms) => ms >= 100 ? NotaNum.F($"{ms:0}") : ms >= 10 ? NotaNum.F($"{ms:0.#}") : NotaNum.F($"{ms:0.0#}");
        static string DbF(double db) => db <= -119 ? "−∞\u2009dB" : NotaNum.F($"{db:0.0}\u2009dB");
        static string HzF(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0}\u2009k") : NotaNum.F($"{hz:0}");
        double ThrDb() => -70 + P(Threshold) * 70;
        double RetDb() => P(Return) * 24;
        double AtkMs() => Exp(P(Attack), 0.01, 100);
        double HoldMs() => Exp(P(Hold), 0.1, 500);
        double RelMs() => Exp(P(Release), 1, 2000);
        double FloorDb() => P(Floor) <= 0.001f ? -120 : -70 + P(Floor) * 70;
        double FloorLin() => P(Floor) <= 0.001f ? 0 : Math.Pow(10, FloorDb() / 20);
        int LookMs() => new[] { 0, 1, 5 }[Sel(Lookahead, 3)];
        bool Duck() => On(Flip);
        string ThrShort(double v) => NotaNum.F($"{-70 + v * 70:0.0}");
        string RetF(double v) => NotaNum.F($"{v * 24:0.0}\u2009dB");
        string AtkF(double v) => MsF(Exp(v, 0.01, 100));
        string HoldF(double v) => MsF(Exp(v, 0.1, 500));
        string RelF(double v) => MsF(Exp(v, 1, 2000));
        string FloorF(double v) => v <= 0.001 ? "−∞\u2009dB" : NotaNum.F($"{-70 + v * 70:0.0}\u2009dB");
        string HpF(double v) => HzF(Exp(v, 20, 2000));
        string LpF(double v) => HzF(Exp(v, 200, 20000));
        string Times() => NotaNum.F($"{MsN(AtkMs())} / {MsN(HoldMs())} / {MsN(RelMs())}\u2009ms");
        string GrText() => Sc(S_GrDb) < 0.05 ? "GR 0.0\u2009dB" : Sc(S_GrDb) > 99 ? "GR −∞\u2009dB" : NotaNum.F($"GR −{Sc(S_GrDb):0.0}\u2009dB");
        string WindowText() { double s = Sc(S_WindowSec); return s <= 0 ? "1\u2009s" : s < 1 ? NotaNum.F($"{s * 1000:0}\u2009ms") : NotaNum.F($"{s:0.#}\u2009s"); }
        int WindowIdx() { double s = Sc(S_WindowSec); return s <= 0 ? 1 : s < 0.5 ? 0 : s < 2 ? 1 : 2; }
        int State() => Math.Clamp((int)Math.Round(Sc(S_State)), 0, 4);

        // Sidechain key: the source (a track, or one pad / chain / voice of it, specs/050) and
        // whether it is in use.
        int Src() => engine.DeviceSidechainSource(track, di);
        bool ExtOn() => On(ExternalKey) && Src() >= 0;
        string KeyName() => ExtOn() ? SidechainSourcePicker.Name(engine, engine.DeviceSidechainKey(track, di)) : "Internal";

        // ---- small builders ---------------------------------------------------------
        static TextBlock Caps(string t, IBrush? c = null, double fs = NotaType.KnobLabel) => new()
        { Text = NotaText.Label(t), FontSize = fs, FontWeight = FontWeight.Medium, Foreground = c ?? TextTertiary, VerticalAlignment = VerticalAlignment.Center };
        // An acronym NotaText.Label does not know (OS, GR) keeps its case: the label as written.
        static TextBlock Mono(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 T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
        static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
        void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));

        // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
        // `steps` > 1 snaps a discrete param (Lookahead).
        Control K(int p, string name, Func<double, string> fmt, IBrush? arc = null, int steps = 0, string? tip = null, double size = 34, double cellW = 44)
        {
            var val = Mono(fmt(P(p)), 7, TextPrimary);
            var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = Def(p), Width = size, Height = size };
            knob.Format = v => fmt(steps > 1 ? Math.Round(v * (steps - 1)) / (steps - 1) : v);   // read-out at any value: typing searches it
            knob.ValueChanged += v =>
            {
                if (steps > 1) v = Math.Round(v * (steps - 1)) / (steps - 1);
                Raw(p, v); val.Text = fmt(P(p)); RefreshAll();
            };
            knob.GestureBegin += () => Begin(p);
            knob.GestureEnd += () => End(p);
            Learn(knob, p);
            if (tip is not null) ToolTip.SetTip(knob, tip);
            readouts.Add(() => { if (knob.Dragging) return; double c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; val.Text = fmt(P(p)); });
            return KnobCell(name, knob, val, cellW);
        }

        // On/off switch bound to a param (>= 0.5 = on).
        Control Toggle(int p, string label, string tip)
        {
            var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); RefreshAll(); }, out var sync);
            readouts.Add(sync);
            Learn(wrap, p);
            ToolTip.SetTip(wrap, tip);
            return wrap;
        }

        // Segmented pill over a normalized discrete param.
        Control Seg(int p, string[] names, string tip)
        {
            int n = names.Length;
            var seg = Segments(names, () => Sel(p, n), iv => { SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); RefreshAll(); }, out var sync, padX: 6);
            readouts.Add(sync);
            Learn(seg, p);
            ToolTip.SetTip(seg, tip);
            return seg;
        }
        Control ModeSeg() => Seg(Flip, new[] { "Gate", "Duck" }, Loc.T("device.shutter.mode_gate_lets_the_signal"));

        // Outlined chips: the chosen one = accent edge + wash.
        Control Chips(string[] names, Func<int, bool> lit, Action<int> pick, int learnParam, string tip)
        {
            var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center };
            var cells = new Border[names.Length];
            var texts = new TextBlock[names.Length];
            for (int i = 0; i < names.Length; i++)
            {
                int iv = i;
                var tb = new TextBlock { Text = names[i], FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
                var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Cell, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
                b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; pick(iv); RefreshAll(); e.Handled = true; };
                cells[i] = b; texts[i] = tb; row.Children.Add(b);
            }
            readouts.Add(() =>
            {
                for (int i = 0; i < names.Length; i++)
                {
                    bool on = lit(i);
                    cells[i].BorderBrush = on ? Brass : NotaPalette.BorderStrong;
                    cells[i].Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
                    texts[i].Foreground = on ? AccentBright : TextSecondary;
                    texts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
                }
            });
            Learn(row, learnParam);
            ToolTip.SetTip(row, tip);
            return row;
        }

        // A latching chip: lit when `lit()`, a click runs `click`. `fill` = a full-width button.
        Border Latch(int p, Func<bool> lit, Action click, Func<string> text, string tip, bool fill = false)
        {
            var tb = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
            var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Cell, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
            if (fill) b.HorizontalAlignment = HorizontalAlignment.Stretch;
            void Hi()
            {
                bool on = lit();
                b.Background = on ? NotaPalette.AccentSubtle : fill ? Raised : Brushes.Transparent;
                b.BorderBrush = on ? Brass : fill ? Brushes.Transparent : NotaPalette.BorderStrong;
                tb.Foreground = on ? AccentBright : fill ? TextPrimary : TextSecondary;
                tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
                tb.Text = text();
            }
            b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); RefreshAll(); e.Handled = true; };
            ToolTip.SetTip(b, tip);
            if (p >= 0) Learn(b, p);
            readouts.Add(Hi); Hi();
            return b;
        }
        Border ToggleLatch(int p, string text, string tip, bool fill = false)
            => Latch(p, () => On(p), () => SetP(p, On(p) ? 0f : 1f), () => text, tip, fill);
        Border ListenLatch(bool fill = false) => ToggleLatch(Listen, "Listen", Loc.T("device.shutter.listen_hear_the_key_as"), fill);

        // The key source: [name ▾] lists Internal and the other tracks. Picking a track switches
        // External Key on; Internal clears the source.
        Control KeyDrop(bool stretch)
        {
            var name = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
            var chev = new Glyph(GlyphKind.ChevronDown, 7) { Margin = new Thickness(6, 0, 0, 0) };
            var box = new Border
            {
                Height = 16, MinWidth = 74, Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Cell,
                Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
                Child = new DockPanel { Children = { Docked(chev, Dock.Right), name } },
            };
            if (stretch) box.HorizontalAlignment = HorizontalAlignment.Stretch;
            readouts.Add(() =>
            {
                bool ext = ExtOn();
                name.Text = KeyName();
                name.Foreground = TextPrimary;   // an external key: a stronger frame and weight, not the accent
                name.FontWeight = ext ? FontWeight.SemiBold : FontWeight.Normal;
                box.BorderBrush = ext ? NotaPalette.BorderStrong : BorderDef;
                chev.Foreground = ext ? TextSecondary : TextTertiary;
            });
            ToolTip.SetTip(box, Loc.T("device.shutter.key_source_internal_keys_off"));
            Learn(box, ExternalKey);
            box.PointerPressed += (_, e) =>
            {
                if (!e.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;
                var fly = new MenuFlyout();
                void Item(string label, bool cur, Action pick)
                {
                    var mi = new MenuItem { Header = label };
                    mi.ToggleType = MenuItemToggleType.Radio; mi.IsChecked = cur;
                    mi.Click += (_, _) => pick();
                    fly.Items.Add(mi);
                }
                Item(Loc.T("device.shutter.internal_this_track"), !ExtOn(), () => { engine.SetDeviceSidechainSource(track, di, -1); ctx.NotifyChanged(); RefreshAll(); });
                // Picking a source means using it.
                void Picked()
                {
                    if (Src() >= 0 && !On(ExternalKey)) SetP(ExternalKey, 1f);
                    ctx.NotifyChanged(); RefreshAll();
                }
                foreach (var row in SidechainSourcePicker.MenuRows(engine, track, di, Picked))
                    fly.Items.Add(SidechainSourcePicker.MenuItemFor(row with { Checked = row.Checked && ExtOn() }));
                fly.ShowAt(box);
                e.Handled = true;
            };
            return box;
        }

        // External sidechain switch: on uses the routed key (picks the first other track when
        // none is routed yet), off keeps the source but keys off this track.
        Control ExtSwitch()
        {
            var sw = Switch("External sidechain", ExtOn, () =>
            {
                if (ExtOn()) SetP(ExternalKey, 0f);
                else
                {
                    if (Src() < 0)
                        for (int i = 0; i < engine.TrackCount; i++)
                            if (engine.TryGetTrackInfo(i, out var ti) && ti.Id != track) { engine.SetDeviceSidechainSource(track, di, ti.Id); break; }
                    if (Src() >= 0) SetP(ExternalKey, 1f);
                }
                ctx.NotifyChanged(); RefreshAll();
            }, out var sync);
            readouts.Add(sync);
            Learn(sw, ExternalKey);
            ToolTip.SetTip(sw, Loc.T("device.shutter.external_sidechain_the_detector_listens"));
            return sw;
        }

        void WireDrag<T>(T v, Func<int, int> param, params ValueField[] fields) where T : ShDragView
        {
            ValueEntry.AttachHandles(v, fields.Select(f => (IReadOnlyList<ValueField>)new[] { f }).ToArray());
            v.Value = h => P(param(h));
            v.Changed += (h, x) => { Raw(param(h), x); Refresh(); };   // the graph redraws from the new value at once
            v.GestureBegin += h => Begin(param(h));
            v.GestureEnd += h => End(param(h));
            v.ResetRequested += h => { Reset(param(h)); RefreshAll(); };
        }

        // ======================================================================
        // CENTRE — Signal
        // ======================================================================
        ShSignalView? signal = null;
        ShSignalView SignalGraph()
        {
            signal = new ShSignalView();
            WireDrag(signal, h => h == ShSignalView.HThreshold ? Threshold : Return,
                F(Threshold, "Threshold", v => ThrShort(v) + "\u2009dB"), F(Return, "Return", RetF));
            ToolTip.SetTip(signal, MenuKit.Keys(Loc.T("device.shutter.the_input_teal_and_what")));
            Learn(signal, Threshold);
            return signal;
        }
        Control LookSeg() => Seg(Lookahead, new[] { "0", "1", "5\u2009ms" }, Loc.T("device.shutter.lookahead_the_gate_opens_this"));
        Control SignalTab()
        {
            var g = SignalGraph();
            var liveBtn = Latch(-1, () => live, () => { live = !live; if (!live) Array.Copy(scope, frozen, kScope); }, () => live ? "Live" : "Frozen",
                Loc.T("device.shutter.live_the_graph_follows_the"));
            var peak = ToggleLatch(PeakHold, "Peak hold", Loc.T("device.shutter.peak_hold_the_detector_holds"));
            return CardLayout.View(g, null, CardLayout.Line(6, Caps("LOOK"), LookSeg(), peak, liveBtn));
        }

        // ======================================================================
        // CENTRE — Envelope
        // ======================================================================
        ShEnvelopeView? envView = null;
        Control EnvelopeTab()
        {
            envView = new ShEnvelopeView();
            WireDrag(envView, h => h switch { ShEnvelopeView.HAttack => Attack, ShEnvelopeView.HHold => Hold, ShEnvelopeView.HRelease => Release, _ => Floor },
                F(Attack, "Attack", AtkF), F(Hold, "Hold", HoldF), F(Release, "Release", RelF), F(Floor, "Floor", FloorF));
            ToolTip.SetTip(envView, MenuKit.Keys(Loc.T("device.shutter.one_opening_attack_hold_release")));
            Learn(envView, Release);

            var shapes = Chips(Shapes, i => Sel(Shape, 3) == i, i => SetP(Shape, i / 2f), Shape,
                Loc.T("device.shutter.shape_linear_straight_ramps_over"));
            var retrig = ToggleLatch(Retrigger, "Retrig", Loc.T("device.shutter.retrigger_trigger_mode_each_hit"));
            return CardLayout.View(envView,
                CardLayout.KnobColumn(K(Attack, "ATTACK", AtkF, cellW: 50), K(Hold, "HOLD", HoldF, cellW: 50), K(Release, "RELEASE", RelF, cellW: 50)),
                CardLayout.Line(6, Caps("SHAPE"), shapes, retrig));
        }

        // ======================================================================
        // CENTRE — Sidechain
        // ======================================================================
        ShKeyView? keyView = null;
        Control SidechainTab()
        {
            keyView = new ShKeyView();
            WireDrag(keyView, h => h == ShKeyView.HHp ? DetHP : DetLP, F(DetHP, "SC HP", HpF), F(DetLP, "SC LP", LpF));
            ToolTip.SetTip(keyView, MenuKit.Keys(Loc.T("device.shutter.the_detectors_band_pass_teal")));
            Learn(keyView, DetHP);

            var eq = Latch(DetFilter, () => On(DetFilter), () => SetP(DetFilter, On(DetFilter) ? 0f : 1f), () => On(DetFilter) ? "SC EQ on" : "SC EQ off",
                Loc.T("device.shutter.sc_eq_the_detector_hears"));
            return CardLayout.View(keyView,
                CardLayout.KnobColumn(K(DetHP, "SC HP", HpF, Teal, cellW: 50), K(DetLP, "SC LP", LpF, Teal, cellW: 50)),
                CardLayout.Line(6, eq, ListenLatch()));
        }

        // ======================================================================
        // CENTRE — Pattern (rhythmic gate)
        // ======================================================================
        int NSteps() => StepCounts[Sel(PatSteps, 3)];
        int NLevels() => LevelCounts[Sel(PatLevels, 3)];
        int RateIdx() => Sel(PatRate, 5);
        string RateName() => On(PatSync) ? RateSync[RateIdx()] : RateFree[RateIdx()];
        float Qz(double v) { int l = NLevels(); return (float)(Math.Round(Math.Clamp(v, 0, 1) * l) / l); }
        float[] StepsNow() { int n = NSteps(); var a = new float[n]; for (int k = 0; k < n; k++) a[k] = P(Step1 + k); return a; }
        static float[] Resample(float[] a, int n) { var r = new float[n]; for (int i = 0; i < n; i++) r[i] = a[(int)((long)i * a.Length / n)]; return r; }
        float[] Template(int i) => Resample(Array.ConvertAll(Patterns[i].Steps, v => v / 8f), NSteps());
        // The browser's name: the shape the steps match, else Custom.
        int PatternIdx()
        {
            var cur = StepsNow();
            for (int i = 0; i < Patterns.Length; i++)
            {
                var t = Template(i);
                bool same = true;
                for (int k = 0; k < cur.Length && same; k++) same = Math.Abs(Qz(t[k]) - Qz(cur[k])) < 1e-3;
                if (same) return i;
            }
            return -1;
        }
        string PatternName() { int i = PatternIdx(); return i < 0 ? "Custom" : Patterns[i].Name; }
        // A one-shot write of the whole grid (each changed step is its own automation gesture).
        void WriteSteps(float[] a)
        {
            for (int k = 0; k < a.Length && k < kMaxSteps; k++)
                if (Math.Abs(P(Step1 + k) - a[k]) > 1e-5) SetP(Step1 + k, a[k]);
            RefreshAll();
        }

        var patBuf = new float[kMaxSteps];
        ShPatternView? patView = null;
        int patTool = 0;

        // A slider drawn as a filled bar with its value inside (Complexity / Smooth / Swing).
        Control FillBar(int p, string name, Func<double, string> fmt, string tip)
        {
            var fill = new Border { HorizontalAlignment = HorizontalAlignment.Left, Background = NotaPalette.Wash(NotaPalette.VizInk, 0x30) };
            var tb = new TextBlock { FontSize = 9, Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
            var grid = new Grid { Children = { fill, tb } };
            var host = new Border
            {
                Height = 18, Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Cell,
                ClipToBounds = true, Cursor = new Cursor(StandardCursorType.SizeWestEast), Child = grid,
            };
            bool drag = false;
            void Paint()
            {
                double v = P(p);
                fill.Width = Math.Max(0, grid.Bounds.Width * v);
                tb.Text = fmt(P(p));
                host.BorderBrush = drag ? Brass : v > 0.004 ? NotaPalette.BorderStrong : BorderDef;
                tb.Foreground = v > 0.004 ? TextPrimary : TextSecondary;
            }
            void SetX(double x) { Raw(p, x / Math.Max(1, grid.Bounds.Width)); Paint(); RefreshAll(); }
            host.PointerPressed += (_, e) =>
            {
                if (!e.GetCurrentPoint(host).Properties.IsLeftButtonPressed) return;
                if ((e.ClickCount == 2 || (e.KeyModifiers & KeyModifiers.Alt) != 0)) { Reset(p); Paint(); RefreshAll(); e.Handled = true; return; }
                drag = true; Begin(p); e.Pointer.Capture(host); SetX(e.GetPosition(grid).X); e.Handled = true;
            };
            host.PointerMoved += (_, e) => { if (drag) SetX(e.GetPosition(grid).X); };
            host.PointerReleased += (_, e) => { if (!drag) return; drag = false; e.Pointer.Capture(null); End(p); };
            host.PointerCaptureLost += (_, _) => { if (!drag) return; drag = false; End(p); };
            grid.SizeChanged += (_, _) => Paint();
            readouts.Add(() => { if (!drag) Paint(); });
            Learn(host, p);
            ToolTip.SetTip(host, MenuKit.Keys(tip + Loc.T("device.shutter.click_to_type")));
            ValueEntry.Attach(host, F(p, name, fmt), tb);
            return host;
        }

        // A plain push button (fills its cell).
        Border Button(string text, Action click, string tip, Func<bool>? enabled = null)
        {
            var tb = new TextBlock { Text = text, FontSize = 9, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
            var b = new Border
            {
                Height = 18, Padding = new Thickness(8, 0), Background = Raised, CornerRadius = NotaRadius.Cell,
                Cursor = new Cursor(StandardCursorType.Hand), Child = tb,
            };
            b.PointerPressed += (_, e) =>
            {
                if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed || enabled?.Invoke() == false) return;
                click(); RefreshAll(); e.Handled = true;
            };
            readouts.Add(() => tb.Foreground = enabled?.Invoke() == false ? TextDisabled : TextPrimary);
            ToolTip.SetTip(b, tip);
            return b;
        }

        void Randomize()
        {
            double c = P(PatComplexity);
            int n = NSteps();
            var a = new float[n];
            for (int i = 0; i < n; i++)
            {
                bool on = i == 0 || Rng.NextDouble() < 0.35 + c * 0.45;
                a[i] = !on ? 0 : Qz(c < 0.3 ? 1 : Math.Clamp(1 - Rng.NextDouble() * c * 0.9, 0.125, 1));
            }
            WriteSteps(a);
        }
        void StepPattern(int dir)
        {
            int cur = PatternIdx();
            int i = ((cur < 0 ? 0 : cur + dir) % Patterns.Length + Patterns.Length) % Patterns.Length;
            WriteSteps(Array.ConvertAll(Template(i), v => Qz(v)));
        }

        Control PatternTab()
        {
            patView = new ShPatternView { Tool = patTool };
            var touched = new HashSet<int>();
            patView.StepsChanged += a =>
            {
                for (int k = 0; k < a.Length; k++)
                {
                    if (Math.Abs(P(Step1 + k) - a[k]) < 1e-5) continue;
                    if (touched.Add(k)) Begin(Step1 + k);
                    Raw(Step1 + k, a[k]);
                }
                RefreshAll();
            };
            patView.GestureEnd += () => { foreach (int k in touched) End(Step1 + k); touched.Clear(); };
            ToolTip.SetTip(patView, Loc.T("device.shutter.the_step_pattern_each_column"));

            var tools = Segments(new[] { "Draw", "Line", "Erase", "Flip" }, () => patTool, i => { patTool = i; if (patView is not null) patView.Tool = i; }, out var toolSync, padX: 6);
            readouts.Add(toolSync);
            ToolTip.SetTip(tools, Loc.T("device.shutter.mouse_tool_for_the_grid"));

            Border Arrow(GlyphKind kind, int dir)
            {
                var b = new Border { Width = 18, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = new Glyph(kind, 7) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center } };
                b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; StepPattern(dir); e.Handled = true; };
                return b;
            }
            var pname = new TextBlock { FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
            readouts.Add(() => pname.Text = PatternName());
            var browser = new Border
            {
                Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Cell,
                Child = new DockPanel { Children = { Docked(Arrow(GlyphKind.ChevronLeft, -1), Dock.Left), Docked(Arrow(GlyphKind.ChevronRight, 1), Dock.Right), pname } },
            };
            ToolTip.SetTip(browser, Loc.T("device.shutter.pattern_shapes_the_arrows_step"));
            var rnd = Button("Rnd", Randomize, Loc.T("device.shutter.roll_a_new_pattern_complexity"));
            var cx = FillBar(PatComplexity, "Complexity", v => "Complexity " + Pct((float)v), Loc.T("device.shutter.complexity_how_busy_and_varied"));
            var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,110"), ColumnSpacing = 5, Height = 20 };
            head.Children.Add(tools); head.Children.Add(Col(browser, 1)); head.Children.Add(Col(rnd, 2)); head.Children.Add(Col(cx, 3));

            var smooth = FillBar(PatSmooth, "Smooth", v => "Smooth " + Pct((float)v), Loc.T("device.shutter.smooth_ramps_into_each_step"));
            var swing = FillBar(PatSwing, "Swing", v => NotaNum.F($"Swing {v * 75:0} %"), Loc.T("device.shutter.swing_every_second_step_comes"));
            var nSt = Mono("", 9, TextPrimary); var nLv = Mono("", 9, TextPrimary);
            readouts.Add(() => { nSt.Text = NSteps().ToString(); nLv.Text = NLevels().ToString(); });
            Border Cycle(TextBlock t, Action a, string tip)
            {
                var b = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = t };
                b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; a(); RefreshAll(); e.Handled = true; };
                ToolTip.SetTip(b, tip);
                return b;
            }
            var gridSize = new Border
            {
                Height = 18, Padding = new Thickness(6, 0), Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Cell,
                Child = Row(4, Caps("GRID"),
                    Cycle(nSt, () =>
                    {
                        var cur = StepsNow();
                        int si = (Sel(PatSteps, 3) + 1) % 3;
                        var next = Resample(cur, StepCounts[si]);
                        SetP(PatSteps, si / 2f);
                        WriteSteps(next);
                    }, Loc.T("device.shutter.steps_8_16_or_32")),
                    Mono("×", 8, TextTertiary),
                    Cycle(nLv, () =>
                    {
                        var cur = StepsNow();
                        SetP(PatLevels, (Sel(PatLevels, 3) + 1) % 3 / 2f);
                        WriteSteps(Array.ConvertAll(cur, v => Qz(v)));
                    }, Loc.T("device.shutter.levels_4_8_or_16"))),
            };
            var target = Seg(PatTarget, new[] { "Off", "Volume", "Map" },
                Loc.T("device.shutter.target_off_volume_the_pattern"));
            var foot = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,Auto,Auto"), ColumnSpacing = 5, Height = 20 };
            foot.Children.Add(smooth); foot.Children.Add(Col(swing, 1)); foot.Children.Add(Col(gridSize, 2)); foot.Children.Add(Col(target, 3));

            return new DockPanel
            {
                LastChildFill = true, Margin = new Thickness(8, 5, 8, 5),
                Children = { Docked(head, Dock.Top), Docked(foot, Dock.Bottom), new Border { Margin = new Thickness(0, 5), Child = patView } },
            };
        }

        // ======================================================================
        // RIGHT — the panel that follows the tab: Detector · Opening · Key · Rhythm
        // ======================================================================
        Control Line(Func<string> k, Func<string> v, IBrush? ink = null)
        {
            var key = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
            var val = Mono("", 8, ink ?? TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
            readouts.Add(() => { key.Text = k(); val.Text = v(); });
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
            g.Children.Add(key);
            g.Children.Add(Col(val, 1));
            return g;
        }
        Control Info(Func<string> text)
        {
            var t = Mono("", 8, TextSecondary);
            t.TextTrimming = TextTrimming.CharacterEllipsis;
            readouts.Add(() => t.Text = text());
            return t;
        }
        static string GrF(double gr) => gr < 0.05 ? "0.0" : gr > 99 ? "−∞" : NotaNum.F($"−{gr:0.0}");

        Control StateBox()
        {
            var t = Caps("STATE");
            var dot = new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Group, VerticalAlignment = VerticalAlignment.Center };
            var l1 = Mono("", 9, TextPrimary);
            var l2 = Mono("", 8, TextSecondary);
            l1.TextTrimming = l2.TextTrimming = TextTrimming.CharacterEllipsis;
            var b = new Border
            {
                Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Cell, Padding = new Thickness(6, 4),
                Child = new StackPanel { Spacing = 2, Children = { t, Row(5, dot, l1), l2 } },
            };
            readouts.Add(() =>
            {
                int st = State();
                bool moving = st is 1 or 3 or 4;
                string name = Duck() ? st switch { 2 => "ducking", 0 => "clear", _ => StateNames[st] } : StateNames[st];
                l1.Text = NotaNum.F($"{name} · {Sc(S_GateGain) * 100:0}\u2009%");
                l2.Text = P(Floor) > 0.001f && st == 0 ? NotaNum.F($"{GrText()} · floor {FloorDb():0.0}") : NotaNum.F($"{GrText()} · look {LookMs()}\u2009ms");
                dot.Background = st == 2 ? Success : moving ? Brass : NotaPalette.BorderStrong;
                l1.Foreground = moving ? AccentBright : TextPrimary;
                b.BorderBrush = moving ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
                t.Foreground = moving ? AccentBright : TextTertiary;
            });
            ToolTip.SetTip(b, Loc.T("device.shutter.what_the_gate_is_doing"));
            return b;
        }

        (Control, Control) DetectorPanel()
        {
            var box = CardLayout.ReadoutBox(new StackPanel { Spacing = 2, Children = {
                Caps("MEASUREMENTS"),
                Line(() => Sc(S_ExtKey) > 0.5 ? "sc in" : "in", () => DbF(Sc(S_ExtKey) > 0.5 ? Sc(S_KeyDb) : Sc(S_InDb))),
                Line(() => "out", () => DbF(Sc(S_OutDb))),
                Line(() => "GR · peak", () => NotaNum.F($"{GrF(Sc(S_GrDb))} · {GrF(Sc(S_PeakGrDb))}\u2009dB")) } });
            var reset = Latch(-1, () => false, () => engine.DeviceAction(track, di, A_ResetMeters, 0, 0), () => "Reset",
                Loc.T("device.shutter.reset_clear_the_peak_reduction"));
            return (CardLayout.Head(CardLayout.Title("Detector"), reset), CardLayout.Rows(StateBox(), box));
        }

        (Control, Control) OpeningPanel()
        {
            var box = CardLayout.ReadoutBox(new StackPanel { Spacing = 2, Children = {
                Caps(Loc.T("device.shutter.opening")),
                Line(() => "attack · hold · release", Times),
                Line(() => Loc.T("device.shutter.one_opening"), () => NotaNum.F($"{MsN(AtkMs() + HoldMs() + RelMs())}\u2009ms")),
                Line(() => "openings", () => NotaNum.F($"{Sc(S_TrigPerBar):0} / bar")) } });
            return (CardLayout.Head(CardLayout.Title(Loc.T("device.shutter.opening"))), CardLayout.Rows(
                box,
                CardLayout.Rule(),
                Info(() => P(Floor) <= 0.001f ? (Duck() ? Loc.T("device.shutter.ducks_to_silence") : Loc.T("device.shutter.closes_to_silence")) : Loc.F("device.shutter.floor_db_instead_of_silence", FloorDb()))));
        }

        (Control, Control) KeyPanel()
        {
            var box = CardLayout.ReadoutBox(new StackPanel { Spacing = 2, Children = {
                Caps("KEY"),
                Line(() => "level", () => DbF(Sc(S_ExtKey) > 0.5 ? Sc(S_KeyDb) : Sc(S_InDb))),
                Line(() => Loc.T("device.shutter.fires_on"), () => On(DetFilter) ? HpF(P(DetHP)) + "…" + LpF(P(DetLP)) : "full band"),
                Line(() => "look", () => NotaNum.F($"{LookMs()}\u2009ms")) } });
            return (CardLayout.Head(ExtSwitch()), CardLayout.Rows(
                CardLayout.LabelRow("SOURCE", KeyDrop(true), stretch: true),
                box,
                CardLayout.Rule(),
                Info(() => NotaNum.F($"{(Duck() ? "ducks" : "closes")} to {(P(Floor) <= 0.001f ? "−∞\u2009dB" : NotaNum.F($"{FloorDb():0.0}\u2009dB"))} · {GrText()}"))));
        }

        (Control, Control) RhythmPanel()
        {
            var rate = K(PatRate, "RATE", _ => RateName(), steps: 5, tip: Loc.T("device.shutter.rate_how_long_the_whole"), size: 28, cellW: 54);
            var depth = K(PatDepth, "DEPTH", v => Pct((float)v), Teal, tip: Loc.T("device.shutter.depth_how_far_an_empty"), size: 28, cellW: 54);
            var clock = Segments(new[] { "Sync", "Free" }, () => On(PatSync) ? 0 : 1, i => { SetP(PatSync, i == 0 ? 1f : 0f); RefreshAll(); }, out var clockSync);
            readouts.Add(clockSync);
            Learn(clock, PatSync);
            ToolTip.SetTip(clock, Loc.T("device.shutter.clock_sync_locks_the_pattern"));
            var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 4, VerticalAlignment = VerticalAlignment.Center };
            btns.Children.Add(Button("Copy", () => _clipboard = StepsNow(), Loc.T("device.shutter.copy_the_steps")));
            btns.Children.Add(Col(Button("Paste", () => { if (_clipboard is { } c) WriteSteps(Array.ConvertAll(Resample(c, NSteps()), v => Qz(v))); }, Loc.T("device.shutter.paste_copied_steps_fitted_to"), () => _clipboard is not null), 1));
            btns.Children.Add(Col(Button("Clear", () => WriteSteps(new float[NSteps()]), Loc.T("device.shutter.clear_every_step")), 2));
            return (CardLayout.Head(CardLayout.Title("Rhythm"), clock), new Border { Padding = new Thickness(8, 4, 8, 0), Child = new StackPanel { Spacing = 4, Children = {
                CardLayout.Pair(rate, depth),
                btns,
                Toggle(PatRetrig, Loc.T("device.shutter.retrig_on_midi_note"), Loc.T("device.shutter.retrig_every_midi_note_on")),
                Toggle(PatGated, Loc.T("device.shutter.only_while_gate_open"), Loc.T("device.shutter.gated_the_pattern_plays_only")) } } });
        }

        // ======================================================================
        // Frames: L (tabs, the panel that follows them, Floor · Threshold · Return under the Gate /
        // Duck switch) · S (the Signal graph over the mode and Threshold · Attack · Release · Floor)
        // ======================================================================
        int centreTab = 0;
        var extras = Mono("", 7, TextTertiary);
        var extrasHost = new Border { Background = Brushes.Transparent, Child = extras, VerticalAlignment = VerticalAlignment.Stretch };
        extrasHost.PointerPressed += (_, e) =>
        {
            if (centreTab != 0 || !e.GetCurrentPoint(extrasHost).Properties.IsLeftButtonPressed) return;
            engine.DeviceAction(track, di, A_Window, (WindowIdx() + 1) % 3, 0);
            e.Handled = true;
        };
        readouts.Add(() =>
        {
            extras.Text = centreTab switch
            {
                1 => NotaNum.F($"one opening · {MsN(AtkMs() + HoldMs() + RelMs())}\u2009ms"),
                2 => NotaNum.F($"key: {KeyName()} · {(On(DetFilter) ? "filter " + HpF(P(DetHP)) + "…" + LpF(P(DetLP)) : "full band")}"),
                3 => NotaNum.F($"step {(int)Sc(kPatAt + P_Step) + 1}/{NSteps()} · {(On(PatSync) ? $"{Sc(S_Bpm):0} BPM" : RateFree[RateIdx()])}"),
                _ => NotaNum.F($"window {WindowText()} · look {LookMs()}\u2009ms"),
            };
            extrasHost.Cursor = centreTab == 0 ? new Cursor(StandardCursorType.Hand) : Cursor.Default;
        });
        ToolTip.SetTip(extrasHost, Loc.T("device.shutter.signal_tab_click_to_change") + string.Join(" · ", WindowNames));

        Control root = CardLayout.IsMini(ctx, di)
            ? CardLayout.Mini(SignalGraph(), ModeSeg(),
                K(Threshold, "THRESH", ThrShort, cellW: 56), K(Attack, "ATTACK", AtkF, cellW: 56), K(Release, "RELEASE", RelF, cellW: 56),
                K(Floor, "FLOOR", FloorF, Teal, tip: Loc.T("device.shutter.floor_the_level_when_closed"), cellW: 56))
            : CardLayout.Large(new[] { "Signal", "Envelope", "Sidechain", "Pattern" }, 0,
                t => t switch { 1 => EnvelopeTab(), 2 => SidechainTab(), 3 => PatternTab(), _ => SignalTab() },
                t => t switch { 1 => OpeningPanel(), 2 => KeyPanel(), 3 => RhythmPanel(), _ => DetectorPanel() },
                extrasHost,
                CardLayout.Output(
                    K(Floor, "FLOOR", FloorF, tip: Loc.T("device.shutter.floor_the_level_when_closed"), cellW: 54),
                    K(Threshold, "THRESH", ThrShort, size: 44, cellW: 58),
                    K(Return, "RETURN", RetF, Teal, tip: Loc.T("device.shutter.return_how_far_under_the"), cellW: 54),
                    ModeSeg()),
                t => { centreTab = t; Refresh(); });

        void Refresh()
        {
            scN = engine.DeviceScope(track, di, scope, kScope);
            int n = scN >= kScope ? Math.Clamp((int)Sc(S_HistN), 0, kHist) : 0;
            var h = Hist();
            if (centreTab == 0 && signal is not null)
                signal.Set(h, H_In, H_Gate, n, ThrDb(), ThrDb() - RetDb(), Duck(), WindowText());
            if (centreTab == 1 && envView is not null)
                envView.Set(AtkMs(), HoldMs(), RelMs(), FloorLin(), Sel(Shape, 3), Duck(), On(Retrigger),
                    P(Floor) <= 0.001f ? "−∞\u2009dB" : NotaNum.F($"{FloorDb():0.0}\u2009dB"), MsN(AtkMs()), MsN(HoldMs()), MsF(RelMs()));
            if (centreTab == 3 && patView is not null)
            {
                int ns = NSteps();
                for (int k = 0; k < ns; k++) patBuf[k] = P(Step1 + k);
                int tg = Sel(PatTarget, 3);
                bool on = tg > 0 && scN >= kScope;
                patView.Set(patBuf, ns, NLevels(), on ? (int)Sc(kPatAt + P_Step) : -1, on ? Sc(kPatAt + P_Phase) : -1,
                    P(PatSmooth), P(PatSwing) * 0.375, P(PatDepth), tg == 2, tg > 0,
                    tg == 2 ? Loc.T("device.shutter.map_pattern_out_2") : tg == 1 ? "gain" : "off");
            }
            if (centreTab == 2 && keyView is not null)
                keyView.Set(Exp(P(DetHP), 20, 2000), Exp(P(DetLP), 200, 20000), On(DetFilter), h, H_Gate, n, Duck() ? "duck" : "reduction");
            RefreshAll();
        }
        // Graphs follow the params every tick, also while dragged (the envelope keeps its time span then).
        ctx.AddDeviceRefresher(Refresh);
        Refresh();
        return root;

    }
}