diff --git a/program/AppMode.cs b/program/AppMode.cs index c4af777..3c7178d 100644 --- a/program/AppMode.cs +++ b/program/AppMode.cs @@ -45,6 +45,28 @@ 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); diff --git a/program/AudioOutput.cs b/program/AudioOutput.cs new file mode 100644 index 0000000..668efd0 --- /dev/null +++ b/program/AudioOutput.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +/// Speaker <-> headphone-jack switching through the sound server +/// (PulseAudio, or PipeWire's pulse layer), using the `pactl` command. +/// +/// Built-in speaker and the 3.5mm jack are normally two PORTS of the same +/// output (sink), so switching is `pactl set-sink-port`. The OpenAL stream +/// keeps playing, it just comes out of the other port. If the headphones are +/// a separate device (USB / Bluetooth), the default sink is changed instead +/// and every playing stream is moved to it. +public static class AudioOutput +{ + public enum Kind { Unknown, Speaker, Jack } + + private class Port + { + public string Name, Desc; + public bool Unplugged; // "not available" = jack empty + public Kind Kind; + } + + private class Sink + { + public string Name; + public string ActivePort; + public List Ports = new List(); + } + + public static event Action Log; + + /// What is playing sound right now. + public static Kind Current() + { + List sinks; string def; + if (!Read(out sinks, out def)) return Kind.Unknown; + + Sink s = sinks.Find(x => x.Name == def); + if (s == null) return Kind.Unknown; + + Port p = s.Ports.Find(x => x.Name == s.ActivePort); + if (p != null && p.Kind != Kind.Unknown) return p.Kind; + return Classify(s.Name, ""); // e.g. a USB headset sink with no ports + } + + /// 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; + List sinks; string def; + if (!Read(out sinks, out def)) { problem = "pactl not available"; return Kind.Unknown; } + + Kind now = Current(); + Kind want = now == Kind.Jack ? Kind.Speaker : Kind.Jack; + + // 1) another port on the same sink (the normal laptop / tablet case) + Sink cur = sinks.Find(x => x.Name == def); + if (cur != null) + { + Port target = cur.Ports.Find(p => p.Kind == want); + if (target != null) + { + if (target.Unplugged && want == Kind.Jack) + { + problem = "jack-empty"; + Emit("headphone port '" + target.Name + "' reports nothing plugged in"); + return now; + } + int code; + Run("set-sink-port " + Quote(cur.Name) + " " + Quote(target.Name), out code); + if (code == 0) + { + Emit("port " + cur.ActivePort + " -> " + target.Name); + return Current(); + } + Emit("set-sink-port failed (exit " + code + ")"); + } + } + + // 2) a different sink of the wanted kind (USB / Bluetooth headphones) + foreach (var s in sinks) + { + if (s.Name == def) continue; + bool match = Classify(s.Name, "") == want || s.Ports.Exists(p => p.Kind == want && !p.Unplugged); + if (!match) continue; + + int code; + Run("set-default-sink " + Quote(s.Name), out code); + if (code != 0) continue; + MoveAllStreams(s.Name); + Emit("default sink " + def + " -> " + s.Name); + return Current(); + } + + problem = want == Kind.Jack ? "no-jack" : "no-speaker"; + Emit("no " + want + " output found"); + return now; + } + + // ── pactl ────────────────────────────────────────────────────────── + + private static bool Read(out List sinks, out string defaultSink) + { + sinks = new List(); + defaultSink = null; + + int code; + string info = Run("info", out code); + if (code != 0 || info == null) return false; + foreach (string line in info.Split('\n')) + if (line.StartsWith("Default Sink:")) + defaultSink = line.Substring("Default Sink:".Length).Trim(); + + string list = Run("list sinks", out code); + if (code != 0 || list == null) return false; + + Sink cur = null; + bool inPorts = false; + foreach (string raw in list.Split('\n')) + { + string line = raw.TrimEnd(); + string t = line.Trim(); + + if (line.StartsWith("Sink #")) { cur = new Sink(); sinks.Add(cur); inPorts = false; continue; } + if (cur == null) continue; + + if (t.StartsWith("Name:")) { cur.Name = t.Substring(5).Trim(); continue; } + if (t.StartsWith("Active Port:")) { cur.ActivePort = t.Substring(12).Trim(); inPorts = false; continue; } + if (t == "Ports:") { inPorts = true; continue; } + + if (inPorts) + { + // port lines are indented two tabs: "\t\tname: Description (type: ..., availability ...)" + if (!line.StartsWith("\t\t") || line.StartsWith("\t\t\t")) { if (!line.StartsWith("\t\t")) inPorts = false; continue; } + int colon = t.IndexOf(':'); + if (colon <= 0) continue; + + var p = new Port { Name = t.Substring(0, colon).Trim() }; + string rest = t.Substring(colon + 1).Trim(); + int paren = rest.IndexOf('('); + p.Desc = paren > 0 ? rest.Substring(0, paren).Trim() : rest; + p.Unplugged = rest.Contains("not available"); + p.Kind = Classify(p.Name, rest); + cur.Ports.Add(p); + } + } + return defaultSink != null; + } + + private static Kind Classify(string name, string desc) + { + string s = (name + " " + desc).ToLowerInvariant(); + if (s.Contains("headphone") || s.Contains("headset") || s.Contains("lineout") || + s.Contains("line-out") || s.Contains("line out")) + return Kind.Jack; + if (s.Contains("speaker")) return Kind.Speaker; + return Kind.Unknown; + } + + private static void MoveAllStreams(string sink) + { + int code; + string list = Run("list short sink-inputs", out code); + if (code != 0 || list == null) return; + foreach (string line in list.Split('\n')) + { + string id = line.Split('\t')[0].Trim(); + if (id.Length > 0) Run("move-sink-input " + id + " " + Quote(sink), out code); + } + } + + private static string Run(string args, out int exitCode) + { + exitCode = -1; + 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)) + { + string output = p.StandardOutput.ReadToEnd(); + string err = p.StandardError.ReadToEnd(); + if (!p.WaitForExit(3000)) { try { p.Kill(); } catch { } return null; } + 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; + } + } + + private static string Quote(string s) { return "\"" + s.Replace("\"", "\\\"") + "\""; } + + private static void Emit(string m) + { + var h = Log; + if (h != null) h(m); else Console.WriteLine("[output] " + m); + } +} \ No newline at end of file diff --git a/program/homepageallv8.glade b/program/homepageallv8.glade index 8398c53..aa7453b 100644 --- a/program/homepageallv8.glade +++ b/program/homepageallv8.glade @@ -24,7 +24,7 @@ True False - media-playback-start-symbolic + audio-speakers-symbolic True @@ -783,6 +783,8 @@ False True never + + never True @@ -794,7 +796,7 @@ True False vertical - 8 + 5 False @@ -887,7 +889,7 @@ MapSectionLabel True False - 10 + 6 0 サイズ @@ -966,7 +968,7 @@ MapSectionLabel True False - 10 + 6 0 視点 @@ -1055,8 +1057,8 @@ MapDivider True False - 12 - 4 + 6 + 2 False @@ -1257,7 +1259,7 @@ MapSectionLabel True False - 10 + 6 0 再生する音 @@ -1345,8 +1347,9 @@ + - 再生テスト + 出力:スピーカー True True True