Newer
Older
EARS-LINUX / program / MapWindow.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Gtk;
using UI = Gtk.Builder.ObjectAttribute;

public class MapWindow : IDisposable
{
    private const float FRONT_Z    = 1.0f;
    private const float BACK_Z     = -1.0f;
    private const float RIGHT_Z    = 0.5f;
    private const float LEFT_Z     = -0.5f;
    private const float Z_TOLERANCE = 0.1f;

    // ══════════════════════════════════════════════════════════════════
    //  TUNABLES — per (jacket size, view). Absolute values, subtracted.
    //  Paste a CalibrationWindow dump into the tuner to overwrite these,
    //  then "Dump seed" to bake the result back into SeedDefaults().
    // ══════════════════════════════════════════════════════════════════

    public class Tune
    {
        public double OffsetX   = 25.0;   // circle cluster shift (SUBTRACTED)
        public double OffsetY   = 50.0;
        public double SizeScale = 1.0;    // circle diameter multiplier
        public double Cluster   = 1.0;    // 1.0 = no clustering
        public double MapZoom   = 1.0;    // see MapFit mode
        public double MapX      = 0.0;    // map nudge, body pixels
        public double MapY      = 0.0;
        public double MapAlpha  = 0.7;
        public double FitMargin = 40.0;   // Form2: panel − 40 (front: −100)
        // cursor calibration
        public double MarginX   = 0.0;
        public double MarginY   = 0.0;
        public bool   MirrorX   = false;  // flip cursor horizontally for this size:view
        public bool   MirrorY   = false;

        public Tune Clone() { return (Tune)MemberwiseClone(); }
    }

    /// How the MAP is sized over the body.
    ///   Native546  — Form2 behaviour: 546x546 drawn at native size, centred.
    ///                MapZoom multiplies that. MapZoom 1.0 == today's output.
    ///   FitBody    — CalibrationWindow behaviour: raw map scaled to fit the
    ///                body, then x MapZoom. Use this to verify a dump.
    public enum MapFit { Native546, FitBody }

    private readonly Dictionary<string, Tune> _tunes = new Dictionary<string, Tune>();
    private MapFit _mapFit = MapFit.FitBody;

    private string TuneKey { get { return JacketSize + ":" + _view; } }

    private Tune T
    {
        get
        {
            string k = TuneKey;
            if (!_tunes.ContainsKey(k)) _tunes[k] = new Tune();
            return _tunes[k];
        }
    }

    private void SeedDefaults()
    {
        // ── L ────────────────────────────────────────────────────────
        Seed("L:front",  9.0,   34.0,   2.75, 1.10,  95, 1.060, -4.0, -14.0, 0.70);
        Seed("L:back",  -2.0,   10.0,   1.95, 0.90,  40, 1.090, 2.0, -7.0, 0.70);
        Seed("L:right", 16.0,  -106.0,  1.00, 0.50,  40, 1.010, -32.0, 71.0, 0.70);
        Seed("L:left", -14.0,  -110.0,  0.80, 0.40,  15, 1.050, 0.0, 5.0, 0.70);

        // ── XL ── (converted from the old XL_* deltas: L_offset − delta)
        // XL front/right/left cursors are mirrored (was hardcoded in TryGetCursorBodyPoint).
        Seed("XL:front",  7.0,   17.0,  2.30, 1.05, 50, 1.060, -4.0, -14.0, 0.70, true);
        Seed("XL:back",   5.0,   10.0,  1.95, 0.90,  40, 1.090, 2.0, -7.0, 0.70);
        Seed("XL:right",  10.0, -108.0,  0.80, 0.40,  40, 1.010, -32.0, 71.0, 0.70, true);
        Seed("XL:left", -4.0, -101.0,  0.80, 0.40,  40, 1.050, 0.0, 5.0, 0.70, true);
    }

    private void Seed(string key, double ox, double oy, double size, double cluster,
                      double fitMargin, double zoom, double mx, double my, double alpha,
                      bool mirrorX = false)
    {
        _tunes[key] = new Tune
        {
            OffsetX = ox, OffsetY = oy, SizeScale = size, Cluster = cluster,
            FitMargin = fitMargin, MapZoom = zoom, MapX = mx, MapY = my, MapAlpha = alpha,
            MirrorX = mirrorX
        };
    }

    /// Shows up in the log at startup, so you can tell which MapWindow.cs is running.
    private const string BuildTag = "2026-10-20 fixes (legacy RFID, body reload, calib, multi-voice)";

    private const int CircleDiameter = 50;
    private const int MapSize = 546;     // Form2: new Bitmap(mapImage, 546, 546)

    // ── glade widgets ──
    [UI] private DrawingArea  MapArea           = null;
    [UI] private Label        MapTitleLabel     = null;
    [UI] private Label        MapCaseLabel      = null;
    [UI] private Button       MapBackButton     = null;
    [UI] private RadioButton  BodySkeletonRadio = null;
    [UI] private RadioButton  BodyJacketRadio   = null;
    [UI] private ComboBoxText JacketSizeCombo   = null;
    [UI] private RadioButton  ViewFrontRadio    = null;
    [UI] private RadioButton  ViewBackRadio     = null;
    [UI] private RadioButton  ViewRightRadio    = null;
    [UI] private RadioButton  ViewLeftRadio     = null;
    [UI] private Switch       ShowNumbersSwitch = null;
    [UI] private Box          ShowNumbersSwitchRow = null;   // 番号を表示 — debug mode only
    [UI] private ScrolledWindow MapControlScroller = null;   // left panel: scrolls only in debug
    [UI] private RadioButton  SizeLRadio        = null;
    [UI] private RadioButton  SizeXLRadio       = null;

    // NEW — needed only so the map-page CSS can reach them.
    [UI] private Button       SoundTestButton   = null;
    [UI] private Switch       BlackAudioSwitch  = null;
    [UI] private Label        JacketSizeLabel   = null;
    // For new UI
    [UI] private DrawingArea HeartWaveArea   = null;
    [UI] private DrawingArea BreathWaveArea  = null;
    [UI] private Label       MapContactLabel = null;
    [UI] private Label MapPointHeader   = null;
    [UI] private Label HeartWaveHeader  = null;
    [UI] private Label BreathWaveHeader = null;
    [UI] private Button MapExplainButton = null;
    [UI] private Switch       ShowVolumeMapSwitch = null;
    [UI] private CheckButton  HideMetersCheck   = null;   // old glade only
    [UI] private Switch       ShowPointListSwitch = null; // new glade: ON = legacy meters shown
    [UI] private Box          ShowPointListSwitchRow = null; // hidden outside legacy (nothing to list)

    private readonly Language    _lang;
    // private readonly SoundLooper _sound = new SoundLooper();
    private readonly AudioEngine _sound = new AudioEngine();
    private AudioEngine.Voice _caseVoice, _heart1, _heart2, _breath;
    // Form2's addHeartSoundcheckBox1 / addBreathSoundcheckbox.
    // No glade widgets for these yet — flip them here to test.
    public bool HeartSoundEnabled  = false;
    public bool BreathSoundEnabled = false;

    private readonly List<RegionSound> _regions = new List<RegionSound>();
    private bool _showRegions = true;   // Ctrl+R toggles the colour overlay
    private bool _showRegionLabels = true;
    private CheckButton _hideLabelsCheck;

    private static readonly string[] RegionLabels = {
        "心音1","心音2","気管","気管支","気管支肺胞","右肺胞","左肺胞" };

    // RGB triples — byte arrays, to avoid a System.Drawing dependency.
    private static readonly byte[][] RegionColors = {
        new byte[]{220, 60, 60}, new byte[]{255,140,  0},
        new byte[]{ 60,160,230}, new byte[]{ 40,100,210},
        new byte[]{ 90,190,140}, new byte[]{180,120,220},
        new byte[]{230,200, 70} };

    private int _lastPx = -1, _lastPy = -1;
    private const int TAG_IDLE_MS  = 250;   // Form2's noDataIntervalMs
    private const int WATCHDOG_MS  = 100;

    private DateTime _lastPosLine = DateTime.MinValue;
    private uint _watchdogId;

    // ── state ──
    private Gdk.Pixbuf _body;        // background, native size
    private Gdk.Pixbuf _map;         // 546x546, black keyed — audio reference
    private Gdk.Pixbuf _mapRaw;      // keyed, ORIGINAL size — used by FitBody mode
    private CaseDefinition _case;
    private string _view = "front";
    private readonly ArduinoConnection _arduino;

    // ── live Arduino position ──
    private float _currentX, _currentY, _currentZ;
    private bool  _hasPosition;

    private static readonly Regex FullRx = new Regex(
        @"(\d+(?:\.\d+)?)\(([+-]?\d+(?:\.\d+)?),([+-]?\d+(?:\.\d+)?),([+-]?\d+(?:\.\d+)?)\)",
        RegexOptions.Compiled);
    private static readonly Regex AvgRx = new Regex(
        @"Avg(\d+(?:\.\d+)?)\(([+-]?\d+(?:\.\d+)?),([+-]?\d+(?:\.\d+)?),([+-]?\d+(?:\.\d+)?)\)",
        RegexOptions.Compiled);
    private string _bodyPath = "(none)";
    private string _mapPath  = "(none)";


    public event EventHandler BackRequested;

    private JacketData _jacket;
    private List<float> _highlighted = new List<float>();
    private static bool _listed;

    // ── tuner state ──
    private Window   _tuner;
    private TextView _tunerOut;
    private Label    _tunerInfo, _tunerKey;
    private readonly Dictionary<string, SpinButton> _spins = new Dictionary<string, SpinButton>();
    private CheckButton _tShowBody, _tShowMap, _tShowCircles, _tGuides;
    private CheckButton _tMirrorX, _tMirrorY;
    private ComboBoxText _tFitCombo;
    private bool _building;
    private bool _keysHooked;

    private bool ShowBody    { get { return _tShowBody    == null || _tShowBody.Active; } }
    private bool ShowMap     { get { return (_tShowMap == null || _tShowMap.Active)
                                        && (ShowVolumeMapSwitch == null || ShowVolumeMapSwitch.Active); } }
    private bool ShowCircles { get { return (_tShowCircles == null || _tShowCircles.Active)
                                        && (ShowNumbersSwitch == null || ShowNumbersSwitch.Active); } }
    private bool ShowGuides  { get { return _tGuides != null && _tGuides.Active; } }

    // ── debug state ──
    private uint _debugSweepId;
    private int  _debugLevel;
    private int  _debugStep = 5;

    // ── debug mouse probe ──
    private bool   _mouseProbe;            // true while the left button is held on the map
    private double _mouseBx, _mouseBy;     // probe point, BODY PIXELS

    // ── waveform boxes ──
    private WaveData _heartWave, _breathWave;
    private double _heartCursor = -1, _breathCursor = -1;   // 0..1, -1 = hidden
    private bool _audible;                                  // true while any sound is unmuted
    private uint _waveTimerId;
    private readonly System.Diagnostics.Stopwatch _playClock = new System.Diagnostics.Stopwatch();
    // Per box: is a sound of that kind audible right now? Each box shows its
    // own cursor only while its own sound is playing.
    private bool _heartAudible, _breathAudible;
    // Current-mode legend levels (0..1), for the point list.
    private float _legendHeart, _legendBreath;

    // ── heart / lung / mix filter ──
    public enum SoundFilter { Mix, HeartOnly, LungOnly }
    private SoundFilter _filter = SoundFilter.Mix;
    // glade: 再生する音 segment (ミックス / 心音のみ / 肺音のみ)
    [UI] private RadioButton SoundMixRadio       = null;
    [UI] private RadioButton SoundHeartOnlyRadio = null;
    [UI] private RadioButton SoundLungOnlyRadio  = null;

    private bool HeartAllowed { get { return _filter != SoundFilter.LungOnly; } }
    private bool LungAllowed  { get { return _filter != SoundFilter.HeartOnly; } }

    // ══════════════════════════════════════════════════════════════════

