diff --git a/OS/.gitkeep b/OS/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/OS/.gitkeep
diff --git a/OS/BACKUP/Readme.md b/OS/BACKUP/Readme.md
new file mode 100644
index 0000000..4578fef
--- /dev/null
+++ b/OS/BACKUP/Readme.md
@@ -0,0 +1,243 @@
+# Restoring Windows on ASUS T101HA
+
+Complete guide to reverting from Xubuntu back to the original Windows installation.
+
+---
+
+## What you have
+
+| Item | Location | Purpose |
+|---|---|---|
+| `t101ha.img.zst` | PC: `E:\git\02 cSharp using mono\main\EARS-LINUX\OS\BACKUP\`
USB: BACKUP partition | Full byte-exact disk image, 17GB compressed |
+| `parts.txt` | Same locations | Partition table reference |
+| `window-key.txt` | Same locations | Windows product key |
+
+**Verified:** SHA256 `CBD4348ACB6777D5110D00F15FD67A6CBABE96152B628E503A8F2F6127E4EB63` (both copies identical)
+
+**Image expands to:** 62,537,072,640 bytes — exact match to device size
+
+---
+
+## Device reference
+
+- **Internal eMMC:** `/dev/mmcblk1` — ~58GiB (62,537,072,640 bytes)
+- **Firmware:** 64-bit UEFI (confirmed via `fw_platform_size`)
+- **Original layout:** ESP, Microsoft reserved, Windows (`p3`), recovery (`p4`)
+
+> **WARNING:** Verify the device with `lsblk` every time. Device names can shift between boots.
+
+---
+
+## Method 1 — Full image restore (recommended)
+
+Restores the exact original system: Windows activated, ASUS recovery partition, everything.
+
+### Preparation
+
+If the image lives on the PC, copy it back to the USB stick's BACKUP partition first. Restoring over a network is not recommended.
+
+### Steps
+
+**1. Boot the Ventoy live session**
+
+Power off fully. Hold F2, tap power, keep holding. Confirm Secure Boot is disabled, boot from USB, select the Xubuntu ISO, choose "Try Xubuntu".
+
+**2. Identify the devices**
+
+```bash
+lsblk -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINT
+```
+
+Confirm:
+- eMMC = the **~58GiB** device (`mmcblk1`)
+- USB = the **~115GiB** device with Ventoy/VTOYEFI/BACKUP partitions
+
+**3. Mount the backup**
+
+```bash
+sudo mkdir -p /mnt/backup
+sudo mount /dev/sda3 /mnt/backup
+ls -lh /mnt/backup
+```
+
+Adjust `sda3` to match the BACKUP partition from step 2.
+
+**4. Verify the image before writing**
+
+```bash
+zstd -t /mnt/backup/t101ha.img.zst
+```
+
+Must complete without error. If it fails, use the PC copy instead — do not proceed with a corrupt image.
+
+**5. Restore**
+
+```bash
+sudo blockdev --getsize64 /dev/mmcblk1
+```
+
+Confirm this prints `62537072640`. Then:
+
+```bash
+zstd -dc /mnt/backup/t101ha.img.zst | sudo dd of=/dev/mmcblk1 bs=4M status=progress
+sync
+```
+
+> **WARNING:** `of=` is the destructive direction. Everything on that device is erased. Read the command twice before pressing Enter.
+
+Takes 1–2 hours. Do not interrupt it, and do not run anything else — 2GB RAM.
+
+**6. Finish**
+
+```bash
+sync
+sudo umount /mnt/backup
+sudo poweroff
+```
+
+Remove the USB stick. Power on. Windows should boot, activated, exactly as it was.
+
+### With a progress bar
+
+```bash
+sudo apt install -y pv
+sudo sh -c 'zstd -dc /mnt/backup/t101ha.img.zst | pv -s 62537072640 | dd of=/dev/mmcblk1 bs=4M'
+```
+
+---
+
+## Method 2 — Recover files only (non-destructive)
+
+To extract files from the Windows image without wiping Xubuntu. Requires ~58GB free space.
+
+```bash
+zstd -d /path/to/t101ha.img.zst -o /tmp/full.img
+sudo losetup -fP --show /tmp/full.img
+```
+
+Note the loop device it prints (e.g. `/dev/loop0`), then:
+
+```bash
+sudo mkdir -p /mnt/win
+sudo mount -o ro /dev/loop0p3 /mnt/win
+```
+
+Windows lives on partition 3. Browse `/mnt/win`, copy what you need.
+
+Cleanup:
+
+```bash
+sudo umount /mnt/win
+sudo losetup -d /dev/loop0
+rm /tmp/full.img
+```
+
+If mount fails with a BitLocker error, the partition is encrypted — you'll need the recovery key from https://account.microsoft.com/devices/recoverykey
+
+---
+
+## Method 3 — Clean Windows install (image lost)
+
+Last resort. The product key is stored in firmware (ACPI MSDM table), so a clean install self-activates without entering anything.
+
+1. Download the Windows 10 ISO from Microsoft on the PC
+2. Write it to USB with Rufus — **GPT**, **UEFI** target
+3. Boot the tablet from it, install to the internal eMMC
+4. Activation happens automatically from firmware
+
+**Caveats:**
+- The ASUS recovery partition is not restored
+- Cherry Trail drivers may need manual installation from ASUS support
+- **Windows 10 is past end of support (October 2025), and this hardware cannot run Windows 11** — a restored image is a supported-nothing situation either way, but a clean install is strictly worse
+
+---
+
+## Recovering the product key
+
+From Linux, on the running tablet:
+
+```bash
+sudo strings /sys/firmware/acpi/tables/MSDM | tail -1
+```
+
+From the saved file:
+
+```bash
+cat /mnt/backup/window-key.txt; echo
+```
+
+From Windows:
+
+```powershell
+(Get-CimInstance SoftwareLicensingService).OA3xOriginalProductKey
+```
+
+**Note:** viewing `window-key.txt` in Notepad may show CJK garbage — it's an encoding guess, not corruption. Read it on Linux with `cat`, or open it in VS Code and set encoding to UTF-8.
+
+---
+
+## Verifying image integrity
+
+Quick check (structural):
+
+```bash
+zstd -t t101ha.img.zst
+```
+
+Full check (byte count vs device):
+
+```bash
+DEV=$(sudo blockdev --getsize64 /dev/mmcblk1)
+IMG=$(zstd -dc /path/to/t101ha.img.zst | wc -c)
+echo "device: $DEV"
+echo "image: $IMG"
+test "$DEV" = "$IMG" && echo MATCH || echo MISMATCH
+```
+
+Compare copies (PowerShell):
+
+```powershell
+Get-FileHash 'path\to\t101ha.img.zst' -Algorithm SHA256
+```
+
+> **WARNING:** `[ "$DEV" = "$IMG" ]` requires spaces inside the brackets. Without them the shell reports "command not found" and prints MISMATCH regardless of the actual values. Use `test` to avoid this.
+
+---
+
+## Troubleshooting
+
+**Restore finishes but won't boot**
+
+Check Secure Boot in BIOS — re-enable it, since the original Windows install expects it. Confirm the boot order lists Windows Boot Manager.
+
+**`dd` reports "No space left on device"**
+
+Wrong target device. Verify with `lsblk` that you're writing to the ~58GiB eMMC.
+
+**Image fails `zstd -t`**
+
+Use the other copy. If both fail, fall back to Method 3.
+
+**Progress appears frozen**
+
+Check it's actually stalled before interrupting:
+
+```bash
+ps -eo pid,stat,cmd | grep -v grep | grep -E 'dd|zstd'
+sudo dmesg | tail -30
+```
+
+STAT `D` plus `mmc` errors in dmesg indicates bad sectors. STAT `R`/`S` with a clean dmesg means it's just slow — eMMC on this tablet throttles when warm.
+
+**"read kernel buffer failed"**
+
+`dmesg` needs root here: `sudo dmesg`
+
+---
+
+## Notes
+
+- Keep both copies of the image. The USB stick is a single point of failure.
+- Restoring reverts to the disk state as of **27 July 2026**. Nothing created in Xubuntu survives.
+- Do a full `zstd -t` on whichever copy you plan to use *before* wiping anything.
+- Original image created with: `sudo zstd -1 -T0 -f -o /mnt/backup/t101ha.img.zst /dev/mmcblk1`
\ No newline at end of file
diff --git a/OS/Readme.md b/OS/Readme.md
new file mode 100644
index 0000000..c9bb2f5
--- /dev/null
+++ b/OS/Readme.md
@@ -0,0 +1,746 @@
+# Xubuntu Setup — Asus T101HA (`ears-tablet`)
+
+Working notes for setting up an Asus T101HA (Atom x5-Z8350, 2 GB RAM / ~1.8 GB
+usable, eMMC) as a Mono + GTK#3 development and runtime machine.
+
+User: `ears` · Hostname: `ears-tablet`
+
+---
+
+## Contents
+
+- [0. Recommended baseline](#0-recommended-baseline)
+- [1. Installing Xubuntu](#1-installing-xubuntu)
+ - [1.1 Check firmware bitness first](#11-check-firmware-bitness-first--this-determines-everything)
+ - [1.2 Build the USB](#12-build-the-usb)
+ - [1.3 BIOS](#13-bios)
+ - [1.4 Install](#14-install)
+ - [1.5 Post-install GRUB fix (IA32 only)](#15-post-install-grub-fix-ia32-machines-only)
+ - [1.6 Expect to fix afterwards](#16-expect-to-fix-afterwards)
+- [2. First boot / recovery mode](#2-first-boot--recovery-mode)
+- [3. Low-RAM tuning](#3-low-ram-tuning)
+ - [Option A — `zram-tools`](#option-a--zram-tools-simple)
+ - [Option B — `systemd-zram-generator`](#option-b--systemd-zram-generator-current-preferred-on-2404)
+ - [Swappiness](#swappiness)
+- [4. apt: repair and sources](#4-apt-repair-and-sources)
+ - [4.1 The modern layout](#41-the-modern-layout)
+ - [4.2 Correct stock sources](#42-correct-stock-sources-2510-example--substitute-your-codename)
+ - [4.3 Which host? archive vs old-releases](#43-which-host-archive-vs-old-releases)
+ - [4.4 Check for genuinely broken packages](#44-check-for-genuinely-broken-packages)
+ - [4.5 Don't do these](#45-dont-do-these)
+ - [4.6 `full-upgrade` checklist](#46-full-upgrade-checklist)
+ - [4.7 Reboot needed?](#47-reboot-needed)
+- [5. Mono + GTK#3](#5-mono--gtk3)
+ - [Install](#install)
+ - [Optional](#optional)
+ - [Verify](#verify)
+ - [Smoke test](#smoke-test)
+ - [Notes vs. the WSL guide](#notes-vs-the-wsl-guide)
+- [6. Display rotation + touchscreen](#6-display-rotation--touchscreen)
+ - [Identify devices](#identify-devices)
+ - [Matrices](#matrices)
+ - [Persistence script](#persistence-script)
+ - [Login screen (LightDM)](#login-screen-lightdm--separate-from-your-session)
+ - [Better: rotate before the session starts](#better-rotate-before-the-session-starts)
+ - [Wallpaper breaks after rotating](#wallpaper-breaks-after-rotating)
+ - [Auto-rotation (optional)](#auto-rotation-optional)
+- [7. Audio](#7-audio)
+ - [Install and test](#install-and-test)
+ - [Choosing the right card](#choosing-the-right-card)
+ - [Renumbering at the kernel level](#renumbering-at-the-kernel-level)
+ - [Caveats](#caveats)
+- [8. Running a script at boot](#8-running-a-script-at-boot)
+- [9. File transfer to/from Windows](#9-file-transfer-tofrom-windows)
+- [10. Quick reference](#10-quick-reference)
+
+---
+
+## 0. Recommended baseline
+
+**Target: Xubuntu 24.04 LTS (Minimal ISO).**
+
+Reasons, from the apt/Mono investigation:
+- The machine was found running **Ubuntu 25.10 "questing"**, which hit end of
+ life on **9 July 2026**. No further updates will ever be published for it.
+- `gtk-sharp3` is **not packaged on 25.10**, and upgrading to 26.04 would not
+ bring it back.
+- `gtk-sharp3` **is** packaged on 24.04 (noble), supported to 2029.
+- Xfce on 24.04 idles around 500–600 MB, which matters at 1.8 GB RAM.
+
+Mono + `mcs` + GTK# is the correct toolchain for this hardware — the .NET SDK
+(~800 MB) and Avalonia are far heavier.
+
+Before reinstalling, back up: `*.cs`, `*.glade`, SSH keys, browser profile.
+
+```bash
+lsblk # is /home a separate partition?
+df -h /
+free -h
+mkdir -p ~/backup && cp ~/*.cs ~/*.glade ~/backup/
+```
+
+If `/home` is its own partition, it can be preserved during install (assign
+`/home` **without** format). Use the same username to keep permissions clean.
+
+---
+
+## 1. Installing Xubuntu
+
+### 1.1 Check firmware bitness first — this determines everything
+
+In Windows: **Settings → System → About → System type**
+
+- *32-bit operating system, x64-based processor* → **IA32 UEFI**, needs the
+ bootia32 workaround below.
+- *64-bit* → skip the GRUB steps.
+
+### 1.2 Build the USB
+
+Ventoy includes IA32 UEFI support, so try it first. If it won't boot, fall back
+to Rufus and copy a 32-bit `bootia32.efi` (GRUB) into `/EFI/BOOT` on the stick.
+
+From Linux, writing directly:
+
+```bash
+sudo dd if=xubuntu-24.04-minimal-amd64.iso of=/dev/sdX bs=4M status=progress conv=fsync
+```
+
+> Verify the target with `lsblk` first. `dd` to the wrong disk destroys it
+> silently.
+
+Verify the ISO: `sha256sum` against the checksum on the download page.
+
+### 1.3 BIOS
+
+- F2 at power-on
+- **Disable Secure Boot** (the ia32 GRUB is unsigned)
+- Boot menu is usually F12 / Esc
+
+### 1.4 Install
+
+Choose **Install**, not *Try* — the live session eats RAM you don't have.
+Don't open Firefox or anything else during install. Let it create swap.
+
+### 1.5 Post-install GRUB fix (IA32 machines only)
+
+The installer writes a 64-bit `grubx64.efi` the firmware can't read. Boot the
+live session, chroot in, and:
+
+```bash
+grub-install --target=i386-efi --efi-directory=/boot/efi
+```
+
+This is **not optional** on IA32 firmware.
+
+### 1.6 Expect to fix afterwards
+
+| Component | Notes |
+|---|---|
+| Wi-Fi | RTL8723BS SDIO — finicky |
+| Audio | ESS ES8316 codec, needs UCM configs |
+| Touchscreen | Works, but rotation needs manual matrix (§6) |
+| Auto-rotation | Needs `iio-sensor-proxy` + custom handler |
+
+A recent 6.x kernel fixes most of these.
+
+---
+
+## 2. First boot / recovery mode
+
+If the user account lacks admin rights:
+
+```bash
+usermod -aG sudo ears
+groups ears # confirm 'sudo' appears
+hostnamectl set-hostname ears-tablet
+localectl set-locale LANG=en_US.UTF-8 # optional, cosmetic
+exit # then 'resume'
+```
+
+`usermod -aG sudo` is the one that isn't optional — without it you can log in
+but can't run any admin command.
+
+---
+
+## 3. Low-RAM tuning
+
+### Option A — `zram-tools` (simple)
+
+```bash
+sudo apt install zram-tools
+```
+
+Edit `/etc/default/zramswap`:
+```
+PERCENT=60
+ALGO=zstd
+```
+
+### Option B — `systemd-zram-generator` (current, preferred on 24.04+)
+
+```bash
+sudo apt install systemd-zram-generator
+
+sudo tee /etc/systemd/zram-generator.conf > /dev/null <<'EOF'
+[zram0]
+zram-size = min(ram / 2, 4096)
+compression-algorithm = zstd
+swap-priority = 100
+EOF
+
+sudo systemctl daemon-reload
+sudo systemctl start systemd-zram-setup@zram0.service
+swapon --show # expect /dev/zram0
+zramctl
+```
+
+The package does nothing without a config file containing at least one section.
+
+### Swappiness
+
+Swapping to zram is cheap, so raise it so the kernel actually uses it:
+
+```bash
+echo 'vm.swappiness=100' | sudo tee /etc/sysctl.d/99-zram.conf
+```
+
+Reboot. Verdict: worth it at 2–4 GB, marginal at 8 GB, skip above 16 GB.
+zram compresses **RAM** — it does nothing for low disk space.
+
+---
+
+## 4. apt: repair and sources
+
+### 4.1 The modern layout
+
+Since 24.04, archive config lives in **`/etc/apt/sources.list.d/ubuntu.sources`**
+(deb822 format). `/etc/apt/sources.list` being empty is normal, not a symptom.
+Most apt advice online predates this and edits a file that does nothing.
+
+### 4.2 Correct stock sources (25.10 example — substitute your codename)
+
+```bash
+sudo tee /etc/apt/sources.list.d/ubuntu.sources > /dev/null <<'EOF'
+Types: deb
+URIs: http://archive.ubuntu.com/ubuntu/
+Suites: questing questing-updates questing-backports
+Components: main restricted universe multiverse
+Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
+
+Types: deb
+URIs: http://security.ubuntu.com/ubuntu/
+Suites: questing-security
+Components: main restricted universe multiverse
+Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
+EOF
+
+sudo apt update
+```
+
+Do not drop the `Signed-By:` line — without it apt falls back to the legacy
+trusted-keyring and you get confusing "not signed" errors later.
+
+`ubuntu.sources.curtin.orig` is the installer's pristine backup. apt ignores
+`.orig` files. Useful as a reference, don't copy blindly.
+
+### 4.3 Which host? archive vs old-releases
+
+An EOL release only moves to `old-releases.ubuntu.com` when the migration
+actually runs — which can lag the EOL date by weeks. Pointing there too early
+gives four clean 404s. Test before switching:
+
+```bash
+for p in questing questing-updates questing-backports questing-security; do
+ echo -n "$p: "
+ curl -sI "http://old-releases.ubuntu.com/ubuntu/dists/$p/Release" | head -1
+done
+
+curl -sI http://archive.ubuntu.com/ubuntu/dists/questing/Release | head -1
+```
+
+`200` = pocket exists. `404` = drop it or use the other host.
+
+### 4.4 Check for genuinely broken packages
+
+All read-only, cheapest first:
+
+```bash
+sudo dpkg --audit # clean = no output at all
+sudo apt-get check # verifies the dependency tree
+dpkg -l | grep -v '^ii' | grep -v '^rc'
+apt-mark showhold # held packages are silently skipped on upgrade
+```
+
+dpkg status codes (desired state, then actual):
+
+| Code | Meaning |
+|---|---|
+| `ii` | Healthy |
+| `rc` | Removed, config left — harmless |
+| `iU` | Unpacked, never configured |
+| `iF` | Half-configured |
+| `iH` | Half-installed |
+| `iW` / `it` | Waiting on / pending triggers |
+| `*R*` | Reinstall required → `apt install --reinstall ` |
+
+Then repair:
+
+```bash
+sudo dpkg --configure -a
+sudo apt --fix-broken install
+sudo apt full-upgrade
+```
+
+### 4.5 Don't do these
+
+```bash
+# WRONG — killall receives 'sudo', 'rm', paths etc. as process names
+sudo killall apt apt-get dpkg 2>/dev/null sudo rm /var/lib/apt/lists/lock ...
+
+# DANGEROUS — rm -rf also targets files named sudo, apt, clean, update in $PWD
+sudo rm -rf /var/lib/apt/lists/* sudo apt clean sudo apt update
+```
+
+These must be separate lines. Also: killing `dpkg` mid-transaction is what
+*creates* the broken state. Check first with `ps aux | grep -E 'apt|dpkg'`.
+
+Don't remove `universe` — it's an Ubuntu component, not a PPA, and
+`gtk-sharp3` lives there. And never run
+`add-apt-repository --remove ppa:repository-name/ppa` literally; that's a
+placeholder from a copied guide.
+
+### 4.6 `full-upgrade` checklist
+
+- Use `full-upgrade`, not `upgrade` — it permits removals where deps changed
+- Read the summary line; mass removals of desktop/kernel packages = stop
+- Plug the tablet in; power loss mid-`dpkg` recreates the broken state
+- On config prompts, keeping the local version (the default) is safe unless
+ you know you edited it
+- Then `sudo apt autoremove` — but answer `n` if anything with `efi` appears
+- Reboot before `do-release-upgrade` so the newest kernel is running
+
+### 4.7 Reboot needed?
+
+```bash
+[ -f /var/run/reboot-required ] && cat /var/run/reboot-required.pkgs
+sudo needrestart # interactive; shows what's running old libs
+```
+
+Kernel / initramfs / systemd / glibc → reboot. Everything else → restart the
+service.
+
+---
+
+## 5. Mono + GTK#3
+
+### Install
+
+```bash
+sudo add-apt-repository universe
+sudo apt update
+sudo apt install mono-complete gtk-sharp3
+```
+
+| Package | Contents | Size |
+|---|---|---|
+| `mono-runtime` | JIT + `mscorlib` only | ~15 MB |
+| `mono-devel` | Compiler + the BCL you need | ~200–400 MB |
+| `mono-complete` | Runtime + `mcs` + entire class library + F#/VB | ~300–500 MB |
+
+**Avoid `mono-runtime`.** The BCL is split across dozens of
+`libmono-system-*-cil` packages; hello-world runs, but anything touching LINQ,
+XML, HTTP, or `System.IO.Ports` (the COM-port combo box in `homepage.glade`)
+throws `Could not load file or assembly`. On a tight disk, `mono-devel` saves
+~100 MB over `mono-complete` and still covers everything this project needs.
+
+### Optional
+
+```bash
+sudo apt install glade # visual designer — skip on this machine
+sudo apt install libgdiplus # only if using System.Drawing
+sudo apt install libcanberra-gtk3-module # silences a harmless console warning
+```
+
+### Verify
+
+```bash
+mono --version
+mcs --version
+pkg-config --list-all | grep gtk-sharp # want gtk-sharp-3.0
+apt policy gtk-sharp3
+```
+
+### Smoke test
+
+```bash
+cat > gtkcheck.cs <<'EOF'
+using System;
+using Gtk;
+
+class GtkCheck {
+ static void Main() {
+ Application.Init();
+ var win = new Window("Hello GTK#3");
+ win.SetDefaultSize(300, 200);
+ win.DeleteEvent += (o, args) => Application.Quit();
+
+ var button = new Button("Click me");
+ button.Clicked += (o, args) => Console.WriteLine("Clicked!");
+ win.Add(button);
+
+ win.ShowAll();
+ Application.Run();
+ }
+}
+EOF
+
+mcs -pkg:gtk-sharp-3.0 gtkcheck.cs
+mono gtkcheck.exe
+```
+
+Do the throwaway test first — it isolates "is gtk-sharp3 working" from "does my
+app compile."
+
+Then the real thing:
+
+```bash
+mcs -pkg:gtk-sharp-3.0 program.cs MainWindow.cs ArduinoConnection.cs -out:test.exe
+mono test.exe
+```
+
+(`ArduinoConnection.cs` is needed because `MainWindow` calls
+`_arduino.Disconnect()`; omitting it gives `CS0246`.)
+
+### Notes vs. the WSL guide
+
+- No WSLg, no `$DISPLAY` fiddling — Xfce is itself GTK3, so the app picks up the
+ system theme and the window just appears.
+- Only exception: over SSH you need `ssh -X`.
+- Companion files (`-r:` DLLs, `homepage.glade`) must sit next to the `.exe`, or
+ you get `FileNotFoundException`.
+- `homepage.glade` targets GTK 3.24, which 22.04 and 24.04 both ship.
+- `gtk-sharp2` is gone from 24.04 onward — use `gtk-sharp3`.
+
+---
+
+## 6. Display rotation + touchscreen
+
+X11 does **not** rotate touch input when you rotate the display. The touch
+device needs its own coordinate transformation matrix.
+
+### Identify devices
+
+```bash
+xrandr # output name — DSI-1, or None-1 on this unit
+xinput list --name-only # look for Silead / GSL / SIS, NOT 'Touchpad'
+```
+
+> On this tablet the output reported as **`None-1`** (xrandr's fallback when the
+> connector type isn't identified — it can change between kernels) and the
+> touchscreen as **`SIS0457:00 0457:11ED`**.
+
+### Matrices
+
+| Rotation | Matrix |
+|---|---|
+| normal | `1 0 0 0 1 0 0 0 1` |
+| right (90° CW) | `0 1 0 -1 0 1 0 0 1` |
+| left (90° CCW) | `0 -1 1 1 0 0 0 0 1` |
+| inverted (180°) | `-1 0 1 0 -1 1 0 0 1` |
+
+```bash
+xrandr --output None-1 --rotate right
+xinput set-prop "SIS0457:00 0457:11ED" "Coordinate Transformation Matrix" 0 1 0 -1 0 1 0 0 1
+```
+
+### Persistence script
+
+```bash
+nano ~/rotate.sh
+```
+
+```bash
+#!/bin/bash
+sleep 3
+OUT=$(xrandr | awk '/ connected/{print $1; exit}')
+xrandr --output "$OUT" --rotate right
+TS=$(xinput list --name-only | grep -iE 'silead|gsl|touchscreen|SIS' | grep -vi 'touchpad' | head -1)
+[ -n "$TS" ] && xinput set-prop "$TS" "Coordinate Transformation Matrix" 0 1 0 -1 0 1 0 0 1
+xset s off
+xset -dpms
+```
+
+```bash
+chmod +x ~/rotate.sh
+~/rotate.sh # test before automating
+```
+
+Then **Settings → Session and Startup → Application Autostart → Add**, command
+`/home/ears/rotate.sh`.
+
+> **Gotcha:** grepping bare `touch` matches the **trackpad** and rotates the
+> pointer instead. Use `touchscreen` and exclude `touchpad`. To undo:
+> ```bash
+> TP=$(xinput list --name-only | grep -i -m1 touchpad)
+> xinput set-prop "$TP" "Coordinate Transformation Matrix" 1 0 0 0 1 0 0 0 1
+> ```
+> Or just log out — the matrix isn't saved anywhere.
+
+The `sleep 3` matters; the touchscreen isn't registered the instant the session
+starts. Raise to 5 if touch still comes out wrong.
+
+**Try Settings → Display first.** Its rotation dropdown often persists on its
+own, leaving the script to handle only the `xinput` part.
+
+### Login screen (LightDM — separate from your session)
+
+```bash
+sudo nano /etc/lightdm/lightdm.conf
+```
+```ini
+[Seat:*]
+display-setup-script=/usr/bin/xrandr --output None-1 --rotate right
+```
+
+### Better: rotate before the session starts
+
+```bash
+sudo nano /etc/X11/xorg.conf.d/10-monitor.conf
+```
+```
+Section "Monitor"
+ Identifier "DSI-1"
+ Option "Rotate" "right"
+EndSection
+```
+
+Whole machine including the text console — add to `/etc/default/grub`:
+`fbcon=rotate:1` plus `video=DSI-1:panel_orientation=right_side_up`, then
+`sudo update-grub`.
+
+### Wallpaper breaks after rotating
+
+The desktop paints the wallpaper onto a surface sized for the old geometry and
+doesn't repaint after `xrandr`. On Xfce:
+
+```bash
+xfdesktop --reload
+```
+
+Also set the image style to **scaled** — `spanned` and `zoom` misbehave badly
+when the aspect ratio flips. Rotating before the session starts avoids this
+entirely.
+
+### Auto-rotation (optional)
+
+Xfce has no built-in handler. Confirm the sensor works before writing anything:
+
+```bash
+sudo apt install -y iio-sensor-proxy
+monitor-sensor # tilt the tablet; orientation should print
+```
+
+If nothing prints, this unit needs a kernel quirk — not worth chasing.
+
+```bash
+monitor-sensor | while read -r line; do
+ case "$line" in
+ *normal*) R=normal; M="1 0 0 0 1 0 0 0 1" ;;
+ *right-up*) R=right; M="0 1 0 -1 0 1 0 0 1" ;;
+ *left-up*) R=left; M="0 -1 1 1 0 0 0 0 1" ;;
+ *bottom-up*) R=inverted; M="-1 0 1 0 -1 1 0 0 1" ;;
+ *) continue ;;
+ esac
+ xrandr --output DSI-1 --rotate "$R"
+ xinput set-prop "SIS0457:00 0457:11ED" "Coordinate Transformation Matrix" $M
+done
+```
+
+> Most community auto-rotate scripts only call `xrandr` and leave touch behind.
+> If a script doesn't contain `xinput set-prop`, it won't rotate touch.
+
+---
+
+## 7. Audio
+
+### Install and test
+
+```bash
+sudo apt install alsa-utils # this is what provides aplay
+
+aplay --version
+aplay -l # list playback devices
+aplay /usr/share/sounds/alsa/Front_Center.wav
+speaker-test -c 2 -t wav -l 1
+```
+
+PipeWire/PulseAudio layer:
+
+```bash
+pactl info # "Server Name" tells you which
+pactl list short sinks
+paplay /usr/share/sounds/alsa/Front_Center.wav
+```
+
+### Choosing the right card
+
+Neither config file exists by default — create whichever you prefer:
+
+```bash
+nano ~/.asoundrc # per-user; wins over the system file
+# or
+sudo nano /etc/asound.conf # system-wide, incl. root and systemd services
+```
+
+```
+defaults.pcm.card 1
+defaults.ctl.card 1
+```
+
+`ctl` is what `alsamixer` reads, `pcm` is what `aplay` reads — set both. No
+reload needed; it's read per-process.
+
+With `plughw` conversion behaviour as the default:
+
+```
+pcm.!default {
+ type plug
+ slave.pcm "hw:1,0"
+}
+ctl.!default {
+ type hw
+ card 1
+}
+```
+
+Verify — `-v` prints the resolved device:
+
+```bash
+aplay -D default -v /usr/share/sounds/alsa/Front_Center.wav 2>&1 | head -20
+```
+
+### Renumbering at the kernel level
+
+```bash
+cat /proc/asound/modules
+sudo nano /etc/modprobe.d/alsa-card-order.conf
+```
+```
+options snd_soc_sst_bytcr_rt5640 index=0
+options snd_hda_intel index=1
+```
+```bash
+sudo update-initramfs -u && sudo reboot
+```
+
+### Caveats
+
+- **PipeWire ignores all of the above.** `~/.asoundrc` only governs programs
+ talking to ALSA directly (`aplay`, `alsamixer`). For desktop apps use
+ `pactl set-default-sink` or `pavucontrol`.
+- Save your mixer levels or they come back muted: `sudo alsactl store 1`
+- Device busy → use `aplay -D default file.wav`, not `-D hw:0,0`
+- Permission errors → `sudo usermod -aG audio $USER`, then re-login
+- `aplay` handles WAV/AU/RAW only — use `mpg123` or `ffplay` for MP3/FLAC
+
+---
+
+## 8. Running a script at boot
+
+```bash
+sudo nano /usr/local/bin/myscript.sh
+sudo chmod +x /usr/local/bin/myscript.sh
+```
+
+Start with `#!/bin/bash` and use **absolute paths** — there's almost no
+environment at boot.
+
+```bash
+sudo nano /etc/systemd/system/myscript.service
+```
+
+```ini
+[Unit]
+Description=My boot script
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=oneshot
+ExecStart=/usr/local/bin/myscript.sh
+RemainAfterExit=yes
+
+[Install]
+WantedBy=multi-user.target
+```
+
+```bash
+sudo systemctl daemon-reload
+sudo systemctl enable --now myscript.service
+systemctl status myscript.service
+journalctl -u myscript.service
+```
+
+Variations:
+
+- Long-running daemon → `Type=simple`, drop `RemainAfterExit`
+- Before the login screen → `Before=display-manager.service` in `[Unit]`,
+ `WantedBy=display-manager.service` in `[Install]`
+- Quick and dirty → `sudo crontab -e`, then
+ `@reboot /usr/local/bin/myscript.sh` (no logging, no ordering)
+- Drop `After=`/`Wants=` if networking isn't needed — it'll run earlier
+
+> **A root systemd service cannot rotate the display** — no `DISPLAY`, no
+> `XAUTHORITY`. Use the config-level methods in §6 instead. Same for audio: a
+> root service has no audio session, so use `systemctl --user` or target the
+> hardware device directly.
+
+---
+
+## 9. File transfer to/from Windows
+
+**Tailscale is not required.** It creates a private network *across the
+internet* — only needed to reach the tablet from outside your home. For a
+tablet and PC on the same Wi-Fi it's just another background daemon on a
+2 GB machine.
+
+Lightest option — SSH:
+
+```bash
+sudo apt install -y openssh-server
+```
+
+Connect from Windows with WinSCP or `scp` in PowerShell. No configuration
+beyond the above.
+
+Samba is only worth it if you want the tablet's folders to appear in Windows
+Explorer as a normal network drive.
+
+---
+
+## 10. Quick reference
+
+```bash
+# state
+free -h; df -h /; lsblk; swapon --show
+cat /etc/os-release
+. /etc/os-release; echo $VERSION_CODENAME
+
+# apt health
+sudo dpkg --audit; sudo apt-get check; apt-mark showhold
+ls /etc/apt/sources.list.d/
+cat /etc/apt/sources.list.d/ubuntu.sources
+
+# display
+xrandr; xinput list --name-only
+~/rotate.sh; xfdesktop --reload
+
+# audio
+aplay -l; pactl list short sinks
+aplay /usr/share/sounds/alsa/Front_Center.wav
+sudo alsactl store 1
+
+# build
+mcs -pkg:gtk-sharp-3.0 program.cs MainWindow.cs ArduinoConnection.cs -out:test.exe
+mono test.exe
+```
\ No newline at end of file
diff --git a/Readme.md b/Readme.md
index 402d96e..d0cd4ac 100644
--- a/Readme.md
+++ b/Readme.md
@@ -1,20 +1,39 @@
# Mono + GTK# + Glade — WSL Setup Guide
## Table of Contents
-- [1. Prerequisites](#1-prerequisites)
-- [2. Install Mono](#2-install-mono)
-- [3. Install GTK# (GTK# 3.0, for Ubuntu 24.04)](#3-install-gtk-gtk-30-for-ubuntu-2404)
-- [4. Install Glade (visual UI designer)](#4-install-glade-visual-ui-designer)
-- [5. Optional: libgdiplus (only if using System.Drawing)](#5-optional-libgdiplus-only-if-using-systemdrawing)
-- [6. Compiling & Running](#6-compiling--running)
-- [7. Minimal Working Examples](#7-minimal-working-examples)
-- [8. Custom Output Names, Targets & Exporting DLLs](#8-custom-output-names-targets--exporting-dlls)
-- [9. Common Errors & Fixes](#9-common-errors--fixes)
-- [10. Notes on Alternatives](#10-notes-on-alternatives)
+- [Mono](#mono)
+ - [1. Prerequisites](#1-prerequisites)
+ - [2. Install Mono](#2-install-mono)
+ - [3. Install GTK# (GTK# 3.0, for Ubuntu 24.04)](#3-install-gtk-gtk-30-for-ubuntu-2404)
+ - [4. Install Glade (visual UI designer)](#4-install-glade-visual-ui-designer)
+ - [5. Optional: libgdiplus (only if using System.Drawing)](#5-optional-libgdiplus-only-if-using-systemdrawing)
+ - [6. Compiling & Running](#6-compiling--running)
+ - [7. Minimal Working Examples](#7-minimal-working-examples)
+ - [8. Custom Output Names, Targets & Exporting DLLs](#8-custom-output-names-targets--exporting-dlls)
+ - [9. Common Errors & Fixes](#9-common-errors--fixes)
+ - [10. Notes on Alternatives](#10-notes-on-alternatives)
+- [OS](#os)
+ - [Workflow](#workflow)
+ - [OS images checked](#os-images-checked)
+ - [OS images to check](#os-images-to-check)
+- [EARS Application](#ears-application)
+ - [11. Project Layout](#11-project-layout)
+ - [12. Single-Window Notebook Architecture](#12-single-window-notebook-architecture)
+ - [13. Glade Rules That Bite](#13-glade-rules-that-bite)
+ - [14. Generating Widgets From Code](#14-generating-widgets-from-code)
+ - [15. Loading cases.csv](#15-loading-casescsv)
+ - [16. File Paths — AppFile()](#16-file-paths--appfile)
+ - [17. Audio Playback](#17-audio-playback)
+ - [18. Build & Run](#18-build--run)
+ - [19. Debugging Autoconnect Failures](#19-debugging-autoconnect-failures)
+ - [20. Windows Deployment Differences](#20-windows-deployment-differences)
+
---
-## 1. Prerequisites
+## Mono
+
+### 1. Prerequisites
- Windows 11 (or updated Windows 10) with WSL2 and **WSLg** enabled for GUI support
- Ubuntu 24.04 (noble) or similar WSL distro
@@ -26,7 +45,7 @@
---
-## 2. Install Mono
+### 2. Install Mono
```bash
sudo apt update
@@ -41,7 +60,7 @@
---
-## 3. Install GTK# (GTK# 3.0, for Ubuntu 24.04)
+### 3. Install GTK# (GTK# 3.0, for Ubuntu 24.04)
> Note: `gtk-sharp2` is **not available** on Ubuntu 24.04 (noble). Use `gtk-sharp3` instead.
@@ -59,7 +78,7 @@
gtk-sharp-3.0 Gtk - Gtk
---
-## 4. Install Glade (visual UI designer)
+### 4. Install Glade (visual UI designer)
```bash
sudo apt install glade
@@ -73,7 +92,7 @@
---
-## 5. Optional: libgdiplus (only if using System.Drawing)
+### 5. Optional: libgdiplus (only if using System.Drawing)
Only needed if your code uses `System.Drawing.Bitmap`, `Graphics`, etc. (not required for plain GTK#/Glade apps):
@@ -83,21 +102,21 @@
---
-## 6. Compiling & Running
+### 6. Compiling & Running
-### Plain console C# program
+#### Plain console C# program
```bash
mcs myprogram.cs
mono myprogram.exe
```
-### GTK# 3.0 program (no Glade)
+#### GTK# 3.0 program (no Glade)
```bash
mcs -pkg:gtk-sharp-3.0 myapp.cs
mono myapp.exe
```
-### GTK# 3.0 program using a Glade file
+#### GTK# 3.0 program using a Glade file
```bash
mcs -pkg:gtk-sharp-3.0 -pkg:glade-sharp-3.0 myapp.cs
mono myapp.exe
@@ -106,9 +125,9 @@
---
-## 7. Minimal Working Examples
+### 7. Minimal Working Examples
-### Hello World (console)
+#### Hello World (console)
```csharp
using System;
@@ -123,7 +142,7 @@
mono hello.exe
```
-### Hello World (GTK# window, no Glade)
+#### Hello World (GTK# window, no Glade)
```csharp
using System;
using Gtk;
@@ -149,7 +168,7 @@
mono gtkcheck.exe
```
-### Loading a UI built in Glade
+#### Loading a UI built in Glade
```csharp
using System;
using Gtk;
@@ -175,11 +194,11 @@
---
-## 8. Custom Output Names, Targets & Exporting DLLs
+### 8. Custom Output Names, Targets & Exporting DLLs
By default, `mcs file.cs` names the output after the source file (`file.exe`). You can control this with `-out:` and change what kind of binary is produced with `-target:`.
-### 8.1 Custom output name
+#### 8.1 Custom output name
```bash
mcs -pkg:gtk-sharp-3.0 Program.cs -out:MyCustomApp.exe
```
@@ -188,7 +207,7 @@
mono MyCustomApp.exe
```
-### 8.2 `-target` options
+#### 8.2 `-target` options
| Target | Produces | Notes |
|---|---|---|
| `exe` (default) | Console executable | Shows a console window when run on Windows |
@@ -202,7 +221,7 @@
```
This produces `programwin.exe`, which on Windows will run without popping up a console window alongside your GTK window.
-### 8.3 Exporting a DLL
+#### 8.3 Exporting a DLL
If you want to package reusable code (helper classes, business logic, etc.) as a library instead of a standalone app:
@@ -213,7 +232,7 @@
- No `Main()` method is required in a `library` target (though it's fine if one class in your project has one — it just won't be used as an entry point for the DLL itself).
- This creates `MyLibrary.dll`, a Mono/.NET assembly that other C# programs can reference.
-### 8.4 Using a DLL in another program
+#### 8.4 Using a DLL in another program
Suppose `MyLibrary.dll` contains:
```csharp
@@ -253,7 +272,7 @@
mono ConsumerApp.exe
```
-### 8.5 Combining `-target:library` with GTK# packages
+#### 8.5 Combining `-target:library` with GTK# packages
If your DLL itself uses GTK# types (e.g., a shared custom widget), include the package flag when building the library too:
```bash
mcs -target:library -pkg:gtk-sharp-3.0 MyGtkWidgets.cs -out:MyGtkWidgets.dll
@@ -263,7 +282,7 @@
mcs -pkg:gtk-sharp-3.0 ConsumerApp.cs -r:MyGtkWidgets.dll -out:ConsumerApp.exe
```
-### 8.6 Quick reference
+#### 8.6 Quick reference
```bash
# Console exe, custom name
mcs Program.cs -out:myapp.exe
@@ -278,7 +297,7 @@
mcs Consumer.cs -r:MyLibrary.dll -out:Consumer.exe
```
-### 8.7 Running the compiled .exe on Windows (outside WSL)
+#### 8.7 Running the compiled .exe on Windows (outside WSL)
Compiling in WSL produces a `.exe` that targets the .NET/Mono runtime — it is **not** a native Windows binary, and it will not run on Windows by itself. Two things are needed:
@@ -308,7 +327,7 @@
---
-## 9. Common Errors & Fixes
+### 9. Common Errors & Fixes
| Error | Cause | Fix |
|---|---|---|
@@ -322,7 +341,7 @@
---
-## 10. Notes on Alternatives
+### 10. Notes on Alternatives
GTK# is a legacy, lightly-maintained binding. For new projects, consider:
- **Avalonia UI** — modern, XAML-based, cross-platform, actively maintained
@@ -353,4 +372,534 @@
to run note:
same for all cases
- mono NAME_OF_THE_FILE.exe
\ No newline at end of file
+ mono NAME_OF_THE_FILE.exe
+
+## OS
+
+To test the application/setup across different Linux distributions, I used **Ventoy** to create a multiboot USB drive. Ventoy lets you copy multiple ISO files onto a single USB stick and choose which one to boot at startup, without needing to reformat or re-flash the drive for each OS.
+
+### Workflow
+1. Install Ventoy on the target USB drive.
+2. Copy the desired `.iso` files directly onto the Ventoy partition (no extraction needed).
+3. Boot from the USB, select the ISO from the Ventoy boot menu, and test the OS live or install it.
+
+### OS images checked
+- Fedora-Workstation-Live-44-1.7.x86_64
+- lubuntu-26.04-desktop-amd64
+- xubuntu-25.10-desktop-amd64
+
+### OS images to check
+- antiX-26_x64-full
+- xubuntu-26.04-minimal-amd64
+
+
+---
+
+# EARS Application
+
+Notes covering the GTK# port of the auscultation trainer: dynamic UI
+generation from CSV, the notebook page structure, and the failure modes
+that cost the most time.
+
+---
+
+## 11. Project Layout
+
+Source lives in `program/`, build output in `program/bin/linux/`.
+Runtime assets must sit **next to the .exe**, not next to the source.
+
+```
+program/
+├── Program.cs
+├── MainWindow.cs root window + splash page
+├── SettingWindow.cs settings page controller
+├── SoundWindow.cs sound page controller
+├── CaseDefinition.cs CSV row model + loader
+├── WavePlayer.cs cross-platform wav playback
+├── ArduinoConnection.cs
+├── Language.cs
+├── homepageallv3.glade
+├── cases.csv
+├── map/
+├── sound/
+└── bin/linux/ ← everything above (minus .cs) copied here
+ ├── program.exe
+ ├── homepageallv3.glade
+ ├── cases.csv
+ ├── map/
+ └── sound/
+```
+
+---
+
+## 12. Single-Window Notebook Architecture
+
+One `GtkWindow` (`Root`) holds one `GtkNotebook` (`RootNoteBook`) with
+tabs hidden. Each "screen" is a notebook page; navigation is just
+`RootNoteBook.CurrentPage = N`. No second window is ever created.
+
+| Page | Index | Root widget | Controller |
+|---|---|---|---|
+| Splash | 0 | `SplashGrid` | `MainWindow` |
+| Settings | 1 | `SettingGird` | `SettingsWindow` |
+| Sound | 2 | `SoundBox` | `SoundWindow` |
+
+`SettingsWindow` and `SoundWindow` are **not** `Gtk.Window` subclasses
+despite the names — they're plain controller classes that receive the
+shared `Builder` and bind their own widgets:
+
+```csharp
+public class SoundWindow
+{
+ [UI] private Label ConditionNameLabel = null;
+ [UI] private Grid SoundButtonGrid = null;
+ [UI] private Button SoundBackButton = null;
+
+ public event EventHandler BackRequested;
+
+ public SoundWindow(Builder builder)
+ {
+ builder.Autoconnect(this);
+ ...
+ }
+}
+```
+
+Wired up in `MainWindow`'s private constructor:
+
+```csharp
+_soundWindow = new SoundWindow(builder);
+_soundWindow.BackRequested += (s, e) => RootNoteBook.CurrentPage = PageSplash;
+Option1Button.Clicked += OnNormalSessionClicked;
+```
+
+Controllers never touch the notebook directly — they raise
+`BackRequested` and let `MainWindow` decide. Keeps navigation in one place.
+
+**All three controllers share one `Builder`.** Each `Autoconnect` call
+binds only the ids matching that class's `[UI]` fields, which is exactly
+why ids must be unique across the entire file (§13).
+
+---
+
+## 13. Glade Rules That Bite
+
+### IDs must be unique file-wide and valid C# identifiers
+
+`Autoconnect` maps glade ids to field names by string match across the
+**whole** builder, not per page. Two widgets sharing an id bind
+unpredictably.
+
+| Broken | Why | Fixed |
+|---|---|---|
+| `Condition Name` | Space — never matches a field name | `ConditionNameLabel` |
+| `BackButto` | Typo | `SoundBackButton` |
+| `BackButton` on two pages | Duplicate across pages | `SettingBackButton` + `SoundBackButton` |
+
+A mismatch **fails silently** — the field stays `null` and you get a
+`NullReferenceException` later, often several clicks away from the cause.
+See §19 for the guard that catches this at startup.
+
+Verify before running:
+
+```bash
+grep -o 'id="[^"]*"' homepageallv3.glade | sort | uniq -d
+```
+
+Any output is a duplicate id.
+
+### Placeholders are design-time only
+
+The hatched empty cells Glade shows in a `GtkGrid` save as
+`` and are **ignored at load time**. A button placed at
+`left-attach=2` in a designer grid with two empty columns to its left
+ends up at column 0 in the running app — this is the classic
+"button jumps to the left" bug.
+
+Never use placeholders for spacing or alignment. Use `halign` + `hexpand`.
+
+### Right-aligning a button
+
+Both properties are required:
+
+```xml
+end
+True
+```
+
+`hexpand` makes the cell consume the full row width; `halign=end` parks
+the button at the right edge of that cell. `halign` alone does nothing
+when the cell is only as wide as the button.
+
+In Glade: **Common** tab → *Horizontal Alignment* = `End`,
+*Expand → Horizontal* = checked.
+
+### Scrolling a grid needs a Viewport
+
+`GtkGrid` doesn't implement `GtkScrollable`. Dropping one into a
+`GtkScrolledWindow` requires an intermediate `GtkViewport` — Glade
+inserts it automatically. Don't delete it.
+
+```
+SoundScroller GtkScrolledWindow hexpand + vexpand, packing expand=True
+└─ GtkViewport (auto-added, required)
+ └─ SoundButtonGrid GtkGrid empty, column-homogeneous=True
+```
+
+`GtkFlowBox` *is* scrollable and wraps children automatically, but the
+`gtk-sharp3` binding on Ubuntu is 2.99.x and may not expose it. Check
+before relying on it:
+
+```bash
+monop -r:/usr/lib/cli/gtk-sharp-3.0/gtk-sharp.dll Gtk.FlowBox
+```
+
+### Expand appears in two tabs
+
+For a widget inside a `GtkBox`, **Common → Expand** sets the widget's own
+`hexpand`/`vexpand`, while **Packing → Expand** sets the box child
+property. They are different things and both usually need setting.
+
+---
+
+## 14. Generating Widgets From Code
+
+Leave the container **empty** in Glade and fill it at runtime. Three
+rules, all of which produce silent failures when broken:
+
+```csharp
+private void BuildButtons(IEnumerable labels, Action onPick)
+{
+ // 1. Remove AND destroy — Remove alone leaks the widget
+ foreach (var child in SoundButtonGrid.Children)
+ {
+ SoundButtonGrid.Remove(child);
+ child.Destroy();
+ }
+
+ int i = 0;
+ foreach (string text in labels)
+ {
+ // 2. Capture the loop variable — otherwise every handler
+ // sees the final value
+ string captured = text;
+
+ var btn = new Button(captured);
+ btn.Hexpand = true;
+ btn.Clicked += (s, e) => onPick(captured);
+ SoundButtonGrid.Attach(btn, i % Columns, i / Columns, 1, 1);
+ i++;
+ }
+
+ // 3. Widgets created in code start HIDDEN. Without this the grid
+ // stays blank with no error of any kind.
+ SoundButtonGrid.ShowAll();
+}
+```
+
+`ShowAll()` on the container is the single most common cause of
+"my buttons didn't appear" in GTK#.
+
+### Drill-down navigation
+
+All three modes (type → condition → play) use one grid and one render
+method. State is a `List` path; Back pops one level:
+
+```csharp
+private readonly List _path = new List();
+
+private void Render()
+{
+ var matches = _allCases.Where(MatchesPath).ToList();
+
+ var options = matches
+ .Where(c => c.TreePath.Length > _path.Count)
+ .Select(c => c.TreePath[_path.Count])
+ .Distinct()
+ .ToList();
+
+ ConditionNameLabel.Text = _path.Count == 0
+ ? "種別を選択"
+ : string.Join(" : ", _path);
+
+ BuildButtons(options, picked => { _path.Add(picked); /* leaf? play : Render(); */ });
+}
+
+private void OnBackClicked(object sender, EventArgs e)
+{
+ if (_path.Count > 0) { _path.RemoveAt(_path.Count - 1); Render(); }
+ else { WavePlayer.Stop(); BackRequested(this, EventArgs.Empty); }
+}
+```
+
+Tree depth varies per row (`Tree_Level3` is often empty), so
+`CaseDefinition.TreePath` returns only the non-empty levels and the
+drill-down adapts automatically.
+
+---
+
+## 15. Loading cases.csv
+
+`CaseDefinition.LoadCasesFromCsv(path)` returns `List`.
+Column → property mapping:
+
+| CSV column | Property |
+|---|---|
+| `Number` | `Number` |
+| `Type` | `Type` (心音 / 呼吸音) — also drives `IsHeart` |
+| `Category` | `CategoryJp` |
+| `Subcategory` | `SubcategoryJp` |
+| `Location` | `LocationJp` |
+| `Tree_Level1..3` | `TreeLevel1..3` |
+| `Image_File` | `MapFront` |
+| `Sound_File` | `SoundPath` |
+| `Image_Right` / `Image_Left` / `Image_Back` | `MapRight` / `MapLeft` / `MapBack` |
+
+Four things the loader must get right:
+
+**Encoding.** The file contains Japanese. Read with `Encoding.UTF8` and
+BOM detection — the default ANSI codepage produces mojibake that only
+shows up on the rendered buttons.
+
+**Delimiter.** The file is TAB separated. Auto-detect so a re-export
+from Excel as comma-separated doesn't break it:
+
+```csharp
+char sep = lines[0].Contains("\t") ? '\t' : ',';
+```
+
+**Header mapping.** Build `name → index` from row 0 rather than
+hardcoding positions, so adding or reordering columns is safe.
+
+**InvariantCulture on every numeric parse.** Same failure class as the
+CSS scaling bug in §"scaling" — under `ja_JP`/`de_DE` the
+culture-sensitive default silently misparses:
+
+```csharp
+int.TryParse(get(f, "Number"), NumberStyles.Integer,
+ CultureInfo.InvariantCulture, out number)
+```
+
+The loader prints its result on every run:
+
+```
+Loaded 98 cases from /path/to/bin/linux/cases.csv
+```
+
+`Loaded 0 cases` points at the path or the delimiter, not the UI.
+
+---
+
+## 16. File Paths — AppFile()
+
+**Never use bare relative paths.** `Path.GetFullPath("cases.csv")`
+resolves against the *working directory*, so the app works when launched
+from `program/` and silently loads nothing from anywhere else.
+
+```csharp
+public static string AppFile(string relative)
+{
+ string dir = Path.GetDirectoryName(
+ System.Reflection.Assembly.GetExecutingAssembly().Location);
+ return Path.Combine(dir, relative);
+}
+```
+
+Use it for **everything**: the glade file, the CSV, maps, sounds.
+
+```csharp
+builder.AddFromFile(SoundWindow.AppFile("homepageallv3.glade"));
+```
+
+Mixing the two conventions is how you end up editing
+`program/homepageallv3.glade` while the app reads
+`bin/linux/homepageallv3.glade` — every fix appears to do nothing.
+
+**Linux is case-sensitive.** `sound/snd200.wav` ≠ `sound/SND200.wav`,
+which was fine on Windows and isn't now. Audit the CSV against the disk:
+
+```bash
+cut -f10 cases.csv | tail -n +2 | while read f; do
+ [ -n "$f" ] && [ -f "$f" ] || echo "MISSING: $f"
+done
+```
+
+---
+
+## 17. Audio Playback
+
+XAudio2/SharpDX from the WinForms build does **not** load under Mono on
+Linux. `WavePlayer` shells out instead:
+
+| Platform | Mechanism |
+|---|---|
+| Linux / WSL | `paplay`, falling back to `aplay` |
+| Windows | `System.Media.SoundPlayer` |
+
+Install both helpers — WSLg routes through PulseAudio, so `paplay` is
+the one that works:
+
+```bash
+sudo apt install pulseaudio-utils alsa-utils
+```
+
+Verify outside the app before blaming the C#:
+
+```bash
+paplay bin/linux/sound/SND200.wav
+echo $PULSE_SERVER # empty under WSLg → wsl --shutdown and retry
+```
+
+**Format matters on Windows.** `SoundPlayer` handles PCM WAV only:
+
+```bash
+file sound/SND200.wav # want: RIFF ... WAVE audio, Microsoft PCM
+```
+
+**`Stop()` is a no-op on Windows** — `SoundPlayer.Play()` returns no
+handle. If stop-on-back is needed there, use `PlaySync()` on a
+background thread or add NAudio.
+
+---
+
+## 18. Build & Run
+
+Debug build (keeps the console so `Console.WriteLine` diagnostics show):
+
+```bash
+mcs -pkg:gtk-sharp-3.0 *.cs -out:./bin/linux/program.exe \
+ && cp homepageallv3.glade cases.csv ./bin/linux/ \
+ && cp -r map sound ./bin/linux/ \
+ && mono ./bin/linux/program.exe
+```
+
+The `cp` steps are not optional — stale assets in `bin/linux/` are a
+recurring source of phantom bugs (§16).
+
+Re-copying every wav on each build gets slow. Once stable, symlink and
+drop the `cp -r`:
+
+```bash
+ln -s ../../map bin/linux/map
+ln -s ../../sound bin/linux/sound
+```
+
+Release build (`-target:winexe` suppresses the console — don't use it
+while debugging):
+
+```bash
+mcs -target:winexe -pkg:gtk-sharp-3.0 *.cs -out:./bin/windows/program.exe
+```
+
+---
+
+## 19. Debugging Autoconnect Failures
+
+An unbound `[UI]` field is `null` with no warning. Add an explicit guard
+to every controller constructor so the failure names the widget at
+startup:
+
+```csharp
+builder.Autoconnect(this);
+
+if (ConditionNameLabel == null || SoundButtonGrid == null || SoundBackButton == null)
+ throw new InvalidOperationException(
+ "Glade id mismatch — ConditionNameLabel=" + (ConditionNameLabel != null) +
+ " SoundButtonGrid=" + (SoundButtonGrid != null) +
+ " SoundBackButton=" + (SoundBackButton != null));
+```
+
+Output looks like:
+
+```
+System.InvalidOperationException: Glade id mismatch —
+ ConditionNameLabel=False SoundButtonGrid=True SoundBackButton=True
+```
+
+For classes with many fields, loop a dictionary instead:
+
+```csharp
+foreach (var pair in new Dictionary {
+ { "ComPortLabel", ComPortLabel }, { "ConnectButton", ConnectButton },
+ { "SettingBackButton", SettingBackButton }, /* ... */ })
+ if (pair.Value == null)
+ throw new InvalidOperationException("Glade id not bound: " + pair.Key);
+```
+
+### Reading a GTK# stack trace
+
+Exceptions inside signal handlers arrive wrapped:
+
+```
+System.Reflection.TargetInvocationException ---> System.NullReferenceException
+ at SoundWindow.Render () [0x0007b]
+```
+
+Ignore the `GLib.SignalClosure` / `MarshalCallback` frames — they're
+plumbing. The first frame naming **your** class is the real site, and
+the `[0x...]` IL offset distinguishes lines within it.
+
+### Common failures
+
+| Symptom | Cause | Fix |
+|---|---|---|
+| NRE in controller ctor | `[UI]` field id mismatch | §19 guard, then fix the glade id |
+| NRE on first click, no CSV log line | Controller never constructed | Assign it in the **private** `MainWindow(Builder)` ctor |
+| Buttons don't appear, no error | Missing `ShowAll()` | Call it on the container after `Attach` |
+| Every button does the same thing | Closure over loop variable | `string captured = text;` |
+| `Loaded 0 cases` | Wrong path or delimiter | Use `AppFile()`; check tab vs comma |
+| Button sits left despite `halign=end` | Relying on grid placeholders | Add `hexpand=True` |
+| Fix appears to do nothing | Editing a different copy of the glade | Use `AppFile()` + `cp` on build |
+| Japanese renders as garbage | Wrong encoding | `File.ReadAllLines(path, Encoding.UTF8)` |
+| GTK warning about scrolling | Grid directly in ScrolledWindow | Keep the `GtkViewport` |
+
+---
+
+## 20. Windows Deployment Differences
+
+The C#, the glade file, and the CSV are **identical**. Four differences:
+
+1. **Audio** — see §17. PCM-only, and `Stop()` doesn't work.
+2. **Build target** — `-target:winexe` for no console window.
+3. **Runtime** — Mono for Windows must be installed on the target
+ machine; it bundles the GTK# runtime.
+4. **Serial ports** — `ArduinoConnection` enumerates `COM*` rather than
+ `/dev/ttyUSB*` / `/dev/ttyACM*`. Mono's Linux `SerialPort.GetPortNames()`
+ has historically missed devices; verify against `ls /dev/tty*`.
+
+Ship this folder:
+
+```
+program.exe
+homepageallv3.glade
+cases.csv
+map/
+sound/
+```
+
+Not problems, for the record: forward slashes in CSV paths work fine on
+Windows, and Windows' case-insensitivity means anything working on Linux
+also works there — never the reverse. Develop on Linux and Windows
+comes free.
+
+## 21. Legacy 7-region Mode
+
+A new `--legacy` flag enables a legacy mode that supports the older Python application's behavior:
+
+- **Flag**: Run with `--legacy` to enable the 7-region audio mode
+- **Data files**: Uses `cases_old.csv`, `map_old/`, and `sound_old/` directories
+- **CSV format**: 28-column format (no header) with positional columns for each region
+- **Audio behavior**: Mixes 7 regional sound sources simultaneously instead of single-map mode
+- **Controls**:
+ - Ctrl+R toggles the color overlay
+ - Audio changes in real-time as you move across the chest
+ - Meters show volume levels for each of the 7 regions
+
+The legacy mode preserves all existing functionality while adding the new multi-region audio capabilities.
+
+The following files are required for the legacy mode:
+- `cases_old.csv` (UTF-8, no header, 28 columns)
+- `map_old/` directory with MAP###.png files
+- `sound_old/` directory with SND###.wav files
+
+When running without `--legacy`, all existing behavior remains unchanged.
diff --git a/ReadmeQuick.md b/ReadmeQuick.md
index f227bb0..768dd98 100644
--- a/ReadmeQuick.md
+++ b/ReadmeQuick.md
@@ -14,4 +14,9 @@
# Program referencing that DLL
mcs Consumer.cs -r:MyLibrary.dll -out:Consumer.exe
+
+#run with edit
+GTK_DEBUG=interactive mono ./bin/linux/program.exe
+
```
+
diff --git a/program/AppMode.cs b/program/AppMode.cs
new file mode 100644
index 0000000..3c7178d
--- /dev/null
+++ b/program/AppMode.cs
@@ -0,0 +1,79 @@
+using System;
+using System.IO;
+
+public static class AppMode
+{
+ /// false = current single-map mode, true = legacy 7-region mode.
+ /// Set once in Program.Main from the --legacy argument, before any UI exists.
+ public static bool Legacy = false;
+
+ public static string CasesCsv
+ {
+ get { return SoundWindow.AppFile(Legacy ? "cases_old.csv" : "cases.csv"); }
+ }
+
+ // Legacy looks in its own folder first and falls back to the shared one,
+ // so files only need to exist once.
+ private static string MapDir { get { return Legacy ? "map_old" : "map"; } }
+ private static string SoundDir { get { return Legacy ? "sound_old" : "sound"; } }
+
+ /// CSV value -> absolute path. Returns null for "none"/empty.
+ public static string ResolveMap(string csvValue) { return Resolve(csvValue, MapDir, "map"); }
+ public static string ResolveSound(string csvValue) { return Resolve(csvValue, SoundDir, "sound"); }
+
+ private static string Resolve(string csvValue, string dir, string fallbackDir)
+ {
+ if (string.IsNullOrWhiteSpace(csvValue)) return null;
+ if (csvValue.Trim().Equals("none", StringComparison.OrdinalIgnoreCase)) return null;
+
+ string file = Path.GetFileName(csvValue.Trim().Replace('\\', '/')); // Python CSVs may use Windows paths
+ string path = SoundWindow.AppFile(Path.Combine(dir, file));
+
+ if (!File.Exists(path) && dir != fallbackDir) // shared asset fallback
+ {
+ string shared = SoundWindow.AppFile(Path.Combine(fallbackDir, file));
+ if (File.Exists(shared)) return shared;
+ }
+
+ // Linux is case-sensitive; the Python data came from Windows.
+ if (!File.Exists(path))
+ {
+ string ci = FindIgnoreCase(dir, file) ?? FindIgnoreCase(fallbackDir, file);
+ if (ci != null) return ci;
+ }
+
+ return path; // may not exist; callers log the missing file
+ }
+
+ /// Explanation image (C100.png … C999.png). The CSV only stores the file
+ /// name, so look in the likely folders, legacy-specific ones first.
+ public static string ResolveManual(string csvValue)
+ {
+ if (string.IsNullOrWhiteSpace(csvValue)) return null;
+ if (csvValue.Trim().Equals("none", StringComparison.OrdinalIgnoreCase)) return null;
+
+ string file = Path.GetFileName(csvValue.Trim().Replace('\\', '/'));
+ string[] dirs = Legacy
+ ? new[] { "manual_old", "explain_old", "map_old", "manual", "explain", "image", "map", "." }
+ : new[] { "manual", "explain", "image", "map", "map_old", "manual_old", "." };
+
+ foreach (string d in dirs)
+ {
+ string p = SoundWindow.AppFile(Path.Combine(d, file));
+ if (File.Exists(p)) return p;
+ string ci = FindIgnoreCase(d, file);
+ if (ci != null) return ci;
+ }
+ return null;
+ }
+
+ private static string FindIgnoreCase(string dir, string file)
+ {
+ string full = SoundWindow.AppFile(dir);
+ if (!Directory.Exists(full)) return null;
+ foreach (string f in Directory.GetFiles(full))
+ if (string.Equals(Path.GetFileName(f), file, StringComparison.OrdinalIgnoreCase))
+ return f;
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/program/Appconfig.cs b/program/Appconfig.cs
new file mode 100644
index 0000000..8eb2fec
--- /dev/null
+++ b/program/Appconfig.cs
@@ -0,0 +1,20 @@
+using System;
+using System.Linq;
+
+public static class AppConfig
+{
+ // // Computed once, cached forever — reading it anywhere costs nothing.
+ // public static readonly bool DebugMode =
+ // Environment.GetCommandLineArgs().Contains("--debug");
+
+ public static readonly bool DebugMode = Compute();
+
+ private static bool Compute()
+ {
+ var argv = Environment.GetCommandLineArgs();
+ Console.WriteLine("argv = [" + string.Join(" | ", argv) + "]");
+ return argv.Contains("--debug")
+ || Environment.GetEnvironmentVariable("EARS_DEBUG") == "1";
+ }
+
+}
\ No newline at end of file
diff --git a/program/ArduinoConnection.cs b/program/ArduinoConnection.cs
new file mode 100644
index 0000000..6edc385
--- /dev/null
+++ b/program/ArduinoConnection.cs
@@ -0,0 +1,373 @@
+using System;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+public class ArduinoConnection : IDisposable
+{
+ public const int BaudRate = 115200;
+
+ // Must match what your sketch replies to "REQUEST_ID" (Form2.cs: EXPECTED_DEVICE_ID)
+ // public const string ExpectedDeviceId = "EARS_READER";
+ public const string ExpectedDeviceId = "N_EARS_ESP32C3";
+
+ private const int HeartbeatTimeoutMs = 10000;
+ private const int HeartbeatCheckMs = 2000;
+ private const int MaxReconnectAttempts = 5;
+ private const int ResetSettleMs = 1500; // board reboots when DTR asserts
+
+ private readonly object _gate = new object();
+ private SerialPort _port;
+ private Thread _reader;
+ private volatile bool _reading;
+
+ private DateTime _lastData = DateTime.MinValue;
+ private uint _heartbeatId;
+ private bool _autoReconnect;
+ private int _reconnectAttempts;
+ private DateTime _nextReconnect = DateTime.MinValue;
+
+ /// Raised on the GTK main thread for every complete line from the device.
+ public event Action LineReceived;
+ /// Raised on the GTK main thread with human-readable status text.
+ public event Action Log;
+ /// Raised on the GTK main thread when the link goes up or down.
+ public event Action ConnectionChanged;
+
+ public string PortName { get; private set; }
+
+ public bool IsOpen
+ {
+ get { lock (_gate) return _port != null && _port.IsOpen; }
+ }
+
+ public static string[] ListPorts()
+ {
+ return SerialPort.GetPortNames()
+ .Distinct()
+ .OrderBy(p => p, StringComparer.Ordinal)
+ .ToArray();
+ }
+
+ // ---------- public API ----------
+
+ public bool Connect(string portName)
+ {
+ if (string.IsNullOrEmpty(portName))
+ {
+ Emit(Log, "No port selected");
+ return false;
+ }
+
+ ClosePort(silent: true);
+
+ if (!OpenPort(portName))
+ return false;
+
+ _autoReconnect = false;
+ _reconnectAttempts = 0;
+ StartHeartbeat();
+
+ Emit(Log, $"Connected to {portName} @ {BaudRate}");
+ Emit(ConnectionChanged, true);
+
+ // Give the board time to finish booting before the first command.
+ Task.Delay(ResetSettleMs).ContinueWith(_ => Send("MODE3"));
+ return true;
+ }
+
+ public void Disconnect()
+ {
+ _autoReconnect = false;
+ StopHeartbeat();
+ ClosePort(silent: false);
+ }
+
+ public void Send(string command)
+ {
+ try
+ {
+ lock (_gate)
+ {
+ if (_port == null || !_port.IsOpen)
+ {
+ Emit(Log, $"Cannot send '{command}' — not connected");
+ return;
+ }
+ _port.Write(command + "\n");
+ }
+ Emit(Log, $"Sent: {command}");
+ }
+ catch (Exception ex)
+ {
+ Emit(Log, $"Send failed: {ex.Message}");
+ }
+ }
+
+ ///
+ /// Probes every port for a device answering REQUEST_ID with the expected ID.
+ /// Returns the port name, or null. Runs off the UI thread; the caller
+ /// connects on the main thread so no GLib call happens from a worker.
+ ///
+ public Task DetectPortAsync()
+ {
+ return Task.Run(() =>
+ {
+ foreach (string p in ListPorts())
+ {
+ if (IsOpen && p == PortName) continue;
+
+ Emit(Log, $"Probing {p}...");
+ string id;
+ if (Probe(p, out id))
+ {
+ Emit(Log, $"Found {ExpectedDeviceId} on {p}");
+ return p;
+ }
+ if (id != null)
+ Emit(Log, $" {p}: reported '{id}' (not a match)");
+ }
+ return (string)null;
+ });
+ }
+
+ // ---------- port plumbing ----------
+
+ private bool OpenPort(string portName)
+ {
+ try
+ {
+ lock (_gate)
+ {
+ _port = new SerialPort(portName, BaudRate)
+ {
+ ReadTimeout = 500,
+ WriteTimeout = 1000,
+ NewLine = "\n",
+ DtrEnable = true,
+ RtsEnable = true,
+ };
+ _port.Open();
+ }
+
+ PortName = portName;
+ _lastData = DateTime.Now;
+ StartReader();
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Emit(Log, $"Open failed on {portName}: {ex.Message}");
+ lock (_gate)
+ {
+ _port?.Dispose();
+ _port = null;
+ }
+ return false;
+ }
+ }
+
+ private void ClosePort(bool silent)
+ {
+ _reading = false;
+
+ Thread t = _reader;
+ _reader = null;
+ if (t != null && t.IsAlive && t != Thread.CurrentThread)
+ t.Join(1000);
+
+ lock (_gate)
+ {
+ try { if (_port != null && _port.IsOpen) _port.Close(); }
+ catch (Exception ex) { Emit(Log, $"Close error: {ex.Message}"); }
+ _port?.Dispose();
+ _port = null;
+ }
+
+ if (!silent)
+ {
+ Emit(Log, "Disconnected");
+ Emit(ConnectionChanged, false);
+ }
+ }
+
+ private void StartReader()
+ {
+ _reading = true;
+ _reader = new Thread(ReaderLoop)
+ {
+ IsBackground = true,
+ Name = "arduino-reader"
+ };
+ _reader.Start();
+ }
+
+ private void ReaderLoop()
+ {
+ var pending = new StringBuilder();
+ var chunk = new byte[4096];
+
+ while (_reading)
+ {
+ SerialPort p;
+ lock (_gate) p = _port;
+
+ if (p == null || !p.IsOpen) { Thread.Sleep(100); continue; }
+
+ try
+ {
+ int n = p.Read(chunk, 0, chunk.Length);
+ if (n <= 0) continue;
+
+ _lastData = DateTime.Now;
+ pending.Append(Encoding.ASCII.GetString(chunk, 0, n));
+
+ string buffered = pending.ToString();
+ int nl;
+ while ((nl = buffered.IndexOf('\n')) >= 0)
+ {
+ string line = buffered.Substring(0, nl).Trim();
+ buffered = buffered.Substring(nl + 1);
+ if (line.Length > 0)
+ Emit(LineReceived, line);
+ }
+ pending.Clear();
+ pending.Append(buffered);
+ }
+ catch (TimeoutException) { /* normal when idle */ }
+ catch (Exception ex)
+ {
+ if (_reading) Emit(Log, $"Read error: {ex.Message}");
+ Thread.Sleep(200);
+ }
+ }
+ }
+
+ private bool Probe(string portName, out string deviceId)
+ {
+ deviceId = null;
+ SerialPort test = null;
+ try
+ {
+ test = new SerialPort(portName, BaudRate)
+ {
+ ReadTimeout = 500,
+ WriteTimeout = 1000,
+ NewLine = "\n",
+ DtrEnable = true,
+ RtsEnable = true,
+ };
+ test.Open();
+ Thread.Sleep(ResetSettleMs);
+ test.DiscardInBuffer();
+ test.Write("REQUEST_ID\n");
+
+ DateTime deadline = DateTime.Now.AddSeconds(3);
+ while (DateTime.Now < deadline)
+ {
+ try
+ {
+ string line = test.ReadLine().Trim();
+ if (line.StartsWith("DEVICE_ID:"))
+ {
+ deviceId = line.Substring("DEVICE_ID:".Length).Trim();
+ return deviceId == ExpectedDeviceId;
+ }
+ }
+ catch (TimeoutException) { }
+ }
+ }
+ catch (Exception ex)
+ {
+ Emit(Log, $" {portName}: {ex.Message}");
+ }
+ finally
+ {
+ try { test?.Close(); } catch { }
+ test?.Dispose();
+ }
+ return false;
+ }
+
+ // ---------- heartbeat / auto-reconnect (runs on the GTK main loop) ----------
+
+ private void StartHeartbeat()
+ {
+ StopHeartbeat();
+ _heartbeatId = GLib.Timeout.Add(HeartbeatCheckMs, OnHeartbeatTick);
+ }
+
+ private void StopHeartbeat()
+ {
+ if (_heartbeatId != 0)
+ {
+ GLib.Source.Remove(_heartbeatId);
+ _heartbeatId = 0;
+ }
+ }
+
+ private bool OnHeartbeatTick()
+ {
+ if (_autoReconnect && !IsOpen)
+ {
+ if (_reconnectAttempts >= MaxReconnectAttempts)
+ {
+ _autoReconnect = false;
+ Log?.Invoke($"Reconnection failed after {MaxReconnectAttempts} attempts. Check USB cable, port and power, then reconnect manually.");
+ StopHeartbeat();
+ return false;
+ }
+
+ if (DateTime.Now >= _nextReconnect)
+ {
+ _reconnectAttempts++;
+ Log?.Invoke($"Reconnect attempt {_reconnectAttempts}/{MaxReconnectAttempts} on {PortName}...");
+
+ if (OpenPort(PortName))
+ {
+ _autoReconnect = false;
+ _reconnectAttempts = 0;
+ Log?.Invoke("Reconnected");
+ ConnectionChanged?.Invoke(true);
+ Task.Delay(ResetSettleMs).ContinueWith(_ => Send("MODE3"));
+ }
+ else
+ {
+ _nextReconnect = DateTime.Now.AddSeconds(2);
+ }
+ }
+ return true;
+ }
+
+ if (!IsOpen) return true;
+
+ if ((DateTime.Now - _lastData).TotalMilliseconds >= HeartbeatTimeoutMs)
+ {
+ Log?.Invoke("Heartbeat timeout — no device activity");
+ ClosePort(silent: true);
+ ConnectionChanged?.Invoke(false);
+ _autoReconnect = true;
+ _reconnectAttempts = 0;
+ _nextReconnect = DateTime.Now.AddSeconds(2);
+ }
+ return true;
+ }
+
+ // ---------- helpers ----------
+
+ private static void Emit(Action handler, T arg)
+ {
+ Action h = handler;
+ if (h == null) return;
+ Gtk.Application.Invoke((s, e) => h(arg));
+ }
+
+ public void Dispose()
+ {
+ _autoReconnect = false;
+ StopHeartbeat();
+ ClosePort(silent: true);
+ }
+}
\ No newline at end of file
diff --git a/program/AudioEngine.cs b/program/AudioEngine.cs
new file mode 100644
index 0000000..b5ba11c
--- /dev/null
+++ b/program/AudioEngine.cs
@@ -0,0 +1,273 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using OpenTK.Audio;
+using OpenTK.Audio.OpenAL;
+using System.Runtime.InteropServices;
+
+
+public class AudioEngine : IDisposable
+{
+ public class Voice
+ {
+ public string Path;
+ public int Buffer;
+ public int Source;
+ public float Gain;
+ }
+
+ private class SharedBuffer
+ {
+ public int Id;
+ public int Refs;
+ }
+
+ private AudioContext _context;
+ private readonly Dictionary _voices =
+ new Dictionary(StringComparer.OrdinalIgnoreCase);
+ // One AL buffer per WAV file, shared by every voice that plays it
+ // (legacy cases often use the same file for several regions).
+ private readonly Dictionary _buffers =
+ new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly object _lock = new object();
+
+ public event Action Log;
+
+ public bool Init()
+ {
+ try
+ {
+ _context = new AudioContext(); // opens default device + context
+ _context.MakeCurrent();
+ AudioOutput.RegisterCurrentDevice();
+ Emit("OpenAL ready: " + AudioContext.CurrentContext.CurrentDevice);
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Emit("OpenAL init failed: " + ex.Message);
+ return false;
+ }
+ }
+
+ /// Load + start looping at gain 0. Idempotent per key.
+ public Voice Warm(string wavPath) { return Warm(wavPath, wavPath); }
+
+ public Voice Warm(string wavPath, string key)
+ {
+ wavPath = AudioOutput.SoundFor(wavPath); // ← add: speaker copy in legacy speaker mode
+ if (string.IsNullOrEmpty(wavPath) || !File.Exists(wavPath))
+ {
+ Emit("Sound file not found: " + wavPath);
+ return null;
+ }
+
+ lock (_lock)
+ {
+ Voice v;
+ if (_voices.TryGetValue(key, out v)) return v;
+
+ int buf = 0;
+ try
+ {
+ buf = AcquireBuffer(wavPath);
+
+ int src = AL.GenSource();
+ AL.Source(src, ALSourcei.Buffer, buf);
+ AL.Source(src, ALSourceb.Looping, true);
+ AL.Source(src, ALSourcef.Gain, 0.0f);
+ AL.SourcePlay(src);
+
+ CheckError("Warm " + Path.GetFileName(wavPath));
+
+ v = new Voice { Path = wavPath, Buffer = buf, Source = src, Gain = 0f };
+ _voices[key] = v;
+ Emit("Warmed " + Path.GetFileName(wavPath) + " [" + key + "] voices=" + _voices.Count);
+ return v;
+ }
+ catch (Exception ex)
+ {
+ if (buf != 0) ReleaseBuffer(wavPath);
+ Emit("Load failed " + wavPath + ": " + ex.Message);
+ return null;
+ }
+ }
+ }
+
+ private int AcquireBuffer(string wavPath)
+ {
+ SharedBuffer sb;
+ if (_buffers.TryGetValue(wavPath, out sb)) { sb.Refs++; return sb.Id; }
+
+ WavFile w = WavFile.Load(wavPath);
+ int buf = AL.GenBuffer();
+ AL.BufferData(buf, w.Format, w.Data, w.Data.Length, w.SampleRate);
+ CheckError("BufferData " + Path.GetFileName(wavPath));
+
+ _buffers[wavPath] = new SharedBuffer { Id = buf, Refs = 1 };
+ return buf;
+ }
+
+ private void ReleaseBuffer(string wavPath)
+ {
+ SharedBuffer sb;
+ if (!_buffers.TryGetValue(wavPath, out sb)) return;
+ if (--sb.Refs > 0) return;
+ AL.DeleteBuffer(sb.Id);
+ _buffers.Remove(wavPath);
+ }
+
+ /// Stops and frees every voice whose key starts with prefix.
+ /// Legacy uses "R" so each case's 7 region voices don't pile up
+ /// (every source keeps looping and being mixed, even at gain 0).
+ public void ReleaseWhereKeyStarts(string prefix)
+ {
+ lock (_lock)
+ {
+ var dead = new List();
+ foreach (var kv in _voices)
+ if (kv.Key.StartsWith(prefix, StringComparison.Ordinal)) dead.Add(kv.Key);
+
+ foreach (string k in dead)
+ {
+ Voice v = _voices[k];
+ AL.SourceStop(v.Source);
+ AL.Source(v.Source, ALSourcei.Buffer, 0); // detach before the buffer can be deleted
+ AL.DeleteSource(v.Source);
+ ReleaseBuffer(v.Path);
+ _voices.Remove(k);
+ if (v == _main) _main = null;
+ }
+
+ if (dead.Count > 0)
+ Emit("Released " + dead.Count + " voice(s) '" + prefix + "*' voices=" + _voices.Count);
+ }
+ }
+
+ /// Rewinds the given voices and starts them in ONE OpenAL call, so they
+ /// share sample position 0. Gains are left as they are (normally 0).
+ public void RestartTogether(IList voices)
+ {
+ if (voices == null || voices.Count == 0) return;
+
+ var ids = new List();
+ foreach (var v in voices) if (v != null) ids.Add(v.Source);
+ if (ids.Count == 0) return;
+
+ int[] arr = ids.ToArray();
+ lock (_lock)
+ {
+ AL.SourceRewind(arr.Length, arr);
+ AL.SourcePlay(arr.Length, arr);
+ CheckError("RestartTogether");
+ }
+ }
+
+ /// Replaces SourceVoice.SetVolume. Linear 0..1.
+ public void SetGain(Voice v, float gain)
+ {
+ if (v == null) return;
+ if (gain < 0f) gain = 0f;
+ if (gain > 1f) gain = 1f;
+ if (Math.Abs(gain - v.Gain) < 0.001f) return; // skip redundant AL calls
+
+ lock (_lock)
+ {
+ v.Gain = gain;
+ AL.Source(v.Source, ALSourcef.Gain, gain);
+
+ if (gain > 0f && AL.GetSourceState(v.Source) != ALSourceState.Playing)
+ AL.SourcePlay(v.Source);
+ }
+ }
+
+ /// Form2's PlayColorFromStart — restart with no leading gap.
+ public void PlayFromStart(Voice v, float gain)
+ {
+ if (v == null) return;
+ lock (_lock)
+ {
+ AL.SourceRewind(v.Source);
+ v.Gain = gain;
+ AL.Source(v.Source, ALSourcef.Gain, gain);
+ AL.SourcePlay(v.Source);
+ }
+ }
+
+ public void MuteAll()
+ {
+ lock (_lock)
+ foreach (var v in _voices.Values)
+ {
+ v.Gain = 0f;
+ AL.Source(v.Source, ALSourcef.Gain, 0f);
+ }
+ }
+
+ public void StopAll()
+ {
+ lock (_lock)
+ foreach (var v in _voices.Values)
+ {
+ AL.SourceStop(v.Source);
+ v.Gain = 0f;
+ }
+ }
+
+ /// Form2's Volume_Control_XAudio2, unchanged — keeps Linux loudness
+ /// matched to the Windows build.
+ public static float VolumeCurve(int range)
+ {
+ const double CURVE = 9.5;
+ double y = Math.Pow(range / 255.0, 1.0 / CURVE);
+ int db = (int)(10000.0 * y - 10000);
+ if (db > 0) db = 0;
+ if (db < -10000) db = -10000;
+ float lin = (float)Math.Pow(10.0, db / 2000.0);
+ return Math.Max(0f, Math.Min(1f, lin));
+ }
+
+ // ── shims so MapWindow's existing calls still compile ──
+
+ private Voice _main;
+
+ public void Start(string wavPath)
+ {
+ _main = Warm(wavPath);
+ SetGain(_main, 0f);
+ }
+
+ public void Stop() { MuteAll(); }
+
+ public Voice MainVoice { get { return _main; } }
+
+ public void Dispose()
+ {
+ lock (_lock)
+ {
+ foreach (var v in _voices.Values)
+ {
+ AL.SourceStop(v.Source);
+ AL.Source(v.Source, ALSourcei.Buffer, 0);
+ AL.DeleteSource(v.Source);
+ }
+ _voices.Clear();
+
+ foreach (var b in _buffers.Values) AL.DeleteBuffer(b.Id);
+ _buffers.Clear();
+ }
+ if (_context != null) { _context.Dispose(); _context = null; }
+ }
+
+ private void CheckError(string where)
+ {
+ ALError e = AL.GetError();
+ if (e != ALError.NoError) Emit(where + ": " + AL.GetErrorString(e));
+ }
+
+ private void Emit(string m)
+ {
+ var h = Log;
+ if (h != null) h(m); else Console.WriteLine("[audio] " + m);
+ }
+}
\ No newline at end of file
diff --git a/program/AudioOutput.cs b/program/AudioOutput.cs
new file mode 100644
index 0000000..ae93708
--- /dev/null
+++ b/program/AudioOutput.cs
@@ -0,0 +1,524 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Threading;
+
+/// Speaker <-> headphone-jack switching through the sound server
+/// (PipeWire's pulse layer, or PulseAudio), using the `pactl` command.
+///
+/// On the T101HA tablet (sof-bytcht rt5645) the speaker and the 3.5mm jack
+/// are NOT two ports of one output. The sound card has separate PROFILES:
+/// HiFi (Headphones, Mic) -> sink ...HiFi__Headphones__sink
+/// HiFi (Mic, Speaker) -> sink ...HiFi__Speaker__sink
+/// Only one exists at a time, so switching = `pactl set-card-profile`.
+/// After the switch the new sink is made the default and every playing
+/// stream (the OpenAL one included) is moved onto it, so it never falls
+/// back to the HDMI output.
+///
+/// Public API is unchanged from the previous version:
+/// AudioOutput.Current(), AudioOutput.Toggle(out problem), AudioOutput.Log
+public static class AudioOutput
+{
+ public enum Kind { Unknown, Speaker, Jack }
+
+ private class Profile
+ {
+ public string Name;
+ public bool Available;
+ public int Priority;
+ public int Sinks;
+ public Kind Kind;
+ }
+
+ private class Card
+ {
+ public string Name;
+ public string ActiveProfile;
+ public List Profiles = new List();
+ }
+
+ public static event Action Log;
+
+ /// Output volume set after switching (both outputs at full level).
+ public const string SpeakerVolume = "100%";
+ public const string JackVolume = "100%";
+
+ /// Extra loudness for LEGACY mode on the tablet SPEAKER only.
+ /// 1.0 = no boost, 2.0 = about +6 dB, 3.0 = about +9.5 dB, 4.0 = +12 dB.
+ /// Earphones, normal mode and the PC always stay at 1.0.
+ /// Raise it if legacy is still too quiet on the speaker; lower it if
+ /// loud spots sound distorted.
+ public const float LegacySpeakerBoost = 1.5f;
+
+ /// True in legacy mode while the TABLET speaker is in use. Then sounds are
+ /// loaded from the speaker-optimised copies (made by make_speaker_sounds.sh).
+ public static bool UseSpeakerSounds { get; private set; }
+
+ /// Raised after the output changed (button or startup), on the caller's
+ /// thread. Legacy mode reloads its region sounds when this fires.
+ public static event Action OutputChanged;
+
+ /// The file to actually load for a sound:
+ /// legacy + tablet speaker -> /speaker/.wav, if it exists
+ /// anything else -> the original path, unchanged
+ public static string SoundFor(string wavPath)
+ {
+ if (!UseSpeakerSounds || string.IsNullOrEmpty(wavPath)) return wavPath;
+ try
+ {
+ string dir = System.IO.Path.GetDirectoryName(wavPath);
+ string name = System.IO.Path.GetFileName(wavPath);
+ if (dir != null && System.IO.Path.GetFileName(dir) == "speaker") return wavPath;
+ string alt = System.IO.Path.Combine(dir ?? "", "speaker", name);
+ return System.IO.File.Exists(alt) ? alt : wavPath;
+ }
+ catch { return wavPath; }
+ }
+
+ /// Records whether legacy speaker mode is on, and sets the boost to match.
+ private static void SetSpeakerMode(bool onTabletSpeaker)
+ {
+ bool use = onTabletSpeaker && AppMode.Legacy;
+ if (use != UseSpeakerSounds)
+ Emit("speaker-optimised sounds: " + (use ? "ON" : "off"));
+ UseSpeakerSounds = use;
+ ApplyBoost(onTabletSpeaker);
+ }
+
+ /// What is playing sound right now.
+ public static Kind Current()
+ {
+ Card c = FindCard();
+ if (c != null) return Classify(c.ActiveProfile);
+
+ // No speaker/headphone card found: guess from the default sink's name.
+ int code;
+ string info = Run("info", out code);
+ if (code != 0 || info == null) return Kind.Unknown;
+ foreach (string line in info.Split('\n'))
+ if (line.StartsWith("Default Sink:"))
+ return Classify(line.Substring("Default Sink:".Length));
+ return Kind.Unknown;
+ }
+
+ /// Switches to the other output. Returns the output now in use, and a
+ /// short reason when it could not switch.
+ public static Kind Toggle(out string problem)
+ {
+ problem = null;
+
+ int code;
+ Run("info", out code);
+ if (code != 0) { problem = "pactl not available"; return Kind.Unknown; }
+
+ Card card = FindCard();
+ if (card == null)
+ {
+ problem = "no-jack";
+ Emit("no sound card with both speaker and headphone profiles");
+ return Current();
+ }
+
+ Kind want = Classify(card.ActiveProfile) == Kind.Jack ? Kind.Speaker : Kind.Jack;
+ return SwitchTo(card, want, true, out problem);
+ }
+
+ /// Call once at program start, BEFORE the audio engine is created.
+ /// Uses the earphones when something is plugged in, otherwise the
+ /// speaker, so OpenAL opens on the right output from the beginning.
+ public static Kind SelectAtStartup()
+ {
+ int code;
+ Run("info", out code);
+ if (code != 0) return Kind.Unknown;
+
+ Card card = FindCard();
+ if (card == null) return Current();
+
+ string problem;
+ Kind got = SwitchTo(card, Kind.Jack, false, out problem);
+ if (got != Kind.Jack)
+ {
+ Emit("startup: earphones not available, using the speaker");
+ card = FindCard();
+ if (card != null) got = SwitchTo(card, Kind.Speaker, false, out problem);
+ }
+ UseSpeakerSounds = got == Kind.Speaker && AppMode.Legacy;
+ Emit("startup output: " + got + (UseSpeakerSounds ? " (speaker-optimised sounds)" : ""));
+ return got;
+ }
+
+ /// Activates the profile of the wanted kind and makes its output the
+ /// default (unmuted, full volume). reopen = also reconnect a running OpenAL.
+ private static Kind SwitchTo(Card card, Kind want, bool reopen, out string problem)
+ {
+ problem = null;
+ int code;
+ Kind now = Classify(card.ActiveProfile);
+
+ if (now != want)
+ {
+ // Best available profile of the wanted kind (highest priority).
+ Profile target = null;
+ foreach (var p in card.Profiles)
+ {
+ if (p.Kind != want || p.Sinks < 1 || !p.Available) continue;
+ if (target == null || p.Priority > target.Priority) target = p;
+ }
+
+ if (target == null)
+ {
+ if (want == Kind.Jack)
+ {
+ problem = "jack-empty";
+ Emit("no headphone profile available - is anything plugged in?");
+ }
+ else
+ {
+ problem = "no-speaker";
+ Emit("no speaker profile available");
+ }
+ return now;
+ }
+
+ Run("set-card-profile " + Quote(card.Name) + " " + Quote(target.Name), out code);
+ if (code != 0)
+ {
+ problem = want == Kind.Jack ? "no-jack" : "no-speaker";
+ Emit("set-card-profile failed (exit " + code + ")");
+ return now;
+ }
+ Emit("profile " + card.ActiveProfile + " -> " + target.Name);
+ }
+
+ // The new sink takes a moment to appear. Make it the default and move
+ // playing streams onto it, otherwise they may land on HDMI.
+ string sink = WaitForSink(card.Name, want);
+ if (sink != null)
+ {
+ Run("set-default-sink " + Quote(sink), out code);
+ Run("set-sink-mute " + Quote(sink) + " 0", out code); // new sink may start muted
+ string vol = want == Kind.Speaker ? SpeakerVolume : JackVolume;
+ Run("set-sink-volume " + Quote(sink) + " " + vol, out code);
+ MoveAllStreams(sink);
+ Emit("default sink -> " + sink + " (unmuted, volume " + vol + ")");
+
+ // OpenAL is still attached to the output that was just deleted:
+ // reconnect it to the new default, keeping all loaded sounds.
+ if (reopen) ReopenOpenAL();
+ SetSpeakerMode(want == Kind.Speaker);
+ var changed = OutputChanged;
+ if (changed != null) changed();
+ }
+ else
+ {
+ Emit("profile switched but its output did not appear");
+ }
+
+ return Current();
+ }
+
+ // ── pactl parsing ──────────────────────────────────────────────────
+
+ /// The built-in card: the one that has both a speaker and a headphone profile.
+ private static Card FindCard()
+ {
+ int code;
+ string list = Run("list cards", out code);
+ if (code != 0 || list == null) return null;
+
+ var cards = new List();
+ Card cur = null;
+ bool inProfiles = false;
+
+ foreach (string raw in list.Split('\n'))
+ {
+ string line = raw.TrimEnd();
+ string t = line.Trim();
+
+ if (line.StartsWith("Card #")) { cur = new Card(); cards.Add(cur); inProfiles = false; continue; }
+ if (cur == null) continue;
+
+ // top-level card fields are indented one tab
+ bool oneTab = line.StartsWith("\t") && !line.StartsWith("\t\t");
+
+ if (oneTab)
+ {
+ inProfiles = false;
+ if (t.StartsWith("Name:")) cur.Name = t.Substring(5).Trim();
+ else if (t.StartsWith("Active Profile:")) cur.ActiveProfile = t.Substring(15).Trim();
+ else if (t == "Profiles:") inProfiles = true;
+ continue;
+ }
+
+ // profile lines: "\t\tNAME: Description (sinks: 1, sources: 1, priority: 8300, available: yes)"
+ if (inProfiles && line.StartsWith("\t\t") && !line.StartsWith("\t\t\t"))
+ {
+ int sep = t.IndexOf(": ");
+ if (sep <= 0) continue;
+ string rest = t.Substring(sep + 2);
+ var p = new Profile
+ {
+ Name = t.Substring(0, sep).Trim(),
+ Sinks = IntAfter(rest, "sinks:"),
+ Priority = IntAfter(rest, "priority:"),
+ Available = !rest.Contains("available: no")
+ };
+ p.Kind = Classify(p.Name);
+ cur.Profiles.Add(p);
+ }
+ }
+
+ foreach (var c in cards)
+ {
+ if (c.Name == null) continue;
+ bool hasSpeaker = c.Profiles.Exists(p => p.Kind == Kind.Speaker);
+ bool hasJack = c.Profiles.Exists(p => p.Kind == Kind.Jack);
+ if (hasSpeaker && hasJack) return c;
+ }
+ return null;
+ }
+
+ private static Kind Classify(string text)
+ {
+ if (text == null) return Kind.Unknown;
+ string s = text.ToLowerInvariant();
+ if (s.Contains("hdmi")) return Kind.Unknown; // never treat HDMI as the speaker
+ if (s.Contains("headphone") || s.Contains("lineout") ||
+ s.Contains("line-out") || s.Contains("line out"))
+ return Kind.Jack;
+ if (s.Contains("speaker")) return Kind.Speaker;
+ return Kind.Unknown;
+ }
+
+ /// Waits up to ~2 s for the card's sink of the given kind to appear.
+ private static string WaitForSink(string cardName, Kind want)
+ {
+ string key = cardName.StartsWith("alsa_card.") ? cardName.Substring(10) : cardName;
+
+ for (int i = 0; i < 20; i++)
+ {
+ int code;
+ string list = Run("list short sinks", out code);
+ if (code == 0 && list != null)
+ {
+ foreach (string line in list.Split('\n'))
+ {
+ string[] cols = line.Split('\t');
+ if (cols.Length < 2) continue;
+ string name = cols[1].Trim();
+ if (name.Contains(key) && Classify(name) == want) return name;
+ }
+ }
+ Thread.Sleep(100);
+ }
+ return null;
+ }
+
+ private static int IntAfter(string s, string key)
+ {
+ int i = s.IndexOf(key);
+ if (i < 0) return 0;
+ i += key.Length;
+ while (i < s.Length && s[i] == ' ') i++;
+ int start = i;
+ while (i < s.Length && char.IsDigit(s[i])) i++;
+ int v;
+ return int.TryParse(s.Substring(start, i - start), out v) ? v : 0;
+ }
+
+ private static void MoveAllStreams(string sink)
+ {
+ int code;
+ string list = Run("list short sink-inputs", out code);
+ if (code != 0 || list == null) return;
+ int moved = 0;
+ foreach (string line in list.Split('\n'))
+ {
+ string id = line.Split('\t')[0].Trim();
+ if (id.Length == 0) continue;
+ Run("move-sink-input " + id + " " + Quote(sink), out code);
+ if (code == 0) moved++;
+ }
+ Emit("moved " + moved + " playing stream(s)");
+ }
+
+ // When PulseAudio is unreachable, pactl itself waits ~30 s before giving up,
+ // and the UI thread waits with it. After one timeout, skip pactl for a while.
+ private const int PactlTimeoutMs = 3000;
+ private static DateTime _pactlDownUntil = DateTime.MinValue;
+
+ private static string Run(string args, out int exitCode)
+ {
+ exitCode = -1;
+ if (DateTime.UtcNow < _pactlDownUntil) return null; // recently timed out: fail fast
+ try
+ {
+ var psi = new ProcessStartInfo("pactl", args)
+ {
+ UseShellExecute = false,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ psi.EnvironmentVariables["LC_ALL"] = "C"; // English output, whatever the system locale
+ psi.EnvironmentVariables["LANG"] = "C";
+
+ using (var p = Process.Start(psi))
+ {
+ // Read in the background: a blocking ReadToEnd() here would wait
+ // for pactl to exit on its own, so the timeout below never fired.
+ var outTask = p.StandardOutput.ReadToEndAsync();
+ var errTask = p.StandardError.ReadToEndAsync();
+
+ if (!p.WaitForExit(PactlTimeoutMs))
+ {
+ try { p.Kill(); } catch { }
+ _pactlDownUntil = DateTime.UtcNow.AddSeconds(30);
+ Emit("pactl " + args + ": no answer in " + PactlTimeoutMs + " ms — skipping pactl for 30 s");
+ return null;
+ }
+ p.WaitForExit(); // flush the redirected streams
+ string output = outTask.Result;
+ string err = errTask.Result;
+ exitCode = p.ExitCode;
+ if (exitCode != 0 && err.Length > 0) Emit("pactl " + args + ": " + err.Trim());
+ return output;
+ }
+ }
+ catch (Exception ex)
+ {
+ Emit("pactl not runnable: " + ex.Message);
+ return null;
+ }
+ }
+
+ // ── reconnect OpenAL after the switch ──────────────────────────────
+ //
+ // Switching profile deletes the old output; OpenAL stays attached to it
+ // and goes silent. ALC_SOFT_reopen_device (OpenAL Soft 1.22+) moves the
+ // open device onto the current default output, keeping every loaded
+ // sound and its playback. Linux only; this file is only used on Linux
+ // anyway, and the platform check keeps it harmless elsewhere.
+
+ private const string OpenALLib = "libopenal.so.1";
+
+ [DllImport(OpenALLib)] private static extern IntPtr alcGetCurrentContext();
+ [DllImport(OpenALLib)] private static extern IntPtr alcGetContextsDevice(IntPtr context);
+ [DllImport(OpenALLib)] private static extern byte alcIsExtensionPresent(IntPtr device, string name);
+ [DllImport(OpenALLib)] private static extern IntPtr alcGetProcAddress(IntPtr device, string name);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ private delegate byte ReopenDeviceFn(IntPtr device, IntPtr deviceName, IntPtr attribs);
+
+ // Every OpenAL device/context the app opened. The app can have more than
+ // one (the log showed two); each must be reconnected and boosted.
+ private static readonly List _devices = new List();
+ private static readonly List _contexts = new List();
+
+ /// Call right after an OpenAL context is created and made current
+ /// (in AudioEngine.Init, after _context.MakeCurrent()).
+ public static void RegisterCurrentDevice()
+ {
+ if (Environment.OSVersion.Platform != PlatformID.Unix) return;
+ try
+ {
+ IntPtr ctx = alcGetCurrentContext();
+ if (ctx == IntPtr.Zero) return;
+ IntPtr dev = alcGetContextsDevice(ctx);
+ if (dev == IntPtr.Zero) return;
+ lock (_devices)
+ {
+ if (!_devices.Contains(dev)) _devices.Add(dev);
+ if (!_contexts.Contains(ctx)) _contexts.Add(ctx);
+ }
+ Emit("registered OpenAL device #" + _devices.Count);
+
+ // start-up: boost straight away if we are already on the speaker
+ Card card = FindCard();
+ SetSpeakerMode(card != null && Classify(card.ActiveProfile) == Kind.Speaker);
+ }
+ catch (Exception ex) { Emit("register failed: " + ex.Message); }
+ }
+
+ private const int AL_GAIN = 0x100A;
+ [DllImport(OpenALLib)] private static extern byte alcMakeContextCurrent(IntPtr context);
+ [DllImport(OpenALLib)] private static extern void alListenerf(int param, float value);
+
+ /// Sets the overall (listener) gain of every registered OpenAL context.
+ /// Boost only for legacy mode on the tablet speaker; 1.0 otherwise.
+ /// OpenAL Soft's output limiter keeps the boosted peaks from clipping harshly.
+ private static void ApplyBoost(bool onTabletSpeaker)
+ {
+ if (Environment.OSVersion.Platform != PlatformID.Unix) return;
+ float gain = (onTabletSpeaker && AppMode.Legacy) ? LegacySpeakerBoost : 1.0f;
+ try
+ {
+ var list = new List();
+ lock (_devices) list.AddRange(_contexts);
+ if (list.Count == 0) return;
+
+ IntPtr prev = alcGetCurrentContext();
+ foreach (IntPtr ctx in list)
+ {
+ alcMakeContextCurrent(ctx);
+ alListenerf(AL_GAIN, gain);
+ }
+ alcMakeContextCurrent(prev); // put the app's context back
+ Emit("volume boost: x" + gain + (gain > 1f ? " (legacy, speaker)" : ""));
+ }
+ catch (Exception ex) { Emit("boost failed: " + ex.Message); }
+ }
+
+ private static bool ReopenOpenAL()
+ {
+ if (Environment.OSVersion.Platform != PlatformID.Unix) return false;
+ try
+ {
+ // registered devices, plus the current one in case nothing registered
+ var list = new List();
+ lock (_devices) list.AddRange(_devices);
+ IntPtr ctx = alcGetCurrentContext();
+ if (ctx != IntPtr.Zero)
+ {
+ IntPtr cur = alcGetContextsDevice(ctx);
+ if (cur != IntPtr.Zero && !list.Contains(cur)) list.Add(cur);
+ }
+ if (list.Count == 0) { Emit("reopen: no OpenAL device"); return false; }
+
+ bool all = true;
+ for (int i = 0; i < list.Count; i++)
+ {
+ IntPtr dev = list[i];
+ if (alcIsExtensionPresent(dev, "ALC_SOFT_reopen_device") == 0)
+ {
+ Emit("reopen: OpenAL Soft is too old (needs 1.22+)");
+ return false;
+ }
+ IntPtr fp = alcGetProcAddress(dev, "alcReopenDeviceSOFT");
+ if (fp == IntPtr.Zero) { Emit("reopen: function not found"); return false; }
+
+ var reopen = (ReopenDeviceFn)Marshal.GetDelegateForFunctionPointer(fp, typeof(ReopenDeviceFn));
+ bool ok = reopen(dev, IntPtr.Zero, IntPtr.Zero) != 0; // null name = default output
+ Emit("reopen OpenAL device " + (i + 1) + "/" + list.Count + ": " + (ok ? "ok" : "FAILED"));
+ all &= ok;
+ }
+ return all;
+ }
+ catch (Exception ex)
+ {
+ Emit("reopen failed: " + ex.Message);
+ return false;
+ }
+ }
+
+ private static string Quote(string s) { return "\"" + s.Replace("\"", "\\\"") + "\""; }
+
+ private static void Emit(string m)
+ {
+ Console.WriteLine("[output] " + m);
+ var h = Log;
+ if (h != null) h(m);
+ }
+}
\ No newline at end of file
diff --git a/program/BatteryMonitor.cs b/program/BatteryMonitor.cs
new file mode 100644
index 0000000..16945d3
--- /dev/null
+++ b/program/BatteryMonitor.cs
@@ -0,0 +1,105 @@
+using System;
+using System.Globalization;
+using System.IO;
+
+public class BatteryStatus
+{
+ public bool Present;
+ public int Percent = -1;
+ public bool Charging;
+ public bool Full;
+}
+
+public static class BatteryMonitor
+{
+ private const string Root = "/sys/class/power_supply";
+ private static string _path; // cached battery directory
+
+ public static BatteryStatus Read()
+ {
+ var s = new BatteryStatus();
+
+ string dir = FindBattery();
+ if (dir == null) return s;
+
+ int pct = ReadPercent(dir);
+ if (pct < 0) return s;
+
+ string status = ReadValue(dir, "status") ?? "Unknown";
+
+ s.Present = true;
+ s.Percent = Math.Max(0, Math.Min(100, pct));
+ s.Charging = string.Equals(status, "Charging", StringComparison.OrdinalIgnoreCase);
+ s.Full = string.Equals(status, "Full", StringComparison.OrdinalIgnoreCase);
+ return s;
+ }
+
+ private static string FindBattery()
+ {
+ if (_path != null && Directory.Exists(_path)) return _path;
+ _path = null;
+
+ if (!Directory.Exists(Root)) return null;
+
+ try
+ {
+ foreach (string dir in Directory.GetDirectories(Root))
+ {
+ if (!string.Equals(ReadValue(dir, "type"), "Battery",
+ StringComparison.OrdinalIgnoreCase)) continue;
+
+ // "scope" is Device on peripherals (stylus, BT mouse) — skip those
+ string scope = ReadValue(dir, "scope");
+ if (scope != null && !string.Equals(scope, "System",
+ StringComparison.OrdinalIgnoreCase)) continue;
+
+ if (ReadPercent(dir) < 0) continue;
+
+ _path = dir;
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("Battery scan failed: " + ex.Message);
+ }
+
+ return _path;
+ }
+
+ private static int ReadPercent(string dir)
+ {
+ long pct = ParseLong(ReadValue(dir, "capacity"));
+ if (pct >= 0) return (int)pct;
+
+ // some firmwares expose energy/charge only
+ long now = ParseLong(ReadValue(dir, "energy_now"));
+ long full = ParseLong(ReadValue(dir, "energy_full"));
+ if (now < 0 || full <= 0)
+ {
+ now = ParseLong(ReadValue(dir, "charge_now"));
+ full = ParseLong(ReadValue(dir, "charge_full"));
+ }
+ if (now >= 0 && full > 0) return (int)Math.Round(now * 100.0 / full);
+
+ return -1;
+ }
+
+ private static string ReadValue(string dir, string file)
+ {
+ try
+ {
+ string p = Path.Combine(dir, file);
+ return File.Exists(p) ? File.ReadAllText(p).Trim() : null;
+ }
+ catch { return null; }
+ }
+
+ private static long ParseLong(string s)
+ {
+ long v;
+ if (s != null && long.TryParse(s, NumberStyles.Integer,
+ CultureInfo.InvariantCulture, out v)) return v;
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/program/Boot.cs b/program/Boot.cs
new file mode 100644
index 0000000..62f1ffc
--- /dev/null
+++ b/program/Boot.cs
@@ -0,0 +1,15 @@
+using System;
+using System.Diagnostics;
+
+public static class Boot
+{
+ private static readonly Stopwatch _sw = Stopwatch.StartNew();
+ private static long _last;
+
+ public static void Mark(string what)
+ {
+ long now = _sw.ElapsedMilliseconds;
+ Console.WriteLine("[boot] " + now.ToString().PadLeft(6) + " ms (+" + (now - _last) + ") " + what);
+ _last = now;
+ }
+}
\ No newline at end of file
diff --git a/program/CaseDefinition.cs b/program/CaseDefinition.cs
new file mode 100644
index 0000000..9b8ad39
--- /dev/null
+++ b/program/CaseDefinition.cs
@@ -0,0 +1,247 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+/// One row of cases.csv (or cases_old.csv in legacy mode).
+public class CaseDefinition
+{
+ public int Number { get; set; } // Number
+ public string Type { get; set; } // Type 心音 / 呼吸音
+ public string CategoryJp { get; set; } // Category
+ public string SubcategoryJp { get; set; } // Subcategory
+ public string LocationJp { get; set; } // Location
+ public string TreeLevel1 { get; set; } // Tree_Level1
+ public string TreeLevel2 { get; set; } // Tree_Level2
+ public string TreeLevel3 { get; set; } // Tree_Level3
+ public string MapFront { get; set; } // Image_File
+ public string SoundPath { get; set; } // Sound_File
+ public string MapRight { get; set; } // Image_Right
+ public string MapLeft { get; set; } // Image_Left
+ public string MapBack { get; set; } // Image_Back
+
+ // ── legacy 7-region fields ────────────────────────────────────────
+ public string[] RegionMaps = new string[7];
+ public string[] RegionSounds = new string[7];
+ public string[] RegionIcons = new string[7];
+ public int InhaleStart, ExhaleStart, ExhaleEnd; // fields, so TryParse(out …) compiles
+ /// Explanation image (C100.png … C999.png). Legacy: column 27.
+ /// Current mode: optional "Manual_File" column in cases.csv.
+ public string ManualFile;
+ public bool IsLegacy;
+
+ public bool IsHeart
+ {
+ get { return !string.IsNullOrEmpty(Type) && Type.Contains("心"); }
+ }
+
+ /// Non-empty levels only, e.g. 呼吸音 → 正常呼吸音 → 気管音.
+ /// Depth varies per row, which is what drives the drill-down.
+ public string[] TreePath
+ {
+ get
+ {
+ var parts = new List();
+ foreach (string s in new[] { Type, TreeLevel1, TreeLevel2, TreeLevel3 })
+ if (!string.IsNullOrWhiteSpace(s)) parts.Add(s.Trim());
+ return parts.ToArray();
+ }
+ }
+
+ public override string ToString()
+ {
+ return Number + ": " + string.Join(" : ", TreePath);
+ }
+
+ // ── loader: current mode (cases.csv) ──────────────────────────────
+
+ public static List LoadCasesFromCsv(string path)
+ {
+ var list = new List();
+
+ if (!File.Exists(path))
+ {
+ Console.WriteLine("CSV not found: " + path);
+ return list;
+ }
+
+ // Encoding.UTF8 with BOM detection. Reading Japanese as the default
+ // ANSI codepage gives mojibake that only shows up on the buttons.
+ string[] lines;
+ try
+ {
+ lines = File.ReadAllLines(path, Encoding.UTF8);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("Failed to read " + path + ": " + ex.Message);
+ return list;
+ }
+
+ if (lines.Length < 2)
+ {
+ Console.WriteLine("CSV has no data rows: " + path);
+ return list;
+ }
+
+ // Your file is TAB separated; fall back to comma if it gets re-exported.
+ char sep = lines[0].Contains("\t") ? '\t' : ',';
+
+ // Header name -> column index, so adding or reordering columns is safe.
+ string[] header = lines[0].TrimStart(new[] { '' }).Split(sep);
+ var idx = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ for (int i = 0; i < header.Length; i++)
+ {
+ string key = header[i].Trim();
+ if (key.Length > 0 && !idx.ContainsKey(key)) idx[key] = i;
+ }
+
+ if (!idx.ContainsKey("Number"))
+ {
+ Console.WriteLine("CSV header has no 'Number' column — wrong file or wrong delimiter?");
+ return list;
+ }
+
+ Func get = (fields, name) =>
+ {
+ int i;
+ if (!idx.TryGetValue(name, out i) || i >= fields.Length) return "";
+ return fields[i].Trim();
+ };
+
+ int skipped = 0;
+
+ for (int r = 1; r < lines.Length; r++)
+ {
+ if (string.IsNullOrWhiteSpace(lines[r])) continue;
+
+ string[] f = lines[r].Split(sep);
+
+ int number;
+ if (!int.TryParse(get(f, "Number"), NumberStyles.Integer,
+ CultureInfo.InvariantCulture, out number))
+ {
+ skipped++;
+ Console.WriteLine("Line " + (r + 1) + ": bad Number, skipped");
+ continue;
+ }
+
+ list.Add(new CaseDefinition
+ {
+ Number = number,
+ Type = get(f, "Type"),
+ CategoryJp = get(f, "Category"),
+ SubcategoryJp = get(f, "Subcategory"),
+ LocationJp = get(f, "Location"),
+ TreeLevel1 = get(f, "Tree_Level1"),
+ TreeLevel2 = get(f, "Tree_Level2"),
+ TreeLevel3 = get(f, "Tree_Level3"),
+ MapFront = get(f, "Image_File"),
+ SoundPath = get(f, "Sound_File"),
+ MapRight = get(f, "Image_Right"),
+ MapLeft = get(f, "Image_Left"),
+ MapBack = get(f, "Image_Back"),
+ ManualFile = get(f, "Manual_File") // optional column; "" when absent
+ });
+ }
+
+ Console.WriteLine("Loaded " + list.Count + " cases from " + path +
+ (skipped > 0 ? " (" + skipped + " skipped)" : ""));
+ return list;
+ }
+
+ // ── loader: legacy mode (cases_old.csv) ───────────────────────────
+
+ /// Reads the Python-format case.csv: no header, 28 positional columns.
+ /// 0 name
+ /// 1..21 7 regions × (map, sound, icon)
+ /// 22 duration parameter (unused)
+ /// 23 1 = heart case, else breath
+ /// 24..26 inhale start, exhale start, exhale end
+ /// 27 explanation image (C100.png … C999.png)
+ /// Pairs row N of cases_old.csv with row N of cases_old_eng.csv (same layout,
+ /// English names in column 0) -> Japanese tree name -> English display name.
+ public static Dictionary LoadLegacyEnglishNames(string jpPath, string engPath)
+ {
+ var map = new Dictionary();
+ if (!File.Exists(jpPath) || !File.Exists(engPath)) return map;
+ Func> names = p =>
+ {
+ var l = new List();
+ foreach (string raw in File.ReadAllLines(p, Encoding.UTF8))
+ {
+ if (string.IsNullOrWhiteSpace(raw)) continue;
+ string line = raw.TrimStart('\uFEFF');
+ l.Add(line.Split(line.Contains("\t") ? '\t' : ',')[0].Trim());
+ }
+ return l;
+ };
+ var jp = names(jpPath); var en = names(engPath);
+ for (int i = 0; i < Math.Min(jp.Count, en.Count); i++) map[jp[i]] = en[i];
+ return map;
+ }
+
+ public static List LoadLegacyCasesFromCsv(string path)
+ {
+ var list = new List();
+ if (!File.Exists(path))
+ {
+ Console.WriteLine("Legacy CSV not found: " + path);
+ return list;
+ }
+
+ string[] lines;
+ try { lines = File.ReadAllLines(path, Encoding.UTF8); }
+ catch (Exception ex)
+ {
+ Console.WriteLine("Failed to read " + path + ": " + ex.Message);
+ return list;
+ }
+
+ int n = 0;
+ foreach (string raw in lines)
+ {
+ if (string.IsNullOrWhiteSpace(raw)) continue;
+
+ string line = raw.TrimStart('');
+ string[] f = line.Split(line.Contains("\t") ? '\t' : ',');
+
+ if (f.Length < 28)
+ {
+ Console.WriteLine("Legacy row skipped: expected 28 fields, got " + f.Length);
+ continue;
+ }
+
+ n++;
+ var d = new CaseDefinition
+ {
+ IsLegacy = true,
+ Number = 900 + n, // no clash with cases.csv, below MULTICOLOR_THRESHOLD
+ TreeLevel1 = f[0].Trim()
+ };
+
+ for (int k = 0; k < 7; k++)
+ {
+ d.RegionMaps[k] = f[1 + k * 3].Trim();
+ d.RegionSounds[k] = f[2 + k * 3].Trim();
+ d.RegionIcons[k] = f[3 + k * 3].Trim();
+ }
+
+ int flag;
+ int.TryParse(f[23].Trim(), out flag);
+ d.Type = (flag == 1) ? "心音" : "呼吸音"; // drives IsHeart and the tree root
+
+ int.TryParse(f[24].Trim(), out d.InhaleStart);
+ int.TryParse(f[25].Trim(), out d.ExhaleStart);
+ int.TryParse(f[26].Trim(), out d.ExhaleEnd);
+ d.ManualFile = f[27].Trim();
+
+ d.MapFront = d.RegionMaps[0]; // so display code has a fallback
+ list.Add(d);
+ }
+
+ Console.WriteLine("Loaded " + list.Count + " legacy cases from " + path);
+ return list;
+ }
+}
\ No newline at end of file
diff --git a/program/JacketData.cs b/program/JacketData.cs
new file mode 100644
index 0000000..fd9883c
--- /dev/null
+++ b/program/JacketData.cs
@@ -0,0 +1,215 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+
+/// One chip position. Mirrors Form2.Circle.
+public class Circle
+{
+ public float Number { get; set; }
+ public int X { get; set; } // screen-space: OriginalX * 50 + MarginX
+ public int Y { get; set; }
+ public float OriginalX { get; set; }
+ public float OriginalY { get; set; }
+ public float OriginalZ { get; set; }
+ public bool Inner { get; set; } // non-integer Number
+}
+
+/// Loads the 8 CSVs from JacketData/ — front|back|right|left x L|XL.
+public class JacketData
+{
+ public const int CoordScale = 50; // Form2: originalX * 50
+ public const int MarginX = 30;
+ public const int MarginY = 30;
+
+ private const string ConfigFile = "config.txt";
+ private const string DefaultDir = "JacketData";
+
+ private static readonly string[] Views = { "front", "back", "right", "left" };
+ private static readonly string[] Sizes = { "L", "XL" };
+
+ private readonly Dictionary> _l = new Dictionary>();
+ private readonly Dictionary> _xl = new Dictionary>();
+
+ public string Folder { get; private set; }
+ public bool Loaded { get; private set; }
+
+ /// Form2.GetCurrentCSVData()
+ public List Get(string size, string view)
+ {
+ var dict = (size == "XL") ? _xl : _l;
+ List list;
+ return dict.TryGetValue(view, out list) ? list : new List();
+ }
+
+ public bool Has(string size, string view)
+ {
+ var dict = (size == "XL") ? _xl : _l;
+ return dict.ContainsKey(view) && dict[view].Count > 0;
+ }
+
+ // ── folder resolution: config.txt, else JacketData/ next to the exe ──
+
+ public static string ResolveFolder()
+ {
+ string cfg = SoundWindow.AppFile(ConfigFile);
+
+ if (File.Exists(cfg))
+ {
+ try
+ {
+ string saved = File.ReadAllText(cfg).Trim();
+ if (Directory.Exists(saved) && Validate(saved))
+ {
+ Logger.Write("jacket", "folder from config.txt: " + saved);
+ return saved;
+ }
+
+ Logger.Write("jacket", "config.txt path invalid, ignoring: " + saved);
+ }
+ catch (Exception ex)
+ {
+ Logger.Write("jacket", "config.txt unreadable: " + ex.Message);
+ }
+ }
+
+ return SoundWindow.AppFile(DefaultDir);
+ }
+
+ public static void SaveFolder(string folder)
+ {
+ try { File.WriteAllText(SoundWindow.AppFile(ConfigFile), folder); }
+ catch (Exception ex) { Logger.Write("jacket", "could not save config.txt: " + ex.Message); }
+ }
+
+ /// Form1.ValidateCSVFiles — all 8 must be present.
+ public static bool Validate(string folder)
+ {
+ foreach (string v in Views)
+ foreach (string s in Sizes)
+ if (!File.Exists(Path.Combine(folder, v + "_" + s + ".csv")))
+ return false;
+ return true;
+ }
+
+ public static string[] MissingFiles(string folder)
+ {
+ var missing = new List();
+ foreach (string v in Views)
+ foreach (string s in Sizes)
+ {
+ string name = v + "_" + s + ".csv";
+ if (!File.Exists(Path.Combine(folder, name))) missing.Add(name);
+ }
+ return missing.ToArray();
+ }
+
+ // ── loading ─────────────────────────────────────────────────────────
+
+ public static JacketData Load()
+ {
+ return Load(ResolveFolder());
+ }
+
+ public static JacketData Load(string folder)
+ {
+ var data = new JacketData();
+ data.Folder = folder;
+
+ if (!Directory.Exists(folder))
+ {
+ Logger.Write("jacket", "folder not found: " + folder);
+ return data;
+ }
+
+ string[] missing = MissingFiles(folder);
+ if (missing.Length > 0)
+ Logger.Write("jacket", "missing " + missing.Length + " file(s): " + string.Join(", ", missing));
+
+ foreach (string view in Views)
+ {
+ foreach (string size in Sizes)
+ {
+ string path = Path.Combine(folder, view + "_" + size + ".csv");
+ var circles = ReadCsv(path);
+ if (circles.Count == 0) continue;
+
+ if (size == "XL") data._xl[view] = circles;
+ else data._l[view] = circles;
+
+ Logger.Write("jacket", "loaded " + circles.Count + " chips from " + view + "_" + size + ".csv");
+ }
+ }
+
+ data.Loaded = (data._l.Count > 0 || data._xl.Count > 0);
+ if (!data.Loaded) Logger.Write("jacket", "NO chip data loaded from " + folder);
+
+ return data;
+ }
+
+ /// Columns: Number, OriginalX, OriginalY, OriginalZ. Header optional.
+ private static List ReadCsv(string path)
+ {
+ var circles = new List();
+
+ if (!File.Exists(path))
+ {
+ Logger.Write("jacket", "file not found: " + path);
+ return circles;
+ }
+
+ string[] lines;
+ try { lines = File.ReadAllLines(path); }
+ catch (Exception ex)
+ {
+ Logger.Write("jacket", "read failed " + path + ": " + ex.Message);
+ return circles;
+ }
+
+ int start = 0;
+ if (lines.Length > 0)
+ {
+ string h = lines[0].ToLower();
+ if (h.Contains("number") || h.Contains("originalx")) start = 1;
+ }
+
+ for (int i = start; i < lines.Length; i++)
+ {
+ string line = lines[i].Trim();
+ if (line.Length == 0) continue;
+
+ string[] p = line.Split(',');
+ if (p.Length < 4)
+ {
+ Logger.Write("jacket", path + " line " + (i + 1) + ": only " + p.Length + " columns");
+ continue;
+ }
+
+ float number, ox, oy, oz;
+ var inv = CultureInfo.InvariantCulture;
+
+ // InvariantCulture matters — under ja_JP/de_DE, "1.5" can fail to parse.
+ if (!float.TryParse(p[0].Trim(), NumberStyles.Float, inv, out number) ||
+ !float.TryParse(p[1].Trim(), NumberStyles.Float, inv, out ox) ||
+ !float.TryParse(p[2].Trim(), NumberStyles.Float, inv, out oy) ||
+ !float.TryParse(p[3].Trim(), NumberStyles.Float, inv, out oz))
+ {
+ Logger.Write("jacket", path + " line " + (i + 1) + ": bad number format");
+ continue;
+ }
+
+ circles.Add(new Circle
+ {
+ Number = number,
+ X = (int)(ox * CoordScale) + MarginX,
+ Y = (int)(oy * CoordScale) + MarginY,
+ OriginalX = ox,
+ OriginalY = oy,
+ OriginalZ = oz,
+ Inner = (number % 1 != 0)
+ });
+ }
+
+ return circles;
+ }
+}
\ No newline at end of file
diff --git a/program/LEGACY_MODE_FIX.md b/program/LEGACY_MODE_FIX.md
new file mode 100644
index 0000000..1ba99e2
--- /dev/null
+++ b/program/LEGACY_MODE_FIX.md
@@ -0,0 +1,156 @@
+# Fix: `--legacy` flag is not reaching the case loader
+
+## Symptom
+
+```
+argv = [.../program.exe | --legacy | --debug]
+Loaded 98 cases from .../bin/linux/cases.csv
+```
+
+`cases.csv` has 98 rows — that is the **current-mode** loader running. The legacy
+loader prints `Loaded N legacy cases from …`, so `LoadLegacyCasesFromCsv` never ran.
+The map looks unchanged for the same reason: the app is in normal mode end to end.
+
+So this is not a map-drawing bug. Fix the flag first, then re-check the map.
+
+## Likely causes, in order
+
+1. `Program.cs` sets `AppMode.Legacy` **after** the widgets are built, so
+ `SoundWindow`'s constructor already ran with `Legacy == false`.
+2. `Program.cs` step was never applied — `argv` is printed by pre-existing arg-parsing
+ code, which proves an arg parser exists but not that ours was added to it.
+3. `SoundWindow` still calls `CaseDefinition.LoadCasesFromCsv(AppFile("cases.csv"))`
+ instead of the `AppMode` version.
+4. Assets aren't next to the exe. Note the working dir is `program/` but files resolve
+ to `program/bin/linux/` — `cases_old.csv`, `map_old/`, `sound_old/` must be in
+ **`bin/linux/`**, not the repo root.
+
+## Step 1 — diagnose before editing
+
+Report back, don't fix yet:
+
+- Paste the full `Program.cs` `Main`, in order, from the first line to
+ `Application.Run()`. Mark exactly where `AppMode.Legacy` is assigned, or state that it
+ is absent.
+- Paste the current `SoundWindow` constructor lines that load `_allCases`.
+- Run `ls -la bin/linux/` and report whether `cases_old.csv`, `map_old/`, `sound_old/`
+ exist there.
+- Confirm whether `AppMode.cs` and `RegionSound.cs` are in the build command actually
+ used to produce `bin/linux/program.exe` (check the Makefile / build script, not just
+ the files on disk).
+
+## Step 2 — make the flag observable
+
+Add these three log lines so the mode is never ambiguous again.
+
+In `Program.cs`, immediately after the `AppMode.Legacy` assignment:
+
+```csharp
+Console.WriteLine("AppMode.Legacy = " + AppMode.Legacy +
+ " cases=" + AppMode.CasesCsv);
+```
+
+In the `SoundWindow` constructor, as the first line:
+
+```csharp
+Console.WriteLine("SoundWindow ctor: AppMode.Legacy = " + AppMode.Legacy);
+```
+
+In `MapWindow.ShowCase`, after `_case` is assigned:
+
+```csharp
+Logger.Write("map", "ShowCase legacy=" + AppMode.Legacy +
+ " regions=" + _regions.Count);
+```
+
+## Step 3 — set the flag before anything reads it
+
+`AppMode.Legacy` must be assigned **before** `Application.Init()` and before any
+`Builder` / window / `SoundWindow` construction. If the existing parser handles
+`--debug`, add `--legacy` to that same parser and move the whole parse block to the top
+of `Main`, above `Application.Init()`. Do not add a second parser.
+
+Target shape:
+
+```csharp
+static void Main(string[] args)
+{
+ Console.WriteLine("argv = [" + string.Join(" | ", args) + "]");
+
+ // --- flags first, before any UI construction ---
+ AppMode.Legacy = Array.IndexOf(args, "--legacy") >= 0;
+ // ... existing --debug handling stays here too ...
+ Console.WriteLine("AppMode.Legacy = " + AppMode.Legacy +
+ " cases=" + AppMode.CasesCsv);
+
+ Application.Init();
+ // ... existing window construction ...
+ Application.Run();
+}
+```
+
+If `Main` already lives in a different file or class than expected, edit that one — find
+it by searching for the `argv = [` line that appears in the log.
+
+## Step 4 — verify `SoundWindow` uses `AppMode`
+
+The constructor must read:
+
+```csharp
+_allCases = AppMode.Legacy
+ ? CaseDefinition.LoadLegacyCasesFromCsv(AppMode.CasesCsv)
+ : CaseDefinition.LoadCasesFromCsv(AppMode.CasesCsv);
+```
+
+If a literal `"cases.csv"` string remains anywhere in `SoundWindow`, replace it.
+Then grep the whole repo for `"cases.csv"` and report every remaining hit — another
+class may be loading the CSV independently.
+
+## Step 5 — assets in the right folder
+
+`SoundWindow.AppFile` resolves next to the assembly, which is `bin/linux/`. If the build
+copies `cases.csv`, `map/`, and `sound/` there, make it copy `cases_old.csv`,
+`map_old/`, and `sound_old/` the same way. Update the Makefile / build script rather
+than copying by hand, and say which file you changed.
+
+## Step 6 — re-verify, then look at the map
+
+Run:
+
+```bash
+mono ./bin/linux/program.exe --legacy --debug
+```
+
+Expected, in this order:
+
+```
+AppMode.Legacy = True cases=.../bin/linux/cases_old.csv
+SoundWindow ctor: AppMode.Legacy = True
+Loaded 28 legacy cases from .../bin/linux/cases_old.csv
+```
+
+Only once you see `Loaded 28 legacy cases`, select a case and check the log for:
+
+```
+[map] region 心音1: MAP100.png + SND100.wav
+[map] ...
+[map] N/7 regions active
+[map] ShowCase legacy=True regions=N
+```
+
+Report which of these appear. Then, and only then, we debug the drawing:
+
+- `regions=0` → the region files aren't resolving; paste the `region … map missing`
+ lines.
+- `regions>0` but the map looks identical → the `ShowCase` branch from Step 9 of the
+ original task wasn't applied, or `_map` is being overwritten after it by a later
+ `LoadMap(MapPathForView())` call. Paste the whole `ShowCase` method.
+- Colours appear but no bars → `DrawRegionMeters` isn't being called from `OnMapDrawn`.
+
+## Rules
+
+- Steps 1 and 6 are report-only. Do not edit files during them.
+- Do not "fix" this by defaulting `AppMode.Legacy` to `true`, by hardcoding
+ `cases_old.csv`, or by calling the legacy loader unconditionally.
+- Do not touch the map-drawing code until the log proves the legacy loader ran.
+- One step per change set, with a diff, and wait for approval.
\ No newline at end of file
diff --git a/program/Language.cs b/program/Language.cs
new file mode 100644
index 0000000..6b4748d
--- /dev/null
+++ b/program/Language.cs
@@ -0,0 +1,207 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using Gtk;
+
+public class Language
+{
+ private const string EngCssPath = "lang_eng.css";
+ private const string JpnCssPath = "lang_jpn.css";
+ private const string EngCsvPath = "info_eng.csv";
+ private const string JpnCsvPath = "info_jpn.csv";
+ private const string TouchCssPath = "touch_friendly.css"; // NEW
+ private const string NamesCsvPath = "names_eng.csv"; // Japanese case/category name -> English
+
+ private readonly Dictionary _engText;
+ private readonly Dictionary _jpnText;
+ private Dictionary _text;
+ private readonly Dictionary _names;
+ private static readonly System.Text.RegularExpressions.Regex EnJpRx =
+ new System.Text.RegularExpressions.Regex(@"^(.*?)\((.*)\)\s*$");
+
+ // widgets whose label is a plain CSV lookup
+ private readonly Dictionary _widgets = new Dictionary();
+
+ public readonly CssProvider _languageCssProvider = new CssProvider();
+ private readonly CssProvider _touchCssProvider = new CssProvider(); // NEW
+
+ public bool IsEnglish { get; private set; }
+
+ /// Raised after every language change, so callers can rebuild state-dependent text.
+ public event EventHandler Changed;
+
+ public Language(bool isEnglish)
+ {
+ // Touch-friendly sizing loads once, at a lower priority than the
+ // language CSS (600) so per-language #id rules can still override
+ // fonts/colors if needed, while touch sizing stays constant.
+ if (File.Exists(TouchCssPath))
+ {
+ _touchCssProvider.LoadFromPath(TouchCssPath);
+ Console.WriteLine("Touch CSS loaded from: " + System.IO.Path.GetFullPath(TouchCssPath));
+ }
+ else
+ {
+ Console.WriteLine("Warning: CSS file not found: " + TouchCssPath);
+ }
+ StyleContext.AddProviderForScreen(Gdk.Screen.Default, _touchCssProvider, 1000);
+ StyleContext.AddProviderForScreen(Gdk.Screen.Default, _languageCssProvider, 600);
+
+ _engText = LoadText(EngCsvPath);
+ _jpnText = LoadText(JpnCsvPath);
+ _names = LoadText(NamesCsvPath);
+
+ // set before any widget is built, so ctor-time lookups are already correct
+ IsEnglish = isEnglish;
+ _text = isEnglish ? _engText : _jpnText;
+ }
+
+ // ---------- registration ----------
+
+ /// Label comes straight from the CSV key. Applied automatically on every change.
+ public void Register(string key, Widget widget)
+ {
+ if (widget == null) return;
+ widget.Name = key; // enables #Key selectors in the lang CSS
+ _widgets[key] = widget;
+
+ // Set the current text now, so widgets registered after the first
+ // Apply() (e.g. SoundWindow, built later) don't wait for a toggle.
+ string value;
+ if (_text.TryGetValue(key, out value)) SetText(widget, value);
+ }
+
+ /// Widget whose text the owner sets itself (state-dependent). Name only, no auto-apply.
+ public void RegisterDynamic(string key, Widget widget)
+ {
+ if (widget != null) widget.Name = key;
+ }
+
+ // ---------- lookup ----------
+
+ public string this[string key] { get { return Get(key); } }
+
+ public string Get(string key)
+ {
+ string value;
+ if (_text.TryGetValue(key, out value)) return value;
+
+ Console.WriteLine("Warning: missing text key '" + key + "'");
+ return key;
+ }
+
+ ///
+ /// Display text for a case-tree name. The Japanese CSV value stays the lookup key;
+ /// this only changes what is shown. "fine crackle(捻髪音)" -> "fine crackle" in English.
+ ///
+ public string Name(string jp)
+ {
+ if (string.IsNullOrEmpty(jp) || !IsEnglish) return jp;
+ string en;
+ if (_names.TryGetValue(jp.Trim(), out en)) return en;
+ var m = EnJpRx.Match(jp);
+ if (m.Success && m.Groups[1].Value.Trim().Length > 0) return m.Groups[1].Value.Trim();
+ return jp;
+ }
+
+ /// Adds Japanese -> English display names (e.g. from cases_old_eng.csv).
+ public void AddNames(Dictionary map)
+ {
+ foreach (var kv in map) _names[kv.Key] = kv.Value;
+ }
+
+ /// Display text for a whole path, e.g. "Breath sounds : Wheeze : Right lung".
+ public string Path(string[] parts, string sep)
+ {
+ var shown = new string[parts.Length];
+ for (int i = 0; i < parts.Length; i++) shown[i] = Name(parts[i]);
+ return string.Join(sep, shown);
+ }
+
+ public string Format(string key, params object[] args)
+ {
+ string template = Get(key);
+ try
+ {
+ return string.Format(CultureInfo.InvariantCulture, template, args);
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine("Warning: bad placeholder in text key '" + key + "'");
+ return template;
+ }
+ }
+
+ // ---------- apply ----------
+
+ public void Apply(bool isEnglish)
+ {
+ IsEnglish = isEnglish;
+ _text = isEnglish ? _engText : _jpnText;
+
+ foreach (var kvp in _widgets)
+ {
+ string value;
+ if (_text.TryGetValue(kvp.Key, out value))
+ SetText(kvp.Value, value);
+ else
+ Console.WriteLine("Warning: missing text key '" + kvp.Key + "'");
+ }
+
+ string cssPath = isEnglish ? EngCssPath : JpnCssPath;
+ if (File.Exists(cssPath))
+ _languageCssProvider.LoadFromPath(cssPath);
+ else
+ Console.WriteLine("Warning: CSS file not found: " + cssPath);
+
+ EventHandler handler = Changed;
+ if (handler != null) handler(this, EventArgs.Empty);
+ }
+
+ private static void SetText(Widget widget, string value)
+ {
+ Button button = widget as Button; // also covers ToggleButton
+ if (button != null) { button.Label = value; return; }
+
+ Label label = widget as Label;
+ if (label != null) { label.Text = value; return; }
+
+ Console.WriteLine("Warning: don't know how to set text on " + widget.GetType().Name);
+ }
+
+ // ---------- csv ----------
+
+ private Dictionary LoadText(string path)
+ {
+ var result = new Dictionary();
+
+ // Prefer the copy next to the exe (same rule as cases*.csv), so the
+ // app finds its text no matter which folder it was launched from.
+ string besideExe = SoundWindow.AppFile(path);
+ if (File.Exists(besideExe)) path = besideExe;
+
+ if (!File.Exists(path))
+ {
+ Console.WriteLine("Warning: text file not found: " + path);
+ return result;
+ }
+
+ string[] lines = File.ReadAllLines(path);
+ for (int i = 1; i < lines.Length; i++) // row 0 is the header
+ {
+ string line = lines[i].Trim();
+ if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue;
+
+ string[] parts = line.Split(new[] { ',' }, 2);
+ if (parts.Length < 2) continue;
+
+ // Value keeps any commas. "\n" in the CSV becomes a real line break,
+ // so a translator controls where a message wraps instead of leaving
+ // it to Pango, which breaks Japanese at arbitrary characters.
+ result[parts[0].Trim()] = parts[1].Replace("\\n", "\n");
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/program/Logger.cs b/program/Logger.cs
new file mode 100644
index 0000000..85b0efe
--- /dev/null
+++ b/program/Logger.cs
@@ -0,0 +1,69 @@
+using System;
+using System.IO;
+using System.Text;
+
+/// Append-only text log next to the .exe: logs/ears-YYYYMMDD.log
+public static class Logger
+{
+ private static readonly object _gate = new object();
+ private static string _path;
+ private static bool _failed;
+
+ public static void Write(string message)
+ {
+ Write(null, message);
+ }
+
+ public static void Write(string tag, string message)
+ {
+ if (_failed) return;
+
+ string line = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
+ (string.IsNullOrEmpty(tag) ? " " : " [" + tag + "] ") +
+ message;
+
+ lock (_gate)
+ {
+ try
+ {
+ if (_path == null) _path = Init();
+ File.AppendAllText(_path, line + Environment.NewLine, Encoding.UTF8);
+ }
+ catch (Exception ex)
+ {
+ _failed = true; // never let logging crash the app
+ Console.WriteLine("[Logger] disabled: " + ex.Message);
+ }
+ }
+ }
+
+ public static void Write(string tag, string format, params object[] args)
+ {
+ Write(tag, string.Format(format, args));
+ }
+
+ public static void Exception(string tag, Exception ex)
+ {
+ Write(tag, ex.GetType().Name + ": " + ex.Message);
+ Write(tag, ex.StackTrace ?? "(no stack)");
+ }
+
+ private static string Init()
+ {
+ string dir = Path.Combine(
+ Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
+ "logs");
+
+ Directory.CreateDirectory(dir);
+
+ string path = Path.Combine(dir, "ears-" + DateTime.Now.ToString("yyyyMMdd") + ".log");
+
+ File.AppendAllText(path,
+ Environment.NewLine +
+ "=== session start " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +
+ " (" + Environment.OSVersion.Platform + ") ===" + Environment.NewLine,
+ Encoding.UTF8);
+
+ return path;
+ }
+}
\ No newline at end of file
diff --git a/program/MainWindow.cs b/program/MainWindow.cs
new file mode 100644
index 0000000..c4c5294
--- /dev/null
+++ b/program/MainWindow.cs
@@ -0,0 +1,780 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using Gtk;
+using UI = Gtk.Builder.ObjectAttribute;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
+public class MainWindow : Window
+{
+
+ // ---- stack + pages (new all-in-one glade) ----
+ [UI] private Notebook RootNoteBook = null;
+
+ private const int PageSplash = 0;
+ private const int PageSettings = 1;
+ private const int PageSound = 2;
+ private const int PageMap = 3;
+
+ // ---- splash page widgets ----
+ [UI] private Button Option1Button = null;
+ [UI] private Button Option2Button = null;
+ [UI] private Button Option3Button = null;
+ // [UI] private Switch LanguageSwitch = null;
+ [UI] private ToggleButton LanguageToggle = null;
+ [UI] private Label LanguageLabel = null;
+ [UI] private Button CloseButton = null;
+ [UI] private Button SettingButton = null;
+ [UI] private Image ConnectionIcon = null; // was GtkIconView in the old glade
+
+ [UI] private Label ConnectionAlertLabel = null;
+ [UI] private DrawingArea BatteryArea = null;
+
+ [UI] private Box BatteryBox = null;
+ [UI] private Label BatteryPercentLabel = null;
+ [UI] private Label ConnectionStatusLabel = null;
+ [UI] private Box StatusDot = null;
+ [UI] private RadioButton LangEnRadio = null;
+
+
+
+ private uint _retryTimerId;
+ private bool _probing;
+ private const uint RetryMs = 1000;
+
+ private CssProvider _scaleCssProvider;
+ // private CssProvider _languageCssProvider;
+ private int _lastAppliedWidth = -1;
+
+ private const int BaseWidth = 1920;
+ private const int BaseHeight = 1080;
+
+ // private const string EngCssPath = "lang_eng.css";
+ // private const string JpnCssPath = "lang_jpn.css";
+
+ // private Dictionary _engText;
+ // private Dictionary _jpnText;
+ // private Dictionary _buttonsById;
+ private bool _connected;
+
+ private readonly ArduinoConnection _arduino = new ArduinoConnection();
+ internal SettingsWindow _settingsWindow;
+ internal Language _Language;
+
+ internal SoundWindow _soundWindow;
+ internal MapWindow _mapWindow;
+ // Battery
+ private BatteryStatus _battery = new BatteryStatus();
+ private uint _batteryTimerId;
+ private const uint BatteryPollMs = 10000;
+
+ private readonly List _regions = new List();
+
+ private static readonly string[] RegionLabels = {
+ "心音1","心音2","気管","気管支","気管支肺胞","右肺胞","左肺胞" };
+
+ // RGB triples — no 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 bool _showRegions = true; // Ctrl+R toggles
+
+
+ public MainWindow() : this(CreateBuilder()) { }
+
+ private static Builder CreateBuilder()
+ {
+ var builder = new Builder();
+ builder.AddFromFile("homepageallv8.glade");
+ return builder;
+ }
+
+ private MainWindow(Builder builder) : base(builder.GetObject("Root").Handle)
+ {
+ builder.Autoconnect(this);
+
+ _scaleCssProvider = new CssProvider();
+ // _languageCssProvider = new CssProvider();
+
+ StyleContext.AddProviderForScreen(Gdk.Screen.Default, _scaleCssProvider, 600);
+ // StyleContext.AddProviderForScreen(Gdk.Screen.Default, _Language._languageCssProvider, 600);
+
+ // // make it full screen
+ // this.Fullscreen();
+ //use the linux computer resolution
+ this.SetDefaultSize(1280, 800);
+ this.SetPosition(WindowPosition.Center);
+
+ // RootStack.TransitionType = StackTransitionType.None;
+ // RootStack.TransitionType = StackTransitionType.SlideLeftRight;
+ // RootStack.TransitionDuration = 150;
+
+ Option1Button.Clicked += OnNormalSessionClicked;
+ Option2Button.Clicked += OnPositionRecordingClicked;
+ Option3Button.Clicked += OnExamModeClicked;
+ CloseButton.Clicked += OnCloseClicked;
+ SettingButton.Clicked += OnSettingClicked;
+ // LanguageSwitch.AddNotification("active", OnLanguageSwitchNotify);
+ LanguageToggle.Toggled += OnLanguageToggled;
+
+ // icons drawn in code (no dependency on the icon theme)
+ SetModeIcon(Option1Button, ModeIcon.Kind.Stethoscope);
+ SetModeIcon(Option2Button, ModeIcon.Kind.BodyTarget);
+ SetModeIcon(Option3Button, ModeIcon.Kind.Chart);
+ SettingButton.Image = PlainIcon(ModeIcon.Kind.Cog, 32);
+ CloseButton.Image = PlainIcon(ModeIcon.Kind.Power, 30);
+
+ DeleteEvent += OnDeleteEvent;
+ SizeAllocated += OnWindowSizeAllocated;
+
+ _arduino.ConnectionChanged += OnArduinoConnectionChanged;
+
+
+ // // _buttonsById = new Dictionary
+ // // {
+ // // { "Option1Button", Option1Button },
+ // // { "Option2Button", Option2Button },
+ // // { "Option3Button", Option3Button },
+ // // { "CloseButton", CloseButton },
+ // // { "SettingButton", SettingButton },
+ // // };
+
+ // // CSS ID selectors (#Option1Button etc.) need the widget Name set explicitly
+ // foreach (var kvp in _buttonsById)
+ // kvp.Value.Name = kvp.Key;
+
+ // // _engText = LoadButtonText("info_eng.csv");
+ // // _jpnText = LoadButtonText("info_jpn.csv");
+
+ // _Language = new Language(_buttonsById,LanguageLabel);
+
+ // // _Language.ApplyLanguage(LanguageSwitch.Active);
+
+ _Language = new Language(LanguageToggle.Active);
+ _Language.Register("Option1Button", Option1Button);
+ _Language.Register("Option2Button", Option2Button);
+ _Language.Register("Option3Button", Option3Button);
+ _Language.Register("CloseButton", CloseButton);
+ _Language.Register("SettingButton", SettingButton);
+ _Language.Register("LanguageLabel", LanguageLabel);
+ _Language.Register("LanguageToggle", LanguageToggle);
+ _Language.RegisterDynamic("ConnectionIcon", ConnectionIcon);
+ _Language.RegisterDynamic("BatteryArea", BatteryArea);
+ if (BatteryArea != null) BatteryArea.Drawn += OnBatteryDrawn;
+ ConnectionAlertLabel.Name = "ConnectionAlertLabel";
+ _Language.Register("ConnectionAlertLabel", ConnectionAlertLabel);
+
+ // Boot.Mark("before settings");
+ _settingsWindow = new SettingsWindow(builder, _arduino, _Language);
+ // Boot.Mark("settings window");
+ _settingsWindow.BackRequested += OnSettingsClosed;
+
+ _mapWindow = new MapWindow(builder, _arduino, _Language);
+ // Boot.Mark("map window");
+ _mapWindow.BackRequested += OnMapClosed;
+
+ _Language.Changed += (s, e) => {
+ OnArduinoConnectionChanged(_connected);
+ UpdateBattery();
+ };
+ _Language.Apply(LanguageToggle.Active);
+
+ // あ / A buttons drive the language directly (LanguageToggle is hidden now)
+ if (LangEnRadio != null)
+ {
+ LangEnRadio.Active = LanguageToggle.Active; // show the current language
+ LangEnRadio.Toggled += (s, e) =>
+ {
+ bool english = LangEnRadio.Active;
+ Console.WriteLine("Language button -> " + (english ? "EN" : "JP"));
+ LanguageToggle.Active = english; // keeps the old toggle in sync
+ if (_Language.IsEnglish != english)
+ _Language.Apply(english); // switch even if the toggle didn't
+ };
+ }
+ else
+ {
+ Console.WriteLine("LangEnRadio not found - is homepageallv9.glade loaded?");
+ }
+
+ UpdateBattery();
+ _batteryTimerId = GLib.Timeout.Add(BatteryPollMs, OnBatteryTick);
+
+ // // single source of truth: the toggle drives both pages
+ // ApplyLanguageEverywhere(LanguageToggle.Active);
+
+ RootNoteBook.ShowTabs = false;
+ RootNoteBook.ShowBorder = false;
+ RootNoteBook.CurrentPage = PageSplash;
+ _soundWindow = new SoundWindow(builder, _Language);
+ _soundWindow.BackRequested += (s, e) => RootNoteBook.CurrentPage = PageSplash;
+ _soundWindow.CaseSelected += OnCaseSelected;
+
+
+ // OnArduinoConnectionChanged(false);
+
+ StartAutoDetectOnLoad();
+
+ if (AppConfig.DebugMode)
+ this.Title = (this.Title ?? "App") + " [DEBUG MODE]";
+ }
+
+
+
+ // ---------- settings panel ----------
+
+ private void OnSettingClicked(object sender, EventArgs e)
+ {
+ // if (_settingsWindow == null)
+ // {
+ // // _settingsWindow = new SettingsWindow(_arduino);
+ // // _settingsWindow.BackRequested += OnSettingsClosed;
+ // // _settingsWindow.ShowAll(); // build it fullscreen once, up front
+ // // _settingsWindow.Fullscreen();
+ // RootNoteBook.CurrentPage = PageSettings;
+ // }
+
+
+ // _settingsWindow.ShowAll();
+ // _settingsWindow.Present();
+ // this.Hide();
+ RootNoteBook.CurrentPage = PageSettings;
+ }
+
+ private void OnSettingsClosed(object sender, EventArgs e)
+ {
+ // this.ShowAll();
+ // this.Present();
+ // _settingsWindow.Hide();
+ RootNoteBook.CurrentPage = PageSplash;
+ }
+
+ private async void StartAutoDetectOnLoad()
+ {
+ // Lock down splash options until we know the device state.
+ OnArduinoConnectionChanged(false);
+
+ string found = await _arduino.DetectPortAsync();
+
+ if (found != null)
+ _arduino.Connect(found); // fires ConnectionChanged(true) -> unlocks options
+ else
+ OnArduinoConnectionChanged(false); // still no device -> stays locked unless debug
+ }
+
+ private void OnArduinoConnectionChanged(bool connected)
+ {
+ _connected = connected;
+
+ // Debug mode bypasses the "device required" restriction entirely.
+ bool allowFullAccess = connected || AppConfig.DebugMode;
+
+ Option1Button.Sensitive = allowFullAccess;
+ Option2Button.Sensitive = allowFullAccess;
+ Option3Button.Sensitive = allowFullAccess;
+ // SettingButton.Sensitive = true; // always reachable, device or not
+
+ if (ConnectionAlertLabel != null)
+ {
+ ConnectionAlertLabel.Visible = !connected;
+ var ctx = ConnectionAlertLabel.StyleContext;
+ if (connected) ctx.RemoveClass("alert");
+ else ctx.AddClass("alert");
+ }
+
+ if (connected || AppConfig.DebugMode) StopAutoRetry();
+ else StartAutoRetry();
+
+ if (ConnectionStatusLabel != null)
+ ConnectionStatusLabel.Text = connected
+ ? (_Language.IsEnglish ? "Connected" : "接続中")
+ : (_Language.IsEnglish ? "Not connected" : "未接続");
+ SetClass(ConnectionStatusLabel, "on", connected);
+ SetClass(StatusDot, "on", connected);
+
+ if (ConnectionIcon == null) return;
+
+ ConnectionIcon.SetFromIconName(
+ connected ? "network-transmit-receive" : "network-offline",
+ IconSize.Dnd);
+
+ ConnectionIcon.TooltipText = connected
+ ? _Language.Format("ConnectionIcon.Connected", _arduino.PortName)
+ : _Language["ConnectionIcon.Disconnected"];
+ }
+
+ private void StartAutoRetry()
+ {
+ if (_retryTimerId != 0) return;
+ _retryTimerId = GLib.Timeout.Add(RetryMs, OnRetryTick);
+ }
+
+ private void StopAutoRetry()
+ {
+ if (_retryTimerId != 0)
+ {
+ GLib.Source.Remove(_retryTimerId);
+ _retryTimerId = 0;
+ }
+ }
+
+ private bool OnRetryTick()
+ {
+ if (_arduino.IsOpen) { _retryTimerId = 0; return false; }
+ if (_probing) return true; // scan still running — don't stack them
+
+ _probing = true;
+ _arduino.DetectPortAsync().ContinueWith(t =>
+ {
+ string port = t.IsFaulted ? null : t.Result;
+ // DetectPortAsync runs off the UI thread; Connect() touches GLib.
+ Gtk.Application.Invoke((s, e) =>
+ {
+ _probing = false;
+ if (port != null && !_arduino.IsOpen)
+ _arduino.Connect(port); // fires ConnectionChanged(true)
+ });
+ });
+ return true;
+ }
+ private bool OnBatteryTick()
+ {
+ UpdateBattery();
+ return true; // keep polling
+ }
+
+ private void UpdateBattery()
+ {
+ if (BatteryArea == null) return;
+
+ _battery = BatteryMonitor.Read();
+
+ if (!_battery.Present) // desktop / dev machine — hide it entirely
+ {
+ if (BatteryBox != null) BatteryBox.Visible = false; else BatteryArea.Visible = false;
+ return;
+ }
+
+ string key = _battery.Full ? "BatteryIcon.Full"
+ : _battery.Charging ? "BatteryIcon.Charging"
+ : "BatteryIcon.Discharging";
+
+ BatteryArea.Visible = true;
+ if (BatteryBox != null) BatteryBox.Visible = true;
+ if (BatteryPercentLabel != null) BatteryPercentLabel.Text = _battery.Percent + "%";
+ BatteryArea.TooltipText = _Language.Format(key, _battery.Percent);
+ BatteryArea.QueueDraw();
+ }
+
+ private void OnBatteryDrawn(object o, DrawnArgs args)
+ {
+ DrawingArea area = (DrawingArea)o;
+ Cairo.Context cr = args.Cr;
+
+ double w = area.AllocatedWidth;
+ double h = area.AllocatedHeight;
+
+ Gdk.RGBA fg = area.StyleContext.GetColor(StateFlags.Normal);
+
+ double stroke = Math.Max(1.5, h * 0.07);
+ double nub = Math.Max(2.0, w * 0.055);
+ double gap = Math.Max(1.0, w * 0.02);
+
+ double bw = w - nub - gap - stroke;
+ double bh = Math.Min(h - stroke, bw * 0.52);
+ double bx = stroke / 2;
+ double by = (h - bh) / 2;
+ double r = bh * 0.20;
+
+ // shell
+ cr.LineWidth = stroke;
+ cr.SetSourceRGBA(fg.Red, fg.Green, fg.Blue, fg.Alpha);
+ RoundedRect(cr, bx, by, bw, bh, r);
+ cr.Stroke();
+
+ // terminal
+ double th = bh * 0.42;
+ cr.Rectangle(bx + bw + gap, (h - th) / 2, nub, th);
+ cr.Fill();
+
+ // level fill
+ double pad = stroke * 1.4;
+ double ix = bx + pad, iy = by + pad;
+ double iw = bw - 2 * pad, ih = bh - 2 * pad;
+ double pct = Math.Max(0, Math.Min(100, _battery.Percent));
+ double fillW = iw * (pct / 100.0);
+
+ if (fillW > 0.5)
+ {
+ double fr, fgc, fb;
+ if (!_battery.Charging && pct <= 10) { fr = 0.78; fgc = 0.16; fb = 0.16; }
+ else if (!_battery.Charging && pct <= 25) { fr = 0.93; fgc = 0.62; fb = 0.09; }
+ else { fr = 0.18; fgc = 0.65; fb = 0.31; }
+
+ cr.Save();
+ RoundedRect(cr, ix, iy, iw, ih, Math.Max(0, r - pad * 0.5));
+ cr.Clip();
+ cr.NewPath();
+ cr.Rectangle(ix, iy, fillW, ih);
+ cr.SetSourceRGB(fr, fgc, fb);
+ cr.Fill();
+ cr.Restore();
+ }
+
+ // The percentage is shown by BatteryPercentLabel now; only the
+ // charging bolt is drawn inside the battery.
+ if (_battery.Charging)
+ {
+ double boltHeight = bh * 0.68, boltWidth = bh * 0.36;
+ cr.SetSourceRGB(1, 1, 1);
+ DrawBolt(cr, bx + (bw - boltWidth) / 2, by + (bh - boltHeight) / 2, boltWidth, boltHeight);
+ }
+ }
+
+ private static void RoundedRect(Cairo.Context cr, double x, double y,
+ double w, double h, double r)
+ {
+ cr.NewPath();
+ cr.Arc(x + w - r, y + r, r, -Math.PI / 2, 0);
+ cr.Arc(x + w - r, y + h - r, r, 0, Math.PI / 2);
+ cr.Arc(x + r, y + h - r, r, Math.PI / 2, Math.PI);
+ cr.Arc(x + r, y + r, r, Math.PI, 3 * Math.PI / 2);
+ cr.ClosePath();
+ }
+
+ private static void DrawBolt(Cairo.Context cr, double x, double y,
+ double w, double h)
+ {
+ cr.NewPath();
+ cr.MoveTo(x + w * 0.58, y);
+ cr.LineTo(x, y + h * 0.58);
+ cr.LineTo(x + w * 0.42, y + h * 0.58);
+ cr.LineTo(x + w * 0.32, y + h);
+ cr.LineTo(x + w, y + h * 0.40);
+ cr.LineTo(x + w * 0.56, y + h * 0.40);
+ cr.ClosePath();
+ cr.Fill();
+ }
+
+ private static string PickBatteryIcon(BatteryStatus b)
+ {
+ string level;
+ if (b.Percent >= 80) level = "full";
+ else if (b.Percent >= 50) level = "good";
+ else if (b.Percent >= 20) level = "low";
+ else if (b.Percent >= 10) level = "caution";
+ else level = "empty";
+
+ string name = b.Full ? "battery-full-charged"
+ : b.Charging ? "battery-" + level + "-charging"
+ : "battery-" + level;
+
+ return FirstAvailableIcon(name + "-symbolic", name, "battery");
+ }
+
+ private static string FirstAvailableIcon(params string[] names)
+ {
+ IconTheme theme = IconTheme.Default;
+ if (theme != null)
+ foreach (string n in names)
+ if (theme.HasIcon(n)) return n;
+
+ return names[names.Length - 1];
+ }
+
+ // ---------- localisation ----------
+
+ // private Dictionary LoadButtonText(string path)
+ // {
+ // var result = new Dictionary();
+
+ // if (!File.Exists(path))
+ // {
+ // Console.WriteLine($"Warning: text file not found: {path}");
+ // return result;
+ // }
+
+ // var lines = File.ReadAllLines(path);
+ // for (int i = 1; i < lines.Length; i++) // skip header row
+ // {
+ // var line = lines[i].Trim();
+ // if (string.IsNullOrEmpty(line)) continue;
+
+ // var parts = line.Split(new[] { ',' }, 2);
+ // if (parts.Length < 2) continue;
+
+ // result[parts[0]] = parts[1];
+ // }
+
+ // return result;
+ // }
+
+ // private void ApplyLanguage(bool isEnglish)
+ // {
+ // var text = isEnglish ? _engText : _jpnText;
+ // string cssPath = isEnglish ? EngCssPath : JpnCssPath;
+
+ // foreach (var kvp in _buttonsById)
+ // {
+ // if (text.TryGetValue(kvp.Key, out var buttonText))
+ // kvp.Value.Label = buttonText;
+ // }
+
+ // if (File.Exists(cssPath))
+ // _languageCssProvider.LoadFromPath(cssPath);
+ // else
+ // Console.WriteLine($"Warning: CSS file not found: {cssPath}");
+
+ // LanguageLabel.Text = isEnglish ? "あ" : "A";
+ // }
+
+ // ---------- scaling ----------
+
+ private void OnWindowSizeAllocated(object o, SizeAllocatedArgs args)
+ {
+ int width = args.Allocation.Width;
+ int height = args.Allocation.Height;
+
+ if (width == _lastAppliedWidth) return;
+ _lastAppliedWidth = width;
+
+ double scaleX = (double)width / BaseWidth;
+ double scaleY = (double)height / BaseHeight;
+
+ ApplyScale(Math.Min(scaleX, scaleY));
+ }
+
+ private void ApplyScale(double scale)
+ {
+ int fontSize = Math.Max(10, (int)(20 * scale));
+ int buttonPadV = Math.Max(4, (int)(12 * scale));
+ int buttonPadH = Math.Max(8, (int)(24 * scale));
+ int switchWidth = Math.Max(30, (int)(40 * scale));
+ int switchHeight= Math.Max(18, (int)(24 * scale));
+
+ // NOTE: integers + InvariantCulture. Interpolating a double here emitted
+ // "40,5px" under ja_JP / de_DE locales and GTK silently dropped the rule.
+ string css = string.Format(CultureInfo.InvariantCulture, @"
+ grid, label, button, switch {{
+ font-size: {0}px;
+ }}
+ button {{
+ padding: {1}px {2}px;
+ }}
+ switch {{
+ min-width: {3}px;
+ min-height: {4}px;
+ }}
+ ", fontSize, buttonPadV, buttonPadH, switchWidth, switchHeight);
+
+ _scaleCssProvider.LoadFromData(css);
+ }
+
+ // ---------- lifecycle ----------
+
+ private void OnDeleteEvent(object sender, DeleteEventArgs a)
+ {
+ if (_mapWindow != null) _mapWindow.StopSession();
+ Application.Quit();
+ a.RetVal = true;
+ // Shutdown();
+ // a.RetVal = true;
+ }
+
+ private void OnCloseClicked(object sender, EventArgs e)
+ {
+ if (KioskMode && !ConfirmPowerOff()) return;
+ Shutdown();
+ }
+
+ private void Shutdown()
+ {
+ // _arduino.Disconnect();
+ // _arduino.Dispose();
+ // // _settingsWindow?.Destroy();
+ // Application.Quit();
+ // Release hardware before the OS starts killing things.
+ if (_mapWindow != null) _mapWindow.StopSession();
+ WavePlayer.Stop();
+ StopAutoRetry();
+ if (_batteryTimerId != 0) { GLib.Source.Remove(_batteryTimerId); _batteryTimerId = 0; }
+ _arduino.Disconnect();
+ _arduino.Dispose();
+
+ if (!KioskMode) { Application.Quit(); return; }
+
+ // CloseButton is the only label MainWindow itself owns on the splash page.
+ CloseButton.Label = _Language["Close.ShuttingDown"];
+ CloseButton.Sensitive = false;
+ Option1Button.Sensitive = false;
+ Option2Button.Sensitive = false;
+ Option3Button.Sensitive = false;
+ SettingButton.Sensitive = false;
+
+ // Return to the main loop so that repaint actually happens, then fire.
+ GLib.Timeout.Add(200, new GLib.TimeoutHandler(OnPowerOffTick));
+ }
+ private bool OnPowerOffTick()
+{
+ if (!RequestPowerOff())
+ {
+ Console.WriteLine("poweroff refused - quitting instead");
+ Application.Quit();
+ }
+ return false; // one shot
+}
+
+ private void OnNormalSessionClicked(object sender, EventArgs e)
+ {
+ Console.WriteLine("Normal Session selected");
+ RootNoteBook.CurrentPage = PageSound;
+ _soundWindow.Reset();
+ }
+
+ private void OnPositionRecordingClicked(object sender, EventArgs e)
+ {
+ Console.WriteLine("Position Recording Mode selected");
+ }
+
+ private void OnExamModeClicked(object sender, EventArgs e)
+ {
+ Console.WriteLine("Exam Mode selected");
+ }
+
+ private void OnLanguageToggled(object sender, EventArgs e)
+ {
+ _Language.Apply(LanguageToggle.Active);
+ }
+
+ // private void ApplyLanguageEverywhere(bool isEnglish)
+ // {
+ // Language.LanguageSwitchValue = isEnglish;
+ // _Language.ApplyLanguage(isEnglish);
+ // _settingsWindow?._Language?.ApplyLanguages(isEnglish);
+ // }
+
+ private void OnCaseSelected(object sender, CaseDefinition def)
+ {
+ // _mapWindow.ShowCase(
+ // string.Join(" : ", def.TreePath), // no DisplayName on CaseDefinition
+ // SoundWindow.AppFile("body/front.png"),
+ // SoundWindow.AppFile(def.MapFront),
+ // SoundWindow.AppFile(def.SoundPath));
+
+ // RootNoteBook.CurrentPage = PageMap;
+ _mapWindow.ShowCase(def, _Language.Path(def.TreePath, " : "));
+ RootNoteBook.CurrentPage = PageMap;
+ }
+
+ private void OnMapClosed(object sender, EventArgs e)
+ {
+ RootNoteBook.CurrentPage = PageSound; // back to disease list
+ }
+
+ // ---------- power ----------
+
+ // Same master switch the boot scripts read. On a dev box the flag is absent,
+ // so Close just exits the app instead of killing your machine.
+ private static bool KioskMode
+ {
+ get
+ {
+ // string home = System.Environment.GetEnvironmentVariable("HOME");
+ // if (string.IsNullOrEmpty(home)) return false;
+ // return System.IO.File.Exists(
+ // System.IO.Path.Combine(home, "kiosk/enabled"));
+ try
+ {
+ string cmdline = System.IO.File.ReadAllText("/proc/cmdline");
+ foreach (string arg in cmdline.Split(new[] { ' ', '\n' },
+ StringSplitOptions.RemoveEmptyEntries))
+ if (arg == "kiosk") return true;
+ }
+ catch { }
+ return false;
+ }
+ }
+
+ private bool ConfirmPowerOff()
+ {
+ var dlg = new Dialog();
+ dlg.Name = "PowerOffDialog";
+ dlg.TransientFor = this;
+ dlg.Modal = true;
+ dlg.Decorated = false; // matchbox gives no useful frame
+ dlg.TypeHint = Gdk.WindowTypeHint.Dialog;
+ dlg.WindowPosition = WindowPosition.CenterOnParent;
+ dlg.SetDefaultSize(780, 320);
+
+ var msg = new Label(_Language["Close.ConfirmPowerOff"]);
+ msg.Name = "PowerOffMessage";
+ msg.LineWrap = true;
+ msg.LineWrapMode = Pango.WrapMode.WordChar;
+ msg.Justify = Justification.Center;
+
+ Box content = dlg.ContentArea;
+ content.Spacing = 0;
+ content.PackStart(msg, true, true, 0);
+
+ var cancel = (Button)dlg.AddButton(_Language["Common.Cancel"], (int)ResponseType.Cancel);
+ var ok = (Button)dlg.AddButton(_Language["Common.PowerOff"], (int)ResponseType.Ok);
+ cancel.Name = "PowerOffCancel";
+ ok.Name = "PowerOffConfirm";
+ dlg.DefaultResponse = ResponseType.Cancel;
+
+ dlg.ShowAll();
+ ResponseType r = (ResponseType)dlg.Run();
+ dlg.Destroy();
+ return r == ResponseType.Ok;
+ }
+
+
+ private static bool RequestPowerOff()
+ {
+ if (Spawn("systemctl", "poweroff")) return true; // logind + polkit
+ if (Spawn("sudo", "-n /sbin/poweroff")) return true; // sudoers fallback
+ return false;
+ }
+ private static bool Spawn(string exe, string args)
+ {
+ try
+ {
+ var psi = new System.Diagnostics.ProcessStartInfo(exe, args);
+ psi.UseShellExecute = false;
+ var proc = System.Diagnostics.Process.Start(psi);
+ if (proc == null) return false;
+ if (!proc.WaitForExit(5000)) return true; // still running = request accepted
+ return proc.ExitCode == 0;
+ }
+ catch { return false; }
+ }
+
+ private static void SetModeIcon(Button b, ModeIcon.Kind kind)
+ {
+ var icon = new ModeIcon(kind, 96);
+ icon.Show();
+ b.Image = icon; // Language still sets the label text.
+ // always-show-image / image-position are set in the glade
+ // (this GTK# version has no AlwaysShowImage property).
+ }
+
+ private static Widget PlainIcon(ModeIcon.Kind kind, int size)
+ {
+ var icon = new ModeIcon(kind, size, false, 10, 1, 1, 1); // white, 10px gap
+ icon.Show();
+ return icon;
+ }
+
+ private static void SetClass(Widget w, string cls, bool on)
+ {
+ if (w == null) return;
+ if (on) w.StyleContext.AddClass(cls); else w.StyleContext.RemoveClass(cls);
+ }
+
+
+}
\ No newline at end of file
diff --git a/program/MapAudio.cs b/program/MapAudio.cs
new file mode 100644
index 0000000..4150f7b
--- /dev/null
+++ b/program/MapAudio.cs
@@ -0,0 +1,105 @@
+using System;
+using System.Runtime.InteropServices;
+
+/// Form2.AnalyzeColorScheme, ported to Gdk.Pixbuf.
+public static class MapAudio
+{
+ public const int MIN_INTENSITY = 50;
+ public const int DOMINANCE_THRESHOLD = 30;
+ public const int MIN_PURITY = 40;
+ public const int BLACK_THRESHOLD = 40;
+ public const int BLACK_PIXEL_CONSTANT_VOLUME = 51; // 20% of 255
+
+ public enum Region { None, Black, Red, Blue }
+
+ public class Result
+ {
+ public Region Region;
+ public bool Play;
+ public int Level; // 0..255, feeds AudioEngine.VolumeCurve
+ public byte R, G, B, A;
+ }
+
+ /// Reads one pixel out of a pixbuf. False if out of bounds.
+ public static bool ReadPixel(Gdk.Pixbuf pb, int x, int y,
+ out byte r, out byte g, out byte b, out byte a)
+ {
+ r = g = b = 0; a = 255;
+ if (pb == null) return false;
+ if (x < 0 || y < 0 || x >= pb.Width || y >= pb.Height) return false;
+
+ int n = pb.NChannels;
+ IntPtr p = pb.Pixels + y * pb.Rowstride + x * n;
+
+ r = Marshal.ReadByte(p, 0);
+ g = Marshal.ReadByte(p, 1);
+ b = Marshal.ReadByte(p, 2);
+ a = (n >= 4) ? Marshal.ReadByte(p, 3) : (byte)255;
+ return true;
+ }
+
+ public static Result Analyze(Gdk.Pixbuf map, int px, int py, bool blackAudioEnabled)
+ {
+ var res = new Result { Region = Region.None, Play = false, Level = 0 };
+
+ byte r, g, b, a;
+ if (!ReadPixel(map, px, py, out r, out g, out b, out a))
+ return res;
+
+ res.R = r; res.G = g; res.B = b; res.A = a;
+
+ int max = Math.Max(Math.Max(r, g), b);
+ int min = Math.Min(Math.Min(r, g), b);
+ int purity = max - min;
+
+ // LoadMap keys out black with AddAlpha, so background arrives as
+ // alpha 0, not RGB(0,0,0). This test has to come first or every
+ // background hit reads as a valid colour.
+ bool isBackground = a < 128 || max < BLACK_THRESHOLD;
+
+ if (isBackground)
+ {
+ res.Region = Region.Black;
+ if (blackAudioEnabled)
+ {
+ res.Play = true;
+ res.Level = BLACK_PIXEL_CONSTANT_VOLUME;
+ }
+ return res;
+ }
+
+ // RED — heart territory
+ if (r >= MIN_INTENSITY &&
+ r > g + DOMINANCE_THRESHOLD &&
+ r > b + DOMINANCE_THRESHOLD &&
+ purity >= MIN_PURITY)
+ {
+ res.Region = Region.Red;
+ res.Play = true;
+ res.Level = LevelFrom(r);
+ return res;
+ }
+
+ // BLUE — breath territory
+ if (b >= MIN_INTENSITY &&
+ b > r + DOMINANCE_THRESHOLD &&
+ b > g + DOMINANCE_THRESHOLD &&
+ purity >= MIN_PURITY)
+ {
+ res.Region = Region.Blue;
+ res.Play = true;
+ res.Level = LevelFrom(b);
+ return res;
+ }
+
+ return res; // unassigned colour -> silence
+ }
+
+ /// Form2: intensity 50..255 maps to volume level 80..255.
+ private static int LevelFrom(int intensity)
+ {
+ float t = (intensity - MIN_INTENSITY) / (255.0f - MIN_INTENSITY);
+ int level = (int)(80 + t * 175);
+ return Math.Max(80, Math.Min(255, level));
+ }
+}
\ No newline at end of file
diff --git a/program/MapWindow.cs b/program/MapWindow.cs
new file mode 100644
index 0000000..8c12384
--- /dev/null
+++ b/program/MapWindow.cs
@@ -0,0 +1,2564 @@
+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 _tunes = new Dictionary();
+ 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 _regions = new List();
+ 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 _highlighted = new List();
+ private static bool _listed;
+
+ // ── tuner state ──
+ private Window _tuner;
+ private TextView _tunerOut;
+ private Label _tunerInfo, _tunerKey;
+ private readonly Dictionary _spins = new Dictionary();
+ 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);
+ foreach (string id in new[] {
+ "BodySectionLabel","BodySkeletonRadio","BodyJacketRadio","JacketSizeLabel",
+ "ViewSectionLabel","ViewFrontRadio","ViewBackRadio","ViewRightRadio","ViewLeftRadio",
+ "DisplaySectionLabel","ShowNumbersSwitchLabel","ShowVolumeMapSwitchLabel",
+ "ShowPointListSwitchLabel","BlackAudioSwitchLabel","SoundFilterSectionLabel",
+ "SoundMixRadio","SoundHeartOnlyRadio","SoundLungOnlyRadio","MapPointHeader",
+ "HeartWaveHeader","BreathWaveHeader","MapExplainButton" })
+ _lang.Register(id, builder.GetObject(id) as Widget); // null-safe
+
+ // ── 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);
+ AudioOutput.OutputChanged += OnOutputChanged;
+ if (SoundTestButton != null)
+ {
+ SoundTestButton.Clicked += (s, e) => ToggleOutput();
+ UpdateOutputButton(AudioOutput.Current(), null);
+ }
+ _lang.Changed += (s, e) => { RefreshCaseTitle(); 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();
+ };
+
+ // Touch (or mouse): hold a finger on the map to hear that spot.
+ // Works in every mode, alongside the RFID chest piece.
+ MapArea.ButtonPressEvent += (o, a) =>
+ {
+ if (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 ─────────────────────────────────────────────────────
+
+ /// Re-translates the title when the language is switched while a case is open.
+ private void RefreshCaseTitle()
+ {
+ if (_case == null || _lang == null) return;
+ string t = _lang.Path(_case.TreePath, " : ");
+ MapTitleLabel.Text = t;
+ MapCaseLabel.Text = t;
+ }
+
+ 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
+ // 解説を見る: hidden when the case only has the placeholder image C999.png
+ if (MapExplainButton != null)
+ {
+ string manual = def.ManualFile ?? "";
+ bool placeholder = System.IO.Path.GetFileName(manual)
+ .Equals("C999.png", StringComparison.OrdinalIgnoreCase);
+ MapExplainButton.NoShowAll = true; // keeps ShowAll() from showing it again
+ MapExplainButton.Visible = !placeholder;
+ }
+ 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();
+ 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(_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 = "" + text + "";
+ 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 = "Editing: " + TuneKey + "";
+ _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_)?(?FRONT|BACK|RIGHT|LEFT)_" +
+ @"(?OFFSET_X|OFFSET_Y|SIZE|CLUSTER|FIT_MARGIN|MAP_ZOOM|MAP_X|MAP_Y|MAP_ALPHA)" +
+ @"\s*=\s*(?-?[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();
+
+ 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(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();
+ var colors = new List();
+ var present = new List();
+ var allowed = new List();
+ var levels = new List();
+
+ if (AppMode.Legacy)
+ {
+ for (int k = 0; k < 7; k++)
+ {
+ RegionSound r = _regions.Find(rs => rs.Index == k);
+ byte[] c = RegionColors[k];
+ labels.Add(_lang != null ? _lang.Name(RegionLabels[k]) : 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();
+ }
+ private void OnOutputChanged()
+ {
+ if (!AppMode.Legacy || _case == null) return;
+ LoadRegions(_case); // re-warms with the right files
+ var group = new List();
+ foreach (var r in _regions) group.Add(r.Voice);
+ _sound.RestartTogether(group);
+ _playClock.Restart();
+ UpdateAudioFromPosition();
+ }
+}
\ No newline at end of file
diff --git a/program/ModeIcon.cs b/program/ModeIcon.cs
new file mode 100644
index 0000000..7e11483
--- /dev/null
+++ b/program/ModeIcon.cs
@@ -0,0 +1,176 @@
+using System;
+using Gtk;
+
+/// Line icons drawn with Cairo, so they never depend on the icon theme or
+/// an SVG loader being installed.
+///
+/// new ModeIcon(kind, 96) mode buttons: white icon on a
+/// translucent rounded plate
+/// new ModeIcon(kind, 32, false, 10, r, g, b) plain icon in any colour
+/// (設定 / 終了 / 戻る / 再生)
+public class ModeIcon : DrawingArea
+{
+ public enum Kind { Stethoscope, BodyTarget, Chart, Cog, Power, Back, Play }
+
+ private readonly Kind _kind;
+ private readonly bool _plate;
+ private readonly int _gap; // space reserved between icon and label
+ private readonly double _r, _g, _b; // stroke colour
+
+ /// Mode-button style: plate + white glyph + 28px gap.
+ public ModeIcon(Kind kind, int size) : this(kind, size, true, 28, 1, 1, 1) { }
+
+ public ModeIcon(Kind kind, int size, bool plate, int gap, double r, double g, double b)
+ {
+ _kind = kind; _plate = plate; _gap = gap;
+ _r = r; _g = g; _b = b;
+ // GTK ignores CSS margins on a button's image, so the gap is part of the icon.
+ SetSizeRequest(size + gap, size);
+ Drawn += OnDrawn;
+ }
+
+ private void OnDrawn(object o, DrawnArgs args)
+ {
+ var cr = args.Cr;
+ double w = AllocatedWidth - _gap, h = AllocatedHeight, s = Math.Min(w, h);
+ double x0 = 0, y0 = (h - s) / 2;
+
+ double k;
+ if (_plate)
+ {
+ double r = s * 0.27;
+ cr.NewPath();
+ cr.Arc(x0 + s - r, y0 + r, r, -Math.PI / 2, 0);
+ cr.Arc(x0 + s - r, y0 + s - r, r, 0, Math.PI / 2);
+ cr.Arc(x0 + r, y0 + s - r, r, Math.PI / 2, Math.PI);
+ cr.Arc(x0 + r, y0 + r, r, Math.PI, 3 * Math.PI / 2);
+ cr.ClosePath();
+ cr.SetSourceRGBA(1, 1, 1, 0.18);
+ cr.Fill();
+ k = s * 0.58 / 24.0;
+ }
+ else
+ {
+ k = s / 24.0;
+ }
+
+ cr.Save();
+ cr.Translate(x0 + (s - 24 * k) / 2, y0 + (s - 24 * k) / 2);
+ cr.Scale(k, k);
+ cr.LineWidth = _plate ? 1.8 : 2.2;
+ cr.LineCap = Cairo.LineCap.Round;
+ cr.LineJoin = Cairo.LineJoin.Round;
+ cr.SetSourceRGB(_r, _g, _b);
+
+ switch (_kind)
+ {
+ case Kind.Stethoscope: Stethoscope(cr); break;
+ case Kind.BodyTarget: BodyTarget(cr); break;
+ case Kind.Chart: Chart(cr); break;
+ case Kind.Cog: Cog(cr); break;
+ case Kind.Power: Power(cr); break;
+ case Kind.Back: Back(cr); break;
+ case Kind.Play: Play(cr); break;
+ }
+ cr.Stroke();
+ cr.Restore();
+
+ args.RetVal = true;
+ }
+
+ // earpieces, binaurals, tubing, chest piece
+ private static void Stethoscope(Cairo.Context cr)
+ {
+ cr.MoveTo(4, 3); cr.LineTo(6, 3);
+ cr.MoveTo(14, 3); cr.LineTo(16, 3);
+ cr.MoveTo(5, 3); cr.LineTo(5, 8);
+ cr.ArcNegative(10, 8, 5, Math.PI, 0); // U-bend to (15,8)
+ cr.LineTo(15, 3);
+ cr.MoveTo(10, 13); cr.LineTo(10, 15.5);
+ cr.ArcNegative(15, 15.5, 5, Math.PI, 0); // tubing to (20,15.5)
+ cr.LineTo(20, 12.5);
+ cr.NewSubPath();
+ cr.Arc(20, 10.5, 2, 0, 2 * Math.PI); // chest piece
+ }
+
+ // torso with an auscultation target on the chest
+ private static void BodyTarget(Cairo.Context cr)
+ {
+ cr.MoveTo(9.5, 3.5); // neckline
+ cr.CurveTo(9.9, 4.7, 10.8, 5.4, 12, 5.4);
+ cr.CurveTo(13.2, 5.4, 14.1, 4.7, 14.5, 3.5);
+ cr.MoveTo(9.5, 3.5); // body outline
+ cr.LineTo(5.5, 5.3); cr.LineTo(3.5, 11); cr.LineTo(6.1, 12);
+ cr.LineTo(7, 9.5); cr.LineTo(7, 21); cr.LineTo(17, 21);
+ cr.LineTo(17, 9.5); cr.LineTo(17.9, 12); cr.LineTo(20.5, 11);
+ cr.LineTo(18.5, 5.3); cr.LineTo(14.5, 3.5);
+ cr.NewSubPath();
+ cr.Arc(12, 13, 2, 0, 2 * Math.PI); // target
+ cr.MoveTo(12, 9.8); cr.LineTo(12, 10.8);
+ cr.MoveTo(12, 15.2); cr.LineTo(12, 16.2);
+ cr.MoveTo(8.8, 13); cr.LineTo(9.8, 13);
+ cr.MoveTo(14.2, 13); cr.LineTo(15.2, 13);
+ }
+
+ // clipboard chart with a check and answer lines
+ private static void Chart(Cairo.Context cr)
+ {
+ cr.Rectangle(9, 3, 6, 3); // clip
+ cr.MoveTo(7, 4.5); cr.LineTo(6, 4.5); // board
+ cr.ArcNegative(6, 5.5, 1, -Math.PI / 2, -Math.PI);
+ cr.LineTo(5, 20);
+ cr.ArcNegative(6, 20, 1, Math.PI, Math.PI / 2);
+ cr.LineTo(18, 21);
+ cr.ArcNegative(18, 20, 1, Math.PI / 2, 0);
+ cr.LineTo(19, 5.5);
+ cr.ArcNegative(18, 5.5, 1, 0, -Math.PI / 2);
+ cr.LineTo(17, 4.5);
+ cr.MoveTo(8.5, 11); cr.LineTo(10.3, 12.8); cr.LineTo(14, 9); // check
+ cr.MoveTo(8.5, 16.5); cr.LineTo(15.5, 16.5);
+ cr.MoveTo(8.5, 19); cr.LineTo(13, 19);
+ }
+
+ // cog wheel: 8 trapezoid teeth around a ring, hole in the middle
+ private static void Cog(Cairo.Context cr)
+ {
+ const int teeth = 8;
+ const double cx = 12, cy = 12, rOut = 10.5, rIn = 8;
+ double step = 2 * Math.PI / teeth;
+ double halfOut = step * 0.20, halfIn = step * 0.30;
+
+ for (int i = 0; i < teeth; i++)
+ {
+ double a = i * step - Math.PI / 2;
+ double a1 = a - halfIn, a2 = a - halfOut, a3 = a + halfOut, a4 = a + halfIn;
+ if (i == 0) cr.MoveTo(cx + rIn * Math.Cos(a1), cy + rIn * Math.Sin(a1));
+ else cr.LineTo(cx + rIn * Math.Cos(a1), cy + rIn * Math.Sin(a1));
+ cr.LineTo(cx + rOut * Math.Cos(a2), cy + rOut * Math.Sin(a2));
+ cr.LineTo(cx + rOut * Math.Cos(a3), cy + rOut * Math.Sin(a3));
+ cr.LineTo(cx + rIn * Math.Cos(a4), cy + rIn * Math.Sin(a4));
+ cr.Arc(cx, cy, rIn, a4, a + step - halfIn); // ring to the next tooth
+ }
+ cr.ClosePath();
+ cr.NewSubPath();
+ cr.Arc(cx, cy, 3.2, 0, 2 * Math.PI);
+ }
+
+ // power symbol
+ private static void Power(Cairo.Context cr)
+ {
+ cr.Arc(12, 13, 8.5, -Math.PI / 2 + 0.75, 3 * Math.PI / 2 - 0.75);
+ cr.MoveTo(12, 2.5); cr.LineTo(12, 11.5);
+ }
+
+ // ‹ chevron
+ private static void Back(Cairo.Context cr)
+ {
+ cr.MoveTo(15, 5); cr.LineTo(8, 12); cr.LineTo(15, 19);
+ }
+
+ // ▶ outline
+ private static void Play(Cairo.Context cr)
+ {
+ cr.MoveTo(7, 4.5); cr.LineTo(19.5, 12); cr.LineTo(7, 19.5);
+ cr.ClosePath();
+ }
+}
diff --git a/program/RegionSound.cs b/program/RegionSound.cs
new file mode 100644
index 0000000..7cd495b
--- /dev/null
+++ b/program/RegionSound.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Runtime.InteropServices;
+
+public class RegionSound : IDisposable
+{
+ /// Pixels below this are silent AND not drawn in the overlay, so what you
+ /// see is where you can hear it. Adjustable live in the tuner (Ctrl+T).
+ public static int MinIntensity = 12;
+
+ public int Index; // 0,1 = heart; 2..6 = breath
+ public string Name;
+ public string SoundPath; // for the legend / waveform
+ public Gdk.Pixbuf Map; // raw, NOT black-keyed — audio reference
+ public AudioEngine.Voice Voice; // owned by AudioEngine's cache
+ public WaveData Wave; // waveform of this region's sound (may be null)
+ public float Volume;
+ public bool Enabled = true;
+
+ private byte[] _px;
+ private int _w, _h, _stride, _ch;
+
+ public bool IsHeart { get { return Index <= 1; } }
+
+ public void CachePixels()
+ {
+ if (Map == null) return;
+ _w = Map.Width; _h = Map.Height;
+ _stride = Map.Rowstride; _ch = Map.NChannels;
+
+ int len = _stride * (_h - 1) + _w * _ch; // last row is short — don't overrun
+ _px = new byte[len];
+ Marshal.Copy(Map.Pixels, _px, 0, len);
+ }
+
+ /// u,v are 0..1 across the map, from MapWindow.BodyToMapUV.
+ public int IntensityAt(double u, double v)
+ {
+ if (_px == null) return 0;
+ int x = (int)(u * _w), y = (int)(v * _h);
+ if (x < 0 || y < 0 || x >= _w || y >= _h) return 0;
+
+ int i = y * _stride + x * _ch;
+ if (i + 2 >= _px.Length) return 0;
+
+ byte r = _px[i], b = _px[i + 2];
+ return r != 0 ? r : b; // Python: R if R != 0 else B
+ }
+
+ /// Python's (v/255)^(1/9.5) is only the first step of Form2's curve; the
+ /// result is then converted through decibels (AudioEngine.VolumeCurve).
+ /// Using the first step directly as the gain made a pixel value of 1 play
+ /// at 56% — the faint edge of every map was almost full volume.
+ public float VolumeAt(double u, double v)
+ {
+ if (!Enabled) return 0f;
+ int val = IntensityAt(u, v);
+ if (val < MinIntensity) return 0f;
+
+ float vol = AudioEngine.VolumeCurve(val);
+ if (!IsHeart) vol *= 0.5f; // Python: breath halved
+ return Math.Max(0f, Math.Min(1f, vol));
+ }
+
+ public void Dispose()
+ {
+ if (Map != null) { Map.Dispose(); Map = null; }
+ _px = null;
+ Voice = null; // engine keeps and reuses it
+ Wave = null;
+ }
+}
\ No newline at end of file
diff --git a/program/SettingWindow.cs b/program/SettingWindow.cs
new file mode 100644
index 0000000..f091c74
--- /dev/null
+++ b/program/SettingWindow.cs
@@ -0,0 +1,217 @@
+using System;
+using Gtk;
+using System.Collections.Generic;
+using UI = Gtk.Builder.ObjectAttribute;
+
+public class SettingsWindow
+{
+ [UI] private Label ComPortLabel = null;
+ [UI] private ComboBoxText ComPortComboBox = null;
+ [UI] private Button ConnectButton = null;
+ [UI] private Button AutoConnectButton = null;
+ [UI] private Button RefreshButton = null;
+ [UI] private Button SettingBackButton = null;
+ [UI] private Label StatusLabel = null;
+ [UI] private Label LogLabel = null;
+ [UI] private TextView LogtextBox = null;
+
+ // private readonly Dictionary _buttonsById;
+ // private readonly Dictionary _labelsById;
+ // internal Language _Language;
+ private readonly Language _lang;
+ private bool _connected;
+
+ private const int MaxLogLines = 500;
+
+ private readonly ArduinoConnection _arduino;
+ private string[] _ports = new string[0];
+
+ /// Raised after the window hides itself, so the caller can re-show the main window.
+ public event EventHandler BackRequested;
+
+
+ public SettingsWindow(Builder builder, ArduinoConnection arduino, Language language)
+ {
+ builder.Autoconnect(this);
+ _arduino = arduino;
+ _lang = language;
+
+ // Title = "Settings";
+ // ComPortLabel.Text = "COM Port";
+ // LogLabel.Text = "Log";
+ LogtextBox.Editable = false;
+ LogtextBox.WrapMode = WrapMode.WordChar;
+
+ RefreshButton.Clicked += (s, e) => RefreshPorts();
+ ConnectButton.Clicked += OnConnectClicked;
+ AutoConnectButton.Clicked += OnAutoConnectClicked;
+ SettingBackButton.Clicked += OnBackClicked;
+
+ // DeleteEvent += (o, a) => { a.RetVal = true; OnBackClicked(o, EventArgs.Empty); };
+
+ _arduino.Log += AppendLog;
+ _arduino.LineReceived += OnLineReceived;
+ _arduino.ConnectionChanged += OnConnectionChanged;
+
+ _lang.Register("ComPortLabel", ComPortLabel);
+ _lang.Register("LogLabel", LogLabel);
+ _lang.Register("AutoConnectButton", AutoConnectButton);
+ _lang.Register("RefreshButton", RefreshButton);
+ _lang.Register("SettingBackButton", SettingBackButton);
+ _lang.RegisterDynamic("ConnectButton", ConnectButton); // set in OnConnectionChanged
+ _lang.RegisterDynamic("StatusLabel", StatusLabel);
+ _lang.Changed += (s, e) => OnConnectionChanged(_connected);
+
+ // _buttonsById = new Dictionary
+ // {
+ // { "ConnectButton", ConnectButton },
+ // { "AutoConnectButton", AutoConnectButton },
+ // { "RefreshButton", RefreshButton },
+ // { "BackButton", BackButton },
+ // };
+
+ // // CSS ID selectors (#Option1Button etc.) need the widget Name set explicitly
+ // foreach (var kvp in _buttonsById)
+ // kvp.Value.Name = kvp.Key;
+
+ // _Language = new Language(_buttonsById);
+ // // _Language.ApplyLanguages(Language.LanguageSwitchValue);
+
+ RefreshPorts();
+ OnConnectionChanged(_arduino.IsOpen);
+ }
+
+ // ---------- UI actions ----------
+
+ private void RefreshPorts()
+ {
+ ComPortComboBox.RemoveAll();
+ _ports = ArduinoConnection.ListPorts();
+
+ foreach (string p in _ports)
+ ComPortComboBox.AppendText(p);
+
+ if (_ports.Length > 0)
+ {
+ ComPortComboBox.Active = 0;
+ AppendLog(_lang.Format("Log.PortsFound", _ports.Length));
+ }
+ else
+ {
+ AppendLog(_lang["Log.NoPorts"]);
+ }
+ }
+
+ private void OnConnectClicked(object sender, EventArgs e)
+ {
+ if (_arduino.IsOpen)
+ {
+ _arduino.Disconnect();
+ return;
+ }
+
+ string port = ComPortComboBox.ActiveText;
+ if (string.IsNullOrEmpty(port))
+ {
+ AppendLog(_lang["Log.SelectPort"]);
+ return;
+ }
+ _arduino.Connect(port);
+ }
+
+ private async void OnAutoConnectClicked(object sender, EventArgs e)
+ {
+ AutoConnectButton.Sensitive = false;
+ ConnectButton.Sensitive = false;
+ AppendLog(_lang["Log.Scanning"]);
+
+ string found = await _arduino.DetectPortAsync();
+
+ if (found != null)
+ {
+ RefreshPorts();
+ SelectPort(found);
+ _arduino.Connect(found);
+ }
+ else
+ {
+ AppendLog(_lang["Log.DeviceNotFound"]);
+ }
+
+ AutoConnectButton.Sensitive = true;
+ ConnectButton.Sensitive = true;
+ }
+
+ private void OnBackClicked(object sender, EventArgs e)
+ {
+ // Hide();
+ BackRequested?.Invoke(this, EventArgs.Empty);
+ }
+
+ private void SelectPort(string portName)
+ {
+ for (int i = 0; i < _ports.Length; i++)
+ {
+ if (_ports[i] == portName)
+ {
+ ComPortComboBox.Active = i;
+ return;
+ }
+ }
+ }
+
+ // ---------- device events ----------
+
+ private void OnConnectionChanged(bool connected)
+ {
+ _connected = connected;
+
+ ConnectButton.Label = connected
+ ? _lang["ConnectButton.Disconnect"]
+ : _lang["ConnectButton.Connect"];
+
+ StatusLabel.Text = connected
+ ? _lang.Format("StatusLabel.Connected", _arduino.PortName)
+ : _lang["StatusLabel.Disconnected"];
+
+ ComPortComboBox.Sensitive = !connected;
+ RefreshButton.Sensitive = !connected;
+
+ StyleContext ctx = StatusLabel.StyleContext;
+ ctx.RemoveClass(connected ? "status-off" : "status-on");
+ ctx.AddClass(connected ? "status-on" : "status-off");
+ }
+
+ private void OnLineReceived(string line)
+ {
+ // Same filtering Form2.cs applied before parsing.
+ if (line.StartsWith("Send Status:")) return;
+ if (line.StartsWith("\u2713") || line.StartsWith("\u2717")) return;
+
+ if (line.Contains("ESPNOW_CONNECTED")) { AppendLog(_lang["Log.EspNowConnected"]); return; }
+ if (line.Contains("ESPNOW_DISCONNECTED")) { AppendLog(_lang["Log.EspNowDisconnected"]); return; }
+
+ AppendLog(line);
+ }
+
+ // ---------- log ----------
+
+ public void AppendLog(string message)
+ {
+ TextBuffer buf = LogtextBox.Buffer;
+
+ TextIter end = buf.EndIter;
+ buf.Insert(ref end, $"[{DateTime.Now:HH:mm:ss.fff}] {message}\n");
+
+ if (buf.LineCount > MaxLogLines)
+ {
+ TextIter start = buf.StartIter;
+ TextIter cut = buf.GetIterAtLine(buf.LineCount - MaxLogLines);
+ buf.Delete(ref start, ref cut);
+ }
+
+ TextMark mark = buf.CreateMark(null, buf.EndIter, false);
+ LogtextBox.ScrollToMark(mark, 0, false, 0, 0);
+ buf.DeleteMark(mark);
+ }
+}
\ No newline at end of file
diff --git a/program/SoundLooper.cs b/program/SoundLooper.cs
new file mode 100644
index 0000000..311d4b6
--- /dev/null
+++ b/program/SoundLooper.cs
@@ -0,0 +1,165 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Media;
+using System.Threading;
+
+public class SoundLooper : IDisposable
+{
+ // ── unix backend ──
+ private Process _proc;
+ private Thread _thread;
+ private volatile bool _running;
+ private string _path;
+
+ // ── windows backend ──
+ private SoundPlayer _player;
+
+ public event Action Log;
+
+ public bool IsPlaying { get { return _running; } }
+
+ private static bool IsWindows
+ {
+ get
+ {
+ var p = Environment.OSVersion.Platform;
+ return p != PlatformID.Unix && p != PlatformID.MacOSX;
+ }
+ }
+
+ public void Start(string wavPath)
+ {
+ Stop();
+
+ if (string.IsNullOrEmpty(wavPath) || !File.Exists(wavPath))
+ {
+ Emit("Sound file not found: " + wavPath);
+ return;
+ }
+
+ _path = wavPath;
+
+ if (IsWindows) StartWindows();
+ else StartUnix();
+ }
+
+ public void Stop()
+ {
+ if (!_running) return;
+ _running = false;
+
+ if (_player != null)
+ {
+ try { _player.Stop(); } catch { }
+ try { _player.Dispose(); } catch { }
+ _player = null;
+ }
+
+ try
+ {
+ var p = _proc;
+ if (p != null && !p.HasExited) p.Kill();
+ }
+ catch { }
+ _proc = null;
+
+ if (_thread != null && _thread.IsAlive) _thread.Join(500);
+ _thread = null;
+
+ Emit("Looping stopped");
+ }
+
+ // ── windows: SoundPlayer loops natively, no thread needed ──────────
+
+ private void StartWindows()
+ {
+ try
+ {
+ _player = new SoundPlayer(_path);
+ _player.Load(); // throws here if the WAV isn't plain PCM
+ _player.PlayLooping(); // gapless, runs until Stop()
+ _running = true;
+ Emit("Looping started (SoundPlayer): " + _path);
+ }
+ catch (Exception ex)
+ {
+ Emit("SoundPlayer failed for " + _path + ": " + ex.Message);
+ _player = null;
+ _running = false;
+ }
+ }
+
+ // ── unix: respawn a CLI player each pass ───────────────────────────
+
+ private void StartUnix()
+ {
+ _running = true;
+ _thread = new Thread(LoopWorker);
+ _thread.IsBackground = true;
+ _thread.Start();
+ Emit("Looping started (" + PlayerCommand() + "): " + _path);
+ }
+
+ private void LoopWorker()
+ {
+ while (_running)
+ {
+ try
+ {
+ var psi = new ProcessStartInfo
+ {
+ FileName = PlayerCommand(),
+ Arguments = "\"" + _path + "\"",
+ UseShellExecute = false,
+ RedirectStandardError = true,
+ RedirectStandardOutput = true,
+ CreateNoWindow = true
+ };
+
+ _proc = Process.Start(psi);
+ _proc.WaitForExit();
+ }
+ catch (Exception ex)
+ {
+ Emit("Playback error: " + ex.Message);
+ _running = false;
+ return;
+ }
+ }
+ }
+
+ private static string _player_cmd;
+ private static string PlayerCommand()
+ {
+ if (_player_cmd != null) return _player_cmd;
+ _player_cmd = Exists("paplay") ? "paplay" : "aplay";
+ return _player_cmd;
+ }
+
+ private static bool Exists(string cmd)
+ {
+ try
+ {
+ var p = Process.Start(new ProcessStartInfo
+ {
+ FileName = "which",
+ Arguments = cmd,
+ UseShellExecute = false,
+ RedirectStandardOutput = true
+ });
+ p.WaitForExit();
+ return p.ExitCode == 0;
+ }
+ catch { return false; }
+ }
+
+ private void Emit(string msg)
+ {
+ var h = Log;
+ if (h != null) h(msg);
+ else Console.WriteLine("[SoundLooper] " + msg);
+ }
+
+ public void Dispose() { Stop(); }
+}
\ No newline at end of file
diff --git a/program/SoundWindow.cs b/program/SoundWindow.cs
new file mode 100644
index 0000000..21def8c
--- /dev/null
+++ b/program/SoundWindow.cs
@@ -0,0 +1,556 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using Gtk;
+using UI = Gtk.Builder.ObjectAttribute;
+
+/// Controller for notebook page 2 (SoundBox). Not a Gtk.Window — same
+/// arrangement as SettingsWindow: it drives widgets inside the shared root.
+///
+/// Design "Mix":
+/// level 0 : 種別を選択 title + big icon tiles (one per top-level branch)
+/// level 1+ : the same tiles, small, as tabs + a 3-column grid of sounds
+public class SoundWindow
+{
+ [UI] private Label ConditionNameLabel = null;
+ [UI] private Grid SoundButtonGrid = null;
+ [UI] private Button SoundBackButton = null;
+ // NEW — optional, so an older glade without them still loads
+ [UI] private Box SoundTabBox = null;
+ [UI] private Label SoundSubtitleLabel = null;
+
+ private const int TopColumns = 2; // big tiles on level 0
+ private const int ListColumns = 3; // sound grid on level 1+
+ private const int ListRowsFit = 7; // more rows than this -> compact buttons
+ private const int TopTileHeight = 400;
+
+ // "fine crackle(捻髪音)" -> main "捻髪音", sub "fine crackle"
+ private static readonly Regex NameRx = new Regex(@"^(.*?)\((.*)\)\s*$", RegexOptions.Compiled);
+
+ // Subtitle per branch index (same index rule as the lung/heart colours)
+ private static readonly string[] BranchSubtitles = { "Breath sounds", "Heart sounds" };
+
+ private readonly List _allCases;
+ private readonly Language _lang;
+ private bool En { get { return _lang != null && _lang.IsEnglish; } }
+ private string Disp(string jp) { return _lang != null ? _lang.Name(jp) : jp; }
+
+ private readonly List _path = new List();
+
+ /// Raised when the drill-down reaches a leaf case.
+ public event EventHandler CaseSelected;
+
+ /// Raised when Back is pressed at the top level.
+ public event EventHandler BackRequested;
+
+ public SoundWindow(Builder builder, Language language)
+ {
+ _lang = language;
+ builder.Autoconnect(this);
+ if (ConditionNameLabel == null || SoundButtonGrid == null || SoundBackButton == null)
+ throw new InvalidOperationException(
+ "Glade id mismatch — ConditionNameLabel=" + (ConditionNameLabel != null) +
+ " SoundButtonGrid=" + (SoundButtonGrid != null) +
+ " SoundBackButton=" + (SoundBackButton != null));
+
+ // GTK3 Builder does not set the CSS name from the glade id — do it here
+ // so the #ConditionNameLabel / #SoundBackButton rules actually match.
+ ConditionNameLabel.Name = "ConditionNameLabel";
+ SoundButtonGrid.Name = "SoundButtonGrid";
+ SoundBackButton.Name = "SoundBackButton";
+ if (_lang != null) _lang.Register("SoundSubtitleLabel", SoundSubtitleLabel); // null-safe
+ else if (SoundSubtitleLabel != null) SoundSubtitleLabel.Name = "SoundSubtitleLabel";
+
+Console.WriteLine("SoundWindow ctor: AppMode.Legacy = " + AppMode.Legacy);
+ _allCases = AppMode.Legacy
+ ? CaseDefinition.LoadLegacyCasesFromCsv(AppMode.CasesCsv)
+ : CaseDefinition.LoadCasesFromCsv(AppMode.CasesCsv);
+
+ if (AppMode.Legacy && _lang != null)
+ _lang.AddNames(CaseDefinition.LoadLegacyEnglishNames(
+ AppMode.CasesCsv, AppFile("cases_old_eng.csv")));
+
+ if (_allCases.Count == 0)
+ Console.WriteLine("WARNING: no cases loaded — check " + AppMode.CasesCsv);
+
+ SoundBackButton.Clicked += OnBackClicked;
+ if (_lang != null) _lang.Changed += (s, e) => Render();
+ }
+
+ /// Call every time the page becomes visible.
+ public void Reset()
+ {
+ _path.Clear();
+ Render();
+ }
+
+ /// Resolve next to the .exe, NOT the working directory.
+ public static string AppFile(string relative)
+ {
+ string dir = Path.GetDirectoryName(
+ System.Reflection.Assembly.GetExecutingAssembly().Location);
+ return Path.Combine(dir, relative);
+ }
+
+ // ── one method covers all three levels ─────────────────────────────
+
+ private void Render()
+ {
+ var matches = _allCases.Where(MatchesPath).ToList();
+
+ // Distinct values one level deeper than where we currently are.
+ var options = matches
+ .Where(c => c.TreePath.Length > _path.Count)
+ .Select(c => c.TreePath[_path.Count])
+ .Distinct()
+ .ToList();
+
+ UpdateHeader();
+
+ BuildButtons(options, picked =>
+ {
+ _path.Add(picked);
+
+ // Landed on a leaf? Play it and stay put.
+ var leaf = _allCases.FirstOrDefault(
+ c => c.TreePath.Length == _path.Count && MatchesPath(c));
+
+ if (leaf != null)
+ {
+ Play(leaf);
+ _path.RemoveAt(_path.Count - 1);
+ return;
+ }
+
+ Render();
+ });
+ }
+
+ private bool MatchesPath(CaseDefinition c)
+ {
+ string[] p = c.TreePath;
+ if (p.Length < _path.Count) return false;
+ for (int i = 0; i < _path.Count; i++)
+ if (!string.Equals(p[i], _path[i], StringComparison.Ordinal)) return false;
+ return true;
+ }
+
+ // ── header: title on level 0, tile tabs + hint below that ──────────
+
+ private List TopLevel()
+ {
+ // Colour by branch index rather than a literal, so renaming or
+ // translating the CSV's top level doesn't silently turn everything blue.
+ return _allCases
+ .Where(c => c.TreePath.Length > 0)
+ .Select(c => c.TreePath[0])
+ .Distinct()
+ .ToList();
+ }
+
+ private int CaseCount(string branch)
+ {
+ return _allCases.Count(c => c.TreePath.Length > 0 &&
+ string.Equals(c.TreePath[0], branch, StringComparison.Ordinal));
+ }
+
+ private void UpdateHeader()
+ {
+ bool top = _path.Count == 0;
+ var ctx = ConditionNameLabel.StyleContext;
+
+ if (top)
+ {
+ ConditionNameLabel.Text = En ? "Select a type" : "種別を選択";
+ ConditionNameLabel.Xalign = 0;
+ ctx.RemoveClass("page-hint");
+ ctx.AddClass("page-title");
+ }
+ else
+ {
+ // The tabs already say 呼吸音 / 心音; show deeper levels as a trail.
+ ConditionNameLabel.Text = _path.Count == 1
+ ? (En ? "Touch a sound to start" : "音源をタッチして開始")
+ : string.Join(" › ", _path.Skip(1).Select(Disp));
+ ConditionNameLabel.Xalign = 1;
+ ctx.RemoveClass("page-title");
+ ctx.AddClass("page-hint");
+ }
+
+ if (SoundSubtitleLabel != null) SoundSubtitleLabel.Visible = top;
+ BuildTabs(top);
+ }
+
+ private void BuildTabs(bool top)
+ {
+ if (SoundTabBox == null) return;
+
+ foreach (var child in SoundTabBox.Children)
+ {
+ SoundTabBox.Remove(child);
+ child.Destroy();
+ }
+
+ SoundTabBox.Visible = !top;
+ if (top) return;
+
+ var branches = TopLevel();
+ for (int k = 0; k < branches.Count; k++)
+ {
+ string branch = branches[k];
+ bool active = string.Equals(branch, _path[0], StringComparison.Ordinal);
+
+ var tab = MakeTypeTile(branch, k, active, true);
+ tab.Clicked += (s, e) =>
+ {
+ if (_path.Count == 1 && active) return; // already here
+ _path.Clear();
+ _path.Add(branch);
+ Render();
+ };
+ // SoundTabBox is no-show-all (so a window-wide ShowAll can't reveal
+ // it on level 0) — which also makes SoundTabBox.ShowAll() a no-op.
+ // Show each tab itself instead.
+ tab.ShowAll();
+ SoundTabBox.PackStart(tab, false, false, 0);
+ }
+ }
+
+ // ── buttons ────────────────────────────────────────────────────────
+
+ private void BuildButtons(IEnumerable labels, Action onPick)
+ {
+ // MUST be first. Attach() stacks; without this every Render() adds a layer
+ // of live buttons whose closures corrupt _path.
+ foreach (var child in SoundButtonGrid.Children)
+ {
+ SoundButtonGrid.Remove(child);
+ child.Destroy();
+ }
+
+ var list = labels.ToList();
+ if (list.Count == 0) { SoundButtonGrid.ShowAll(); return; }
+
+ bool top = _path.Count == 0;
+ var branches = TopLevel();
+
+ if (top)
+ {
+ // Level 0: big icon tiles, centred vertically.
+ SoundButtonGrid.Valign = Align.Center;
+ SoundButtonGrid.ColumnSpacing = 28;
+ SoundButtonGrid.RowSpacing = 28;
+ SoundButtonGrid.ColumnHomogeneous = false;
+ SoundButtonGrid.RowHomogeneous = false;
+
+ int i = 0;
+ foreach (string text in list)
+ {
+ string captured = text;
+ var tile = MakeTypeTile(captured, branches.IndexOf(captured), false, false);
+ tile.HeightRequest = TopTileHeight;
+ tile.Hexpand = true;
+ tile.Clicked += (s, e) => onPick(captured);
+ SoundButtonGrid.Attach(tile, i % TopColumns, i / TopColumns, 1, 1);
+ i++;
+ }
+ }
+ else
+ {
+ // Level 1+: 3-column grid, row by row.
+ SoundButtonGrid.Valign = Align.Start;
+ SoundButtonGrid.ColumnSpacing = 10;
+ SoundButtonGrid.RowSpacing = 10;
+ // English: some names wrap to 2 lines — make every button the same
+ // width and height so the grid stays even. Japanese layout unchanged.
+ SoundButtonGrid.ColumnHomogeneous = En;
+ SoundButtonGrid.RowHomogeneous = En;
+
+ int rows = (list.Count + ListColumns - 1) / ListColumns;
+ bool compact = rows > ListRowsFit;
+ int branchIx = branches.IndexOf(_path[0]);
+
+ int i = 0;
+ foreach (string text in list)
+ {
+ string captured = text;
+ var btn = MakeClipButton(captured, branchIx, compact);
+ btn.Clicked += (s, e) => onPick(captured);
+ SoundButtonGrid.Attach(btn, i % ListColumns, i / ListColumns, 1, 1);
+ i++;
+ }
+ }
+
+ SoundButtonGrid.ShowAll();
+ }
+
+ /// Big tile (level 0) or small tab (level 1+): icon + name + subtitle.
+ private Button MakeTypeTile(string name, int branchIx, bool active, bool small)
+ {
+ var btn = new Button();
+ var ctx = btn.StyleContext;
+ ctx.AddClass(small ? "type-tab" : "type-tile");
+ if (branchIx == 0) ctx.AddClass("lung");
+ else if (branchIx == 1) ctx.AddClass("heart");
+ if (active) ctx.AddClass("active");
+
+ var icon = new SoundIcon(branchIx == 1 ? SoundIcon.Kind.Heart : SoundIcon.Kind.Lungs,
+ small ? 54 : 140, active);
+
+ string sub = (!En && branchIx >= 0 && branchIx < BranchSubtitles.Length
+ ? BranchSubtitles[branchIx] + " · " : "")
+ + CaseCount(name) + (En ? " sounds" : " 音源");
+
+ var title = new Label(Disp(name));
+ title.StyleContext.AddClass("tile-title");
+ var subtitle = new Label(sub);
+ subtitle.StyleContext.AddClass("tile-sub");
+
+ if (small)
+ {
+ title.Xalign = 0;
+ subtitle.Xalign = 0;
+ var text = new Box(Orientation.Vertical, 0);
+ text.Valign = Align.Center;
+ text.PackStart(title, false, false, 0);
+ text.PackStart(subtitle, false, false, 0);
+
+ var row = new Box(Orientation.Horizontal, 14);
+ icon.Valign = Align.Center;
+ row.PackStart(icon, false, false, 0);
+ row.PackStart(text, false, false, 0);
+ btn.Add(row);
+ }
+ else
+ {
+ var col = new Box(Orientation.Vertical, 18);
+ col.Halign = Align.Center;
+ col.Valign = Align.Center;
+ icon.Halign = Align.Center;
+ col.PackStart(icon, false, false, 0);
+ col.PackStart(title, false, false, 0);
+ col.PackStart(subtitle, false, false, 0);
+ btn.Add(col);
+ }
+ return btn;
+ }
+
+ /// White card: Japanese name bold on top, English name small below.
+ private Button MakeClipButton(string text, int branchIx, bool compact)
+ {
+ string main = text, sub = null;
+ var m = NameRx.Match(text);
+ if (En)
+ {
+ main = Disp(text); // English part of "en(jp)", or names_eng.csv
+ }
+ else if (m.Success && m.Groups[2].Value.Trim().Length > 0)
+ {
+ main = m.Groups[2].Value.Trim();
+ sub = m.Groups[1].Value.Trim();
+ }
+
+ var btn = new Button();
+ btn.Hexpand = true;
+ btn.Vexpand = false;
+ btn.TooltipText = Disp(text);
+
+ var ctx = btn.StyleContext;
+ ctx.AddClass("sound-clip");
+ if (compact) ctx.AddClass("compact");
+ if (branchIx == 0) ctx.AddClass("lung");
+ else if (branchIx == 1) ctx.AddClass("heart");
+
+ var col = new Box(Orientation.Vertical, 2);
+ col.Valign = Align.Center;
+
+ Label l1;
+ if (En)
+ {
+ // Long English names ("Hypertrophic obstructive cardiomyopathy") wrap
+ // to a 2nd line; "…" only if 2 lines still aren't enough.
+ l1 = new MultiLineLabel(main, 2);
+ l1.LineWrap = true;
+ l1.LineWrapMode = Pango.WrapMode.Word;
+ l1.MaxWidthChars = 1; // don't let long text widen its column
+ }
+ else
+ {
+ l1 = new Label(main); // Japanese: unchanged, 1 line
+ }
+ l1.Xalign = 0;
+ l1.Ellipsize = Pango.EllipsizeMode.End; // GTK's "lines" needs this set
+ l1.StyleContext.AddClass("clip-main");
+ col.PackStart(l1, false, false, 0);
+
+ if (!string.IsNullOrEmpty(sub))
+ {
+ var l2 = new Label(sub);
+ l2.Xalign = 0;
+ l2.Ellipsize = Pango.EllipsizeMode.End;
+ l2.StyleContext.AddClass("clip-sub");
+ col.PackStart(l2, false, false, 0);
+ }
+
+ btn.Add(col);
+ return btn;
+ }
+
+ private void Play(CaseDefinition c)
+ {
+ if (c.IsLegacy)
+ {
+ // Legacy audio lives in RegionSounds[0..6], not SoundPath
+ int found = 0;
+ for (int k = 0; k < 7; k++)
+ {
+ string p = AppMode.ResolveSound(c.RegionSounds[k]);
+ if (p == null) continue; // "none" / empty = region disabled
+ if (File.Exists(p)) found++;
+ else Console.WriteLine("Region " + k + " sound missing for case " + c.Number + ": " + p);
+ }
+ if (found == 0)
+ {
+ Console.WriteLine("No region sounds found for legacy case " + c.Number);
+ return;
+ }
+ }
+ else if (string.IsNullOrWhiteSpace(c.SoundPath))
+ {
+ Console.WriteLine("No Sound_File for case " + c.Number);
+ return;
+ }
+
+ WavePlayer.Stop(); // the map page owns audio from here on
+
+ var h = CaseSelected;
+ if (h != null) h(this, c);
+
+ if (!c.IsLegacy)
+ {
+ string full = AppMode.ResolveSound(c.SoundPath);
+ if (full == null || !File.Exists(full))
+ Console.WriteLine("Sound file missing for case " + c.Number);
+ }
+ }
+
+ private void OnBackClicked(object sender, EventArgs e)
+ {
+ if (_path.Count > 0)
+ {
+ _path.RemoveAt(_path.Count - 1);
+ Render();
+ }
+ else
+ {
+ WavePlayer.Stop();
+ if (BackRequested != null) BackRequested(this, EventArgs.Empty);
+ }
+ }
+}
+
+/// Lungs / heart icon in a circle, drawn with Cairo (no image files needed).
+/// Inactive: tinted circle + coloured stroke. Active: solid circle + white stroke.
+public class SoundIcon : DrawingArea
+{
+ public enum Kind { Lungs, Heart }
+
+ private readonly Kind _kind;
+ private readonly bool _active;
+
+ public SoundIcon(Kind kind, int size, bool active)
+ {
+ _kind = kind;
+ _active = active;
+ SetSizeRequest(size, size);
+ Drawn += OnDrawn;
+ }
+
+ private void OnDrawn(object o, DrawnArgs args)
+ {
+ var cr = args.Cr;
+ int w = AllocatedWidth, h = AllocatedHeight;
+ double s = Math.Min(w, h);
+
+ bool heart = _kind == Kind.Heart;
+ double r = heart ? 0.753 : 0.122, g = heart ? 0.224 : 0.435, b = heart ? 0.169 : 0.698; // #C0392B / #1F6FB2
+
+ // circle
+ cr.Arc(w / 2.0, h / 2.0, s / 2.0, 0, 2 * Math.PI);
+ if (_active) cr.SetSourceRGB(r, g, b);
+ else if (heart) cr.SetSourceRGB(0.984, 0.906, 0.906); // #FBE7E7
+ else cr.SetSourceRGB(0.890, 0.933, 0.976); // #E3EEF9
+ cr.Fill();
+
+ // glyph, authored on a 64x64 grid, scaled to 60% of the circle
+ double k = s * 0.6 / 64.0;
+ cr.Save();
+ cr.Translate((w - 64 * k) / 2.0, (h - 64 * k) / 2.0);
+ cr.Scale(k, k);
+ cr.LineWidth = 3.2;
+ cr.LineCap = Cairo.LineCap.Round;
+ cr.LineJoin = Cairo.LineJoin.Round;
+ if (_active) cr.SetSourceRGB(1, 1, 1);
+ else cr.SetSourceRGB(r, g, b);
+
+ if (heart) HeartPath(cr); else LungsPath(cr);
+ cr.Stroke();
+ cr.Restore();
+
+ args.RetVal = true;
+ }
+
+ private static void LungsPath(Cairo.Context cr)
+ {
+ // trachea + bronchi
+ cr.MoveTo(32, 6); cr.LineTo(32, 28);
+ cr.MoveTo(32, 28); cr.CurveTo(29, 28, 26, 31, 24, 31);
+ cr.MoveTo(32, 28); cr.CurveTo(35, 28, 38, 31, 40, 31);
+ // left lobe
+ cr.MoveTo(24, 31);
+ cr.CurveTo(22, 23, 18, 18, 14, 18);
+ cr.CurveTo(8, 18, 5, 30, 5, 42);
+ cr.CurveTo(5, 51, 8, 57, 14, 57);
+ cr.CurveTo(21, 57, 24, 52, 24, 45);
+ cr.ClosePath();
+ // right lobe
+ cr.MoveTo(40, 31);
+ cr.CurveTo(42, 23, 46, 18, 50, 18);
+ cr.CurveTo(56, 18, 59, 30, 59, 42);
+ cr.CurveTo(59, 51, 56, 57, 50, 57);
+ cr.CurveTo(43, 57, 40, 52, 40, 45);
+ cr.ClosePath();
+ }
+
+ private static void HeartPath(Cairo.Context cr)
+ {
+ cr.MoveTo(32, 54);
+ cr.CurveTo(32, 54, 8, 40, 8, 22);
+ cr.CurveTo(8, 14, 14, 9, 20, 9);
+ cr.CurveTo(25, 9, 29, 12, 32, 16);
+ cr.CurveTo(35, 12, 39, 9, 44, 9);
+ cr.CurveTo(50, 9, 56, 14, 56, 22);
+ cr.CurveTo(56, 40, 32, 54, 32, 54);
+ cr.ClosePath();
+ // ECG trace
+ cr.MoveTo(14, 30);
+ cr.LineTo(24, 30);
+ cr.LineTo(28, 23);
+ cr.LineTo(34, 37);
+ cr.LineTo(38, 30);
+ cr.LineTo(50, 30);
+ }
+}
+
+/// Gtk.Label with GTK3's "lines" property (max lines before ellipsizing).
+/// This gtk-sharp binding has no Label.Lines and SetProperty is protected,
+/// so it is set from a subclass. CSS still matches it as a normal "label".
+public class MultiLineLabel : Label
+{
+ public MultiLineLabel(string text, int lines) : base(text)
+ {
+ SetProperty("lines", new GLib.Value(lines));
+ }
+}
diff --git a/program/WavFile.cs b/program/WavFile.cs
new file mode 100644
index 0000000..ba90981
--- /dev/null
+++ b/program/WavFile.cs
@@ -0,0 +1,134 @@
+using System;
+using System.IO;
+using System.Text;
+using OpenTK.Audio.OpenAL;
+
+public class WavFile
+{
+ public byte[] Data;
+ public ALFormat Format; // Al.FORMAT_*
+ public int SampleRate;
+
+ private const short FORMAT_PCM = 1;
+ private const short FORMAT_FLOAT = 3;
+ private const short FORMAT_EXTENSIBLE = unchecked((short)0xFFFE);
+
+ public static WavFile Load(string path)
+ {
+ using (var fs = File.OpenRead(path))
+ using (var br = new BinaryReader(fs))
+ {
+ if (new string(br.ReadChars(4)) != "RIFF") throw new Exception("Not RIFF: " + path);
+ br.ReadInt32();
+ if (new string(br.ReadChars(4)) != "WAVE") throw new Exception("Not WAVE: " + path);
+
+ short format = FORMAT_PCM, channels = 0, bits = 0;
+ int rate = 0;
+ byte[] data = null;
+
+ while (fs.Position < fs.Length - 8)
+ {
+ string id = new string(br.ReadChars(4));
+ int len = br.ReadInt32();
+
+ if (id == "fmt ")
+ {
+ format = br.ReadInt16(); // 1 = PCM, 3 = float, 0xFFFE = extensible
+ channels = br.ReadInt16();
+ rate = br.ReadInt32();
+ br.ReadInt32(); // byte rate
+ br.ReadInt16(); // block align
+ bits = br.ReadInt16();
+ int rest = len - 16;
+
+ // WAVE_FORMAT_EXTENSIBLE: the real format is the first
+ // 2 bytes of the SubFormat GUID, 8 bytes further in.
+ if (format == FORMAT_EXTENSIBLE && rest >= 10)
+ {
+ br.ReadInt16(); // cbSize
+ br.ReadInt16(); // valid bits
+ br.ReadInt32(); // channel mask
+ format = br.ReadInt16(); // SubFormat (first 2 bytes)
+ rest -= 10;
+ }
+ if (rest > 0) br.ReadBytes(rest);
+ }
+ else if (id == "data")
+ {
+ if (len < 0 || len > fs.Length - fs.Position) len = (int)(fs.Length - fs.Position);
+ data = br.ReadBytes(len);
+ }
+ else
+ {
+ br.ReadBytes(len); // skip unknown chunk
+ }
+
+ if ((len & 1) == 1 && fs.Position < fs.Length) br.ReadByte(); // chunks are word-aligned
+ }
+
+ if (data == null) throw new Exception("No data chunk: " + path);
+ if (channels != 1 && channels != 2)
+ throw new Exception("Unsupported WAV: " + channels + " channels (" + path + ")");
+
+ // OpenAL core only takes 8/16-bit. Convert anything wider to 16-bit.
+ if (format == FORMAT_FLOAT && bits == 32) { data = Float32To16(data); bits = 16; }
+ else if (format == FORMAT_PCM && bits == 24) { data = Int24To16(data); bits = 16; }
+ else if (format == FORMAT_PCM && bits == 32) { data = Int32To16(data); bits = 16; }
+ else if (format != FORMAT_PCM)
+ throw new Exception("Unsupported WAV encoding " + format + " (" + path + ")");
+
+ ALFormat fmt;
+ if (channels == 1 && bits == 8) fmt = ALFormat.Mono8;
+ else if (channels == 1 && bits == 16) fmt = ALFormat.Mono16;
+ else if (channels == 2 && bits == 8) fmt = ALFormat.Stereo8;
+ else if (channels == 2 && bits == 16) fmt = ALFormat.Stereo16;
+ else throw new Exception("Unsupported WAV: " + channels + "ch " + bits + "bit");
+
+ // a partial last frame makes alBufferData fail
+ int frame = channels * bits / 8;
+ if (data.Length % frame != 0)
+ Array.Resize(ref data, data.Length - data.Length % frame);
+
+ return new WavFile { Data = data, Format = fmt, SampleRate = rate };
+ }
+ }
+
+ private static byte[] Int24To16(byte[] src)
+ {
+ int n = src.Length / 3;
+ var dst = new byte[n * 2];
+ for (int i = 0; i < n; i++)
+ {
+ dst[i * 2] = src[i * 3 + 1]; // drop the lowest byte
+ dst[i * 2 + 1] = src[i * 3 + 2];
+ }
+ return dst;
+ }
+
+ private static byte[] Int32To16(byte[] src)
+ {
+ int n = src.Length / 4;
+ var dst = new byte[n * 2];
+ for (int i = 0; i < n; i++)
+ {
+ dst[i * 2] = src[i * 4 + 2]; // keep the top 16 bits
+ dst[i * 2 + 1] = src[i * 4 + 3];
+ }
+ return dst;
+ }
+
+ private static byte[] Float32To16(byte[] src)
+ {
+ int n = src.Length / 4;
+ var dst = new byte[n * 2];
+ for (int i = 0; i < n; i++)
+ {
+ float f = BitConverter.ToSingle(src, i * 4);
+ if (f > 1f) f = 1f; else if (f < -1f) f = -1f;
+ short s = (short)Math.Round(f * 32767f);
+ dst[i * 2] = (byte)(s & 0xFF);
+ dst[i * 2 + 1] = (byte)((s >> 8) & 0xFF);
+ }
+ return dst;
+ }
+}
\ No newline at end of file
diff --git a/program/WaveData.cs b/program/WaveData.cs
new file mode 100644
index 0000000..8d84899
--- /dev/null
+++ b/program/WaveData.cs
@@ -0,0 +1,147 @@
+using System;
+using System.IO;
+using System.Text;
+
+/// A WAV file decoded to mono floats, plus a per-pixel min/max cache for drawing.
+public class WaveData
+{
+ public float[] Samples;
+ public int SampleRate;
+
+ private int _cacheWidth = -1;
+ private float[] _mins, _maxs;
+
+ public double Duration
+ {
+ get { return (Samples == null || SampleRate <= 0) ? 0 : (double)Samples.Length / SampleRate; }
+ }
+
+ public static WaveData Load(string path, out string error)
+ {
+ float[] s; int rate;
+ if (!ReadWav(path, out s, out rate, out error)) return null;
+ return new WaveData { Samples = s, SampleRate = rate };
+ }
+
+ /// Min/max of the samples that fall into each of `width` pixel columns.
+ public void GetPeaks(int width, out float[] mins, out float[] maxs)
+ {
+ if (width != _cacheWidth)
+ {
+ _cacheWidth = width;
+ _mins = new float[width];
+ _maxs = new float[width];
+ int n = Samples.Length;
+
+ for (int x = 0; x < width; x++)
+ {
+ int s0 = (int)((long)x * n / width);
+ int s1 = (int)((long)(x + 1) * n / width);
+ if (s1 <= s0) s1 = s0 + 1;
+ if (s1 > n) s1 = n;
+
+ float mn = 1f, mx = -1f;
+ for (int i = s0; i < s1; i++)
+ {
+ float v = Samples[i];
+ if (v < mn) mn = v;
+ if (v > mx) mx = v;
+ }
+ _mins[x] = mn;
+ _maxs[x] = mx;
+ }
+ }
+ mins = _mins;
+ maxs = _maxs;
+ }
+
+ // PCM 8/16/24/32-bit or float32, mono or stereo (left channel), normalized to [-1, 1]
+ public static bool ReadWav(string path, out float[] samples, out int sampleRate, out string error)
+ {
+ samples = null; sampleRate = 0; error = null;
+ try
+ {
+ if (!File.Exists(path)) { error = "not found: " + path; return false; }
+
+ using (var br = new BinaryReader(File.OpenRead(path)))
+ {
+ long len = br.BaseStream.Length;
+ if (Id(br) != "RIFF") { error = "not RIFF"; return false; }
+ br.ReadInt32();
+ if (Id(br) != "WAVE") { error = "not WAVE"; return false; }
+
+ int fmtTag = 0, channels = 0, bits = 0;
+ byte[] data = null;
+
+ while (br.BaseStream.Position + 8 <= len)
+ {
+ string id = Id(br);
+ long size = (uint)br.ReadInt32();
+ long start = br.BaseStream.Position;
+
+ if (id == "fmt ")
+ {
+ fmtTag = (ushort)br.ReadInt16();
+ channels = br.ReadInt16();
+ sampleRate = br.ReadInt32();
+ br.ReadInt32(); // byte rate
+ br.ReadInt16(); // block align
+ bits = br.ReadInt16();
+ if (fmtTag == 0xFFFE && size >= 40) // WAVE_FORMAT_EXTENSIBLE
+ {
+ br.ReadInt16(); br.ReadInt16(); br.ReadInt32();
+ fmtTag = (ushort)br.ReadInt16();
+ }
+ }
+ else if (id == "data")
+ {
+ data = br.ReadBytes((int)Math.Min(size, len - start));
+ break;
+ }
+
+ long next = start + size + (size & 1);
+ if (next > len) break;
+ br.BaseStream.Position = next;
+ }
+
+ if (data == null || channels <= 0 || sampleRate <= 0 || bits <= 0)
+ { error = "missing fmt/data chunk"; return false; }
+
+ int frame = (bits / 8) * channels;
+ int frames = data.Length / frame;
+ if (frames == 0) { error = "empty data"; return false; }
+
+ var s = new float[frames];
+ float peak = 0f;
+ for (int i = 0; i < frames; i++)
+ {
+ int o = i * frame;
+ float v;
+ switch (bits)
+ {
+ case 8: v = (data[o] - 128) / 128f; break;
+ case 16: v = BitConverter.ToInt16(data, o) / 32768f; break;
+ case 24: v = (data[o] | (data[o + 1] << 8) | ((sbyte)data[o + 2] << 16)) / 8388608f; break;
+ case 32: v = fmtTag == 3 ? BitConverter.ToSingle(data, o)
+ : BitConverter.ToInt32(data, o) / 2147483648f; break;
+ default: error = "unsupported bits: " + bits; return false;
+ }
+ s[i] = v;
+ if (Math.Abs(v) > peak) peak = Math.Abs(v);
+ }
+
+ if (peak > 0f)
+ for (int i = 0; i < frames; i++) s[i] /= peak;
+
+ samples = s;
+ return true;
+ }
+ }
+ catch (Exception ex) { error = ex.Message; return false; }
+ }
+
+ private static string Id(BinaryReader br)
+ {
+ return Encoding.ASCII.GetString(br.ReadBytes(4));
+ }
+}
\ No newline at end of file
diff --git a/program/WavePlayer.cs b/program/WavePlayer.cs
new file mode 100644
index 0000000..00cd07a
--- /dev/null
+++ b/program/WavePlayer.cs
@@ -0,0 +1,60 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+
+public static class WavePlayer
+{
+ private static Process _current;
+
+ private static bool IsUnix
+ {
+ get
+ {
+ int p = (int)Environment.OSVersion.Platform;
+ return p == 4 || p == 6 || p == 128;
+ }
+ }
+
+ public static void Play(string absolutePath)
+ {
+ Stop();
+
+ if (!IsUnix)
+ {
+ try
+ {
+ var sp = new System.Media.SoundPlayer(absolutePath);
+ sp.Play();
+ }
+ catch (Exception ex) { Console.WriteLine("Playback failed: " + ex.Message); }
+ return;
+ }
+
+ foreach (string player in new[] { "paplay", "aplay" })
+ {
+ try
+ {
+ var psi = new ProcessStartInfo(player, "\"" + absolutePath + "\"")
+ {
+ UseShellExecute = false,
+ RedirectStandardError = true
+ };
+ _current = Process.Start(psi);
+ return;
+ }
+ catch { /* not installed, try the next one */ }
+ }
+
+ Console.WriteLine("No audio player found — install pulseaudio-utils or alsa-utils");
+ }
+
+ public static void Stop()
+ {
+ try
+ {
+ if (_current != null && !_current.HasExited) _current.Kill();
+ }
+ catch { }
+ _current = null;
+ }
+}
\ No newline at end of file
diff --git a/program/cases_old.csv b/program/cases_old.csv
new file mode 100644
index 0000000..c15c513
--- /dev/null
+++ b/program/cases_old.csv
@@ -0,0 +1,26 @@
+正常呼吸音,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND200.wav,IMG200.png,MAP201.png,SND201.wav,IMG201.png,MAP202.png,SND202.wav,IMG202.png,MAP203.png,SND203.wav,IMG203.png,MAP203.png,SND203.wav,IMG203.png,2797,0,3000,14500,31000,C999.png
+fine crackle(捻髪音),MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND300.wav,IMG200.png,MAP208.png,SND301.wav,IMG301.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND210.wav,IMG210.png,MAP210.png,SND210.wav,IMG210.png,2171,0,300,12000,21000,C204.png
+coarse crackle(水泡音),MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND305.wav,IMG200.png,MAP208.png,SND306.wav,IMG306.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND220.wav,IMG220.png,MAP210.png,SND220.wav,IMG220.png,3545,0,500,17800,31300,C205.png
+rhonchi(いびき音),MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND310.wav,IMG310.png,MAP208.png,SND311.wav,IMG311.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND230.wav,IMG230.png,MAP210.png,SND230.wav,IMG230.png,4110,0,4000,18000,41000,C206.png
+wheeze(笛音),MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND315.wav,IMG315.png,MAP208.png,SND316.wav,IMG316.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND240.wav,IMG240.png,MAP210.png,SND240.wav,IMG240.png,4216,0,3500,20400,34800,C207.png
+squawk(スクォーク),MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND320.wav,IMG320.png,MAP208.png,SND321.wav,IMG321.png,MAP202.png,SND202.wav,IMG202.png,MAP213.png,SND250.wav,IMG250.png,MAP213.png,SND250.wav,IMG250.png,3026,0,2800,18600,38890,C208.png
+pleural friction rub(胸膜摩擦音),MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND320.wav,IMG320.png,MAP208.png,SND321.wav,IMG321.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND260.wav,IMG260.png,MAP216.png,SND203.wav,IMG203.png,3270,0,500,18000,32000,C209.png
+正常心音,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,798,1,3000,14500,31000,C999.png
+大動脈弁狭窄症,MAP105.png,SND130.wav,IMG130.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,798,1,3000,14500,31000,C102.png
+閉塞性肥大型心筋症,MAP106.png,SND171.wav,IMG171.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,801,1,3000,14500,31000,C108.png
+心室中隔欠損症,MAP106.png,SND173.wav,IMG173.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,699,1,3000,14500,31000,C110.png
+僧帽弁逆流症,MAP104.png,SND121.wav,IMG121.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,801,1,3000,14500,31000,C105.png
+三尖弁逆流症,MAP106.png,SND140.wav,IMG140.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1566,1,3000,14500,31000,C107.png
+心房中隔欠損症,MAP106.png,SND170.wav,IMG170.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,712,1,3000,14500,31000,C109.png
+大動脈弁逆流症,MAP105.png,SND131.wav,IMG131.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,793,1,3000,14500,31000,C103.png
+肺動脈弁逆流症,MAP150.png,SND150.wav,IMG150.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,778,1,3000,14500,31000,C999.png
+僧房弁狭窄症,MAP104.png,SND120.wav,IMG120.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,760,1,3000,14500,31000,C104.png
+動脈管開存症,MAP106.png,SND172.wav,IMG172.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,799,1,3000,14500,31000,C111.png
+Ⅲ音,MAP102.png,SND110.wav,IMG110.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1013,1,3000,14500,31000,C101.png
+Ⅳ音,MAP103.png,SND111.wav,IMG111.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,900,1,3000,14500,31000,C101.png
+心膜摩擦音,MAP106.png,SND160.wav,IMG160.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,985,1,3000,14500,31000,C999.png
+心膜ノック音,MAP106.png,SND161.wav,IMG161.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,644,1,3000,14500,31000,C999.png
+僧房弁解放音,MAP104.png,SND123.wav,IMG123.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,928,1,3000,14500,31000,C999.png
+収縮中期クリック音,MAP106.png,SND174.wav,IMG174.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1089,1,3000,14500,31000,C999.png
+三尖弁狭窄症,MAP106.png,SND141.wav,IMG141.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1566,1,3000,14500,31000,C999.png
+僧房弁逸脱症,MAP104.png,SND122.wav,IMG122.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,800,1,3000,14500,31000,C106.png
diff --git a/program/cases_old_eng.csv b/program/cases_old_eng.csv
new file mode 100644
index 0000000..581c695
--- /dev/null
+++ b/program/cases_old_eng.csv
@@ -0,0 +1,26 @@
+Normal breath sounds,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND200.wav,IMG200.png,MAP201.png,SND201.wav,IMG201.png,MAP202.png,SND202.wav,IMG202.png,MAP203.png,SND203.wav,IMG203.png,MAP203.png,SND203.wav,IMG203.png,2797,0,3000,14500,31000,C999.png
+Fine crackles,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND300.wav,IMG200.png,MAP208.png,SND301.wav,IMG301.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND210.wav,IMG210.png,MAP210.png,SND210.wav,IMG210.png,2171,0,300,12000,21000,C204.png
+Coarse crackles,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND305.wav,IMG200.png,MAP208.png,SND306.wav,IMG306.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND220.wav,IMG220.png,MAP210.png,SND220.wav,IMG220.png,3545,0,500,17800,31300,C205.png
+Rhonchi,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND310.wav,IMG310.png,MAP208.png,SND311.wav,IMG311.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND230.wav,IMG230.png,MAP210.png,SND230.wav,IMG230.png,4110,0,4000,18000,41000,C206.png
+Wheezes,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND315.wav,IMG315.png,MAP208.png,SND316.wav,IMG316.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND240.wav,IMG240.png,MAP210.png,SND240.wav,IMG240.png,4216,0,3500,20400,34800,C207.png
+Squawks,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND320.wav,IMG320.png,MAP208.png,SND321.wav,IMG321.png,MAP202.png,SND202.wav,IMG202.png,MAP213.png,SND250.wav,IMG250.png,MAP213.png,SND250.wav,IMG250.png,3026,0,2800,18600,38890,C208.png
+Pleural friction rub,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND320.wav,IMG320.png,MAP208.png,SND321.wav,IMG321.png,MAP202.png,SND202.wav,IMG202.png,MAP210.png,SND260.wav,IMG260.png,MAP216.png,SND203.wav,IMG203.png,3270,0,500,18000,32000,C209.png
+Normal heart sounds,MAP100.png,SND100.wav,heart.png,MAP101.png,SND101.wav,heart.png,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,798,1,3000,14500,31000,C999.png
+Aortic stenosis,MAP105.png,SND130.wav,IMG130.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,798,1,3000,14500,31000,C102.png
+Hypertrophic obstructive cardiomyopathy,MAP106.png,SND171.wav,IMG171.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,801,1,3000,14500,31000,C108.png
+Ventricular septal defect,MAP106.png,SND173.wav,IMG173.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,699,1,3000,14500,31000,C110.png
+Mitral regurgitation,MAP104.png,SND121.wav,IMG121.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,801,1,3000,14500,31000,C105.png
+Tricuspid regurgitation,MAP106.png,SND140.wav,IMG140.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1566,1,3000,14500,31000,C107.png
+Atrial septal defect,MAP106.png,SND170.wav,IMG170.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,712,1,3000,14500,31000,C109.png
+Aortic regurgitation,MAP105.png,SND131.wav,IMG131.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,793,1,3000,14500,31000,C103.png
+Pulmonary regurgitation,MAP150.png,SND150.wav,IMG150.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,778,1,3000,14500,31000,C999.png
+Mitral stenosis,MAP104.png,SND120.wav,IMG120.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,760,1,3000,14500,31000,C104.png
+Patent ductus arteriosus,MAP106.png,SND172.wav,IMG172.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,799,1,3000,14500,31000,C111.png
+Third heart sound (S3),MAP102.png,SND110.wav,IMG110.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1013,1,3000,14500,31000,C101.png
+Fourth heart sound (S4),MAP103.png,SND111.wav,IMG111.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,900,1,3000,14500,31000,C101.png
+Pericardial friction rub,MAP106.png,SND160.wav,IMG160.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,985,1,3000,14500,31000,C999.png
+Pericardial knock,MAP106.png,SND161.wav,IMG161.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,644,1,3000,14500,31000,C999.png
+Mitral opening snap,MAP104.png,SND123.wav,IMG123.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,928,1,3000,14500,31000,C999.png
+Mid-systolic click,MAP106.png,SND174.wav,IMG174.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1089,1,3000,14500,31000,C999.png
+Tricuspid stenosis,MAP106.png,SND141.wav,IMG141.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,1566,1,3000,14500,31000,C999.png
+Mitral valve prolapse,MAP104.png,SND122.wav,IMG122.png,none,none,none,MAP200.png,SND200.wav,breath.png,MAP201.png,SND201.wav,breath.png,MAP202.png,SND202.wav,breath.png,MAP203.png,SND203.wav,breath.png,MAP203.png,SND203.wav,IMG203.png,800,1,3000,14500,31000,C106.png
diff --git a/program/homepage.glade b/program/homepage.glade
new file mode 100644
index 0000000..7c21a1d
--- /dev/null
+++ b/program/homepage.glade
@@ -0,0 +1,380 @@
+
+
+
+
+
+
+ False
+ 1280
+ 800
+
+
+
+ True
+ False
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ False
+ EARS
+ 1280
+ 800
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/program/homepage.glade~ b/program/homepage.glade~
new file mode 100644
index 0000000..fade189
--- /dev/null
+++ b/program/homepage.glade~
@@ -0,0 +1,347 @@
+
+
+
+
+
+ False
+ 1280
+ 800
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+
+
+ False
+
+
+
+
+
+ False
+ EARS
+ 1280
+ 800
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/program/homepageall.glade b/program/homepageall.glade
new file mode 100644
index 0000000..03f30c2
--- /dev/null
+++ b/program/homepageall.glade
@@ -0,0 +1,487 @@
+
+
+
+
+
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ A / あ
+ True
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+
+
+
+
+
+ False
+ 1280
+ 800
+
+
+ True
+ False
+ vertical
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+
+ True
+ False
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ False
+ True
+ 1
+
+
+
+
+
+ True
+ False
+
+
+ Back
+ True
+ True
+ True
+ end
+ True
+ right
+
+
+ 2
+ 0
+
+
+
+
+
+
+
+
+
+
+ False
+ True
+ 2
+
+
+
+
+
+
diff --git a/program/homepageallv3.glade b/program/homepageallv3.glade
new file mode 100644
index 0000000..284cfee
--- /dev/null
+++ b/program/homepageallv3.glade
@@ -0,0 +1,445 @@
+
+
+
+
+
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ A / あ
+ True
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+ True
+ False
+ vertical
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ True
+ False
+ False
+ never
+ in
+
+
+ True
+ False
+
+
+
+ True
+ False
+ 6
+ 6
+ True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ True
+ right
+
+
+ False
+ True
+ 4
+
+
+
+
+ 2
+
+
+
+
+
+
+
+
+
diff --git a/program/homepageallv4.glade b/program/homepageallv4.glade
new file mode 100644
index 0000000..6f3fd9c
--- /dev/null
+++ b/program/homepageallv4.glade
@@ -0,0 +1,472 @@
+
+
+
+
+
+ False
+
+
+
+ True
+ False
+
+
+ True
+ False
+ True
+ True
+ bodyImage
+ True
+
+
+ 1
+ 0
+
+
+
+
+
+
+
+
+
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ A / あ
+ True
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+ True
+ False
+ vertical
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ True
+ False
+ False
+ never
+ in
+
+
+ True
+ False
+
+
+
+ True
+ False
+ 6
+ 6
+ True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ True
+ right
+
+
+ False
+ True
+ 4
+
+
+
+
+ 2
+
+
+
+
+
+
+
+
+
diff --git a/program/homepageallv5.glade b/program/homepageallv5.glade
new file mode 100644
index 0000000..dd9fd65
--- /dev/null
+++ b/program/homepageallv5.glade
@@ -0,0 +1,499 @@
+
+
+
+
+
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ A / あ
+ True
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+ True
+ False
+ vertical
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ True
+ False
+ False
+ never
+ in
+
+
+ True
+ False
+
+
+
+ True
+ False
+ 6
+ 6
+ True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ True
+ right
+
+
+ False
+ True
+ 4
+
+
+
+
+ 2
+
+
+
+
+ True
+ False
+ vertical
+ 6
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ True
+ True
+
+
+ True
+ True
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ True
+
+
+ False
+ True
+ 2
+
+
+
+
+ 3
+
+
+
+
+
+
+
+
+
diff --git a/program/homepageallv6.glade b/program/homepageallv6.glade
new file mode 100644
index 0000000..094dffa
--- /dev/null
+++ b/program/homepageallv6.glade
@@ -0,0 +1,831 @@
+
+
+
+
+
+ False
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ True
+ False
+ 3
+ 5
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 50
+ 50
+ 50
+ True
+ True
+
+
+ 1
+ 3
+
+
+
+
+ A / あ
+ True
+ True
+ True
+ True
+
+
+ 3
+ 0
+
+
+
+
+ True
+ False
+ Language
+
+
+ 2
+ 0
+
+
+
+
+ Close
+ True
+ True
+ True
+ True
+ True
+ fill
+ fill
+
+
+ 4
+ 4
+
+
+
+
+ Settings
+ True
+ True
+ True
+ True
+ True
+ fill
+ fill
+
+
+ 4
+ 3
+
+
+
+
+ True
+ False
+ network-offline
+ 6
+
+
+ 4
+ 0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+ True
+ False
+ vertical
+
+
+ True
+ False
+ label
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ True
+ False
+ False
+ never
+ in
+
+
+ True
+ False
+
+
+
+ True
+ False
+ 6
+ 6
+ True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ Back
+ True
+ True
+ True
+ end
+ True
+ right
+
+
+ False
+ True
+ 4
+
+
+
+
+ 2
+
+
+
+
+ True
+ False
+ 12
+
+
+ 340
+ True
+ True
+ never
+
+
+ True
+ False
+
+
+ True
+ False
+ 12
+ 12
+ 12
+ 12
+ vertical
+ 10
+
+
+ True
+ False
+ 0
+ in
+
+
+ True
+ False
+ 8
+ 8
+ 6
+ 6
+ -
+ True
+ 0
+
+
+
+
+ True
+ False
+ 選択中の症例
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ 0
+ in
+
+
+ True
+ False
+ 8
+ 8
+ 6
+ 6
+ vertical
+
+
+ スケルトン
+ True
+ True
+ False
+ True
+ True
+
+
+ False
+ True
+ 0
+
+
+
+
+ ジャケット
+ True
+ True
+ False
+ True
+ BodySkeletonRadio
+
+
+ False
+ True
+ 1
+
+
+
+
+
+
+ True
+ False
+ 体の画像選択
+
+
+
+
+ False
+ True
+ 1
+
+
+
+
+ True
+ False
+ 8
+
+
+ True
+ False
+ サイズ:
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ 0
+
+ - L
+ - XL
+
+
+
+ False
+ True
+ 1
+
+
+
+
+ False
+ True
+ 2
+
+
+
+
+ True
+ False
+ 0
+ in
+
+
+ True
+ False
+ 8
+ 8
+ 6
+ 6
+ True
+
+
+ 前
+ True
+ True
+ False
+ True
+ False
+
+
+ True
+ True
+ 0
+
+
+
+
+ 後
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 1
+
+
+
+
+ 右
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 2
+
+
+
+
+ 左
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 3
+
+
+
+
+
+
+ True
+ False
+ 視点
+
+
+
+
+ False
+ True
+ 3
+
+
+
+
+ 番号を隠す
+ True
+ True
+ False
+ True
+ True
+
+
+ False
+ True
+ 4
+
+
+
+
+ 黒画素でも再生
+ True
+ True
+ False
+ True
+
+
+ False
+ True
+ 5
+
+
+
+
+ 再生テスト
+ True
+ True
+ True
+
+
+ False
+ True
+ 6
+
+
+
+
+ True
+ False
+ True
+ vertical
+ 8
+
+
+ True
+ True
+ 7
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ end
+
+
+ False
+ True
+ 8
+
+
+
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ 12
+ 12
+ 12
+ True
+ vertical
+ 6
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ True
+ True
+
+
+ True
+ True
+ 1
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ 3
+
+
+
+
+
+
+
+
+
diff --git a/program/homepageallv7.glade b/program/homepageallv7.glade
new file mode 100644
index 0000000..f97663a
--- /dev/null
+++ b/program/homepageallv7.glade
@@ -0,0 +1,849 @@
+
+
+
+
+
+ False
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ True
+ False
+ 20
+ 5
+ 20
+
+
+
+ 0
+ 0
+ 2
+
+
+
+
+ Normal Session
+ True
+ True
+ True
+ 50
+ 20
+ True
+ True
+
+
+ 0
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ 50
+ 20
+ True
+ True
+
+
+ 0
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ 50
+ 20
+ True
+ True
+
+
+ 0
+ 3
+
+
+
+
+ Settings
+ True
+ True
+ True
+ center
+ center
+ True
+ True
+ 20
+ 40
+
+
+ 1
+ 2
+
+
+
+
+ Close
+ True
+ True
+ True
+ center
+ center
+ True
+ True
+ 20
+ 40
+
+
+ 1
+ 3
+
+
+
+
+ True
+ False
+ center
+ center
+ True
+ Problem connecting with device
+
+
+ 0
+ 4
+ 2
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+ True
+ False
+ vertical
+
+
+ True
+ False
+ label
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ True
+ False
+ False
+ never
+ in
+
+
+ True
+ False
+
+
+
+ True
+ False
+ 6
+ 6
+ True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ end
+ True
+ right
+
+
+ False
+ True
+ 4
+
+
+
+
+ 2
+
+
+
+
+ True
+ False
+ 12
+
+
+ 340
+ True
+ True
+ never
+
+
+ True
+ False
+
+
+ True
+ False
+ 12
+ 12
+ 12
+ 12
+ vertical
+ 10
+
+
+ True
+ False
+ 0
+ in
+
+
+ True
+ False
+ 8
+ 8
+ 6
+ 6
+ -
+ True
+ 0
+
+
+
+
+ True
+ False
+ 選択中の症例
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ 0
+ in
+
+
+ True
+ False
+ 8
+ 8
+ 6
+ 6
+ vertical
+
+
+ スケルトン
+ True
+ True
+ False
+ True
+ True
+
+
+ False
+ True
+ 0
+
+
+
+
+ ジャケット
+ True
+ True
+ False
+ True
+ BodySkeletonRadio
+
+
+ False
+ True
+ 1
+
+
+
+
+
+
+ True
+ False
+ 体の画像選択
+
+
+
+
+ False
+ True
+ 1
+
+
+
+
+ True
+ False
+ 8
+
+
+ True
+ False
+ サイズ:
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ 0
+
+ - L
+ - XL
+
+
+
+ False
+ True
+ 1
+
+
+
+
+ False
+ True
+ 2
+
+
+
+
+ True
+ False
+ 0
+ in
+
+
+ True
+ False
+ 8
+ 8
+ 6
+ 6
+ True
+
+
+ 前
+ True
+ True
+ False
+ True
+ False
+
+
+ True
+ True
+ 0
+
+
+
+
+ 後
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 1
+
+
+
+
+ 右
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 2
+
+
+
+
+ 左
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 3
+
+
+
+
+
+
+ True
+ False
+ 視点
+
+
+
+
+ False
+ True
+ 3
+
+
+
+
+ 番号を隠す
+ True
+ True
+ False
+ True
+ True
+
+
+ False
+ True
+ 4
+
+
+
+
+ 黒画素でも再生
+ True
+ True
+ False
+ True
+
+
+ False
+ True
+ 5
+
+
+
+
+ 再生テスト
+ True
+ True
+ True
+
+
+ False
+ True
+ 6
+
+
+
+
+ True
+ False
+ True
+ vertical
+ 8
+
+
+ True
+ True
+ 7
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ end
+
+
+ False
+ True
+ 8
+
+
+
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ 12
+ 12
+ 12
+ True
+ vertical
+ 6
+
+
+ True
+ False
+ label
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ True
+ True
+
+
+ True
+ True
+ 1
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ 3
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/program/homepageallv8.glade b/program/homepageallv8.glade
new file mode 100644
index 0000000..aa7453b
--- /dev/null
+++ b/program/homepageallv8.glade
@@ -0,0 +1,1638 @@
+
+
+
+
+
+
+ True
+ False
+ emblem-system-symbolic
+ 32
+
+
+ True
+ False
+ system-shutdown-symbolic
+ 30
+
+
+ True
+ False
+ go-previous-symbolic
+
+
+ True
+ False
+ audio-speakers-symbolic
+
+
+ True
+ False
+ go-previous-symbolic
+
+
+ False
+ False
+
+
+ True
+ True
+ False
+ False
+
+
+
+ SplashGrid
+ True
+ False
+ 20
+ 5
+
+
+
+
+ 0
+ 0
+ 2
+
+
+
+
+ Normal Session
+ True
+ True
+ True
+ True
+ left
+ 50
+ 20
+ True
+ True
+ 0
+
+
+ 0
+ 1
+
+
+
+
+ Position Recording Mode
+ True
+ True
+ True
+ True
+ left
+ 50
+ 20
+ True
+ True
+ 0
+
+
+ 0
+ 2
+
+
+
+
+ Exam Mode
+ True
+ True
+ True
+ True
+ left
+ 50
+ 20
+ True
+ True
+ 0
+
+
+ 0
+ 3
+
+
+
+
+ Settings
+ True
+ True
+ True
+ center
+ center
+ True
+ True
+ 20
+ 40
+ SettingIcon
+ left
+ True
+
+
+ 1
+ 2
+
+
+
+
+ Close
+ True
+ True
+ True
+ center
+ center
+ True
+ True
+ 20
+ 40
+ CloseIcon
+ left
+ True
+
+
+ 1
+ 3
+
+
+
+
+ True
+ False
+ center
+ center
+ True
+ Problem connecting with device
+
+
+ 0
+ 4
+ 2
+
+
+
+
+
+
+
+ True
+ False
+ 3
+ 3
+ True
+
+
+ True
+ False
+ center
+ True
+ True
+ COM Port
+
+
+ 0
+ 0
+
+
+
+
+ True
+ False
+ center
+ True
+ True
+
+
+ 1
+ 0
+
+
+
+
+ Connect
+ True
+ True
+ True
+ start
+ center
+ True
+ True
+
+
+ 2
+ 0
+
+
+
+
+ Auto Connect
+ True
+ True
+ True
+ center
+ start
+ True
+ True
+
+
+ 1
+ 1
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ end
+ end
+ True
+ True
+
+
+ 2
+ 2
+
+
+
+
+ True
+ False
+ Log
+
+
+ 0
+ 2
+
+
+
+
+ True
+ True
+ True
+ True
+ in
+
+
+ True
+ True
+ False
+ True
+
+
+
+
+ 1
+ 2
+
+
+
+
+ True
+ False
+ vertical
+
+
+ Refresh Ports
+ True
+ True
+ True
+ center
+ start
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ Disconnected
+
+
+ False
+ True
+ 1
+
+
+
+
+ 2
+ 1
+
+
+
+
+
+
+
+ 1
+
+
+
+
+
+ SoundBox
+ True
+ False
+ vertical
+ 14
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ SoundSubtitleLabel
+ True
+ True
+ False
+ 0
+ 学習したい音の種類をタッチしてください
+
+
+ False
+ True
+ 1
+
+
+
+
+ True
+ True
+ True
+ True
+ never
+ none
+
+
+ True
+ False
+ none
+
+
+ True
+ False
+ 10
+ 10
+ True
+
+
+
+
+
+
+
+
+
+ True
+ True
+ 2
+
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ end
+ SoundBackIcon
+ left
+ True
+
+
+ False
+ True
+ 3
+
+
+
+
+ 2
+
+
+
+
+
+ MapBox
+ True
+ False
+ vertical
+ 14
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+
+ True
+ False
+ horizontal
+ 16
+ True
+ True
+
+
+
+ 300
+ True
+ False
+ True
+ never
+
+ never
+
+
+ True
+ False
+ none
+
+
+ MapControlBox
+ True
+ False
+ vertical
+ 5
+
+
+ False
+ True
+ False
+ 0
+ none
+
+
+ True
+ False
+ -
+ True
+ 0
+
+
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+
+ MapSectionLabel
+ True
+ False
+ 0
+ 体の画像
+
+
+ False
+ True
+ 1
+
+
+
+
+ MapSegment
+ True
+ False
+ 4
+ True
+
+
+ スケルトン
+ True
+ True
+ False
+ True
+ False
+
+
+ True
+ True
+ 0
+
+
+
+
+ ジャケット
+ True
+ True
+ False
+ False
+ BodySkeletonRadio
+
+
+ True
+ True
+ 1
+
+
+
+
+ False
+ True
+ 2
+
+
+
+
+
+ MapSectionLabel
+ True
+ False
+ 6
+ 0
+ サイズ
+
+
+ False
+ True
+ 3
+
+
+
+
+ MapSegment
+ True
+ False
+ 4
+ True
+
+
+ SizeLRadio
+ L
+ True
+ True
+ False
+ True
+ False
+
+
+ True
+ True
+ 0
+
+
+
+
+ SizeXLRadio
+ XL
+ True
+ True
+ False
+ False
+ SizeLRadio
+
+
+ True
+ True
+ 1
+
+
+
+
+ False
+ True
+ 4
+
+
+
+
+ False
+ True
+ False
+ 0
+
+ - L
+ - XL
+
+
+
+ False
+ True
+ 5
+
+
+
+
+
+ MapSectionLabel
+ True
+ False
+ 6
+ 0
+ 視点
+
+
+ False
+ True
+ 6
+
+
+
+
+ MapSegment
+ True
+ False
+ 4
+ True
+
+
+ 前
+ True
+ True
+ False
+ True
+ False
+
+
+ True
+ True
+ 0
+
+
+
+
+ 後
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 1
+
+
+
+
+ 右
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 2
+
+
+
+
+ 左
+ True
+ True
+ False
+ False
+ ViewFrontRadio
+
+
+ True
+ True
+ 3
+
+
+
+
+ False
+ True
+ 7
+
+
+
+
+ MapDivider
+ True
+ False
+ 6
+ 2
+
+
+ False
+ True
+ 8
+
+
+
+
+
+ MapSectionLabel
+ True
+ False
+ 0
+ 表示
+
+
+ False
+ True
+ 9
+
+
+
+
+
+
+ False
+ True
+ 10
+
+
+
+
+
+ MapToggleRow
+ True
+ False
+ 12
+
+
+ MapToggleLabel
+ True
+ False
+ 0
+ 音量マップを表示
+ ShowVolumeMapSwitch
+
+
+ True
+ True
+ 0
+
+
+
+
+ ShowVolumeMapSwitch
+ True
+ True
+ center
+ True
+
+
+ False
+ False
+ 1
+
+
+
+
+ False
+ True
+ 11
+
+
+
+
+
+ MapToggleRow
+ True
+ False
+ 12
+
+
+ MapToggleLabel
+ True
+ False
+ 0
+ 聴診点リストを表示
+ ShowPointListSwitch
+
+
+ True
+ True
+ 0
+
+
+
+
+ ShowPointListSwitch
+ True
+ True
+ center
+ False
+
+
+ False
+ False
+ 1
+
+
+
+
+ False
+ True
+ 12
+
+
+
+
+
+ MapToggleRow
+ True
+ False
+ 12
+
+
+ MapToggleLabel
+ True
+ False
+ 0
+ 黒画素でも再生
+ BlackAudioSwitch
+
+
+ True
+ True
+ 0
+
+
+
+
+ BlackAudioSwitch
+ True
+ True
+ center
+ True
+
+
+ False
+ False
+ 1
+
+
+
+
+ False
+ True
+ 13
+
+
+
+
+
+ MapSectionLabel
+ True
+ False
+ 6
+ 0
+ 再生する音
+
+
+ False
+ True
+ 14
+
+
+
+
+ MapSegment
+ True
+ False
+ 4
+ True
+
+
+ SoundMixRadio
+ ミックス
+ True
+ True
+ False
+ True
+ False
+
+
+ True
+ True
+ 0
+
+
+
+
+ SoundHeartOnlyRadio
+ 心音のみ
+ True
+ True
+ False
+ False
+ SoundMixRadio
+
+
+ True
+ True
+ 1
+
+
+
+
+ SoundLungOnlyRadio
+ 肺音のみ
+ True
+ True
+ False
+ False
+ SoundMixRadio
+
+
+ True
+ True
+ 2
+
+
+
+
+ False
+ True
+ 15
+
+
+
+
+
+ True
+ False
+ True
+ vertical
+ 9
+
+
+ True
+ True
+ 16
+
+
+
+
+
+ 出力:スピーカー
+ True
+ True
+ True
+ SoundTestIcon
+ left
+ True
+
+
+ False
+ True
+ 17
+
+
+
+
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+
+ MapPointCard
+ True
+ False
+ vertical
+ 10
+ True
+ True
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ True
+ False
+ True
+ True
+
+
+ True
+ True
+ 1
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+
+ 340
+ True
+ False
+ False
+ True
+ vertical
+ 16
+
+
+ HeartWaveCard
+ True
+ False
+ vertical
+ 8
+ True
+
+
+ True
+ False
+ 8
+
+
+ HeartSwatch
+ 14
+ 14
+ True
+ False
+ center
+
+
+ False
+ False
+ 0
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ 150
+ True
+ False
+ False
+ True
+
+
+ True
+ True
+ 1
+
+
+
+
+ True
+ True
+ 0
+
+
+
+
+ BreathWaveCard
+ True
+ False
+ vertical
+ 8
+ True
+
+
+ True
+ False
+ 8
+
+
+ BreathSwatch
+ 14
+ 14
+ True
+ False
+ center
+
+
+ False
+ False
+ 0
+
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ False
+ True
+ 0
+
+
+
+
+ 150
+ True
+ False
+ False
+ True
+
+
+ True
+ True
+ 1
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ True
+ False
+ vertical
+ 10
+
+
+
+ MapExplainButton
+ 解説を見る
+ True
+ True
+ True
+
+
+ False
+ True
+ 0
+
+
+
+
+
+ 戻る
+ True
+ True
+ True
+ MapBackIcon
+ left
+ True
+
+
+ False
+ True
+ 1
+
+
+
+
+ False
+ True
+ 2
+
+
+
+
+ False
+ True
+ 2
+
+
+
+
+ True
+ True
+ 1
+
+
+
+
+ 3
+
+
+
+
+
+
+
+
+
diff --git a/program/info_eng.csv b/program/info_eng.csv
new file mode 100644
index 0000000..9420f05
--- /dev/null
+++ b/program/info_eng.csv
@@ -0,0 +1,59 @@
+key,text
+Option1Button,Normal Session
+Option2Button,Position Recording Mode
+Option3Button,Exam Mode
+SettingButton,Settings
+CloseButton,Close
+LanguageLabel,Language
+LanguageToggle,あ
+ComPortLabel,COM Port
+LogLabel,Log
+AutoConnectButton,Auto Connect
+RefreshButton,Refresh Ports
+SettingBackButton,Back
+ConnectButton.Connect,Connect
+ConnectButton.Disconnect,Disconnect
+StatusLabel.Connected,Connected ({0})
+StatusLabel.Disconnected,Disconnected
+ConnectionIcon.Connected,Connected to {0}
+ConnectionIcon.Disconnected,Device not connected
+Log.PortsFound,{0} port(s) found
+Log.NoPorts,No serial ports found
+Log.SelectPort,Select a COM port first
+Log.Scanning,Scanning ports for device...
+Log.DeviceNotFound,Device not found — use manual connection
+Log.EspNowConnected,[ESP-NOW] Peer connected
+Log.EspNowDisconnected,[ESP-NOW] Peer disconnected
+SoundBackButton,Back
+MapBackButton,Back
+ConnectionAlertLabel,Problem connecting with device
+BatteryIcon.Charging,Battery {0}% — charging
+BatteryIcon.Discharging,Battery {0}%
+BatteryIcon.Full,Battery fully charged
+Close.ConfirmPowerOff,The tablet will shut down.\nAre you sure?
+Close.ShuttingDown,Shutting down...
+Common.Cancel,Cancel
+Common.PowerOff,Shut Down
+BodySectionLabel,Body image
+BodySkeletonRadio,Skeleton
+BodyJacketRadio,Jacket
+JacketSizeLabel,Size
+ViewSectionLabel,View
+ViewFrontRadio,Front
+ViewBackRadio,Back
+ViewRightRadio,Right
+ViewLeftRadio,Left
+DisplaySectionLabel,Display
+ShowNumbersSwitchLabel,Show numbers
+ShowVolumeMapSwitchLabel,Show volume map
+ShowPointListSwitchLabel,Show auscultation point list
+BlackAudioSwitchLabel,Play on black pixels too
+SoundFilterSectionLabel,Sounds to play
+SoundMixRadio,Mix
+SoundHeartOnlyRadio,Heart only
+SoundLungOnlyRadio,Lung only
+MapPointHeader,Auscultation points
+HeartWaveHeader,Heart sound waveform
+BreathWaveHeader,Breath sound waveform
+MapExplainButton,View explanation
+SoundSubtitleLabel,Touch the type of sound you want to study
diff --git a/program/info_jpn.csv b/program/info_jpn.csv
new file mode 100644
index 0000000..de4b382
--- /dev/null
+++ b/program/info_jpn.csv
@@ -0,0 +1,59 @@
+key,text
+Option1Button,通常セッション
+Option2Button,位置記録モード
+Option3Button,試験モード
+SettingButton,設定
+CloseButton,終了
+LanguageLabel,言語
+LanguageToggle,A
+ComPortLabel,COMポート
+LogLabel,ログ
+AutoConnectButton,自動接続
+RefreshButton,ポート更新
+SettingBackButton,戻る
+ConnectButton.Connect,接続
+ConnectButton.Disconnect,切断
+StatusLabel.Connected,接続済み ({0})
+StatusLabel.Disconnected,未接続
+ConnectionIcon.Connected,{0} に接続しました
+ConnectionIcon.Disconnected,デバイスが接続されていません
+Log.PortsFound,ポートが {0} 個見つかりました
+Log.NoPorts,シリアルポートが見つかりません
+Log.SelectPort,COMポートを選択してください
+Log.Scanning,デバイスを検索中...
+Log.DeviceNotFound,デバイスが見つかりません — 手動で接続してください
+Log.EspNowConnected,[ESP-NOW] 相手が接続しました
+Log.EspNowDisconnected,[ESP-NOW] 相手が切断しました
+SoundBackButton,戻る
+MapBackButton,戻る
+ConnectionAlertLabel,デバイスに接続できません
+BatteryIcon.Charging,バッテリー {0}% — 充電中
+BatteryIcon.Discharging,バッテリー {0}%
+BatteryIcon.Full,バッテリー 満充電
+Close.ConfirmPowerOff,タブレットの電源を切ります\nよろしいですか?
+Close.ShuttingDown,シャットダウン中...
+Common.Cancel,キャンセル
+Common.PowerOff,電源を切る
+BodySectionLabel,体の画像
+BodySkeletonRadio,スケルトン
+BodyJacketRadio,ジャケット
+JacketSizeLabel,サイズ
+ViewSectionLabel,視点
+ViewFrontRadio,前
+ViewBackRadio,後
+ViewRightRadio,右
+ViewLeftRadio,左
+DisplaySectionLabel,表示
+ShowNumbersSwitchLabel,番号を表示
+ShowVolumeMapSwitchLabel,音量マップを表示
+ShowPointListSwitchLabel,聴診点リストを表示
+BlackAudioSwitchLabel,黒画素でも再生
+SoundFilterSectionLabel,再生する音
+SoundMixRadio,ミックス
+SoundHeartOnlyRadio,心音のみ
+SoundLungOnlyRadio,肺音のみ
+MapPointHeader,聴診点
+HeartWaveHeader,心音波形
+BreathWaveHeader,呼吸音波形
+MapExplainButton,解説を見る
+SoundSubtitleLabel,学習したい音の種類をタッチしてください
diff --git a/program/lang_eng.css b/program/lang_eng.css
new file mode 100644
index 0000000..220280a
--- /dev/null
+++ b/program/lang_eng.css
@@ -0,0 +1,6 @@
+#Option1Button, #Option2Button, #Option3Button, #CloseButton {
+ font-family: 'Sans';
+}
+
+#StatusLabel.status-on { color: #2e7d32; font-weight: bold; }
+#StatusLabel.status-off { color: #c62828; font-weight: bold; }
\ No newline at end of file
diff --git a/program/lang_jpn.css b/program/lang_jpn.css
new file mode 100644
index 0000000..dcc6859
--- /dev/null
+++ b/program/lang_jpn.css
@@ -0,0 +1,6 @@
+#Option1Button, #Option2Button, #Option3Button, #CloseButton {
+ font-family: 'Noto Sans JP';
+}
+
+#StatusLabel.status-on { color: #2e7d32; font-weight: bold; }
+#StatusLabel.status-off { color: #c62828; font-weight: bold; }
\ No newline at end of file
diff --git a/program/names_eng.csv b/program/names_eng.csv
new file mode 100644
index 0000000..fa623ef
--- /dev/null
+++ b/program/names_eng.csv
@@ -0,0 +1,45 @@
+jp,en
+呼吸音,Breath sounds
+心音,Heart sounds
+正常呼吸音,Normal breath sounds
+気管音,Tracheal
+気管支音,Bronchial
+気管支肺胞音,Bronchovesicular
+肺胞音,Vesicular
+両肺,Both lungs
+右肺,Right lung
+左肺,Left lung
+全肺野,All lung fields
+上肺野,Upper lung fields
+下肺野,Lower lung fields
+両肺下肺野,Both lower lung fields
+右肺下肺野,Right lower lung field
+左肺下肺野,Left lower lung field
+大動脈弁狭窄症,Aortic stenosis
+閉塞性肥大型心筋症,Hypertrophic obstructive cardiomyopathy
+心室中隔欠損症,Ventricular septal defect
+僧帽弁逆流症,Mitral regurgitation
+三尖弁逆流症,Tricuspid regurgitation
+心房中隔欠損症,Atrial septal defect
+大動脈弁逆流症,Aortic regurgitation
+肺動脈弁逆流症,Pulmonary regurgitation
+僧帽弁狭窄症,Mitral stenosis
+動脈管開存症,Patent ductus arteriosus
+Ⅰ音,S1 (first heart sound)
+Ⅱ音,S2 (second heart sound)
+Ⅲ音,S3 (third heart sound)
+Ⅳ音,S4 (fourth heart sound)
+心膜摩擦音,Pericardial friction rub
+心膜ノック音,Pericardial knock
+僧帽弁解放音,Mitral opening snap
+収縮中期クリック音,Mid-systolic click
+三尖弁狭窄症,Tricuspid stenosis
+肺動脈弁狭窄症,Pulmonary stenosis
+僧帽弁逸脱症,Mitral valve prolapse
+心音1,Heart 1
+心音2,Heart 2
+気管,Trachea
+気管支,Bronchus
+気管支肺胞,Bronchovesicular
+右肺胞,Right alveolar
+左肺胞,Left alveolar
diff --git a/program/program.cs b/program/program.cs
new file mode 100644
index 0000000..7e21433
--- /dev/null
+++ b/program/program.cs
@@ -0,0 +1,31 @@
+using System;
+using Gtk;
+
+class Program
+{
+ [STAThread]
+ static void Main(string[] args)
+ {
+ Console.WriteLine("argv = [" + string.Join(" | ", args) + "]");
+
+ // --- flags first, before any UI construction ---
+ AppMode.Legacy = Array.IndexOf(args, "--legacy") >= 0;
+ // ... existing --debug handling stays here too ...
+ Console.WriteLine("AppMode.Legacy = " + AppMode.Legacy +
+ " cases=" + AppMode.CasesCsv);
+
+ Application.Init();
+
+ var app = new MainWindow();
+ app.ShowAll();
+
+ // Tell the kiosk the window is drawn, so the splash video can close
+ GLib.Timeout.Add(300, () =>
+ {
+ try { System.IO.File.WriteAllText("/tmp/kiosk-ready", ""); } catch { }
+ return false;
+ });
+
+ Application.Run();
+ }
+}
diff --git a/program/style.css b/program/style.css
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/program/style.css
diff --git a/program/touch_friendly.css b/program/touch_friendly.css
new file mode 100644
index 0000000..11c6e02
--- /dev/null
+++ b/program/touch_friendly.css
@@ -0,0 +1,672 @@
+/* touch_friendly.css — EARS look, authored at 1280x800 */
+
+window {
+ background-image: url("back.png");
+ background-size: cover;
+ background-position: center;
+}
+
+notebook, notebook > stack, notebook header,
+grid, box, viewport, scrolledwindow, frame {
+ background-color: transparent;
+ background-image: none;
+}
+scrolledwindow, #SoundScroller { border: none; box-shadow: none; }
+
+/* NOTE: scoped to standalone labels only — a bare `label {}` rule would
+ repaint every button's text and override the button colors below. */
+#StatusLabel, #ComPortLabel, #LogLabel, #LanguageLabel,
+checkbutton, radiobutton, combobox {
+ font-family: 'Noto Sans JP', 'IPAPGothic', 'Noto Sans', sans-serif;
+ color: #1e1e1e;
+ font-size: 14px;
+}
+
+/* ---------- shared button look ---------- */
+button, button label {
+ font-family: 'Noto Sans JP', 'IPAPGothic', 'Noto Sans', sans-serif;
+ font-weight: 700;
+ color: #ffffff;
+}
+button {
+ border-radius: 0;
+ border: 2px solid rgba(0,0,0,0.45);
+ background-image: none;
+ box-shadow: none;
+ text-shadow: none;
+ padding: 0;
+ min-height: 0;
+ min-width: 0;
+}
+
+/* #ConditionNameLabel is styled in the SOUND PAGE section below. */
+
+/* ══════════════════════════════════════════════════════════════════
+ SPLASH / MAIN MENU — design "Final" (A1 buttons + status capsule)
+ ══════════════════════════════════════════════════════════════════ */
+
+#SplashGrid {
+ background-color: rgba(239, 234, 224, 0.92);
+ padding-bottom: 20px;
+}
+
+/* ── mode buttons: rounded green, icon (ModeIcon) + label ── */
+#Option1Button, #Option2Button, #Option3Button {
+ min-height: 95px;
+ padding: 0 34px;
+ background-color: #5E8E1B;
+ background-image: none;
+ border-width: 0;
+ border-radius: 24px;
+ box-shadow: 0 6px 18px rgba(70, 105, 18, 0.28);
+ outline-style: none;
+}
+#Option1Button label, #Option2Button label, #Option3Button label {
+ font-size: 50px;
+ font-weight: 900;
+ color: #FFFFFF;
+}
+#Option1Button:hover, #Option2Button:hover, #Option3Button:hover { background-color: #6A9C22; }
+#Option1Button:active, #Option2Button:active, #Option3Button:active { background-color: #4F7A15; }
+
+/* modes locked until the device connects */
+#Option1Button:disabled, #Option2Button:disabled, #Option3Button:disabled {
+ background-color: #A9B39B;
+ box-shadow: none;
+}
+#Option1Button:disabled label,
+#Option2Button:disabled label,
+#Option3Button:disabled label { color: #F2F4EE; }
+
+/* ── 設定 / 終了 ── */
+#SettingButton, #CloseButton {
+ min-height: 95px;
+ min-width: 200px;
+ border-width: 0;
+ border-radius: 20px;
+ background-image: none;
+ outline-style: none;
+}
+#SettingButton label, #CloseButton label { font-size: 32px; font-weight: 900; color: #FFFFFF; }
+#SettingButton image, #CloseButton image { color: #FFFFFF; margin-right: 10px; }
+
+#SettingButton { background-color: #F28A0A; box-shadow: 0 6px 16px rgba(242, 138, 10, 0.28); }
+#SettingButton:hover { background-color: #FF9A24; }
+#SettingButton:active { background-color: #D96C00; }
+
+#CloseButton { background-color: #6B7280; box-shadow: 0 6px 16px rgba(60, 66, 76, 0.25); }
+#CloseButton:hover { background-color: #7B828F; }
+#CloseButton:active { background-color: #575D69; }
+
+/* ── status capsule (top-right) ── */
+#StatusCapsule {
+ background-color: #FFFFFF;
+ border: 1px solid #E2DDD2;
+ border-radius: 27px;
+ padding: 6px 6px 6px 18px;
+ box-shadow: 0 2px 8px rgba(30, 36, 48, 0.06);
+}
+#CapsuleDivider { background-color: #E2DDD2; min-width: 1px; }
+
+#BatteryArea { color: #4A505B; } /* battery outline (OnBatteryDrawn) */
+#BatteryPercentLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 16px;
+ font-weight: 700;
+ color: #1E2430;
+}
+
+#StatusDot { background-color: #D93025; border-radius: 5px; }
+#StatusDot.on { background-color: #2E9E4F; }
+#ConnectionStatusLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 15px;
+ font-weight: 700;
+ color: #A3201B;
+}
+#ConnectionStatusLabel.on { color: #1E6B32; }
+
+/* あ / A segmented switch (drives the hidden LanguageToggle) */
+#LangSegment { background-color: #ECEEF1; border-radius: 22px; padding: 3px; }
+#LangJpRadio, #LangEnRadio,
+#LangJpRadio button, #LangEnRadio button {
+ min-height: 38px;
+ min-width: 50px;
+ padding: 0;
+ background-color: transparent;
+ background-image: none;
+ border-width: 0;
+ border-radius: 19px;
+ box-shadow: none;
+ outline-style: none;
+}
+#LangJpRadio label, #LangEnRadio label { font-size: 17px; font-weight: 500; color: #4A505B; }
+#LangJpRadio:checked, #LangEnRadio:checked,
+#LangJpRadio button:checked, #LangEnRadio button:checked { background-color: #0B3B6B; }
+#LangJpRadio:checked label, #LangEnRadio:checked label { color: #FFFFFF; font-weight: 700; }
+
+/* ── connection alert (bottom centre) ── */
+#ConnectionAlertLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 21px;
+ font-weight: 700;
+ color: #FFFFFF;
+ background-color: #C62828;
+ border-radius: 28px;
+ padding: 12px 30px;
+ margin: 8px 40px;
+ box-shadow: 0 6px 16px rgba(198, 40, 40, 0.28);
+}
+
+/* ---------- back buttons ---------- */
+/* MapBackButton and SoundBackButton are styled in their page sections
+ (red, bottom-right). */
+#SettingBackButton {
+ min-width: 100px;
+ min-height: 58px;
+ background-color: #F0F0F0;
+ border: 2px solid #B5B5B5;
+}
+#SettingBackButton label { font-size: 20px; color: #111111; }
+#SettingBackButton:hover { background-color: #E2E2E2; }
+
+/* ══════════════════════════════════════════════════════════════════
+ SOUND PAGE — design "Mix" (icon tiles → tile tabs + 3-column grid)
+ Classes come from SoundWindow.cs: type-tile, type-tab, active,
+ lung, heart, sound-clip, compact, clip-main, clip-sub,
+ tile-title, tile-sub, page-title, page-hint.
+ ══════════════════════════════════════════════════════════════════ */
+
+#SoundBox {
+ background-color: rgba(239, 234, 224, 0.92);
+ padding: 22px 40px 20px 40px;
+}
+
+/* title on level 0, quiet hint on the list levels */
+#ConditionNameLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 40px;
+ font-weight: 900;
+ color: #1E2430;
+ background-color: transparent;
+ padding: 0;
+ margin: 0;
+}
+#ConditionNameLabel.page-hint {
+ font-size: 17px;
+ font-weight: 400;
+ color: #5E636D;
+}
+#SoundSubtitleLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 18px;
+ color: #5E636D;
+}
+
+/* ── level 0: big icon tiles ── */
+button.type-tile {
+ background-color: #FFFFFF;
+ background-image: none;
+ border: 1px solid #E2DDD2;
+ border-radius: 20px;
+ box-shadow: 0 2px 8px rgba(30, 36, 48, 0.08);
+ outline-style: none;
+}
+button.type-tile:hover { background-color: #FAF8F4; }
+button.type-tile:active { background-color: #F1EEE8; }
+button.type-tile label.tile-title { font-size: 48px; font-weight: 900; color: #1E2430; }
+button.type-tile label.tile-sub { font-size: 18px; font-weight: 400; color: #5E636D; }
+
+/* ── level 1+: the same tiles, small, as tabs ── */
+button.type-tab {
+ min-height: 80px;
+ min-width: 300px;
+ padding: 0 18px 0 12px;
+ background-color: #FFFFFF;
+ background-image: none;
+ border: 1.5px solid #E2DDD2;
+ border-radius: 16px;
+ box-shadow: none;
+ outline-style: none;
+}
+button.type-tab:hover { background-color: #FAF8F4; }
+button.type-tab label.tile-title { font-size: 26px; font-weight: 700; color: #1E2430; }
+button.type-tab label.tile-sub { font-size: 14px; font-weight: 400; color: #6B6F78; }
+
+button.type-tab.active.lung { background-color: #F2F7FC; border: 2.5px solid #1F6FB2; }
+button.type-tab.active.heart { background-color: #FDF3F3; border: 2.5px solid #C0392B; }
+button.type-tab.active.lung label.tile-title { color: #0F4C85; font-weight: 900; }
+button.type-tab.active.heart label.tile-title { color: #9B2A20; font-weight: 900; }
+
+/* ── sound buttons: white cards, Japanese name bold, English below ── */
+.sound-clip {
+ min-height: 72px;
+ padding: 0 18px;
+ background-color: #FFFFFF;
+ background-image: none;
+ border: 1px solid #E2DDD2;
+ border-radius: 12px;
+ box-shadow: none;
+ outline-style: none;
+}
+.sound-clip:hover { background-color: #F7F5F1; }
+.sound-clip:active { background-color: #EDE9E1; }
+.sound-clip.lung:active { border-color: #1F6FB2; }
+.sound-clip.heart:active { border-color: #C0392B; }
+.sound-clip label.clip-main { font-size: 20px; font-weight: 700; color: #1E2430; }
+.sound-clip label.clip-sub { font-size: 14px; font-weight: 400; color: #6B6F78; }
+
+.sound-clip.compact { min-height: 56px; }
+.sound-clip.compact label.clip-main { font-size: 18px; }
+.sound-clip.compact label.clip-sub { font-size: 13px; }
+
+/* 戻る — red, bottom-right (matches the map page) */
+#SoundBackButton {
+ min-height: 60px;
+ min-width: 130px;
+ padding: 0 26px 0 18px;
+ background-color: #C62828;
+ background-image: none;
+ border-width: 0;
+ border-radius: 12px;
+ outline-style: none;
+}
+#SoundBackButton label { color: #FFFFFF; font-size: 21px; font-weight: 700; }
+#SoundBackButton image { color: #FFFFFF; margin-right: 6px; }
+#SoundBackButton:hover { background-color: #D33A3A; }
+#SoundBackButton:active { background-color: #A61F1F; }
+
+/* ---------- settings page ---------- */
+#ConnectButton, #AutoConnectButton, #RefreshButton {
+ min-height: 46px; min-width: 150px; background-color: #0B3B6B;
+}
+#ConnectButton label, #AutoConnectButton label, #RefreshButton label { font-size: 19px; }
+#ComPortComboBox { min-height: 40px; font-size: 17px; }
+#StatusLabel.status-on { color: #2e7d32; font-weight: bold; font-size: 17px; }
+#StatusLabel.status-off { color: #c62828; font-weight: bold; font-size: 17px; }
+
+/* ══════════════════════════════════════════════════════════════════
+ MAP PAGE — design A "grouped side panel"
+
+ Rule of the page: a LABEL never has a fill or border; anything you
+ can press always has one. One filled primary button (解説を見る).
+
+ Selector sources:
+ #Name — set either by MapWindow.SetName()/Language.Register()
+ or by the in the glade.
+ .class — added in MapWindow via AddClass() (map-title,
+ contact-chip, panel-header, nav-button).
+
+ Sizes target the `label` node directly because _scaleCssProvider
+ emits a plain `label {}` rule that beats any inherited value.
+ ══════════════════════════════════════════════════════════════════ */
+
+/* flat warm ground so the white cards read clearly over back.png */
+#MapBox {
+ background-color: rgba(239, 234, 224, 0.92);
+ padding: 16px 20px 20px 20px;
+}
+
+/* ── cards ── */
+#MapControlBox, #MapPointCard, #HeartWaveCard, #BreathWaveCard {
+ background-color: #FFFFFF;
+ border: 1px solid #E2DDD2;
+ border-radius: 14px;
+}
+#MapControlBox { padding: 18px; }
+#MapPointCard, #HeartWaveCard, #BreathWaveCard { padding: 14px 16px; }
+
+/* ── header ── */
+label.map-title {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 30px;
+ font-weight: 900;
+ color: #1E2430;
+ background-color: transparent;
+ padding: 0 4px;
+}
+
+/* status pill — soft tint + dark text, clearly not a button */
+label.contact-chip {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 17px;
+ font-weight: 700;
+ color: #A3201B;
+ background-color: #FCE8E6;
+ border: 1px solid #F2B8B5;
+ border-radius: 22px;
+ padding: 8px 20px;
+}
+label.contact-chip.contact-ok {
+ color: #1E6B32;
+ background-color: #E6F4EA;
+ border-color: #A8D5B5;
+}
+
+/* ── section labels (plain grey text) ── */
+#MapSectionLabel, #JacketSizeLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 15px;
+ font-weight: 700;
+ color: #6B6F78;
+ background-color: transparent;
+}
+
+/* panel titles: 聴診点 / 心音波形 / 呼吸音波形 */
+label.panel-header {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 20px;
+ font-weight: 700;
+ color: #1E2430;
+ background-color: transparent;
+ padding: 0;
+}
+#HeartSwatch { background-color: #C62828; border-radius: 3px; }
+#BreathSwatch { background-color: #1F6FB2; border-radius: 3px; }
+
+#MapDivider { background-color: #E4E6EA; min-height: 1px; }
+
+/* ── segmented controls: grey track, buttons inside ── */
+#MapSegment {
+ background-color: #ECEEF1;
+ border-radius: 10px;
+ padding: 4px;
+}
+
+/* GtkRadioButton with draw-indicator=False — `#Id button` kept as well,
+ in case the theme puts the button node one level down. */
+#BodySkeletonRadio, #BodyJacketRadio, #SizeLRadio, #SizeXLRadio,
+#ViewFrontRadio, #ViewBackRadio, #ViewRightRadio, #ViewLeftRadio,
+#BodySkeletonRadio button, #BodyJacketRadio button,
+#SizeLRadio button, #SizeXLRadio button,
+#ViewFrontRadio button, #ViewBackRadio button,
+#ViewRightRadio button, #ViewLeftRadio button {
+ min-height: 46px;
+ background-color: transparent;
+ background-image: none;
+ border-width: 0;
+ border-radius: 7px;
+ box-shadow: none;
+ outline-style: none;
+}
+#BodySkeletonRadio label, #BodyJacketRadio label,
+#SizeLRadio label, #SizeXLRadio label,
+#ViewFrontRadio label, #ViewBackRadio label,
+#ViewRightRadio label, #ViewLeftRadio label {
+ font-size: 18px;
+ font-weight: 500;
+ color: #4A505B;
+}
+#BodySkeletonRadio:hover, #BodyJacketRadio:hover, #SizeLRadio:hover, #SizeXLRadio:hover,
+#ViewFrontRadio:hover, #ViewBackRadio:hover, #ViewRightRadio:hover, #ViewLeftRadio:hover {
+ background-color: rgba(255, 255, 255, 0.55);
+}
+
+/* body + size: selected = raised white chip, navy text */
+#BodySkeletonRadio:checked, #BodyJacketRadio:checked,
+#SizeLRadio:checked, #SizeXLRadio:checked,
+#BodySkeletonRadio button:checked, #BodyJacketRadio button:checked,
+#SizeLRadio button:checked, #SizeXLRadio button:checked {
+ background-color: #FFFFFF;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.18);
+}
+#BodySkeletonRadio:checked label, #BodyJacketRadio:checked label,
+#SizeLRadio:checked label, #SizeXLRadio:checked label {
+ color: #0B3B6B;
+ font-weight: 700;
+}
+
+/* 視点: selected = solid navy (it changes what you are looking at) */
+#ViewFrontRadio:checked, #ViewBackRadio:checked,
+#ViewRightRadio:checked, #ViewLeftRadio:checked,
+#ViewFrontRadio button:checked, #ViewBackRadio button:checked,
+#ViewRightRadio button:checked, #ViewLeftRadio button:checked {
+ background-color: #0B3B6B;
+}
+#ViewFrontRadio:checked label, #ViewBackRadio:checked label,
+#ViewRightRadio:checked label, #ViewLeftRadio:checked label {
+ color: #FFFFFF;
+ font-weight: 700;
+}
+
+/* ── 表示 rows: label left, sliding switch right ── */
+#MapToggleRow { min-height: 48px; }
+#MapToggleLabel {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 18px;
+ font-weight: 400;
+ color: #1E2430;
+}
+
+/* GtkSwitch: the `switch` node is the track, `slider` is the knob */
+#ShowNumbersSwitch, #ShowVolumeMapSwitch, #ShowPointListSwitch, #BlackAudioSwitch {
+ min-width: 56px;
+ min-height: 30px;
+ padding: 0;
+ border: none;
+ border-radius: 17px;
+ background-color: #C4C8CF;
+ background-image: none;
+ box-shadow: none;
+ outline-style: none;
+ color: transparent; /* hide the theme's I / O glyphs */
+ font-size: 0;
+}
+#ShowNumbersSwitch:checked, #ShowVolumeMapSwitch:checked,
+#ShowPointListSwitch:checked, #BlackAudioSwitch:checked {
+ background-color: #2E7D32;
+}
+#ShowNumbersSwitch image, #ShowVolumeMapSwitch image,
+#ShowPointListSwitch image, #BlackAudioSwitch image {
+ color: transparent;
+ -gtk-icon-source: none;
+}
+#ShowNumbersSwitch slider, #ShowVolumeMapSwitch slider,
+#ShowPointListSwitch slider, #BlackAudioSwitch slider {
+ min-width: 26px;
+ min-height: 26px;
+ margin: 2px;
+ border: none;
+ border-radius: 50%;
+ background-color: #FFFFFF;
+ background-image: none;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35);
+}
+
+/* ── buttons ── */
+
+/* 再生テスト — secondary: outline */
+#SoundTestButton {
+ min-height: 54px;
+ background-color: #FFFFFF;
+ background-image: none;
+ border: 2px solid #0B3B6B;
+ border-radius: 10px;
+ outline-style: none;
+}
+#SoundTestButton label { color: #0B3B6B; font-size: 20px; font-weight: 700; }
+#SoundTestButton image { color: #0B3B6B; margin-right: 6px; }
+#SoundTestButton:hover { background-color: #EEF3F9; }
+#SoundTestButton:active { background-color: #DCE6F2; }
+
+/* 解説を見る — the one primary action: solid navy */
+#MapExplainButton {
+ min-height: 60px;
+ background-color: #0B3B6B;
+ background-image: none;
+ border-width: 0;
+ border-radius: 12px;
+ outline-style: none;
+}
+#MapExplainButton label { color: #FFFFFF; font-size: 22px; font-weight: 700; }
+#MapExplainButton:hover { background-color: #14538F; }
+#MapExplainButton:active { background-color: #082C51; }
+
+/* 戻る — red, below 解説を見る, bottom-right like every other page */
+#MapBackButton {
+ min-height: 56px;
+ padding: 0 16px;
+ background-color: #C62828;
+ background-image: none;
+ border-width: 0;
+ border-radius: 12px;
+ outline-style: none;
+}
+#MapBackButton label { color: #FFFFFF; font-size: 20px; font-weight: 700; }
+#MapBackButton image { color: #FFFFFF; margin-right: 6px; }
+#MapBackButton:hover { background-color: #D33A3A; }
+#MapBackButton:active { background-color: #A61F1F; }
+
+/* the popup of any combo is a separate toplevel — keep it readable */
+window.popup list row label { color: #111111; }
+
+/* #BatteryLabel { margin-left: 4px; } */
+#BatteryLabel.battery-low { color: #c62828; font-weight: bold; }
+
+/* ---------- power-off confirmation ---------- */
+/* Own toplevel, so the generic `window` and `button` rules at the top of
+ this file apply to it. Undo both, then restyle from scratch. */
+#PowerOffDialog {
+ background-image: none;
+ background-color: #FFFFFF;
+ border: 4px solid #0B3B6B;
+}
+#PowerOffDialog box,
+#PowerOffDialog .dialog-vbox,
+#PowerOffDialog .dialog-action-area {
+ background-color: transparent;
+ background-image: none;
+}
+
+#PowerOffMessage {
+ font-family: 'Noto Sans JP', 'IPAPGothic', 'Noto Sans', sans-serif;
+ font-size: 40px;
+ font-weight: 700;
+ color: #1e1e1e;
+ margin: 36px 40px 24px 40px;
+}
+
+#PowerOffDialog button {
+ min-height: 90px;
+ min-width: 280px;
+ margin: 0 20px 30px 20px;
+ border: 2px solid rgba(0,0,0,0.45);
+ border-radius: 0;
+}
+#PowerOffDialog button label { font-size: 34px; color: #ffffff; }
+
+#PowerOffCancel { background-color: #808080; }
+#PowerOffCancel:hover { background-color: #909090; }
+#PowerOffCancel:active { background-color: #6E6E6E; }
+
+#PowerOffConfirm { background-color: #C62828; }
+#PowerOffConfirm:hover { background-color: #D33A3A; }
+#PowerOffConfirm:active { background-color: #A61F1F; }
+
+/* ══════════════════════════════════════════════════════════════════
+ MAP PAGE ADDITIONS — paste at the very END of touch_friendly.css.
+ The "compact side panel" part overrides sizes defined earlier in the
+ file, so it must come after them.
+ ══════════════════════════════════════════════════════════════════ */
+
+/* ── 再生する音: ミックス / 心音のみ / 肺音のみ ──
+ Same look as the body / size segments; the selected chip is tinted
+ red for heart and blue for lung so it matches the waveform cards. */
+#SoundMixRadio, #SoundHeartOnlyRadio, #SoundLungOnlyRadio,
+#SoundMixRadio button, #SoundHeartOnlyRadio button, #SoundLungOnlyRadio button {
+ min-height: 38px;
+ background-color: transparent;
+ background-image: none;
+ border-width: 0;
+ border-radius: 7px;
+ box-shadow: none;
+ outline-style: none;
+}
+#SoundMixRadio label, #SoundHeartOnlyRadio label, #SoundLungOnlyRadio label {
+ font-size: 16px;
+ font-weight: 500;
+ color: #4A505B;
+}
+#SoundMixRadio:hover, #SoundHeartOnlyRadio:hover, #SoundLungOnlyRadio:hover {
+ background-color: rgba(255, 255, 255, 0.55);
+}
+#SoundMixRadio:checked, #SoundHeartOnlyRadio:checked, #SoundLungOnlyRadio:checked,
+#SoundMixRadio button:checked, #SoundHeartOnlyRadio button:checked,
+#SoundLungOnlyRadio button:checked {
+ background-color: #FFFFFF;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.18);
+}
+#SoundMixRadio:checked label { color: #0B3B6B; font-weight: 700; }
+#SoundHeartOnlyRadio:checked label { color: #C62828; font-weight: 700; }
+#SoundLungOnlyRadio:checked label { color: #1F6FB2; font-weight: 700; }
+
+/* ── compact side panel: fits 1280x800 with no scrolling ──
+ MapWindow turns scrolling off in normal mode and on in debug mode
+ (debug adds the 番号を表示 row, so it may need to scroll). */
+#MapControlBox { padding: 10px 14px; }
+
+#MapSegment { padding: 3px; }
+
+#BodySkeletonRadio, #BodyJacketRadio, #SizeLRadio, #SizeXLRadio,
+#ViewFrontRadio, #ViewBackRadio, #ViewRightRadio, #ViewLeftRadio,
+#BodySkeletonRadio button, #BodyJacketRadio button,
+#SizeLRadio button, #SizeXLRadio button,
+#ViewFrontRadio button, #ViewBackRadio button,
+#ViewRightRadio button, #ViewLeftRadio button,
+#SoundMixRadio, #SoundHeartOnlyRadio, #SoundLungOnlyRadio,
+#SoundMixRadio button, #SoundHeartOnlyRadio button, #SoundLungOnlyRadio button {
+ min-height: 34px;
+}
+#BodySkeletonRadio label, #BodyJacketRadio label,
+#SizeLRadio label, #SizeXLRadio label,
+#ViewFrontRadio label, #ViewBackRadio label,
+#ViewRightRadio label, #ViewLeftRadio label {
+ font-size: 17px;
+}
+
+#MapToggleRow { min-height: 34px; }
+#MapToggleLabel { font-size: 17px; }
+
+#MapSectionLabel, #JacketSizeLabel { font-size: 14px; }
+
+#SoundTestButton { min-height: 40px; }
+#SoundTestButton label { font-size: 18px; }
+
+/* ── 解説を見る: explanation image window ──
+ Own toplevel, so the global `window` background and `button` rules at
+ the top of touch_friendly.css apply to it. Undo them, then restyle. */
+#ExplainDialog {
+ background-image: none;
+ background-color: #FFFFFF;
+ border: 3px solid #0B3B6B;
+}
+#ExplainDialog box,
+#ExplainDialog .dialog-vbox,
+#ExplainDialog .dialog-action-area {
+ background-color: transparent;
+ background-image: none;
+}
+#ExplainDialog .dialog-action-area { margin: 0 20px 16px 20px; }
+
+#ExplainMessage {
+ font-family: 'Noto Sans JP', 'IPAPGothic', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #1E2430;
+ margin: 40px;
+}
+
+/* 戻る — same red as the page back buttons */
+#ExplainBackButton {
+ min-height: 60px;
+ min-width: 180px;
+ padding: 0 26px;
+ background-color: #C62828;
+ background-image: none;
+ border-width: 0;
+ border-radius: 12px;
+ outline-style: none;
+}
+#ExplainBackButton label { color: #FFFFFF; font-size: 22px; font-weight: 700; }
+#ExplainBackButton:hover { background-color: #D33A3A; }
+#ExplainBackButton:active { background-color: #A61F1F; }
\ No newline at end of file