    public MapWindow(Builder builder, ArduinoConnection arduino, Language language)
    {
        builder.Autoconnect(this);
        _arduino = arduino;
        Logger.Write("map", "MapWindow build " + BuildTag);

        SeedDefaults();
        LoadCalibFile(false);           // calib.txt overrides seeds if present

        _jacket = JacketData.Load();
        Logger.Write("jacket", "folder: " + _jacket.Folder + " loaded=" + _jacket.Loaded);

        if (MapArea == null || MapTitleLabel == null || MapBackButton == null)
            throw new InvalidOperationException(
                "Glade id mismatch — MapArea=" + (MapArea != null) +
                " MapTitleLabel=" + (MapTitleLabel != null) +
                " MapBackButton=" + (MapBackButton != null));

        _lang = language;

        // ── styling hooks ─────────────────────────────────────────────
        // GTK3's Builder does NOT copy the glade id into the CSS name, so
        // #Id selectors match nothing unless we assign Name ourselves. The
        // shared "mappage" class then lets touch_friendly.css restyle this
        // page without touching the splash / sound / settings pages.
        Widget[] mapWidgets = {
            MapArea, MapTitleLabel, MapCaseLabel, MapBackButton,
            BodySkeletonRadio, BodyJacketRadio, JacketSizeCombo, JacketSizeLabel,
            ViewFrontRadio, ViewBackRadio, ViewRightRadio, ViewLeftRadio,
            ShowNumbersSwitch, BlackAudioSwitch, SoundTestButton, ShowVolumeMapSwitch,
            SizeLRadio, SizeXLRadio, HideMetersCheck
        };
        foreach (var w in mapWidgets)
            if (w != null) w.StyleContext.AddClass("mappage");

        AddClass(MapTitleLabel,    "map-title");
        AddClass(MapContactLabel,  "contact-chip");
        AddClass(MapPointHeader,   "panel-header");
        AddClass(HeartWaveHeader,  "panel-header");
        AddClass(BreathWaveHeader, "panel-header");
        AddClass(MapExplainButton, "nav-button");
        AddClass(MapBackButton,    "nav-button");

        SetName(MapArea,           "MapArea");
        SetName(MapTitleLabel,     "MapTitleLabel");
        SetName(MapCaseLabel,      "MapCaseLabel");
        SetName(BodySkeletonRadio, "BodySkeletonRadio");
        SetName(BodyJacketRadio,   "BodyJacketRadio");
        SetName(JacketSizeCombo,   "JacketSizeCombo");
        SetName(JacketSizeLabel,   "JacketSizeLabel");
        SetName(ViewFrontRadio,    "ViewFrontRadio");
        SetName(ViewBackRadio,     "ViewBackRadio");
        SetName(ViewRightRadio,    "ViewRightRadio");
        SetName(ViewLeftRadio,     "ViewLeftRadio");
        SetName(SoundTestButton,   "SoundTestButton");
        SetName(HideMetersCheck, "HideMetersCheck");
        SetName(ShowNumbersSwitch,   "ShowNumbersSwitch");
        SetName(BlackAudioSwitch,    "BlackAudioSwitch");
        SetName(ShowVolumeMapSwitch, "ShowVolumeMapSwitch");
        SetName(SizeLRadio,          "SizeLRadio");
        SetName(SizeXLRadio,         "SizeXLRadio");

        // Register() assigns Name itself and pulls the label from the CSVs.
        _lang.Register("MapBackButton", MapBackButton);

        // ── signals ───────────────────────────────────────────────────
        MapArea.Drawn         += OnMapDrawn;
        HeartWaveArea.Drawn  += (o, a) => DrawWave(a, HeartWaveArea,  _heartWave,  _heartCursor,
                                                   _heartAudible  && HeartAllowed, 0.86, 0.22, 0.20);
        BreathWaveArea.Drawn += (o, a) => DrawWave(a, BreathWaveArea, _breathWave, _breathCursor,
                                                   _breathAudible && LungAllowed,  0.21, 0.57, 0.78);
        MapBackButton.Clicked += OnBackClicked;

        BodySkeletonRadio.Toggled += (s, e) => { if (BodySkeletonRadio.Active) ReloadBody(); };
        BodyJacketRadio.Toggled   += (s, e) => { if (BodyJacketRadio.Active)   ReloadBody(); };
        JacketSizeCombo.Changed   += (s, e) => { ReloadBody(); SyncSpins(); MapArea.QueueDraw(); };

        // 解説を見る — shows the case's explanation image (C100.png … C999.png)
        MapExplainButton.Clicked += (s, e) => ShowExplanation();

        // former 再生テスト — now switches output: speaker <-> headphone jack
        AudioOutput.Log += m => Logger.Write("output", m);
        if (SoundTestButton != null)
        {
            SoundTestButton.Clicked += (s, e) => ToggleOutput();
            UpdateOutputButton(AudioOutput.Current(), null);
        }
        _lang.Changed += (s, e) => { UpdateOutputButton(AudioOutput.Current(), null); UpdateContactChip(true); };

        HookView(ViewFrontRadio, "front");
        HookView(ViewBackRadio,  "back");
        HookView(ViewRightRadio, "right");
        HookView(ViewLeftRadio,  "left");

        if (ShowNumbersSwitch != null)
            ShowNumbersSwitch.AddNotification("active", (o, a) => MapArea.QueueDraw());

        // 番号を表示 is a calibration aid: only offered in debug mode (--debug or
        // EARS_DEBUG=1). Outside debug mode the row is hidden and numbers stay off.
        if (ShowNumbersSwitchRow != null)
        {
            ShowNumbersSwitchRow.NoShowAll = true;          // survives window.ShowAll()
            ShowNumbersSwitchRow.Visible   = AppConfig.DebugMode;
        }
        if (!AppConfig.DebugMode && ShowNumbersSwitch != null)
            ShowNumbersSwitch.Active = false;

        // Left panel: fixed in normal mode (sized in touch_friendly.css to fit),
        // scrollable in debug mode because of the extra 番号を表示 row.
        if (MapControlScroller != null)
            MapControlScroller.SetPolicy(PolicyType.Never,
                AppConfig.DebugMode ? PolicyType.Automatic : PolicyType.Never);
        if (ShowVolumeMapSwitch != null)
            ShowVolumeMapSwitch.AddNotification("active", (o, a) => MapArea.QueueDraw());
        // 聴診点リスト = colour legend + live level per sound, in both modes:
        // legacy lists the 7 regions, current mode lists heart / breath.
        if (ShowPointListSwitch != null)
        {
            ShowPointListSwitch.AddNotification("active", (o, a) =>
            {
                Logger.Write("map", "point list " + (ShowPointListSwitch.Active ? "ON" : "OFF"));
                MapArea.QueueDraw();
            });
        }

        HookFilter(SoundMixRadio,       SoundFilter.Mix);
        HookFilter(SoundHeartOnlyRadio, SoundFilter.HeartOnly);
        HookFilter(SoundLungOnlyRadio,  SoundFilter.LungOnly);
        if (BlackAudioSwitch != null)
            BlackAudioSwitch.AddNotification("active", (o, a) =>
            {
                _lastPx = _lastPy = -1;
                UpdateAudioFromPosition();
                Logger.Write("audio", "black-pixel audio " + (BlackAudioEnabled ? "ON" : "OFF"));
            });

        // L / XL buttons drive the hidden JacketSizeCombo, so JacketSize keeps working
        if (SizeLRadio != null)
            SizeLRadio.Toggled  += (s, e) => { if (SizeLRadio.Active)  JacketSizeCombo.Active = 0; };
        if (SizeXLRadio != null)
            SizeXLRadio.Toggled += (s, e) => { if (SizeXLRadio.Active) JacketSizeCombo.Active = 1; };

        // Ctrl+T anywhere, or Ctrl+double-click on the map, opens the tuner.
        MapArea.Realized += (s, e) => HookKeys();
        MapArea.AddEvents((int)(Gdk.EventMask.ButtonPressMask |
                                Gdk.EventMask.ButtonReleaseMask |
                                Gdk.EventMask.Button1MotionMask));
        MapArea.ButtonPressEvent += (o, a) =>
        {
            if (a.Event.Type == Gdk.EventType.TwoButtonPress &&
                (a.Event.State & Gdk.ModifierType.ControlMask) != 0)
                ToggleTuner();
        };

        // Debug mode: hold the left button on the map to hear that spot.
        MapArea.ButtonPressEvent += (o, a) =>
        {
            if (!AppConfig.DebugMode || a.Event.Button != 1) return;
            if (a.Event.Type != Gdk.EventType.ButtonPress) return;           // ignore double-click
            if ((a.Event.State & Gdk.ModifierType.ControlMask) != 0) return; // Ctrl = tuner
            MouseProbe(a.Event.X, a.Event.Y);
        };
        MapArea.MotionNotifyEvent += (o, a) =>
        {
            if (_mouseProbe) MouseProbe(a.Event.X, a.Event.Y);
        };
        MapArea.ButtonReleaseEvent += (o, a) =>
        {
            if (!_mouseProbe || a.Event.Button != 1) return;
            _mouseProbe = false;
            _lastPx = _lastPy = -1;
            UpdateContactChip();
            UpdateAudioFromPosition();       // mutes, unless a real tag is on the jacket
            MapArea.QueueDraw();
        };

        _sound.Log += msg => Logger.Write("sound", msg);
        if (!_sound.Init())
            Logger.Write("sound", "OpenAL init failed — session will be silent");
        // live position feed
        _arduino.LineReceived      += OnArduinoLine;
        _watchdogId = GLib.Timeout.Add(WATCHDOG_MS, OnTagWatchdog);
        _arduino.ConnectionChanged += OnArduinoConnectionChanged;
    }

    /// Null-safe: SoundTestButton / BlackAudioCheck / JacketSizeLabel are
    /// optional — an older glade without them must still load.
    private static void SetName(Widget w, string name)
    {
        if (w != null) w.Name = name;
    }

    private static void AddClass(Widget w, string cls)
    {
        if (w != null) w.StyleContext.AddClass(cls);
    }

    private void HookKeys()
    {
        if (_keysHooked) return;
        var top = MapArea.Toplevel as Window;
        if (top == null) return;
        _keysHooked = true;

        top.KeyPressEvent += (o, a) =>
        {
            if ((a.Event.State & Gdk.ModifierType.ControlMask) == 0) return;
            if (a.Event.Key == Gdk.Key.t || a.Event.Key == Gdk.Key.T)
                ToggleTuner();
            else if (a.Event.Key == Gdk.Key.r || a.Event.Key == Gdk.Key.R)
            {
                _showRegions = !_showRegions;
                MapArea.QueueDraw();
            }
        };
    }

    // ══════════════════════════════════════════════════════════════════
    //  チェストピース 接触 / 未接触 chip (header, top-right)
    // ══════════════════════════════════════════════════════════════════

    private int _contactState = -1;   // -1 unknown, 0 off, 1 on, 2 reader offline

    /// Green "接触中" while a chip is on the target (or the debug mouse probe
    /// is held), red "未接触" otherwise, grey-red "リーダー未接続" when the
    /// RFID reader is disconnected. Only touches the widget when it changes.
    private void UpdateContactChip(bool force = false)
    {
        if (MapContactLabel == null) return;

        int state = (_hasPosition || _mouseProbe) ? 1
                  : (_arduino != null && !_arduino.IsOpen && !AppConfig.DebugMode) ? 2
                  : 0;
        if (!force && state == _contactState) return;
        _contactState = state;

        bool en = _lang != null && _lang.IsEnglish;
        switch (state)
        {
            case 1:  MapContactLabel.Text = en ? "Chest piece in contact" : "チェストピース接触中"; break;
            case 2:  MapContactLabel.Text = en ? "Reader not connected"   : "リーダー未接続";       break;
            default: MapContactLabel.Text = en ? "Chest piece not in contact" : "チェストピース未接触"; break;
        }

        var ctx = MapContactLabel.StyleContext;
        if (state == 1) ctx.AddClass("contact-ok"); else ctx.RemoveClass("contact-ok");
    }

    // ══════════════════════════════════════════════════════════════════
    //  OUTPUT: speaker <-> headphone jack (the button that was 再生テスト)
    // ══════════════════════════════════════════════════════════════════

    private uint _outputMsgId;

    private void ToggleOutput()
    {
        string problem;
        var now = AudioOutput.Toggle(out problem);
        UpdateOutputButton(now, problem);
    }

    /// Button shows where sound comes out now. A problem (no headphones
    /// plugged in, no pactl) is shown on the button for 2.5 s.
    private void UpdateOutputButton(AudioOutput.Kind now, string problem)
    {
        if (SoundTestButton == null) return;
        bool en = _lang != null && _lang.IsEnglish;

        string label, icon;
        switch (now)
        {
            case AudioOutput.Kind.Jack:
                label = en ? "Output: Headphones" : "出力:イヤホン";
                icon  = "audio-headphones-symbolic";
                break;
            case AudioOutput.Kind.Speaker:
                label = en ? "Output: Speaker" : "出力:スピーカー";
                icon  = "audio-speakers-symbolic";
                break;
            default:
                label = en ? "Output: unknown" : "出力:不明";
                icon  = "audio-card-symbolic";
                break;
        }

        string msg = null;
        if (problem == "jack-empty" || problem == "no-jack")
            msg = en ? "No headphones plugged in" : "イヤホンが接続されていません";
        else if (problem == "no-speaker")
            msg = en ? "No speaker output found" : "スピーカーが見つかりません";
        else if (problem != null)
            msg = en ? "Cannot switch output" : "出力を切り替えられません";

        var img = SoundTestButton.Image as Gtk.Image;
        if (img != null) img.SetFromIconName(icon, IconSize.Button);

        if (_outputMsgId != 0) { GLib.Source.Remove(_outputMsgId); _outputMsgId = 0; }
        if (msg != null)
        {
            SoundTestButton.Label = msg;
            _outputMsgId = GLib.Timeout.Add(2500, () =>
            {
                _outputMsgId = 0;
                SoundTestButton.Label = label;
                return false;
            });
        }
        else SoundTestButton.Label = label;

        SoundTestButton.TooltipText = en ? "Tap to switch speaker / headphones"
                                         : "タップでスピーカー/イヤホンを切り替え";
    }

    // ══════════════════════════════════════════════════════════════════
    //  解説を見る — explanation image with a 戻る button
    // ══════════════════════════════════════════════════════════════════

    private void ShowExplanation()
    {
        bool en = _lang != null && _lang.IsEnglish;
        string file = _case != null ? _case.ManualFile : null;
        string path = AppMode.ResolveManual(file);
        Logger.Write("explain", "case " + (_case != null ? _case.Number.ToString() : "-") +
                     " manual='" + (file ?? "") + "' -> " + (path ?? "(not found)"));

        var top = MapArea.Toplevel as Window;
        int w = top != null ? top.AllocatedWidth  : 1280;
        int h = top != null ? top.AllocatedHeight : 800;

        var dlg = new Dialog();
        dlg.Name           = "ExplainDialog";
        dlg.TransientFor   = top;
        dlg.Modal          = true;
        dlg.Decorated      = false;
        dlg.TypeHint       = Gdk.WindowTypeHint.Dialog;
        dlg.WindowPosition = WindowPosition.CenterOnParent;
        dlg.SetDefaultSize((int)(w * 0.94), (int)(h * 0.94));

        Box content = dlg.ContentArea;
        content.Spacing = 12;

        const int buttonRow = 90;                     // room for 戻る
        int maxW = (int)(w * 0.94) - 40, maxH = (int)(h * 0.94) - buttonRow - 40;

        Widget body = null;
        if (path != null)
        {
            try
            {
                using (var raw = new Gdk.Pixbuf(path))
                {
                    double s = Math.Min(1.0, Math.Min((double)maxW / raw.Width, (double)maxH / raw.Height));
                    int iw = Math.Max(1, (int)(raw.Width * s)), ih = Math.Max(1, (int)(raw.Height * s));
                    var img = new Gtk.Image(raw.ScaleSimple(iw, ih, Gdk.InterpType.Bilinear));
                    img.Name = "ExplainImage";
                    body = img;
                }
            }
            catch (Exception ex)
            {
                Logger.Write("explain", "load failed " + path + ": " + ex.Message);
            }
        }

        if (body == null)
        {
            var msg = new Label(en ? "No explanation image for this case."
                                   : "この症例の解説画像はありません。");
            msg.Name = "ExplainMessage";
            msg.LineWrap = true;
            body = msg;
        }
        content.PackStart(body, true, true, 10);

        // 戻る — same red as the page's back buttons
        var back = (Button)dlg.AddButton(en ? "Back" : "戻る", (int)ResponseType.Close);
        back.Name = "ExplainBackButton";
        dlg.DefaultResponse = ResponseType.Close;

        dlg.ShowAll();
        dlg.Run();
        dlg.Destroy();
    }

    private void HookFilter(RadioButton rb, SoundFilter f)
    {
        if (rb == null) return;                 // older glade without the segment
        rb.Toggled += (s, e) =>
        {
            if (!rb.Active || _filter == f) return;
            _filter = f;
            Logger.Write("audio", "filter -> " + f);
            _lastPx = _lastPy = -1;             // force a re-mix at the current spot
            UpdateAudioFromPosition();
            HeartWaveArea.QueueDraw();
            BreathWaveArea.QueueDraw();
            MapArea.QueueDraw();
        };
    }

    private void HookView(RadioButton rb, string view)
    {
        if (rb == null) return;
        rb.Toggled += (s, e) => { if (rb.Active) SetView(view); };
    }

    // ══════════════════════════════════════════════════════════════════
    //  ARDUINO POSITION
    // ══════════════════════════════════════════════════════════════════

    /// Parses every line the same way in BOTH modes. The legacy/current
    /// split happens later, in UpdateAudioFromPosition — a legacy branch
    /// here would run before the position is parsed and mute everything.
    private void OnArduinoLine(string line)
    {
        var fullMatches = FullRx.Matches(line);
        var avgMatch    = AvgRx.Match(line);

        float avgChipNumber = -1f;
        float x = 0, y = 0, z = 0;
        bool havePosition = false;

        _highlighted.Clear();

        Logger.Write("chip", "raw='" + line + "'  fullMatches=" + fullMatches.Count +
                             "  avgMatch=" + avgMatch.Success);

        if (avgMatch.Success)
        {
            avgChipNumber = ParseF(avgMatch.Groups[1].Value);
            x = ParseF(avgMatch.Groups[2].Value);
            y = ParseF(avgMatch.Groups[3].Value);
            z = ParseF(avgMatch.Groups[4].Value);
            havePosition = true;
        }

        if (fullMatches.Count > 0)
        {
            foreach (Match m in fullMatches)
            {
                float chipNumber = ParseF(m.Groups[1].Value);
                if (Math.Abs(chipNumber - avgChipNumber) < 0.001f) continue; // that's the Avg entry itself
                _highlighted.Add(chipNumber);   // feeds the existing yellow-fill in DrawOneCircle
            }

            if (!havePosition)
            {
                var first = fullMatches[0];
                x = ParseF(first.Groups[2].Value);
                y = ParseF(first.Groups[3].Value);
                z = ParseF(first.Groups[4].Value);
                havePosition = true;
            }
        }

        if (!havePosition)
        {
            // Reader explicitly says there's nothing there -> clear now, don't
            // wait out the watchdog. Heartbeats and mode echoes fall through and
            // let the watchdog decide, so they can't chop the audio mid-touch.
            if (line.Contains("All tags cleared") || line.Contains("Tags detected: 0"))
                ClearPosition();
            return;
        }

        _lastPosLine = DateTime.Now;        // feeds the watchdog

        _currentX = x;
        _currentY = y;
        _currentZ = z;
        _hasPosition = _highlighted.Count > 0;   // marker only shows when a chip is actually on the target
        UpdateContactChip();

        string newView = DetermineViewFromZ(z);
        if (newView != _view)
            SwitchViewFromArduino(newView);

        MapArea.QueueDraw();
        UpdateAudioFromPosition();          // legacy and current both branch from here
    }

    private static float ParseF(string s)
    {
        return float.Parse(s, CultureInfo.InvariantCulture);
    }

    private void OnArduinoConnectionChanged(bool connected)
    {
        if (!connected)
        {
            _hasPosition = false;
            MuteVoices();
            MapArea.QueueDraw();
        }
        UpdateContactChip();            // offline <-> 未接触, both directions
    }

    private void UpdateAudioFromPosition()
    {
        // ── legacy: 7 region voices mixed by UV position ──
        if (AppMode.Legacy)
        {
            double lbx, lby;
            if (_case == null || (!_hasPosition && !_mouseProbe) ||
                !TryGetCursorBodyPoint(out lbx, out lby))
            {
                MuteRegions();
                SetAudible(false, false);
                return;
            }
            ApplyRegionAudio(lbx, lby);
            return;
        }

        // ── current: one voice, level from the colour map ──
        if (_caseVoice == null) return;

        double bx, by;
        if ((!_hasPosition && !_mouseProbe) || !TryGetCursorBodyPoint(out bx, out by))
        {
            MuteVoices();
            return;
        }

        int px, py;
        if (!BodyToMapPixel(bx, by, out px, out py))
        {
            MuteVoices();              // probe is off the map rectangle
            return;
        }

        // Serial lines arrive far faster than the tag moves a whole pixel.
        if (px == _lastPx && py == _lastPy) return;
        _lastPx = px; _lastPy = py;

        var res = MapAudio.Analyze(AudioSourcePixbuf, px, py, BlackAudioEnabled);

        Logger.Write("audio", "map(" + px + "," + py + ") rgba(" +
                    res.R + "," + res.G + "," + res.B + "," + res.A + ") -> " +
                    res.Region + " level=" + res.Level);

        if (!res.Play) { MuteVoices(); return; }

        ApplyLevel(res.Level);
    }

    /// Form2's AdjustAudioVolumes — same /3 and /4 divisors, so the mix
    /// matches the Windows build.
    private void ApplyLevel(int level)
    {
        bool caseIsHeart = _case != null && _case.IsHeart;
        bool caseAllowed = caseIsHeart ? HeartAllowed : LungAllowed;

        float caseGain  = caseAllowed ? AudioEngine.VolumeCurve(level) : 0f;
        float heartGain = (_heart1 != null && HeartAllowed) ? AudioEngine.VolumeCurve(level / 3) : 0f;
        float lungGain  = (_breath != null && LungAllowed)  ? AudioEngine.VolumeCurve(level / 4) : 0f;

        _sound.SetGain(_caseVoice, caseGain);
        if (_heart1 != null) _sound.SetGain(_heart1, heartGain);
        if (_heart2 != null) _sound.SetGain(_heart2, heartGain);
        if (_breath != null) _sound.SetGain(_breath, lungGain);

        _legendHeart  = caseIsHeart ? caseGain : heartGain;
        _legendBreath = caseIsHeart ? lungGain : caseGain;
        SetAudible(_legendHeart > 0f, _legendBreath > 0f);
        MapArea.QueueDraw();                    // legend levels
    }

    /// Which waveform boxes have a sound playing right now.
    private void SetAudible(bool heart, bool breath)
    {
        _heartAudible  = heart;
        _breathAudible = breath;
        _audible       = heart || breath;
    }

    private void MuteVoices()
    {
        SetAudible(false, false);
        _legendHeart = _legendBreath = 0f;
        _lastPx = _lastPy = -1;
        _sound.SetGain(_caseVoice, 0f);
        if (_heart1 != null) _sound.SetGain(_heart1, 0f);
        if (_heart2 != null) _sound.SetGain(_heart2, 0f);
        if (_breath != null) _sound.SetGain(_breath, 0f);
        MuteRegions();                  // legacy voices too; no-op in current mode
    }

    /// Form2's TimestampTimer_Tick. The reader going quiet is not an event —
    /// nothing arrives to tell us the tag left, so we have to notice ourselves.
    private bool OnTagWatchdog()
    {
        if (_hasPosition &&
            (DateTime.Now - _lastPosLine).TotalMilliseconds >= TAG_IDLE_MS)
        {
            Logger.Write("chip", "tag idle " + TAG_IDLE_MS + "ms — clearing");
            ClearPosition();
        }
        return true;                    // keep the timer alive
    }

    private void ClearPosition()
    {
        _highlighted.Clear();
        _hasPosition = false;
        _currentX = _currentY = _currentZ = 0f;
        if (_mouseProbe) UpdateAudioFromPosition();   // debug click still held
        else MuteVoices();
        UpdateContactChip();
        MapArea.QueueDraw();
    }

    // ── circle / cursor geometry ───────────────────────────────────────

    /// Everything DrawCircles derives from the jacket CSV, in BODY PIXELS.
    /// The cursor uses the same numbers so it lands on the same circles.
    private struct CircleGeom
    {
        public double Scale, OffsetX, OffsetY, AvgX, AvgY;
        public int PanelW, PanelH;
    }

    private bool TryGetCircleGeom(out CircleGeom g)
    {
        g = new CircleGeom();
        if (_jacket == null || _body == null) return false;

        var circles = _jacket.Get(JacketSize, _view);
        if (circles.Count == 0) return false;

        var t = T;
        g.PanelW = _body.Width;
        g.PanelH = _body.Height;

        float minX = float.MaxValue, maxX = float.MinValue;
        float minY = float.MaxValue, maxY = float.MinValue;
        foreach (var c in circles)
        {
            if (c.X < minX) minX = c.X;
            if (c.X > maxX) maxX = c.X;
            if (c.Y < minY) minY = c.Y;
            if (c.Y > maxY) maxY = c.Y;
        }

        double availW = g.PanelW - t.FitMargin, availH = g.PanelH - t.FitMargin;
        const double circleRadius = 2.1 / 2;
        double dataW = (maxX - minX) + circleRadius * 2;
        double dataH = (maxY - minY) + circleRadius * 2;
        if (dataW <= 0 || dataH <= 0) return false;

        g.Scale   = Math.Min(availW / dataW, availH / dataH) * 0.9;
        g.OffsetX = (g.PanelW - (maxX - minX) * g.Scale) / 2 - minX * g.Scale;
        g.OffsetY = (g.PanelH - (maxY - minY) * g.Scale) / 2 - minY * g.Scale;

        // cluster centroid, in already-offset space
        foreach (var c in circles)
        {
            g.AvgX += c.X * g.Scale + g.OffsetX - t.OffsetX;
            g.AvgY += c.Y * g.Scale + g.OffsetY - t.OffsetY;
        }
        g.AvgX /= circles.Count;
        g.AvgY /= circles.Count;
        return true;
    }

    /// Live Arduino (x,y) -> BODY PIXELS, through the same scale / offset /
    /// cluster steps DrawOneCircle applies, then MarginX/Y and mirror.
    /// In debug mode a held mouse button overrides the tag.
    private bool TryGetCursorBodyPoint(out double bx, out double by)
    {
        if (_mouseProbe) { bx = _mouseBx; by = _mouseBy; return true; }

        bx = by = 0;
        if (!_hasPosition) return false;

        CircleGeom g;
        if (!TryGetCircleGeom(out g)) return false;

        var t = T;

        // Form2: raw Arduino units run ~50x smaller than CSV/circle units.
        bx = (_currentX * 50 + t.MarginX) * g.Scale + g.OffsetX - t.OffsetX;
        by = (_currentY * 50 + t.MarginY) * g.Scale + g.OffsetY - t.OffsetY;

        if (Math.Abs(t.Cluster - 1.0) > 0.001)
        {
            bx = g.AvgX + (bx - g.AvgX) * t.Cluster;
            by = g.AvgY + (by - g.AvgY) * t.Cluster;
        }

        if (t.MirrorX) bx = g.PanelW - bx;
        if (t.MirrorY) by = g.PanelH - by;
        return true;
    }

    private void DrawCursor(Cairo.Context cr, double x, double y)
    {
        const double arm  = 14;   // same as the old marker
        const double ring = 5;

        cr.LineCap = Cairo.LineCap.Round;

        System.Action path = () =>
        {
            cr.NewPath();
            cr.MoveTo(x - arm, y); cr.LineTo(x + arm, y);
            cr.MoveTo(x, y - arm); cr.LineTo(x, y + arm);
            cr.NewSubPath();
            cr.Arc(x, y, ring, 0, 2 * Math.PI);
        };

        // 1) black outline
        path();
        cr.SetSourceRGBA(0, 0, 0, 0.9);
        cr.LineWidth = 5;
        cr.Stroke();

        // 2) orange on top (#FF7A00), same width as the old marker
        path();
        cr.SetSourceRGBA(1.0, 0.478, 0.0, 1.0);
        cr.LineWidth = 2.5;
        cr.Stroke();
    }
    private void DrawCoordHud(Cairo.Context cr, int w, int h)
    {
        string text = string.Format(CultureInfo.InvariantCulture,
            "X={0:F2}  Y={1:F2}  Z={2:F2}  view={3}", _currentX, _currentY, _currentZ, _view);

        cr.SelectFontFace("Monospace", Cairo.FontSlant.Normal, Cairo.FontWeight.Bold);
        cr.SetFontSize(13);
        var ext = cr.TextExtents(text);

        double pad = 6, bx = 8, by = 8;
        double bw = ext.Width + pad * 2, bh = ext.Height + pad * 2;

        cr.NewPath();
        cr.Rectangle(bx, by, bw, bh);
        cr.SetSourceRGBA(0, 0, 0, 0.55);
        cr.Fill();

        cr.MoveTo(bx + pad - ext.XBearing, by + pad + ext.Height);
        cr.SetSourceRGBA(1, 1, 1, 1);
        cr.ShowText(text);
    }

    // ── public API ─────────────────────────────────────────────────────

    public void ShowCase(CaseDefinition def, string title)
    {
        _case = def;
        _view = "front";
        if (ViewFrontRadio != null) ViewFrontRadio.Active = true;

        MapTitleLabel.Text = title ?? "";
        MapCaseLabel.Text  = title ?? "-";

        DisposePixbufs();
        ReloadBody();                   // logs which body image was loaded

        if (AppMode.Legacy)
        {
            // Voices from a previous current-mode case must not answer the tag.
            _caseVoice = _heart1 = _heart2 = _breath = null;

            LoadRegions(def);
            var overlay = BuildRegionOverlay(MapSize, MapSize);
            _mapRaw  = overlay != null ? overlay.Copy() : null;
            _map     = overlay;
            _mapPath = "(7 regions composite)";
        }
        else
        {
            _map = LoadMap(MapPathForView(), MapNeedsMirror());
        }

        MapArea.QueueDraw();
        UpdateTunerInfo();
        UpdateOutputButton(AudioOutput.Current(), null);   // headphones may have been plugged in since
        UpdateContactChip(true);

        if (!AppMode.Legacy)
        {
            _caseVoice = _sound.Warm(SoundWindow.AppFile(def.SoundPath));

            if (HeartSoundEnabled)
            {
                _heart1 = _sound.Warm(AppMode.ResolveSound("SND100.wav"));
                _heart2 = _sound.Warm(AppMode.ResolveSound("SND101.wav"));
            }
            if (BreathSoundEnabled)
                _breath = _sound.Warm(AppMode.ResolveSound("SND200.wav"));

            _sound.MuteAll();               // everything loops silently until a tag lands
        }

        LoadWaveforms(def);

        // Start every voice of this case from sample 0 in one OpenAL call, and
        // the waveform clock with them. Warm() starts each source as soon as its
        // file is loaded, and cached voices are wherever they were left, so
        // without this the regions (and the cursor) are out of step.
        var group = new List<AudioEngine.Voice>();
        if (AppMode.Legacy) foreach (var r in _regions) group.Add(r.Voice);
        else { group.Add(_caseVoice); group.Add(_heart1); group.Add(_heart2); group.Add(_breath); }
        _sound.RestartTogether(group);
        _playClock.Restart();
        StartWaveTimer();
        _lastPx = _lastPy = -1;
        StartDebugSweep();

        Logger.Write("case", "open: " + title + " | map=" + _mapPath +
                             (AppMode.Legacy ? " | legacy regions=" + _regions.Count : ""));
    }

    public void StopSession()
    {
        StopDebugSweep();
        _mouseProbe = false;
        MuteRegions();                  // stop legacy audio too
        _sound.MuteAll();               // keep voices warm — re-entry is instant
        StopWaveTimer();
        _lastPx = _lastPy = -1;
        Logger.Write("case", "closed");
    }

    /// Raw MAP pixbuf — Form2's originalMapForAudio. Never composited.
    public Gdk.Pixbuf AudioReference { get { return _map; } }

    /// Body-pixel point -> pixel index inside the MAP that is drawn there.
    /// Stays correct in both fit modes, so audio sampling tracks the display.
    public bool BodyToMapPixel(double bx, double by, out int px, out int py)
    {
        px = py = 0;
        double mx, my, mw, mh;
        if (!MapRect(out mx, out my, out mw, out mh)) return false;
        if (mw <= 0 || mh <= 0) return false;

        double u = (bx - mx) / mw, v = (by - my) / mh;
        if (u < 0 || u >= 1 || v < 0 || v >= 1) return false;

        Gdk.Pixbuf src = (_mapFit == MapFit.FitBody && _mapRaw != null) ? _mapRaw : _map;
        if (src == null) return false;

        px = (int)(u * src.Width);
        py = (int)(v * src.Height);
        return true;
    }

    // ── the paint ──────────────────────────────────────────────────────

    /// Where the MAP lands, in BODY PIXELS. Single source of truth for both
    /// the draw and BodyToMapPixel.
    private bool MapRect(out double mx, out double my, out double mw, out double mh)
    {
        mx = my = mw = mh = 0;
        if (_body == null) return false;

        var t = T;

        if (_mapFit == MapFit.FitBody)
        {
            if (_mapRaw == null) return false;
            double ms = Math.Min((double)_body.Width  / _mapRaw.Width,
                                 (double)_body.Height / _mapRaw.Height) * t.MapZoom;
            mw = _mapRaw.Width * ms;
            mh = _mapRaw.Height * ms;
        }
        else
        {
            if (_map == null) return false;
            mw = _map.Width  * t.MapZoom;
            mh = _map.Height * t.MapZoom;
        }

        mx = (_body.Width  - mw) / 2.0 + t.MapX;
        my = (_body.Height - mh) / 2.0 + t.MapY;
        return true;
    }

    private void OnMapDrawn(object o, DrawnArgs args)
    {
        var cr = args.Cr;
        int w  = MapArea.AllocatedWidth;
        int h  = MapArea.AllocatedHeight;

        cr.SetSourceRGB(1, 1, 1);
        cr.Rectangle(0, 0, w, h);
        cr.Fill();

        if (_body == null) { args.RetVal = true; return; }

        // ONE scale factor, derived from the body — this is what keeps the
        // overlay registered. Zoom-to-fit, same as PictureBoxSizeMode.Zoom.
        double s  = Math.Min((double)w / _body.Width, (double)h / _body.Height);
        double ox = (w - _body.Width  * s) / 2.0;
        double oy = (h - _body.Height * s) / 2.0;

        cr.Save();
        cr.Translate(ox, oy);
        cr.Scale(s, s);                 // everything below is in BODY PIXELS

        if (ShowBody)
        {
            Gdk.CairoHelper.SetSourcePixbuf(cr, _body, 0, 0);
            cr.Paint();
        }

        double mx, my, mw, mh;
        bool haveMap = MapRect(out mx, out my, out mw, out mh);

        if (haveMap && ShowMap)
        {
            Gdk.Pixbuf src = (_mapFit == MapFit.FitBody && _mapRaw != null) ? _mapRaw : _map;
            double sx = mw / src.Width, sy = mh / src.Height;

            cr.Save();
            cr.Translate(mx, my);
            cr.Scale(sx, sy);
            Gdk.CairoHelper.SetSourcePixbuf(cr, src, 0, 0);
            if (!AppMode.Legacy || _showRegions)
                cr.PaintWithAlpha(T.MapAlpha);
            cr.Restore();
        }

        if (ShowCircles)
            DrawCircles(cr);            // body-pixel coords; transform does the rest

        double cx, cy;
        if (TryGetCursorBodyPoint(out cx, out cy))
            DrawCursor(cr, cx, cy);

        if (ShowGuides)
        {
            if (haveMap)
            {
                cr.NewPath();
                cr.SetSourceRGBA(1, 0, 0, 0.6);
                cr.LineWidth = 1.5;
                cr.Rectangle(mx, my, mw, mh);
                cr.Stroke();
            }

            cr.NewPath();
            cr.SetSourceRGBA(0, 0, 1, 0.35);
            cr.LineWidth = 1.0;
            cr.MoveTo(_body.Width / 2.0, 0);
            cr.LineTo(_body.Width / 2.0, _body.Height);
            cr.MoveTo(0, _body.Height / 2.0);
            cr.LineTo(_body.Width, _body.Height / 2.0);
            cr.Stroke();
        }

        cr.Restore();
        // screen-space readout, unaffected by the body scale/translate above
        if (_hasPosition)
            DrawCoordHud(cr, w, h);

        // New glade replaced HideMetersCheck with ShowPointListSwitch (ON = shown).
        bool hideMeters = HideMetersCheck != null ? HideMetersCheck.Active
                        : ShowPointListSwitch != null ? !ShowPointListSwitch.Active
                        : true;
        if (!hideMeters)
            DrawRegionMeters(cr);           // colour legend + live levels, both modes

        args.RetVal = true;
    }

    private void DrawCircles(Cairo.Context cr)
    {
        CircleGeom g;
        if (!TryGetCircleGeom(out g)) return;

        var circles = _jacket.Get(JacketSize, _view);
        var t = T;

        cr.SelectFontFace("Sans", Cairo.FontSlant.Normal, Cairo.FontWeight.Bold);

        foreach (var c in circles)
            DrawOneCircle(cr, c, t, g.Scale, g.OffsetX, g.OffsetY, g.AvgX, g.AvgY);
    }

    private void DrawOneCircle(Cairo.Context cr, Circle c, Tune t,
                               double scale, double ox, double oy,
                               double avgX, double avgY)
    {
        double x = c.X * scale + ox - t.OffsetX;
        double y = c.Y * scale + oy - t.OffsetY;

        if (Math.Abs(t.Cluster - 1.0) > 0.001)
        {
            x = avgX + (x - avgX) * t.Cluster;
            y = avgY + (y - avgY) * t.Cluster;
        }

        double d = CircleDiameter * scale * t.SizeScale;
        double r = d / 2;

        bool hot = false;
        foreach (float n in _highlighted)
            if (Math.Abs(c.Number - n) < 0.001f) { hot = true; break; }

        cr.NewPath();
        cr.Arc(x, y, r, 0, 2 * Math.PI);

        if (hot)
        {
            cr.SetSourceRGBA(1.0, 0.922, 0.231, 1.0);   // Color.FromArgb(255,235,59)
            cr.FillPreserve();
        }

        cr.SetSourceRGBA(0.5, 0.5, 0.5, 1.0);           // BorderColor = Gray
        cr.LineWidth = Math.Max(1.0, scale);
        cr.Stroke();

        string text = (c.Number % 1 == 0)
            ? ((int)c.Number).ToString()
            : c.Number.ToString("F1", CultureInfo.InvariantCulture);

        cr.SetFontSize(Math.Max(6.0, d / (c.Inner ? 3 : 4)));
        var ext = cr.TextExtents(text);
        cr.MoveTo(x - ext.Width / 2 - ext.XBearing, y + ext.Height / 2);
        cr.SetSourceRGBA(0.2, 0.2, 0.2, 1.0);           // TextColor
        cr.ShowText(text);
        cr.NewPath();
    }

    // ══════════════════════════════════════════════════════════════════
    //  TUNER
    // ══════════════════════════════════════════════════════════════════

    public void ToggleTuner()
    {
        if (_tuner != null) { _tuner.Destroy(); _tuner = null; return; }
        BuildTuner();
    }

    private void BuildTuner()
    {
        _tuner = new Window("MapWindow tuner  —  Ctrl+T to close");
        _tuner.SetDefaultSize(430, 760);
        _tuner.DeleteEvent += (o, a) => { _tuner = null; _tMirrorX = _tMirrorY = null; };

        var scroll = new ScrolledWindow();
        var col = new Box(Orientation.Vertical, 4);
        col.MarginLeft = col.MarginRight = col.MarginTop = col.MarginBottom = 8;

        _tunerKey = new Label(); _tunerKey.Xalign = 0;
        col.PackStart(_tunerKey, false, false, 0);

        _tunerInfo = new Label(); _tunerInfo.Xalign = 0;
        _tunerInfo.Selectable = true;
        col.PackStart(_tunerInfo, false, false, 0);

        col.PackStart(Header("Sound map"), false, false, 0);

        _tFitCombo = new ComboBoxText();
        _tFitCombo.AppendText("Native546 (Form2)");
        _tFitCombo.AppendText("FitBody (calibrator)");
        _tFitCombo.Active = (_mapFit == MapFit.FitBody) ? 1 : 0;
        _tFitCombo.Changed += (s, e) =>
        {
            if (_building) return;
            _mapFit = _tFitCombo.Active == 1 ? MapFit.FitBody : MapFit.Native546;
            UpdateTunerInfo();
            MapArea.QueueDraw();
        };
        col.PackStart(Row("Map fit mode", _tFitCombo), false, false, 0);

        AddSpin(col, "MapZoom",  "Zoom",          0.10, 3.00, 0.01, 2);
        AddSpin(col, "MapX",     "Offset X (px)", -600, 600, 1, 0);
        AddSpin(col, "MapY",     "Offset Y (px)", -600, 600, 1, 0);
        AddSpin(col, "MapAlpha", "Opacity",       0.00, 1.00, 0.05, 2);

        // legacy: pixels below this are silent and not drawn
        var minSpin = new SpinButton(0, 255, 1);
        minSpin.Value = RegionSound.MinIntensity;
        minSpin.ValueChanged += (s, e) =>
        {
            RegionSound.MinIntensity = (int)minSpin.Value;
            if (AppMode.Legacy) RebuildLegacyMap();
            _lastPx = _lastPy = -1;
            UpdateAudioFromPosition();
            MapArea.QueueDraw();
        };
        col.PackStart(Row("Legacy silence <", minSpin), false, false, 0);

        col.PackStart(Header("Circle cluster"), false, false, 0);
        AddSpin(col, "OffsetX",   "Offset X (px)",  -600, 600, 1, 0);
        AddSpin(col, "OffsetY",   "Offset Y (px)",  -600, 600, 1, 0);
        AddSpin(col, "SizeScale", "Circle size",    0.05, 4.00, 0.05, 2);
        AddSpin(col, "Cluster",   "Cluster factor", 0.05, 2.00, 0.05, 2);
        AddSpin(col, "FitMargin", "Fit margin (px)", 0, 400, 5, 0);

        col.PackStart(Header("Cursor (Arduino)"), false, false, 0);
        AddSpin(col, "MarginX", "Margin X (raw units)", -2000, 2000, 1, 0);
        AddSpin(col, "MarginY", "Margin Y (raw units)", -2000, 2000, 1, 0);

        _tMirrorX = new CheckButton("Mirror X (flip cursor horizontally)");
        _tMirrorX.Toggled += (s, e) =>
        {
            if (_building) return;
            T.MirrorX = _tMirrorX.Active;
            _lastPx = _lastPy = -1;
            MapArea.QueueDraw();
        };
        col.PackStart(_tMirrorX, false, false, 0);

        _tMirrorY = new CheckButton("Mirror Y (flip cursor vertically)");
        _tMirrorY.Toggled += (s, e) =>
        {
            if (_building) return;
            T.MirrorY = _tMirrorY.Active;
            _lastPx = _lastPy = -1;
            MapArea.QueueDraw();
        };
        col.PackStart(_tMirrorY, false, false, 0);

        col.PackStart(Header("Display"), false, false, 0);
        _tShowBody    = Chk(col, "Show body",    true);
        _tShowMap     = Chk(col, "Show map",     true);
        _tShowCircles = Chk(col, "Show circles", true);
        _tGuides      = Chk(col, "Show guides",  false);

        col.PackStart(Header("Images"), false, false, 0);
        var imgRow = new Box(Orientation.Horizontal, 4);
        imgRow.PackStart(Btn("Reload images", () =>
        {
            ReloadBody();
            if (AppMode.Legacy) RebuildLegacyMap();
            else
            {
                if (_map != null)    { _map.Dispose();    _map = null; }
                if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; }
                _map = LoadMap(MapPathForView(), MapNeedsMirror());
            }
            UpdateTunerInfo();
            MapArea.QueueDraw();
        }), true, true, 0);
        imgRow.PackStart(Btn("Cycle view", () =>
        {
            string[] v = { "front", "back", "right", "left" };
            int i = Array.IndexOf(v, _view);
            string next = v[(i + 1) % v.Length];
            RadioButton rb = next == "back" ? ViewBackRadio
                           : next == "right" ? ViewRightRadio
                           : next == "left" ? ViewLeftRadio : ViewFrontRadio;
            if (rb != null) rb.Active = true; else SetView(next);
        }), true, true, 0);
        col.PackStart(imgRow, false, false, 0);

        col.PackStart(Header("Constants"), false, false, 0);

        var r1 = new Box(Orientation.Horizontal, 4);
        r1.PackStart(Btn("Apply pasted C#", ApplyPastedCSharp), true, true, 0);
        r1.PackStart(Btn("Dump C# (calib)", () => Emit(DumpCalibStyle())), true, true, 0);
        col.PackStart(r1, false, false, 0);

        var r2 = new Box(Orientation.Horizontal, 4);
        r2.PackStart(Btn("Dump seed", () => Emit(DumpSeed())), true, true, 0);
        r2.PackStart(Btn("Reset view", () =>
        {
            _tunes.Remove(TuneKey);
            var fresh = new Dictionary<string, Tune>(_tunes);
            SeedDefaults();
            foreach (var kv in fresh) if (kv.Key != TuneKey) _tunes[kv.Key] = kv.Value;
            SyncSpins(); MapArea.QueueDraw();
        }), true, true, 0);
        col.PackStart(r2, false, false, 0);

        var r3 = new Box(Orientation.Horizontal, 4);
        r3.PackStart(Btn("Load calib.txt", () => { LoadCalibFile(true); SyncSpins(); MapArea.QueueDraw(); }), true, true, 0);
        r3.PackStart(Btn("Save calib.txt", SaveCalibFile), true, true, 0);
        col.PackStart(r3, false, false, 0);

        _tunerOut = new TextView();
        _tunerOut.OverrideFont(Pango.FontDescription.FromString("Monospace 9"));
        _tunerOut.WrapMode = WrapMode.None;
        var outScroll = new ScrolledWindow();
        outScroll.HeightRequest = 220;
        outScroll.Add(_tunerOut);
        col.PackStart(outScroll, true, true, 0);

        col.PackStart(new Label(
            "Paste a CalibrationWindow dump above, then Apply pasted C#.") { Xalign = 0 },
            false, false, 0);

        scroll.Add(col);
        _tuner.Add(scroll);
        _tuner.ShowAll();

        SyncSpins();
        UpdateTunerInfo();
    }

    // ── tuner widget helpers ──

    private Label Header(string text)
    {
        var l = new Label();
        l.Markup = "<b>" + text + "</b>";
        l.Xalign = 0;
        l.MarginTop = 8;
        return l;
    }

    private Box Row(string label, Widget w)
    {
        var box = new Box(Orientation.Horizontal, 6);
        var l = new Label(label);
        l.Xalign = 0;
        l.WidthRequest = 130;
        box.PackStart(l, false, false, 0);
        box.PackStart(w, true, true, 0);
        return box;
    }

    private Button Btn(string label, System.Action onClick)
    {
        var b = new Button(label);
        b.Clicked += (s, e) => onClick();
        return b;
    }

    private CheckButton Chk(Box parent, string label, bool active)
    {
        var c = new CheckButton(label);
        c.Active = active;
        c.Toggled += (s, e) => MapArea.QueueDraw();
        parent.PackStart(c, false, false, 0);
        return c;
    }

    private void AddSpin(Box parent, string field, string label,
                         double min, double max, double step, uint digits)
    {
        var sb = new SpinButton(min, max, step);
        sb.Digits = digits;
        sb.Numeric = true;
        sb.ValueChanged += (s, e) =>
        {
            if (_building) return;
            SetField(field, sb.Value);
            _lastPx = _lastPy = -1;
            UpdateTunerInfo();
            MapArea.QueueDraw();
        };
        _spins[field] = sb;
        parent.PackStart(Row(label, sb), false, false, 0);
    }

    private void SetField(string field, double v)
    {
        var t = T;
        switch (field)
        {
            case "OffsetX":   t.OffsetX   = v; break;
            case "OffsetY":   t.OffsetY   = v; break;
            case "SizeScale": t.SizeScale = v; break;
            case "Cluster":   t.Cluster   = v; break;
            case "MapZoom":   t.MapZoom   = v; break;
            case "MapX":      t.MapX      = v; break;
            case "MapY":      t.MapY      = v; break;
            case "MapAlpha":  t.MapAlpha  = v; break;
            case "FitMargin": t.FitMargin = v; break;
            case "MarginX":   t.MarginX   = v; break;
            case "MarginY":   t.MarginY   = v; break;
        }
    }

    private double GetField(string field)
    {
        var t = T;
        switch (field)
        {
            case "OffsetX":   return t.OffsetX;
            case "OffsetY":   return t.OffsetY;
            case "SizeScale": return t.SizeScale;
            case "Cluster":   return t.Cluster;
            case "MapZoom":   return t.MapZoom;
            case "MapX":      return t.MapX;
            case "MapY":      return t.MapY;
            case "MapAlpha":  return t.MapAlpha;
            case "FitMargin": return t.FitMargin;
            case "MarginX":   return t.MarginX;
            case "MarginY":   return t.MarginY;
        }
        return 0;
    }

    private void SyncSpins()
    {
        if (_tuner == null) return;
        _building = true;
        foreach (var kv in _spins) kv.Value.Value = GetField(kv.Key);
        if (_tMirrorX != null) _tMirrorX.Active = T.MirrorX;
        if (_tMirrorY != null) _tMirrorY.Active = T.MirrorY;
        if (_tunerKey != null) _tunerKey.Markup = "<b>Editing: " + TuneKey + "</b>";
        _building = false;
    }

    private void UpdateTunerInfo()
    {
        if (_tunerInfo == null) return;

        var sb = new StringBuilder();
        sb.Append("body: ").Append(_bodyPath);
        if (_body != null) sb.Append("  [").Append(_body.Width).Append("x").Append(_body.Height).Append("]");
        else sb.Append("  [MISSING]");
        sb.AppendLine();

        sb.Append("map:  ").Append(_mapPath);
        if (_mapRaw != null) sb.Append("  raw[").Append(_mapRaw.Width).Append("x").Append(_mapRaw.Height).Append("]");
        if (_map != null) sb.Append("  used[").Append(_map.Width).Append("x").Append(_map.Height).Append("]");
        else sb.Append("  [MISSING]");
        sb.AppendLine();

        if (AppMode.Legacy)
            sb.Append("legacy regions: ").Append(_regions.Count).AppendLine("/7");

        double mx, my, mw, mh;
        if (MapRect(out mx, out my, out mw, out mh))
            sb.AppendFormat(CultureInfo.InvariantCulture,
                "rect: x={0:F1} y={1:F1} w={2:F1} h={3:F1}\n", mx, my, mw, mh);

        if (_mapFit == MapFit.FitBody)
            sb.AppendLine("NOTE: FitBody changes display geometry; AudioReference\n" +
                          "      is still the 546 pixbuf — sample via BodyToMapPixel.");

        _tunerInfo.Text = sb.ToString();
    }

    private void Emit(string msg)
    {
        if (_tunerOut == null) { Logger.Write("tune", msg); return; }
        _tunerOut.Buffer.Text = msg + "\n\n" + _tunerOut.Buffer.Text;
    }

    // ── C# constant round-trip ──

    private static readonly Regex ConstRx = new Regex(
        @"(?<xl>XL_)?(?<view>FRONT|BACK|RIGHT|LEFT)_" +
        @"(?<field>OFFSET_X|OFFSET_Y|SIZE|CLUSTER|FIT_MARGIN|MAP_ZOOM|MAP_X|MAP_Y|MAP_ALPHA)" +
        @"\s*=\s*(?<val>-?[0-9]*\.?[0-9]+)",
        RegexOptions.IgnoreCase | RegexOptions.Compiled);

    /// Parses a CalibrationWindow "Dump" block pasted into the text view.
    private void ApplyPastedCSharp()
    {
        if (_tunerOut == null) return;
        string text = _tunerOut.Buffer.Text;

        var inv = CultureInfo.InvariantCulture;
        int applied = 0;
        var touched = new List<string>();

        foreach (Match m in ConstRx.Matches(text))
        {
            string size = m.Groups["xl"].Success ? "XL" : "L";
            string view = m.Groups["view"].Value.ToLower();
            string key  = size + ":" + view;

            double v;
            if (!double.TryParse(m.Groups["val"].Value, NumberStyles.Float, inv, out v)) continue;

            if (!_tunes.ContainsKey(key)) _tunes[key] = new Tune();
            var t = _tunes[key];

            switch (m.Groups["field"].Value.ToUpper())
            {
                case "OFFSET_X":   t.OffsetX   = v; break;
                case "OFFSET_Y":   t.OffsetY   = v; break;
                case "SIZE":       t.SizeScale = v; break;
                case "CLUSTER":    t.Cluster   = v; break;
                case "FIT_MARGIN": t.FitMargin = v; break;
                case "MAP_ZOOM":   t.MapZoom   = v; break;
                case "MAP_X":      t.MapX      = v; break;
                case "MAP_Y":      t.MapY      = v; break;
                case "MAP_ALPHA":  t.MapAlpha  = v; break;
                default: continue;
            }
            applied++;
            if (!touched.Contains(key)) touched.Add(key);
        }

        SyncSpins();
        UpdateTunerInfo();
        MapArea.QueueDraw();

        if (applied == 0)
            Emit("no constants recognised — expected lines like\n" +
                 "  private const float FRONT_OFFSET_X = 25.0f;");
        else
            Emit("applied " + applied + " values to: " + string.Join(", ", touched.ToArray()) +
                 "\nIf MAP_ZOOM came from the calibrator, switch fit mode to FitBody.");
    }

    /// Same format CalibrationWindow emits — round-trips through Apply.
    private string DumpCalibStyle()
    {
        var inv = CultureInfo.InvariantCulture;
        var sb = new StringBuilder();
        sb.AppendLine("// MapWindow tuner " + DateTime.Now.ToString("yyyy-MM-dd HH:mm") +
                      "  fit=" + _mapFit);

        foreach (string size in new[] { "L", "XL" })
        {
            sb.AppendLine("// ---- " + size + " ----");
            foreach (string view in new[] { "front", "back", "right", "left" })
            {
                string k = size + ":" + view;
                if (!_tunes.ContainsKey(k)) continue;
                var t = _tunes[k];
                string p = (size == "XL" ? "XL_" : "") + view.ToUpper();

                sb.AppendLine("private const float " + p + "_OFFSET_X   = " + t.OffsetX.ToString("F1", inv) + "f;");
                sb.AppendLine("private const float " + p + "_OFFSET_Y   = " + t.OffsetY.ToString("F1", inv) + "f;");
                sb.AppendLine("private const float " + p + "_SIZE       = " + t.SizeScale.ToString("F2", inv) + "f;");
                sb.AppendLine("private const float " + p + "_CLUSTER    = " + t.Cluster.ToString("F2", inv) + "f;");
                sb.AppendLine("private const float " + p + "_FIT_MARGIN = " + t.FitMargin.ToString("F0", inv) + "f;");
                sb.AppendLine("private const double " + p + "_MAP_ZOOM  = " + t.MapZoom.ToString("F3", inv) + ";");
                sb.AppendLine("private const double " + p + "_MAP_X     = " + t.MapX.ToString("F1", inv) + ";");
                sb.AppendLine("private const double " + p + "_MAP_Y     = " + t.MapY.ToString("F1", inv) + ";");
                sb.AppendLine("private const double " + p + "_MAP_ALPHA = " + t.MapAlpha.ToString("F2", inv) + ";");
                sb.AppendLine();
            }
        }
        return sb.ToString();
    }

    /// Paste this straight over SeedDefaults() to bake values into the build.
    /// Margins live in calib.txt, not in the seed.
    private string DumpSeed()
    {
        var inv = CultureInfo.InvariantCulture;
        var sb = new StringBuilder();
        sb.AppendLine("private void SeedDefaults()");
        sb.AppendLine("{");
        foreach (string size in new[] { "L", "XL" })
            foreach (string view in new[] { "front", "back", "right", "left" })
            {
                string k = size + ":" + view;
                if (!_tunes.ContainsKey(k)) continue;
                var t = _tunes[k];
                sb.AppendFormat(inv,
                    "    Seed(\"{0}\", {1:F1}, {2:F1}, {3:F2}, {4:F2}, {5:F0}, {6:F3}, {7:F1}, {8:F1}, {9:F2}{10});\n",
                    k, t.OffsetX, t.OffsetY, t.SizeScale, t.Cluster,
                    t.FitMargin, t.MapZoom, t.MapX, t.MapY, t.MapAlpha,
                    t.MirrorX ? ", true" : "");
            }
        sb.AppendLine("}");
        sb.AppendLine("// _mapFit = MapFit." + _mapFit + ";");
        return sb.ToString();
    }

    // ── calib.txt (CalibrationWindow tab format + cursor columns) ──
    //  0 size:view  1 offsetX  2 offsetY  3 sizeScale  4 cluster  5 mapZoom
    //  6 mapX  7 mapY  8 mapAlpha  9 fitMargin
    //  10 marginX  11 marginY  12 mirrorX  13 mirrorY   (optional — old files have 10 columns)

    private static string CalibPath { get { return SoundWindow.AppFile("calib.txt"); } }

    private void LoadCalibFile(bool verbose)
    {
        string p = CalibPath;
        if (!File.Exists(p))
        {
            if (verbose) Emit("calib.txt not found at " + p);
            return;
        }

        var inv = CultureInfo.InvariantCulture;
        int n = 0, withMargins = 0;
        foreach (string line in File.ReadAllLines(p))
        {
            if (line.StartsWith("#") || line.Trim().Length == 0) continue;
            string[] f = line.Split('\t');
            if (f.Length < 10) continue;

            try
            {
                string key = f[0].Trim();
                var t = new Tune();
                // Keep the seeded mirror unless the file says otherwise.
                if (_tunes.ContainsKey(key)) { t.MirrorX = _tunes[key].MirrorX; t.MirrorY = _tunes[key].MirrorY; }

                t.OffsetX   = double.Parse(f[1], inv);
                t.OffsetY   = double.Parse(f[2], inv);
                t.SizeScale = double.Parse(f[3], inv);
                t.Cluster   = double.Parse(f[4], inv);
                t.MapZoom   = double.Parse(f[5], inv);
                t.MapX      = double.Parse(f[6], inv);
                t.MapY      = double.Parse(f[7], inv);
                t.MapAlpha  = double.Parse(f[8], inv);
                t.FitMargin = double.Parse(f[9], inv);
                if (f.Length > 10) t.MarginX = double.Parse(f[10], inv);
                if (f.Length > 11) t.MarginY = double.Parse(f[11], inv);
                if (f.Length > 12) t.MirrorX = f[12].Trim() == "1";
                if (f.Length > 13) t.MirrorY = f[13].Trim() == "1";
                if (f.Length > 11) withMargins++;

                _tunes[key] = t;
                n++;
            }
            catch (Exception ex)
            {
                Logger.Write("tune", "bad calib line '" + line + "': " + ex.Message);
            }
        }

        Logger.Write("tune", "loaded " + n + " entries (" + withMargins + " with cursor margins) from " + p);
        if (verbose) Emit("loaded " + n + " entries (" + withMargins + " with cursor margins) from " + p +
                          "\ncalib.txt zoom values assume FitBody mode.");
    }

    private void SaveCalibFile()
    {
        var inv = CultureInfo.InvariantCulture;
        var sb = new StringBuilder();
        sb.AppendLine("# size:view offsetX offsetY sizeScale cluster mapZoom mapX mapY mapAlpha fitMargin marginX marginY mirrorX mirrorY");
        foreach (var kv in _tunes)
        {
            var t = kv.Value;
            sb.AppendLine(string.Join("\t", new[]
            {
                kv.Key,
                t.OffsetX.ToString(inv),   t.OffsetY.ToString(inv),
                t.SizeScale.ToString(inv), t.Cluster.ToString(inv),
                t.MapZoom.ToString(inv),   t.MapX.ToString(inv),
                t.MapY.ToString(inv),      t.MapAlpha.ToString(inv),
                t.FitMargin.ToString(inv), t.MarginX.ToString(inv),
                t.MarginY.ToString(inv),
                t.MirrorX ? "1" : "0",     t.MirrorY ? "1" : "0"
            }));
        }

        try
        {
            // keep the previous file once, in case something goes wrong
            if (File.Exists(CalibPath)) File.Copy(CalibPath, CalibPath + ".bak", true);
            File.WriteAllText(CalibPath, sb.ToString());
            Emit("saved " + CalibPath + " (previous copy: calib.txt.bak)");
        }
        catch (Exception ex) { Emit("save failed: " + ex.Message); }
    }

    // ── loading ────────────────────────────────────────────────────────

    private void SetView(string view)
    {
        if (_view == view) return;
        _view = view;

        ReloadBody();
        _lastPx = _lastPy = -1;

        if (AppMode.Legacy)
        {
            RebuildLegacyMap();
            SyncSpins();
            UpdateTunerInfo();
            MapArea.QueueDraw();
            Logger.Write("view", "-> " + view + " (legacy)");
            return;
        }

        if (_map != null)    { _map.Dispose();    _map = null; }
        if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; }
        _map = LoadMap(MapPathForView(), MapNeedsMirror());

        SyncSpins();
        UpdateTunerInfo();
        MapArea.QueueDraw();
        Logger.Write("view", "-> " + view);
    }

    /// Swaps the BACKGROUND image for the current view + skeleton/jacket.
    /// The sound map is rebuilt by SetView, not here.
    private void ReloadBody()
    {
        if (_body != null) { _body.Dispose(); _body = null; }
        _body = LoadBody();
        Logger.Write("body", "-> " + _bodyPath +
                     (_body != null ? " [" + _body.Width + "x" + _body.Height + "]" : " [MISSING]"));
        _lastPx = _lastPy = -1;
        UpdateTunerInfo();
        MapArea.QueueDraw();
    }

    private Gdk.Pixbuf LoadBody()
    {
        string stem = BodyStem();

        foreach (string ext in new[] { ".png", ".jpg", ".jpeg", ".bmp" })
        {
            string full = SoundWindow.AppFile(Path.Combine("map", stem + ext));
            if (!File.Exists(full)) continue;
            _bodyPath = "map/" + stem + ext;
            return Load(full);
        }

        _bodyPath = "map/" + stem + ".png";
        Logger.Write("body", "not found: map/" + stem + " (.png/.jpg/.bmp)");
        ListFolderOnce("map");
        return null;
    }

    private static void ListFolderOnce(string rel)
    {
        if (_listed) return;
        _listed = true;

        string dir = SoundWindow.AppFile(rel);
        if (!Directory.Exists(dir)) { Logger.Write("body", "folder missing: " + dir); return; }

        foreach (string f in Directory.GetFiles(dir))
            Logger.Write("body", "found: " + Path.GetFileName(f));
    }

    private string BodyStem()
    {
        bool skeleton = (BodySkeletonRadio != null && BodySkeletonRadio.Active);

        if (skeleton)
        {
            switch (_view)
            {
                case "back":  return "jacketBackBody";
                case "right": return "jacketRightBody";
                case "left":  return "jacketLeftBody";
                default:      return "jacketFrontBody";
            }
        }

        switch (_view)
        {
            case "back":  return "jacketBack";
            case "right": return "jacketRight";
            case "left":  return "jacketLeft";
            default:      return "jacketFront";
        }
    }

    /// Back view with no dedicated Image_Back in the CSV — Form2's
    /// CreateFlippedImage fallback. Computed from _view every call, so it
    /// cannot go stale when the view changes.
    private bool MapNeedsMirror()
    {
        return _case != null && _view == "back" && string.IsNullOrEmpty(_case.MapBack);
    }

    private string MapPathForView()
    {
        if (_case == null) return null;

        string rel;
        switch (_view)
        {
            case "back":  rel = _case.MapBack;  break;
            case "right": rel = _case.MapRight; break;
            case "left":  rel = _case.MapLeft;  break;
            default:      rel = _case.MapFront; break;
        }

        // Form2 falls back to a mirrored front map when there's no dedicated back.
        if (string.IsNullOrEmpty(rel)) rel = _case.MapFront;

        return string.IsNullOrEmpty(rel) ? null : SoundWindow.AppFile(rel);
    }

    private static Gdk.Pixbuf Load(string path)
    {
        if (string.IsNullOrEmpty(path) || !File.Exists(path))
        {
            Logger.Write("map", "image not found: " + path);
            return null;
        }

        try { return new Gdk.Pixbuf(path); }
        catch (Exception ex)
        {
            Logger.Write("map", "load failed " + path + ": " + ex.Message);
            return null;
        }
    }

    private Gdk.Pixbuf LoadMap(string path, bool mirror)
    {
        _mapPath = path ?? "(none)";

        var raw = Load(path);
        if (raw == null) return null;

        // Key out black FIRST, then scale. Scaling first leaves near-black
        // edge pixels (1,0,2) that AddAlpha won't match — that's the dark halo.
        var keyed = raw.AddAlpha(true, 0, 0, 0);
        raw.Dispose();

        if (mirror)
        {
            var flipped = keyed.Flip(true);
            keyed.Dispose();
            keyed = flipped;
            Logger.Write("map", "mirrored front map for back view");
        }

        if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; }   // defensive

        // Keep the keyed original for FitBody mode — the calibrator never
        // resized to 546, so its zoom numbers refer to THIS pixbuf.
        _mapRaw = keyed.Copy();

        var sized = keyed.ScaleSimple(MapSize, MapSize, Gdk.InterpType.Bilinear);
        keyed.Dispose();
        return sized;
    }

    // ── plumbing ───────────────────────────────────────────────────────

    private void OnBackClicked(object sender, EventArgs e)
    {
        StopSession();
        var h = BackRequested;
        if (h != null) h(this, EventArgs.Empty);
    }

    private void DisposePixbufs()
    {
        if (_body != null)   { _body.Dispose();   _body = null; }
        if (_map != null)    { _map.Dispose();    _map = null; }
        if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; }
    }

    public void Dispose()
    {
        StopWaveTimer();
        _arduino.LineReceived      -= OnArduinoLine;
        _arduino.ConnectionChanged -= OnArduinoConnectionChanged;
        if (_watchdogId != 0) { GLib.Source.Remove(_watchdogId); _watchdogId = 0; }

        foreach (var r in _regions) r.Dispose();
        _regions.Clear();

        _sound.Dispose();
        DisposePixbufs();
        if (_tuner != null) { _tuner.Destroy(); _tuner = null; }
    }

    private string JacketSize
    {
        get { return (JacketSizeCombo != null ? JacketSizeCombo.ActiveText : null) ?? "L"; }
    }

    private string DetermineViewFromZ(float z)
    {
        float frontDiff = Math.Abs(z - FRONT_Z);
        float backDiff  = Math.Abs(z - BACK_Z);
        float rightDiff = Math.Abs(z - RIGHT_Z);
        float leftDiff  = Math.Abs(z - LEFT_Z);

        float minDiff = Math.Min(Math.Min(frontDiff, backDiff), Math.Min(rightDiff, leftDiff));
        if (minDiff > Z_TOLERANCE) return _view;   // no clean match — stay put

        if (minDiff == frontDiff) return "front";
        if (minDiff == backDiff)  return "back";
        if (minDiff == rightDiff) return "right";
        return "left";
    }

    /// Drives the same radio buttons a manual click would, so the UI and
    /// _view stay in sync (SetView no-ops if it's already the active view).
    private void SwitchViewFromArduino(string view)
    {
        RadioButton rb = view == "back"  ? ViewBackRadio
                        : view == "right" ? ViewRightRadio
                        : view == "left"  ? ViewLeftRadio
                        : ViewFrontRadio;
        if (rb != null) rb.Active = true;
        else SetView(view);
    }

    //=========================================
    //debug
    private void StartDebugSweep()
    {
        if (!AppConfig.DebugMode) return;
        if (_debugSweepId != 0) return;          // already running
        if (_sound.MainVoice == null) return;    // no case loaded yet

        _debugLevel = 0;
        _debugStep  = 5;

        _debugSweepId = GLib.Timeout.Add(50, () =>
        {
            _debugLevel += _debugStep;

            if (_debugLevel >= 255) { _debugLevel = 255; _debugStep = -5; }
            else if (_debugLevel <= 0) { _debugLevel = 0; _debugStep = 5; }

            float gain = AudioEngine.VolumeCurve(_debugLevel);
            _sound.SetGain(_sound.MainVoice, gain);

            if (_debugLevel % 50 == 0)
                Logger.Write("sound", string.Format("sweep level={0}/255 gain={1:F3}",
                                                    _debugLevel, gain));
            return true;                          // keep firing
        });

        Logger.Write("sound", "debug volume sweep started");
    }

    private void StopDebugSweep()
    {
        if (_debugSweepId == 0) return;
        GLib.Source.Remove(_debugSweepId);
        _debugSweepId = 0;
        Logger.Write("sound", "debug volume sweep stopped");
    }

    /// Debug mode: the mouse stands in for the RFID tag. Widget coords are
    /// converted to BODY PIXELS with the inverse of OnMapDrawn's transform.
    private void MouseProbe(double wx, double wy)
    {
        if (_body == null) return;

        int w = MapArea.AllocatedWidth, h = MapArea.AllocatedHeight;
        double s  = Math.Min((double)w / _body.Width, (double)h / _body.Height);
        double ox = (w - _body.Width  * s) / 2.0;
        double oy = (h - _body.Height * s) / 2.0;

        _mouseBx = (wx - ox) / s;
        _mouseBy = (wy - oy) / s;
        _mouseProbe = true;
        UpdateContactChip();

        Logger.Write("debug", string.Format(CultureInfo.InvariantCulture,
            "mouse probe body({0:F0},{1:F0})", _mouseBx, _mouseBy));

        UpdateAudioFromPosition();
        MapArea.QueueDraw();
    }

    /// audible = this box's sound is playing now. A silent box draws its wave
    /// faded and without a cursor, so you can tell at a glance what you hear.
    private void DrawWave(DrawnArgs args, DrawingArea area, WaveData wave, double cursor,
                          bool audible, double r, double g, double b)
    {
        var cr = args.Cr;
        int w = area.AllocatedWidth, h = area.AllocatedHeight;
        double mid = h / 2.0;

        cr.SetSourceRGB(0.965, 0.969, 0.976);
        cr.Rectangle(0, 0, w, h);
        cr.Fill();

        cr.SetSourceRGBA(r, g, b, audible ? 1.0 : 0.30);

        if (wave == null || wave.Samples == null || w < 2)
        {
            // no sound of this kind in the case — flat line
            cr.LineWidth = 1.5;
            cr.MoveTo(0, mid);
            cr.LineTo(w, mid);
            cr.Stroke();
            args.RetVal = true;
            return;
        }

        float[] mins, maxs;
        wave.GetPeaks(w, out mins, out maxs);

        double amp = mid * 0.9;
        cr.LineWidth = 1;
        for (int x = 0; x < w; x++)
        {
            double y1 = mid - maxs[x] * amp;
            double y2 = mid - mins[x] * amp;
            if (y2 - y1 < 1) y2 = y1 + 1;        // quiet parts stay visible
            cr.MoveTo(x + 0.5, y1);
            cr.LineTo(x + 0.5, y2);
        }
        cr.Stroke();

        if (audible && cursor >= 0)
        {
            double cx = Math.Min(w - 1, cursor * w);
            cr.SetSourceRGB(0.1, 0.1, 0.1);      // dark cursor, contrasts with red and blue waves
            cr.LineWidth = 2;
            cr.MoveTo(cx, 0);
            cr.LineTo(cx, h);
            cr.Stroke();
        }

        args.RetVal = true;
    }

    /// Each box shows a sound that this case can actually play:
    ///   legacy  — the first heart region / first breath region (ApplyRegionAudio
    ///             then switches to whichever region is loudest);
    ///   current — the case sound in its own box; the other box only if that
    ///             extra voice (HeartSoundEnabled / BreathSoundEnabled) is loaded.
    private void LoadWaveforms(CaseDefinition def)
    {
        _heartCursor = _breathCursor = -1;
        SetAudible(false, false);

        if (def.IsLegacy)
        {
            RegionSound h = _regions.Find(r => r.IsHeart && r.Wave != null);
            RegionSound b = _regions.Find(r => !r.IsHeart && r.Wave != null);
            _heartWave  = h != null ? h.Wave : null;
            _breathWave = b != null ? b.Wave : null;
        }
        else
        {
            WaveData caseWave = LoadWave(def.SoundPath);
            if (def.IsHeart)
            {
                _heartWave  = caseWave;
                _breathWave = _breath != null ? LoadWave("SND200.wav") : null;
            }
            else
            {
                _breathWave = caseWave;
                _heartWave  = _heart1 != null ? LoadWave("SND100.wav") : null;
            }
        }

        HeartWaveArea.QueueDraw();
        BreathWaveArea.QueueDraw();
    }

    private static WaveData LoadWave(string csvValue)
    {
        string full = AppMode.ResolveSound(csvValue);
        if (full == null)
        {
            Logger.Write("wave", "no sound for waveform (" + (csvValue ?? "null") + ")");
            return null;                                // draw code shows a flat line
        }

        string err;
        WaveData w = WaveData.Load(full, out err);
        if (w == null) Logger.Write("wave", "load failed " + full + ": " + err);
        else Logger.Write("wave", "loaded " + full + " (" +
                        w.Duration.ToString("F2", CultureInfo.InvariantCulture) + " s)");
        return w;
    }

    private void StartWaveTimer()
    {
        if (_waveTimerId != 0) return;
        _waveTimerId = GLib.Timeout.Add(16, OnWaveTick);   // ~60 fps
    }

    private void StopWaveTimer()
    {
        if (_waveTimerId != 0) { GLib.Source.Remove(_waveTimerId); _waveTimerId = 0; }
        SetAudible(false, false);
        _heartCursor = _breathCursor = -1;
        if (HeartWaveArea != null)  HeartWaveArea.QueueDraw();
        if (BreathWaveArea != null) BreathWaveArea.QueueDraw();
    }

    /// Each box runs its own cursor, only while its own sound is audible.
    /// All voices were started together with _playClock, so t % duration is
    /// where each one is in its loop.
    private bool OnWaveTick()
    {
        double t = _playClock.Elapsed.TotalSeconds;
        bool heartOn  = _heartAudible  && HeartAllowed;
        bool breathOn = _breathAudible && LungAllowed;

        double hc = heartOn  ? CursorFor(_heartWave,  t) : -1;
        double bc = breathOn ? CursorFor(_breathWave, t) : -1;

        if (hc >= 0 || _heartCursor >= 0)  { _heartCursor  = hc; HeartWaveArea.QueueDraw(); }
        if (bc >= 0 || _breathCursor >= 0) { _breathCursor = bc; BreathWaveArea.QueueDraw(); }
        return true;
    }

    /// Where the looping voice is right now, 0..1 across the box.
    private static double CursorFor(WaveData w, double seconds)
    {
        if (w == null || w.Duration <= 0) return -1;
        return (seconds % w.Duration) / w.Duration;
    }

    /// Form2's checkBoxBlackAudio. Defaults ON; if the glade id is missing,
    /// the null check keeps it ON rather than silently killing the audio.
    private bool BlackAudioEnabled
    {
        get { return BlackAudioSwitch == null || BlackAudioSwitch.Active; }
    }

    /// Must match the pixbuf BodyToMapPixel indexes into, or px/py land
    /// on the wrong image.
    private Gdk.Pixbuf AudioSourcePixbuf
    {
        get { return (_mapFit == MapFit.FitBody && _mapRaw != null) ? _mapRaw : _map; }
    }

    /// Body-pixel point -> 0..1 position inside the drawn map rect.
    public bool BodyToMapUV(double bx, double by, out double u, out double v)
    {
        u = v = 0;
        double mx, my, mw, mh;
        if (!MapRect(out mx, out my, out mw, out mh)) return false;
        if (mw <= 0 || mh <= 0) return false;

        u = (bx - mx) / mw;
        v = (by - my) / mh;
        return (u >= 0 && u < 1 && v >= 0 && v < 1);
    }

    private void LoadRegions(CaseDefinition def)
    {
        _sound.MuteAll();
        foreach (var r in _regions) r.Dispose();
        _regions.Clear();
        // Free the previous case's region voices. Every OpenAL source keeps
        // looping and being mixed even at gain 0, so they must not pile up.
        _sound.ReleaseWhereKeyStarts("R");

        var waves = new Dictionary<string, WaveData>(StringComparer.OrdinalIgnoreCase);
        for (int k = 0; k < 7; k++)
        {
            string mapPath = AppMode.ResolveMap(def.RegionMaps[k]);
            string sndPath = AppMode.ResolveSound(def.RegionSounds[k]);
            if (mapPath == null || sndPath == null) continue;          // region disabled

            var pb = Load(mapPath);
            if (pb == null)
            {
                Logger.Write("map", "region " + RegionLabels[k] + " map missing: " + mapPath);
                continue;
            }

            var voice = _sound.Warm(sndPath, "R" + k + ":" + sndPath);
            if (voice == null)
            {
                Logger.Write("sound", "region " + RegionLabels[k] + " sound failed: " + sndPath);
                pb.Dispose();
                continue;
            }
            _sound.SetGain(voice, 0f);

            var rs = new RegionSound
            {
                Index = k, Name = RegionLabels[k], SoundPath = sndPath,
                Map = pb, Voice = voice
            };
            rs.CachePixels();

            // waveform for this region's own sound (shared when regions reuse a file)
            WaveData w;
            if (!waves.TryGetValue(sndPath, out w))
            {
                string err;
                w = WaveData.Load(sndPath, out err);
                if (w == null) Logger.Write("wave", "load failed " + sndPath + ": " + err);
                waves[sndPath] = w;
            }
            rs.Wave = w;
            _regions.Add(rs);

            Logger.Write("map", "region " + RegionLabels[k] + ": " +
                        Path.GetFileName(mapPath) + " + " + Path.GetFileName(sndPath));
        }

        Logger.Write("map", _regions.Count + "/7 regions active");
    }

    /// Call with the same body-pixel coords the single-map path uses.
    private void ApplyRegionAudio(double bx, double by)
    {
        double u, v;
        if (!BodyToMapUV(bx, by, out u, out v)) { MuteRegions(); SetAudible(false, false); return; }
        if (_view == "back") u = 1.0 - u;          // mirrored front map

        foreach (var r in _regions) r.Volume = r.VolumeAt(u, v);

        // Heart conflict: only the louder of the two heart modules plays.
        RegionSound h1 = _regions.Find(r => r.Index == 0);
        RegionSound h2 = _regions.Find(r => r.Index == 1);
        if (h1 != null && h2 != null)
        {
            if (h1.Volume >= h2.Volume) h2.Volume = 0f;
            else                        h1.Volume = 0f;
        }

        // 心音のみ / 肺音のみ / ミックス
        foreach (var r in _regions)
            if (r.IsHeart ? !HeartAllowed : !LungAllowed) r.Volume = 0f;

        foreach (var r in _regions) _sound.SetGain(r.Voice, r.Volume);

        // Each waveform box shows the loudest sound of its own kind, so with
        // heart + breath both playing you see two waves and two cursors.
        RegionSound hTop = Loudest(true), bTop = Loudest(false);
        if (hTop != null && hTop.Wave != null && hTop.Wave != _heartWave)  { _heartWave  = hTop.Wave; HeartWaveArea.QueueDraw(); }
        if (bTop != null && bTop.Wave != null && bTop.Wave != _breathWave) { _breathWave = bTop.Wave; BreathWaveArea.QueueDraw(); }
        SetAudible(hTop != null, bTop != null);

        MapArea.QueueDraw();                     // repaint the meters
    }

    /// Loudest currently-audible region of one kind, or null if none is playing.
    private RegionSound Loudest(bool heart)
    {
        RegionSound best = null;
        foreach (var r in _regions)
            if (r.IsHeart == heart && r.Volume > 0f && (best == null || r.Volume > best.Volume))
                best = r;
        return best;
    }

    private void MuteRegions()
    {
        if (_regions.Count == 0) return;
        foreach (var r in _regions) { r.Volume = 0f; _sound.SetGain(r.Voice, 0f); }
        MapArea.QueueDraw();
    }

    /// Brightest region wins each pixel; alpha tracks intensity.
    private Gdk.Pixbuf BuildRegionOverlay(int w, int h, bool mirror = false)
    {
        if (_regions.Count == 0) return null;

        int stride = w * 4;
        var px   = new byte[stride * h];
        var best = new byte[w * h];

        foreach (var r in _regions)
        {
            byte[] c = RegionColors[r.Index];

            for (int y = 0; y < h; y++)
            {
                double v = (y + 0.5) / h;
                for (int x = 0; x < w; x++)
                {
                    double u = (x + 0.5) / w;
                    if (mirror) u = 1.0 - u;
                    int val = r.IntensityAt(u, v);
                    if (val < RegionSound.MinIntensity) continue;   // same cut-off as the audio

                    int k = y * w + x;
                    if (val <= best[k]) continue;
                    best[k] = (byte)val;

                    int o = y * stride + x * 4;
                    px[o]     = c[0];
                    px[o + 1] = c[1];
                    px[o + 2] = c[2];
                    px[o + 3] = (byte)(val * 0.55);
                }
            }
        }

        return new Gdk.Pixbuf(px, Gdk.Colorspace.Rgb, true, 8, w, h, stride);
    }

    /// 聴診点リスト: one row per sound — colour swatch (the colour it has on the
    /// map), name, live volume bar. Rows the case doesn't have are grey;
    /// rows muted by the 心音のみ / 肺音のみ filter are dimmed.
    private void DrawRegionMeters(Cairo.Context cr)
    {
        if (!_showRegionLabels) return;

        // rows: label, colour, present?, allowed?, level 0..1
        var labels  = new List<string>();
        var colors  = new List<double[]>();
        var present = new List<bool>();
        var allowed = new List<bool>();
        var levels  = new List<double>();

        if (AppMode.Legacy)
        {
            for (int k = 0; k < 7; k++)
            {
                RegionSound r = _regions.Find(rs => rs.Index == k);
                byte[] c = RegionColors[k];
                labels.Add(RegionLabels[k]);
                colors.Add(new[] { c[0] / 255.0, c[1] / 255.0, c[2] / 255.0 });
                present.Add(r != null && r.Enabled);
                allowed.Add(k <= 1 ? HeartAllowed : LungAllowed);
                levels.Add(r != null ? r.Volume : 0.0);
            }
        }
        else
        {
            bool en = _lang != null && _lang.IsEnglish;
            bool caseHeart = _case != null && _case.IsHeart;
            labels.Add(en ? "Heart (red)"  : "心音(赤)");
            colors.Add(new[] { 0.776, 0.157, 0.157 });
            present.Add(caseHeart || _heart1 != null);
            allowed.Add(HeartAllowed);
            levels.Add(_legendHeart);

            labels.Add(en ? "Breath (blue)" : "呼吸音(青)");
            colors.Add(new[] { 0.122, 0.435, 0.698 });
            present.Add(!caseHeart || _breath != null);
            allowed.Add(LungAllowed);
            levels.Add(_legendBreath);
        }

        int n = labels.Count;
        const double rowH = 30, sw = 16, labelX = 12 + sw + 10, barX = 168, barW = 150, barH = 12, pad = 12;
        double y0 = pad;

        cr.Save();
        cr.NewPath();
        cr.SetSourceRGBA(0, 0, 0, 0.72);
        cr.Rectangle(pad - 6, y0 - 6, barX + barW + 12, n * rowH + 12);
        cr.Fill();

        var layout = Pango.CairoHelper.CreateLayout(cr);
        layout.FontDescription = Pango.FontDescription.FromString("Noto Sans CJK JP Bold 14");

        for (int k = 0; k < n; k++)
        {
            double y   = y0 + k * rowH;
            double[] c = colors[k];
            bool on    = present[k] && allowed[k];
            double a   = present[k] ? (allowed[k] ? 1.0 : 0.35) : 0.25;

            // colour swatch — always shown, so it works as a key
            cr.NewPath();
            cr.SetSourceRGBA(c[0], c[1], c[2], a);
            cr.Rectangle(pad, y + (rowH - sw) / 2.0, sw, sw);
            cr.Fill();

            // label
            layout.SetText(labels[k]);
            int lw, lh;
            layout.GetPixelSize(out lw, out lh);
            cr.SetSourceRGBA(1, 1, 1, present[k] ? (allowed[k] ? 1.0 : 0.45) : 0.35);
            cr.MoveTo(labelX, y + (rowH - lh) / 2.0);
            Pango.CairoHelper.ShowLayout(cr, layout);
            cr.NewPath();

            // live level
            double by = y + (rowH - barH) / 2.0;
            cr.SetSourceRGB(0.30, 0.30, 0.30);
            cr.Rectangle(barX, by, barW, barH);
            cr.Fill();
            if (on && levels[k] > 0)
            {
                cr.SetSourceRGB(c[0], c[1], c[2]);
                cr.Rectangle(barX, by, barW * Math.Min(1.0, levels[k]), barH);
                cr.Fill();
            }
        }

        layout.Dispose();
        cr.Restore();
    }

    /// Legacy: rebuild the 7-region composite for the current view.
    /// Back = mirrored front (same as Form2's CreateFlippedImage fallback).
    private void RebuildLegacyMap()
    {
        if (_map != null)    { _map.Dispose();    _map = null; }
        if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; }

        bool mirrored = _view == "back";
        bool shown    = _view == "front" || mirrored;

        if (shown)
        {
            var overlay = BuildRegionOverlay(MapSize, MapSize, mirrored);
            _mapRaw  = overlay != null ? overlay.Copy() : null;
            _map     = overlay;
            _mapPath = mirrored ? "(7 regions, mirrored)" : "(7 regions composite)";
        }
        else _mapPath = "(no legacy map for " + _view + ")";

        foreach (var r in _regions) r.Enabled = shown;
        if (!shown) MuteRegions();
    }
}