diff --git a/winui/Kern/Dienst.cs b/winui/Kern/Dienst.cs new file mode 100644 index 00000000..d5fcd67d --- /dev/null +++ b/winui/Kern/Dienst.cs @@ -0,0 +1,152 @@ +using System.Diagnostics; +using System.Net.Sockets; +using System.Runtime.InteropServices; + +namespace Pokerfreak.Cockpit.Kern; + +/// +/// Windows: den Python-Server selbst hochziehen, falls sein Port tot ist (wie cockpit/src/dienst.rs; +/// am Mac macht das ServerProzess.swift). Mit `--client` (ausser COCKPIT_KLON=1) und dem Tisch-Desktop +/// COINPOKER_DESKTOP (Vorgabe "1", ein ausdruecklicher Wert gewinnt) - den erbt der Laeufer ueber den +/// Server. Ein Job-Objekt mit KILL_ON_JOB_CLOSE raeumt Server und alles, was er startete, beim Ende weg. +/// +public sealed class Dienst : IDisposable +{ + private Process? _kind; + private IntPtr _job; + + /// Der Desktop-Schalter: leer/fehlend -> "1". + public static string DesktopSchalter(string? vorhanden) => + string.IsNullOrWhiteSpace(vorhanden) ? "1" : vorhanden.Trim(); + + public static string Desktop => DesktopSchalter(Environment.GetEnvironmentVariable("COINPOKER_DESKTOP")); + + public static List ServerArgumente(int port, bool klon) + { + var a = new List { Path.Combine("sicht", "start.py"), "--port", port.ToString(), "--art", "App" }; + if (!klon) a.Add("--client"); + return a; + } + + private static bool PortOffen(int port) + { + try + { + using var c = new TcpClient(); + return c.ConnectAsync("127.0.0.1", port).Wait(300) && c.Connected; + } + catch { return false; } + } + + private static string Python(string wurzel) + { + foreach (var p in new[] { Path.Combine(wurzel, ".venv", "Scripts", "python.exe"), Path.Combine(wurzel, "venv", "Scripts", "python.exe") }) + if (File.Exists(p)) return p; + return "python"; + } + + /// Startet den Server, wenn die Adresse lokal ist und dort keiner lauscht. Blockiert nicht + /// auf den Start - die Verbindung verbindet von selbst neu, sobald er antwortet. + public static Dienst Starten(Adresse a) + { + var d = new Dienst(); + if (a.Host is not ("127.0.0.1" or "localhost") || PortOffen(a.Port)) return d; + var wurzel = Wurzel.Finden(); + if (wurzel == null) + { + Debug.WriteLine("Server nicht gestartet: Projektwurzel (sicht/start.py) nicht gefunden"); + return d; + } + var info = new ProcessStartInfo(Python(wurzel)) + { + WorkingDirectory = wurzel, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = false, + }; + foreach (var x in ServerArgumente(a.Port, Environment.GetEnvironmentVariable("COCKPIT_KLON")?.Trim() == "1")) + info.ArgumentList.Add(x); + info.Environment["PYTHONUTF8"] = "1"; // sonst bricht der Server an Umlauten ab + info.Environment["PYTHONIOENCODING"] = "utf-8"; + info.Environment["COINPOKER_DESKTOP"] = Desktop; // erbt der Laeufer (steuern.laeufer_starten) + try + { + var p = Process.Start(info); + if (p == null) return d; + d._job = JobMitKillswitch(p.Handle); + // Ging er sofort wieder (Python fehlt, Importfehler, Sperre belegt), nicht als laufend fuehren. + if (p.WaitForExit(250)) + { + if (d._job != IntPtr.Zero) CloseHandle(d._job); + d._job = IntPtr.Zero; + return d; + } + d._kind = p; + } + catch (Exception e) + { + Debug.WriteLine($"Server nicht gestartet: {e.Message}"); + } + return d; + } + + public bool Gestartet => _kind != null; + + public void Dispose() + { + try { if (_kind is { HasExited: false }) _kind.Kill(true); } catch { } + _kind = null; + if (_job != IntPtr.Zero) CloseHandle(_job); + _job = IntPtr.Zero; + } + + // ---- Job-Objekt --------------------------------------------------------------------------- + + private static IntPtr JobMitKillswitch(IntPtr prozess) + { + var job = CreateJobObjectW(IntPtr.Zero, null); + if (job == IntPtr.Zero) return IntPtr.Zero; + var info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION(); + info.BasicLimitInformation.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + var groesse = Marshal.SizeOf(); + var zeiger = Marshal.AllocHGlobal(groesse); + try + { + Marshal.StructureToPtr(info, zeiger, false); + SetInformationJobObject(job, 9 /* JobObjectExtendedLimitInformation */, zeiger, (uint)groesse); + } + finally { Marshal.FreeHGlobal(zeiger); } + AssignProcessToJobObject(job, prozess); + return job; + } + + [StructLayout(LayoutKind.Sequential)] + private struct JOBOBJECT_BASIC_LIMIT_INFORMATION + { + public long PerProcessUserTimeLimit, PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass, SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + private struct IO_COUNTERS + { + public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount, ReadTransferCount, WriteTransferCount, OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION + { + public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; + public IO_COUNTERS IoInfo; + public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CreateJobObjectW(IntPtr a, string? name); + [DllImport("kernel32.dll")] private static extern bool SetInformationJobObject(IntPtr job, int klasse, IntPtr info, uint laenge); + [DllImport("kernel32.dll")] private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr prozess); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr h); +} diff --git a/winui/Kern/Ort.cs b/winui/Kern/Ort.cs new file mode 100644 index 00000000..2a0ff2dc --- /dev/null +++ b/winui/Kern/Ort.cs @@ -0,0 +1,159 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.UI.Dispatching; + +namespace Pokerfreak.Cockpit.Kern; + +/// +/// Wo das Cockpit steht - fuer das Kacheln und den Tisch-Desktop (wie cockpit/src/ort.rs). +/// 1. Rahmen melden: jede Sekunde den echten Rahmen (physische Pixel, ohne DWM-Rand) als +/// `cockpit.json` in den Treffpunkt schreiben, wenn er sich geaendert hat - die Tische werden +/// daneben gekachelt (sicht/tische.py `rahmen_fuer`). Versteckt oder minimiert: Datei weg, die Tische +/// duerfen die ganze Flaeche nehmen. Beim Ende wird sie geloescht. +/// 2. Auf allen Desktops: liegen die Tische auf ihrem eigenen virtuellen Desktop (COINPOKER_DESKTOP=1), +/// heftet sich das Cockpit ueber den Fensterdienst (`anheften`) an alle Desktops - sonst waere es +/// unsichtbar, sobald der Owner zu den Tischen wechselt. +/// +public sealed class Ort : IDisposable +{ + private const int AnheftenVersuche = 5; + + private readonly IntPtr _hwnd; + private readonly string? _datei; + private readonly string? _fensterdienst; + private readonly DispatcherQueueTimer _timer; + private (int, int, int, int)? _letzter; + private bool _wegGemeldet, _angeheftet, _heftet; + private int _versuche; + + /// Wie client/umgebung.py `treffpunkt`: SCRATCH, sonst betrieb/scratch, ohne betrieb/ scratch/. + public static string Treffpunkt(string wurzel, string? scratch) + { + if (!string.IsNullOrWhiteSpace(scratch)) return scratch.Trim(); + return Directory.Exists(Path.Combine(wurzel, "betrieb")) + ? Path.Combine(wurzel, "betrieb", "scratch") + : Path.Combine(wurzel, "scratch"); + } + + /// `form: "fenster"`: das Kacheln nimmt die Flaeche neben dem Rahmen (kein Leisten-Ziel). + public static string CockpitJson(int x, int y, int w, int h) => + $"{{\"rect\": [{x}, {y}, {w}, {h}], \"form\": \"fenster\", \"quelle\": \"windows-cockpit\"}}"; + + /// Der Fensterdienst, release vor debug (hand/winfenster.py `_bin`). + public static string? Fensterdienst(string wurzel) + { + var basis = Path.Combine(wurzel, "werkzeuge", "fensterdienst", "target"); + return new[] { "release", "debug" }.Select(a => Path.Combine(basis, a, "fensterdienst.exe")).FirstOrDefault(File.Exists); + } + + public Ort(IntPtr hwnd, DispatcherQueue ui) + { + _hwnd = hwnd; + var wurzel = Wurzel.Finden(); + _datei = wurzel == null ? null : Path.Combine(Treffpunkt(wurzel, Environment.GetEnvironmentVariable("SCRATCH")), "cockpit.json"); + var isoliert = Dienst.Desktop == "1"; + _fensterdienst = wurzel == null ? null : Fensterdienst(wurzel); + if (isoliert && _fensterdienst == null) + Debug.WriteLine("Fensterdienst nicht gebaut (werkzeuge/fensterdienst): Cockpit bleibt auf einem Desktop"); + _angeheftet = !isoliert || _fensterdienst == null; + _timer = ui.CreateTimer(); + _timer.Interval = TimeSpan.FromSeconds(1); + _timer.IsRepeating = true; + _timer.Tick += (_, _) => Takt(); + _timer.Start(); + Takt(); + } + + /// Ist das Fenster an alle Desktops geheftet (oder braucht es das nicht)? + public bool Angeheftet => _angeheftet; + + private void Takt() + { + if (_datei != null) + { + var sichtbar = IsWindowVisible(_hwnd) && !IsIconic(_hwnd); + if (sichtbar && Rahmen() is var (x, y, w, h)) + { + if (_letzter != (x, y, w, h) || _wegGemeldet) + { + Schreiben(_datei, CockpitJson(x, y, w, h)); + _letzter = (x, y, w, h); + _wegGemeldet = false; + } + } + else if (!_wegGemeldet) + { + try { File.Delete(_datei); } catch { } + _letzter = null; + _wegGemeldet = true; + } + } + if (!_angeheftet && !_heftet && _versuche++ < AnheftenVersuche && _fensterdienst != null) + { + _heftet = true; + var exe = _fensterdienst; + var h = _hwnd.ToInt64(); + Task.Run(() => Anheften(exe, h)); + } + } + + /// Einmal `fensterdienst anheften {"id":hwnd}` - im Hintergrund (COM, ~100 ms). + private void Anheften(string exe, long h) + { + try + { + var info = new ProcessStartInfo(exe) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + info.ArgumentList.Add("anheften"); + info.ArgumentList.Add($"{{\"befehl\":\"anheften\",\"id\":{h}}}"); + using var p = Process.Start(info)!; + var text = p.StandardOutput.ReadToEnd(); + p.WaitForExit(5000); + if (text.Contains("\"ok\":true") || text.Contains("\"ok\": true")) _angeheftet = true; + else Debug.WriteLine("Cockpit nicht angeheftet: " + text.Trim()); + } + catch (Exception e) + { + Debug.WriteLine($"Fensterdienst nicht gestartet ({exe}): {e.Message}"); + } + finally { _heftet = false; } + } + + private (int, int, int, int)? Rahmen() + { + var ok = DwmGetWindowAttribute(_hwnd, 9 /* DWMWA_EXTENDED_FRAME_BOUNDS */, out RECT r, Marshal.SizeOf()) == 0 + || GetWindowRect(_hwnd, out r); + return ok && r.Rechts > r.Links && r.Unten > r.Oben ? (r.Links, r.Oben, r.Rechts - r.Links, r.Unten - r.Oben) : null; + } + + private static void Schreiben(string datei, string inhalt) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(datei)!); + var tmp = Path.ChangeExtension(datei, ".json.tmp"); + File.WriteAllText(tmp, inhalt); + File.Move(tmp, datei, true); + } + catch { } + } + + public void Dispose() + { + _timer.Stop(); + if (_datei != null) try { File.Delete(_datei); } catch { } + } + + [StructLayout(LayoutKind.Sequential)] + private struct RECT { public int Links, Oben, Rechts, Unten; } + + [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr h, int attr, out RECT r, int groesse); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr h); +} diff --git a/winui/Kern/Schale.cs b/winui/Kern/Schale.cs new file mode 100644 index 00000000..62ccb9e3 --- /dev/null +++ b/winui/Kern/Schale.cs @@ -0,0 +1,136 @@ +using System.Runtime.InteropServices; + +namespace Pokerfreak.Cockpit.Kern; + +/// +/// Das Tray-Symbol (wie cockpit/src/schale.rs): Minimieren versteckt das Cockpit ins Tray statt in die +/// Taskleiste; Klick aufs Symbol holt es zurueck, Rechtsklick zeigt "Cockpit zeigen" und "Beenden". +/// Die Nachrichten kommen ueber eine Unterklasse des Hauptfensters (SetWindowSubclass). +/// +public sealed class Schale : IDisposable +{ + private const uint WmTray = 0x8000 + 41; // WM_APP + 41 + private const int MenueZeigen = 1, MenueBeenden = 2; + + private readonly IntPtr _hwnd; + private readonly SubclassProc _proc; // haelt den Delegaten am Leben + private readonly Action _zeigen, _beenden; + private IntPtr _icon; + private bool _da; + + public Schale(IntPtr hwnd, string icoPfad, string tipp, Action zeigen, Action beenden) + { + _hwnd = hwnd; + _zeigen = zeigen; + _beenden = beenden; + _proc = Nachricht; + SetWindowSubclass(hwnd, _proc, (UIntPtr)41, UIntPtr.Zero); + _icon = LoadImageW(IntPtr.Zero, icoPfad, 1 /* IMAGE_ICON */, 16, 16, 0x10 /* LR_LOADFROMFILE */); + var d = Daten(); + d.uFlags = 0x1 | 0x2 | 0x4; // NIF_MESSAGE | NIF_ICON | NIF_TIP + d.uCallbackMessage = WmTray; + d.hIcon = _icon; + d.szTip = tipp; + _da = Shell_NotifyIconW(0 /* NIM_ADD */, ref d); + } + + /// Den Hinweistext am Symbol aendern (z. B. Laeufer-Zustand). + public void Tipp(string text) + { + if (!_da) return; + var d = Daten(); + d.uFlags = 0x4; + d.szTip = text.Length > 127 ? text[..127] : text; + Shell_NotifyIconW(1 /* NIM_MODIFY */, ref d); + } + + private NOTIFYICONDATAW Daten() => new() + { + cbSize = (uint)Marshal.SizeOf(), + hWnd = _hwnd, + uID = 1, + szTip = "", + szInfo = "", + szInfoTitle = "", + }; + + private IntPtr Nachricht(IntPtr h, uint msg, IntPtr wp, IntPtr lp, UIntPtr id, UIntPtr daten) + { + if (msg == WmTray) + { + switch ((uint)(lp.ToInt64() & 0xFFFF)) + { + case 0x202: // WM_LBUTTONUP + _zeigen(); + break; + case 0x205: // WM_RBUTTONUP + Menue(); + break; + } + return IntPtr.Zero; + } + return DefSubclassProc(h, msg, wp, lp); + } + + private void Menue() + { + var m = CreatePopupMenu(); + AppendMenuW(m, 0, (UIntPtr)MenueZeigen, "Cockpit zeigen"); + AppendMenuW(m, 0, (UIntPtr)MenueBeenden, "Beenden"); + GetCursorPos(out var p); + SetForegroundWindow(_hwnd); + var wahl = TrackPopupMenu(m, 0x2 | 0x100 | 0x80 /* RIGHTBUTTON|RETURNCMD|NONOTIFY */, p.X, p.Y, 0, _hwnd, IntPtr.Zero); + PostMessageW(_hwnd, 0, IntPtr.Zero, IntPtr.Zero); + DestroyMenu(m); + if (wahl == MenueZeigen) _zeigen(); + else if (wahl == MenueBeenden) _beenden(); + } + + public void Dispose() + { + if (_da) + { + var d = Daten(); + Shell_NotifyIconW(2 /* NIM_DELETE */, ref d); + _da = false; + } + RemoveWindowSubclass(_hwnd, _proc, (UIntPtr)41); + if (_icon != IntPtr.Zero) DestroyIcon(_icon); + _icon = IntPtr.Zero; + } + + private delegate IntPtr SubclassProc(IntPtr h, uint msg, IntPtr wp, IntPtr lp, UIntPtr id, UIntPtr daten); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct NOTIFYICONDATAW + { + public uint cbSize; + public IntPtr hWnd; + public uint uID, uFlags, uCallbackMessage; + public IntPtr hIcon; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string szTip; + public uint dwState, dwStateMask; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string szInfo; + public uint uVersion; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string szInfoTitle; + public uint dwInfoFlags; + public Guid guidItem; + public IntPtr hBalloonIcon; + } + + [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode)] private static extern bool Shell_NotifyIconW(uint was, ref NOTIFYICONDATAW d); + [DllImport("comctl32.dll")] private static extern bool SetWindowSubclass(IntPtr h, SubclassProc p, UIntPtr id, UIntPtr daten); + [DllImport("comctl32.dll")] private static extern bool RemoveWindowSubclass(IntPtr h, SubclassProc p, UIntPtr id); + [DllImport("comctl32.dll")] private static extern IntPtr DefSubclassProc(IntPtr h, uint msg, IntPtr wp, IntPtr lp); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr LoadImageW(IntPtr inst, string name, uint typ, int cx, int cy, uint flags); + [DllImport("user32.dll")] private static extern bool DestroyIcon(IntPtr h); + [DllImport("user32.dll")] private static extern IntPtr CreatePopupMenu(); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern bool AppendMenuW(IntPtr m, uint flags, UIntPtr id, string text); + [DllImport("user32.dll")] private static extern bool DestroyMenu(IntPtr m); + [DllImport("user32.dll")] private static extern int TrackPopupMenu(IntPtr m, uint flags, int x, int y, int r, IntPtr h, IntPtr rect); + [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p); + [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] private static extern bool PostMessageW(IntPtr h, uint msg, IntPtr wp, IntPtr lp); +} diff --git a/winui/Kern/Wurzel.cs b/winui/Kern/Wurzel.cs index a95c99fa..0285f273 100644 --- a/winui/Kern/Wurzel.cs +++ b/winui/Kern/Wurzel.cs @@ -1,83 +1,87 @@ -namespace Pokerfreak.Cockpit.Kern; - -/// -/// Was die App selbst auf der Platte tut - so wenig wie moeglich: die Pausendateien (wie Mac- und -/// Rust-App, bruecke_live.rs) und der zuletzt gewaehlte Modus (geteilt mit dem Rust-Cockpit). -/// -public static class Wurzel -{ - /// Der Projektordner: POKERFREAK_WURZEL, sonst aufwaerts vom Programm bis zu einem Ordner mit lesen/ und sicht/. - public static string? Finden() - { - var env = Environment.GetEnvironmentVariable("POKERFREAK_WURZEL"); - if (!string.IsNullOrEmpty(env) && Directory.Exists(env)) return env; - var d = new DirectoryInfo(AppContext.BaseDirectory); - while (d != null) - { - if (Directory.Exists(Path.Combine(d.FullName, "lesen")) && Directory.Exists(Path.Combine(d.FullName, "sicht"))) - return d.FullName; - d = d.Parent; - } - return null; - } - - private static IEnumerable PausePfade() - { - var w = Finden(); - if (w == null) yield break; - foreach (var p in new[] { "scratch/pause", "hand/scratch/pause", "betrieb/scratch/pause" }) - yield return Path.Combine(w, p); - } - - public static bool Pausiert() => PausePfade().Any(File.Exists); - - /// Pause setzen oder loesen; die Rueckmeldung sagt, ob es geklappt hat. - public static Rueckmeldung PauseSetzen(bool an) - { - var pfade = PausePfade().ToList(); - var fehler = new List(); - foreach (var p in pfade) - { - try - { - if (an) - { - Directory.CreateDirectory(Path.GetDirectoryName(p)!); - File.WriteAllText(p, "pause"); - } - else if (File.Exists(p)) File.Delete(p); - } - catch (Exception) { fehler.Add(p); } - } - var ok = fehler.Count == 0 && pfade.Count > 0; - var text = (an, ok) switch - { - (true, true) => "Pause - der Läufer klickt nicht mehr, Tische und Sitz bleiben", - (false, true) => "Fortgesetzt - der Läufer spielt weiter", - _ when pfade.Count == 0 => "Projektordner nicht gefunden - Pause nicht gesetzt", - _ => $"Pause nicht {(an ? "gesetzt" : "gelöst")}: {string.Join(", ", fehler)}", - }; - return new Rueckmeldung(an ? "pausieren" : "fortsetzen", ok, text); - } - - // %APPDATA%\Pokerfreak\modus.txt ("echt" | "uebung") - dieselbe Datei wie das Rust-Cockpit. - private static string ModusDatei() => - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Pokerfreak", "modus.txt"); - - /// Nur ein ausdrueckliches "echt" gibt Echtgeld, alles andere Uebung. - public static Modus ModusLesen() - { - try { return File.ReadAllText(ModusDatei()).Trim() == "echt" ? Modus.Echt : Modus.Uebung; } - catch { return Modus.Uebung; } - } - - public static void ModusMerken(Modus m) - { - try - { - Directory.CreateDirectory(Path.GetDirectoryName(ModusDatei())!); - File.WriteAllText(ModusDatei(), m == Modus.Echt ? "echt" : "uebung"); - } - catch { } - } -} +namespace Pokerfreak.Cockpit.Kern; + +/// +/// Was die App selbst auf der Platte tut - so wenig wie moeglich: die Pausendateien (wie Mac- und +/// Rust-App, bruecke_live.rs) und der zuletzt gewaehlte Modus (geteilt mit dem Rust-Cockpit). +/// +public static class Wurzel +{ + /// Der Projektordner: POKERFREAK_WURZEL, sonst aufwaerts vom Programm bis zu einem Ordner mit lesen/ und sicht/. + public static string? Finden() + { + var env = Environment.GetEnvironmentVariable("POKERFREAK_WURZEL"); + if (!string.IsNullOrEmpty(env) && Directory.Exists(env)) return env; + // Wie dienst.rs `wurzel_finden`: vom Arbeitsverzeichnis und vom Programm aus aufwaerts + foreach (var start in new[] { Environment.CurrentDirectory, AppContext.BaseDirectory }) + { + var d = new DirectoryInfo(start); + while (d != null) + { + if (File.Exists(Path.Combine(d.FullName, "sicht", "start.py")) && Directory.Exists(Path.Combine(d.FullName, "lesen"))) + return d.FullName; + d = d.Parent; + } + } + return null; + } + + private static IEnumerable PausePfade() + { + var w = Finden(); + if (w == null) yield break; + foreach (var p in new[] { "scratch/pause", "hand/scratch/pause", "betrieb/scratch/pause" }) + yield return Path.Combine(w, p); + } + + public static bool Pausiert() => PausePfade().Any(File.Exists); + + /// Pause setzen oder loesen; die Rueckmeldung sagt, ob es geklappt hat. + public static Rueckmeldung PauseSetzen(bool an) + { + var pfade = PausePfade().ToList(); + var fehler = new List(); + foreach (var p in pfade) + { + try + { + if (an) + { + Directory.CreateDirectory(Path.GetDirectoryName(p)!); + File.WriteAllText(p, "pause"); + } + else if (File.Exists(p)) File.Delete(p); + } + catch (Exception) { fehler.Add(p); } + } + var ok = fehler.Count == 0 && pfade.Count > 0; + var text = (an, ok) switch + { + (true, true) => "Pause - der Läufer klickt nicht mehr, Tische und Sitz bleiben", + (false, true) => "Fortgesetzt - der Läufer spielt weiter", + _ when pfade.Count == 0 => "Projektordner nicht gefunden - Pause nicht gesetzt", + _ => $"Pause nicht {(an ? "gesetzt" : "gelöst")}: {string.Join(", ", fehler)}", + }; + return new Rueckmeldung(an ? "pausieren" : "fortsetzen", ok, text); + } + + // %APPDATA%\Pokerfreak\modus.txt ("echt" | "uebung") - dieselbe Datei wie das Rust-Cockpit. + private static string ModusDatei() => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Pokerfreak", "modus.txt"); + + /// Nur ein ausdrueckliches "echt" gibt Echtgeld, alles andere Uebung. + public static Modus ModusLesen() + { + try { return File.ReadAllText(ModusDatei()).Trim() == "echt" ? Modus.Echt : Modus.Uebung; } + catch { return Modus.Uebung; } + } + + public static void ModusMerken(Modus m) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(ModusDatei())!); + File.WriteAllText(ModusDatei(), m == Modus.Echt ? "echt" : "uebung"); + } + catch { } + } +} diff --git a/winui/MainWindow.xaml.cs b/winui/MainWindow.xaml.cs index 4ef3b407..13235beb 100644 --- a/winui/MainWindow.xaml.cs +++ b/winui/MainWindow.xaml.cs @@ -31,6 +31,9 @@ public sealed partial class MainWindow : Window private readonly StackPanel _laufzeit = Ui.Reihe(4); private readonly TextBlock _laufzeitText = Ui.Winzig(""); private readonly Button _zahnrad; + private readonly Dienst _dienst; + private readonly Ort _ort; + private readonly Schale _schale; public MainWindow(Adresse adresse) { @@ -44,6 +47,26 @@ public sealed partial class MainWindow : Window AppWindow.Resize(new SizeInt32((int)(440 * skala), (int)(900 * skala))); if (AppWindow.Presenter is OverlappedPresenter p) p.PreferredMinimumWidth = (int)(380 * skala); + // Windows: den Server selbst hochziehen (mit Tisch-Desktop), den Rahmen fuers Kacheln melden, + // bei Tisch-Desktop an alle Desktops heften, ins Tray minimieren (wie das Rust-Cockpit). + _dienst = Dienst.Starten(adresse); + var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this); + _ort = new Ort(hwnd, DispatcherQueue); + _schale = new Schale(hwnd, Path.Combine(AppContext.BaseDirectory, "Assets", "cockpit.ico"), "Pokerfreak Cockpit", + Hervorholen, Close); + AppWindow.Changed += (_, e) => + { + if (e.DidPresenterChange || e.DidSizeChange) + if (AppWindow.Presenter is OverlappedPresenter op && op.State == OverlappedPresenterState.Minimized) + AppWindow.Hide(); + }; + Closed += (_, _) => + { + _schale.Dispose(); + _ort.Dispose(); + _dienst.Dispose(); + }; + _z = new CockpitZustand(adresse, DispatcherQueue); _seiten["cash"] = new CashSeite(_z); _seiten["haende"] = new HaendeSeite(_z); @@ -133,6 +156,13 @@ public sealed partial class MainWindow : Window Wurzel.BorderThickness = new Thickness(_z.NotAus || cash ? 1.5 : 0.5); _sichtbar?.Zeichnen(); } + /// Aus dem Tray zurueck: zeigen, wiederherstellen, nach vorn. + private void Hervorholen() + { + AppWindow.Show(); + if (AppWindow.Presenter is OverlappedPresenter op && op.State == OverlappedPresenterState.Minimized) op.Restore(); + Activate(); + } } /// Ein Reiter: zeichnet sich aus dem Zustand neu; `Takt` jede Sekunde fuer laufende Zeit. @@ -140,4 +170,5 @@ public interface ISeite { void Zeichnen(); void Takt() { } + } diff --git a/winui/Seiten/CashSeite.cs b/winui/Seiten/CashSeite.cs index c7ffc5d8..3fd2a7d6 100644 --- a/winui/Seiten/CashSeite.cs +++ b/winui/Seiten/CashSeite.cs @@ -1,603 +1,610 @@ -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Shapes; -using Pokerfreak.Cockpit.Kern; -using Windows.UI; - -namespace Pokerfreak.Cockpit.Seiten; - -/// -/// Der Reiter "Cash" nach der Mac-App (Wurzel.swift `Kopfzeile` + Tische.swift `LiveAnsicht`): oben der -/// Kopf (Modus als Kapsel, Instrument-Kacheln, Tischzahl/-form, "Was spielen", Status, Hauptknopf mit -/// rundem Not-Aus), darunter die Rueckmeldungen, dann die Live-Ansicht zum Scrollen. -/// Die Steuerelemente bleiben stehen; `Zeichnen` setzt ihre Werte, Listen bauen nur bei neuem Abdruck. -/// -public sealed class CashSeite : UserControl, ISeite -{ - private readonly CockpitZustand _z; - private bool _zeichnet; - - // Modus - private readonly Border[] _modusTeil = new Border[3]; - private readonly TextBlock[] _modusText = new TextBlock[3]; - private readonly Tippflaeche[] _modusTipp = new Tippflaeche[3]; - private static readonly string[] ModusTon = { "teal", "blau", "rot" }; - private readonly Border _cashFrage; - - // Kacheln - private readonly TextBlock _tischeWert = Ui.Gross("", 24), _tischeFuss = Ui.Winzig(""); - private readonly TextBlock _geldTitel = Ui.Winzig(""), _geldWert = Ui.Gross("Chips", 20, "grau"), _geldFuss = Ui.Winzig(""); - private readonly TextBox _budget = new() - { - PlaceholderText = "alles", - FontSize = 20, - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - BorderThickness = new Thickness(0), - Padding = new Thickness(0), - MinHeight = 0, - Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), - }; - private readonly TextBlock _planWert = Ui.Text("", 14, fett: true), _planFuss = Ui.Winzig(""); - private readonly UIElement[] _nurLaeufer; - - // Zeilen - private readonly ComboBox _sitzungArt = new() { FontSize = 12, MinWidth = 0, Padding = new Thickness(8, 2, 4, 2) }; - private readonly TextBlock _stepperText = Ui.Text("", 12); - private readonly Tippflaeche _minus, _plus; - private readonly ComboBox _form = new() { FontSize = 12, MinWidth = 0, Padding = new Thickness(8, 2, 4, 2) }; - private readonly ToggleSwitch _micro = new() { OnContent = "", OffContent = "", MinWidth = 0, Width = 44 }; - - // Was spielen - private readonly TextBlock _zusammen = Ui.Winzig(""); - private readonly ToggleButton _ausweichen = new() { Content = "Ausweichen", FontSize = 11, Padding = new Thickness(8, 1, 8, 2), MinHeight = 0 }; - private readonly StackPanel _zielZeile = Ui.Reihe(6); - private readonly TextBlock _zielText = Ui.Winzig(""); - private readonly Grid _formate = new() { ColumnSpacing = 6, RowSpacing = 6 }; - - // Status und Knoepfe - private readonly Border _phase = Ui.Flaeche(null, 10, 0.06, 0); - private readonly Ellipse _statusPunkt = Ui.Punkt("grau", 10); - private readonly TextBlock _statusSatz = Ui.Text("", 14, fett: true, umbruch: true); - private readonly Grid _statusZeile; - private readonly StackPanel _konto = Ui.Spalte(4); - private readonly Grid _knoepfe = new() { ColumnSpacing = 10 }; - private readonly Border _hauptknopf = new() { CornerRadius = new CornerRadius(22), Height = 44 }; - private readonly Tippflaeche _hauptTipp; - private readonly FontIcon _hauptZeichen = Ui.Zeichen("", 15, ""); - private readonly ProgressRing _hauptRing = new() { Width = 16, Height = 16, IsActive = false, Foreground = Ui.Pinsel("") }; - private readonly TextBlock _hauptTitel = Ui.Text("…", 15, "", fett: true); - private readonly Grid _notAusBand; - private readonly TextBlock _portWarnung; - - // Rueckmeldungen - private readonly Border _wartet, _meldung; - private readonly TextBlock _wartetText = Ui.Text("", 13, umbruch: true), _meldungText = Ui.Text("", 13, umbruch: true); - private readonly FontIcon _meldungZeichen = Ui.Zeichen("", 14); - - private readonly LiveTeil _live; - - public CashSeite(CockpitZustand z) - { - _z = z; - _live = new LiveTeil(z); - - // ---- Modus: Zuschauer | Übung | Echtgeld als Kapsel --------------------------------------- - var modus = new Grid(); - string[] titel = { "Zuschauer", "Übung", "Echtgeld" }; - for (int i = 0; i < 3; i++) - { - int n = i; - modus.ColumnDefinitions.Add(new ColumnDefinition()); - _modusText[i] = Ui.Text(titel[i], 14, fett: true); - _modusText[i].HorizontalAlignment = HorizontalAlignment.Center; - _modusTeil[i] = new Border { CornerRadius = new CornerRadius(16), Padding = new Thickness(0, 6, 0, 7), Child = _modusText[i] }; - _modusTipp[i] = _modusTeil[i].Tippen(() => _z.ModusWaehlen(n), 16); - modus.Children.Add(_modusTipp[i].Spalte(i)); - } - var modusKapsel = new Border { Background = Ui.Weiss(0.07), CornerRadius = new CornerRadius(19), Padding = new Thickness(3), Child = modus }; - ToolTipService.SetToolTip(modusKapsel, "Zuschauer: liest nur, klickt nie · Übung: Claim Chips · Echtgeld: Geld"); - - var abbrechen = new Button { Content = "Abbrechen", FontSize = 12 }; - abbrechen.Click += (_, _) => _z.CashAbbrechen(); - var einschalten = new Button { Content = "Echtgeld einschalten", FontSize = 12, Background = Ui.Pinsel("rot"), Foreground = Ui.Pinsel("") }; - einschalten.Click += (_, _) => _z.CashBestaetigen(); - _cashFrage = Ui.Getoent(Ui.Spalte(8, - Ui.Reihe(6, Ui.Zeichen("", 13, "rot"), Ui.Text("Echtgeld heißt echtes Geld", 14, "rot", fett: true)), - Ui.Klein("Der Läufer öffnet selbst Tische und setzt Geld.", true), - Ui.Zeile(abbrechen, einschalten)), "rot", 0.12, 12); - - // ---- Kacheln: Tische | Budget/Geld | Plan -------------------------------------------------- - _budget.KeyDown += (_, e) => { if (e.Key == Windows.System.VirtualKey.Enter) BudgetUebernehmen(); }; - _budget.LostFocus += (_, _) => BudgetUebernehmen(); - var budgetFeld = new Grid(); - budgetFeld.Children.Add(_geldWert); - budgetFeld.Children.Add(_budget); - var kacheln = new Grid { ColumnSpacing = 8 }; - for (int i = 0; i < 3; i++) kacheln.ColumnDefinitions.Add(new ColumnDefinition()); - kacheln.Children.Add(Kachel(Ui.Winzig("Tische"), _tischeWert, _tischeFuss)); - kacheln.Children.Add(Kachel(_geldTitel, budgetFeld, _geldFuss).Spalte(1)); - kacheln.Children.Add(Kachel(Ui.Winzig("Plan"), _planWert, _planFuss).Spalte(2)); - - // ---- Tische je Sitzung, Tischform, Micro only ---------------------------------------------- - _sitzungArt.Items.Add("immer 1"); - _sitzungArt.Items.Add("ausgelost"); - _sitzungArt.SelectionChanged += (_, _) => - { - if (_zeichnet || _sitzungArt.SelectedIndex < 0) return; - _z.Eingabe(w => w.TischeBisSetzen(_sitzungArt.SelectedIndex == 1 ? Math.Min(Spielplan.Hoechstens, w.Tische + 2) : null)); - }; - _minus = Stufe("", () => _z.Eingabe(w => { if (w.TischeBis is int b) w.TischeBisSetzen(b - 1); else w.TischeSetzen(w.Tische - 1); })); - _plus = Stufe("", () => _z.Eingabe(w => { if (w.TischeBis is int b) w.TischeBisSetzen(b + 1); else w.TischeSetzen(w.Tische + 1); })); - var stepper = Ui.Reihe(6, _stepperText.Mit(t => t.VerticalAlignment = VerticalAlignment.Center), Stepper(_minus, _plus)); - var zahlZeile = Ui.Reihe(8, Ui.Text("Tische je Sitzung", 12, fett: true).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _sitzungArt, stepper); - - foreach (var f in new[] { "Multiway", "Heads-Up", "Beide" }) _form.Items.Add(f); - _form.SelectionChanged += (_, _) => - { - if (_zeichnet || _form.SelectedIndex < 0) return; - _z.Eingabe(w => w.Tischform = (Tischform)_form.SelectedIndex); - }; - ToolTipService.SetToolTip(_form, "Multiway = Ring-Tische (Engine-Stärke). Heads-Up = nur 2-Platz-Tische. Beide = egal."); - _micro.Toggled += (_, _) => { if (!_zeichnet) _z.Eingabe(w => w.MicroOnly = _micro.IsOn); }; - ToolTipService.SetToolTip(_micro, "Nur die kleinsten Stakes (Big Blind ≤ 0.10) - schnelles Testen. Kappt das Einsatz-Band nach oben."); - var formZeile = Ui.Zeile( - Ui.Reihe(8, Ui.Text("Tischform", 12, fett: true).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _form), - Ui.Reihe(6, Ui.Text("Micro only", 12).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _micro)); - - // ---- Was spielen --------------------------------------------------------------------------- - _ausweichen.Click += (_, _) => _z.Eingabe(w => w.Ausweichen(_ausweichen.IsChecked == true)); - ToolTipService.SetToolTip(_ausweichen, "Ein Tischziel: gibt es von einem Format zu wenig freie Tische, nimmt er das nächste"); - var wasKopf = Ui.Zeile(Ui.Winzig("Was spielen", fett: true).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), - Ui.Reihe(8, _zusammen.Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _ausweichen)); - _zielZeile.Children.Add(_zielText.Mit(t => t.VerticalAlignment = VerticalAlignment.Center)); - _zielZeile.Children.Add(Stepper(Stufe("", () => _z.Eingabe(w => w.ZielSetzen((w.Ziel ?? 1) - 1))), - Stufe("", () => _z.Eingabe(w => w.ZielSetzen((w.Ziel ?? 1) + 1))))); - _formate.ColumnDefinitions.Add(new ColumnDefinition()); - _formate.ColumnDefinitions.Add(new ColumnDefinition()); - var wasSpielen = Ui.Spalte(6, wasKopf, _zielZeile, _formate); - - // ---- Status, Konto, Hauptknopf + Not-Aus --------------------------------------------------- - _statusZeile = new Grid { ColumnSpacing = 8 }; - _statusZeile.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - _statusZeile.ColumnDefinitions.Add(new ColumnDefinition()); - _statusPunkt.VerticalAlignment = VerticalAlignment.Top; - _statusPunkt.Margin = new Thickness(0, 5, 0, 0); - _statusZeile.Children.Add(_statusPunkt); - _statusZeile.Children.Add(_statusSatz.Spalte(1)); - - var hauptInhalt = Ui.Reihe(7, _hauptZeichen, _hauptRing, _hauptTitel); - hauptInhalt.HorizontalAlignment = HorizontalAlignment.Center; - hauptInhalt.VerticalAlignment = VerticalAlignment.Center; - _hauptknopf.Child = hauptInhalt; - _hauptTipp = _hauptknopf.Tippen(() => _z.HauptknopfDruecken(), 22); - var notAus = new NotAusKnopf(44, () => _z.NotAusSetzen()); - _knoepfe.ColumnDefinitions.Add(new ColumnDefinition()); - _knoepfe.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - _knoepfe.Children.Add(_hauptTipp); - _knoepfe.Children.Add(notAus.Spalte(1)); - - var loesen = new LoesenKnopf(44, () => _z.NotAusLoesen()); - _notAusBand = new Grid { ColumnSpacing = 10, Padding = new Thickness(10), CornerRadius = new CornerRadius(14) }; - _notAusBand.Background = new LinearGradientBrush - { - StartPoint = new Windows.Foundation.Point(0, 0.5), - EndPoint = new Windows.Foundation.Point(1, 0.5), - GradientStops = - { - new GradientStop { Color = Color.FromArgb(255, 0xD9, 0x1F, 0x24), Offset = 0 }, - new GradientStop { Color = Color.FromArgb(255, 0x8C, 0x0D, 0x14), Offset = 1 }, - }, - }; - _notAusBand.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - _notAusBand.ColumnDefinitions.Add(new ColumnDefinition()); - _notAusBand.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - _notAusBand.Children.Add(Ui.Zeichen(NotAusKnopf.Hand, 18, "").Mit(f => f.VerticalAlignment = VerticalAlignment.Center)); - _notAusBand.Children.Add(Ui.Spalte(1, Ui.Text("Not-Aus aktiv", 14, "", fett: true), - Ui.Text("Es wird nichts geklickt. Zum Lösen den grünen Knopf gedrückt halten.", 11, pinsel: Ui.Weiss(0.85), umbruch: true)) - .Mit(s => s.VerticalAlignment = VerticalAlignment.Center).Spalte(1)); - _notAusBand.Children.Add(loesen.Spalte(2)); - - _portWarnung = Ui.Text("CoinPoker läuft ohne Debug-Port: Tische öffnen und Selbstheilen gehen nicht. Aufhören, dann neu starten.", - 12, "orange", umbruch: true); - - // ---- Rueckmeldungen ------------------------------------------------------------------------ - var wartetRing = new ProgressRing { IsActive = true, Width = 14, Height = 14 }; - _wartet = Ui.Getoent(Ui.Reihe(8, wartetRing, _wartetText), "blau", 0.12, 10); - var weg = Ui.Symbolknopf("", "Ausblenden", () => _z.MeldungWeg(), 10); - var meldungInhalt = new Grid { ColumnSpacing = 8 }; - meldungInhalt.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - meldungInhalt.ColumnDefinitions.Add(new ColumnDefinition()); - meldungInhalt.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - meldungInhalt.Children.Add(_meldungZeichen); - meldungInhalt.Children.Add(_meldungText.Mit(t => t.IsTextSelectionEnabled = true).Spalte(1)); - meldungInhalt.Children.Add(weg.Spalte(2)); - _meldung = Ui.Getoent(meldungInhalt, "gruen", 0.14, 10); - - // ---- Aufbau -------------------------------------------------------------------------------- - _nurLaeufer = new UIElement[] { kacheln, zahlZeile, formZeile, wasSpielen }; - var kopf = Ui.Spalte(10, modusKapsel, _cashFrage, kacheln, zahlZeile, formZeile, wasSpielen, - _phase, _statusZeile, _konto, _knoepfe, _notAusBand, _portWarnung); - kopf.Padding = new Thickness(12, 6, 12, 10); - var rueck = Ui.Spalte(6, _wartet, _meldung); - rueck.Padding = new Thickness(12, 0, 12, 0); - - var scroll = new ScrollViewer - { - Content = _live, - HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, - Padding = new Thickness(12, 10, 12, 12), - }; - var seite = new Grid(); - seite.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - seite.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - seite.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - seite.RowDefinitions.Add(new RowDefinition()); - seite.Children.Add(kopf); - seite.Children.Add(rueck.Zeile(1)); - seite.Children.Add(new Rectangle { Height = 1, Fill = Ui.Weiss(0.12), Margin = new Thickness(0, 8, 0, 0) }.Zeile(2)); - seite.Children.Add(scroll.Zeile(3)); - Content = seite; - } - - /// Eine Instrument-Kachel (Spielplan.swift `Kachel`): Titel klein, Inhalt 30 hoch, Fuss klein. - private static Border Kachel(TextBlock titel, FrameworkElement inhalt, TextBlock fuss) - { - inhalt.Height = 30; - inhalt.VerticalAlignment = VerticalAlignment.Center; - return Ui.Flaeche(Ui.Spalte(2, titel, inhalt, fuss), 14, 0.06, 10); - } - - private static Tippflaeche Stufe(string glyph, Action tun) - { - var z = Ui.Zeichen(glyph, 9, ""); - z.HorizontalAlignment = HorizontalAlignment.Center; - z.VerticalAlignment = VerticalAlignment.Center; - var b = new Border { Width = 24, Height = 22, Child = z, Background = Ui.Weiss(0) }; - return b.Tippen(tun, 6); - } - - /// Ein Stepper wie am Mac: zwei kleine Knoepfe in einer Kapsel. - private static Border Stepper(Tippflaeche minus, Tippflaeche plus) => new() - { - Background = Ui.Weiss(0.12), - CornerRadius = new CornerRadius(6), - Child = Ui.Reihe(0, minus, new Rectangle { Width = 1, Fill = Ui.Weiss(0.15), Margin = new Thickness(0, 4, 0, 4) }, plus), - VerticalAlignment = VerticalAlignment.Center, - }; - - private void BudgetUebernehmen() - { - if (_zeichnet) return; - var roh = _budget.Text.Replace(".", "").Replace(",", ".").Trim(); - double? neu = double.TryParse(roh, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var v) && v > 0 ? v : null; - if (neu == _z.Wahl.Budget) { _budget.Text = neu is double n ? Format.Zahl(n) : ""; return; } - _z.Eingabe(w => w.Budget = neu); - } - - // ---- Zeichnen ------------------------------------------------------------------------------- - - public void Takt() => _live.Takt(); - - public void Zeichnen() - { - _zeichnet = true; - try { Werte(); } - finally { _zeichnet = false; } - _live.Zeichnen(); - } - - private static Visibility Sichtbar(bool b) => b ? Visibility.Visible : Visibility.Collapsed; - - private void Werte() - { - var a = _z.Ansicht; - var w = _z.Wahl; - var k = a.Kopf; - bool laeuft = a.Laeuft, zuschauen = a.Zuschauen, cash = w.Cash && !zuschauen; - - // Modus - int an = zuschauen ? 0 : cash ? 2 : 1; - for (int i = 0; i < 3; i++) - { - _modusTeil[i].Background = i == an ? Ui.Pinsel(ModusTon[i]) : null; - _modusText[i].Foreground = i == an ? Ui.Pinsel("") : Ui.Zweit; - _modusTipp[i].An = !laeuft && _z.Verbunden; - _modusTipp[i].Opacity = 1; - } - _cashFrage.Visibility = Sichtbar(_z.CashFragen); - - // Der Spielplan gilt nur fuer den Laeufer - foreach (var e in _nurLaeufer) e.Visibility = Sichtbar(!zuschauen); - - // Tische-Kachel: die Summe (die Zahl je Format steht unter "Was spielen") - int tische = w.Tische; - _tischeWert.Text = w.TischeBis is int b ? $"{tische}–{b}" : $"{tische}"; - _tischeWert.FontSize = w.TischeBis == null ? 24 : 20; - var offen = (int?)k.Zahl("tische_offen") ?? 0; - _tischeFuss.Text = laeuft ? $"{offen} von {tische} offen" : "füllt der Läufer auf"; - - // Geld-Kachel: Echtgeld = Budget (eintippbar), sonst Chips mit dem Buy-in - _geldTitel.Text = w.Cash ? "Budget" : "Geld"; - _budget.Visibility = Sichtbar(w.Cash); - _geldWert.Visibility = Sichtbar(!w.Cash); - _geldFuss.Text = w.Cash ? $"{w.ReserveBuyins} Buy-ins/Tisch" : $"Buy-in {(w.KaufMax ? "Max" : "Min")}"; - if (w.Cash && _budget.FocusState == FocusState.Unfocused) - _budget.Text = w.Budget is double bu ? Format.Zahl(bu) : ""; - - var (pt, pf) = w.PlanText(); - _planWert.Text = pt; - _planFuss.Text = pf; - - // Tische je Sitzung - _sitzungArt.Items[0] = $"immer {tische}"; - _sitzungArt.SelectedIndex = w.TischeBis != null ? 1 : 0; - _stepperText.Text = w.TischeBis is int bis ? $"{tische} bis {bis}" : $"{tische} {(tische == 1 ? "Tisch" : "Tische")}"; - _minus.An = w.TischeBis is int b2 ? b2 > tische + 1 : tische > 1; - _plus.An = (w.TischeBis ?? tische) < Spielplan.Hoechstens; - _form.SelectedIndex = (int)w.Tischform; - _micro.IsOn = w.MicroOnly; - - // Was spielen - _zusammen.Text = tische == 0 ? "nichts gewählt" : $"{tische} Tisch{(tische == 1 ? "" : "e")} zusammen"; - _ausweichen.IsChecked = w.Ziel != null; - _zielZeile.Visibility = Sichtbar(w.Ziel != null); - if (w.Ziel is int zz) _zielText.Text = $"Ziel: {zz} Tisch{(zz == 1 ? "" : "e")} · Zahlen unten sind Obergrenzen"; - FormatKarten(w); - - // Phase des Zeitplans - if (laeuft && k.Obj("phase") is { } ph) - { - var art = ph.Text("art"); - string glyph = art switch { "pause" => "", "ausserhalb" => "", "fertig" => "", "spielen" => "", _ => "" }; - string? ton = art == "spielen" ? null : "orange"; - _phase.Child = Ui.Reihe(8, Ui.Zeichen(glyph, 12, ton), Ui.Text(ph.T("text"), 12, ton, fett: true, umbruch: true)) - .Mit(r => r.Margin = new Thickness(10, 6, 10, 6)); - _phase.Visibility = Visibility.Visible; - } - else _phase.Visibility = Visibility.Collapsed; - - // Status: was gerade passiert (ohne Verbindung steht dort, was los ist) - string satz, ton2; - if (!_z.Verbunden) { satz = _z.JemalsVerbunden ? $"Server weg - {_z.Getrennt}" : _z.Getrennt; ton2 = "grau"; } - else - { - satz = k.Obj("status").Text("satz") ?? k.Text("text") ?? "liest …"; - ton2 = k.Obj("status").Text("farbe") ?? "grau"; - } - _statusPunkt.Fill = Ui.Pinsel(ton2); - _statusSatz.Text = satz; - bool notAus = _z.NotAus; - _statusZeile.Visibility = Sichtbar(!(notAus && _z.Verbunden)); - - // Konto-Alarme: Verdacht, Sperre, laufende Ruhezeit - var alarme = k.Obj("konto").Texte("felder") - .Where(f => f.StartsWith("Verdacht: ja") || f.StartsWith("Gesperrt: ja") || f.Contains("(JETZT)")).ToList(); - var abdruck = string.Join("|", alarme); - if ((string?)_konto.Tag != abdruck) - { - _konto.Tag = abdruck; - _konto.Children.Clear(); - foreach (var f in alarme) - { - var t = f.Contains("(JETZT)") ? "orange" : "rot"; - _konto.Children.Add(Ui.Getoent(Ui.Text(f, 11, t, umbruch: true), t, 0.12, 9, 4) - .Mit(x => x.HorizontalAlignment = HorizontalAlignment.Left)); - } - } - _konto.Visibility = Sichtbar(alarme.Count > 0); - - // Hauptknopf oder Not-Aus-Band - _knoepfe.Visibility = Sichtbar(!notAus); - _notAusBand.Visibility = Sichtbar(notAus); - var knopf = _z.Knopf; - bool beschaeftigt = _z.Laufend.Count > 0; - _hauptTitel.Text = knopf.Titel(); - _hauptZeichen.Glyph = knopf.Zeichen(); - _hauptZeichen.Visibility = Sichtbar(!beschaeftigt); - _hauptRing.IsActive = beschaeftigt; - _hauptRing.Visibility = Sichtbar(beschaeftigt); - var farbe = Ui.Farbe(knopf.Ton()); - _hauptknopf.Background = knopf.Ton() == "grau" ? Ui.Weiss(0.14) : new LinearGradientBrush - { - StartPoint = new Windows.Foundation.Point(0, 0), - EndPoint = new Windows.Foundation.Point(0, 1), - GradientStops = - { - new GradientStop { Color = farbe, Offset = 0 }, - new GradientStop { Color = Color.FromArgb(255, (byte)(farbe.R * 0.8), (byte)(farbe.G * 0.8), (byte)(farbe.B * 0.8)), Offset = 1 }, - }, - }; - _hauptTipp.An = knopf.Wirksam() && !beschaeftigt; - ToolTipService.SetToolTip(_hauptTipp, knopf.Hilfe()); - - _portWarnung.Visibility = Sichtbar(laeuft && k.WahrOderNull("client_port") == false); - - // Rueckmeldungen - _wartet.Visibility = Sichtbar(beschaeftigt); - _wartetText.Text = "läuft: " + string.Join(", ", _z.Laufend.Select(x => x.Replace('_', ' '))); - if (_z.Meldung is { } m) - { - _meldung.Visibility = Visibility.Visible; - _meldung.Background = Ui.Pinsel(m.Ok ? "gruen" : "orange", 0.14); - _meldungZeichen.Glyph = m.Ok ? "" : ""; - _meldungZeichen.Foreground = Ui.Pinsel(m.Ok ? "gruen" : "orange"); - _meldungText.Text = m.Text; - } - else _meldung.Visibility = Visibility.Collapsed; - } - - /// "Was spielen" (FormatWahl.swift): je Format eine Karte im Zweierraster. In Uebung nur - /// Gemessenes (oder schon Gewaehltes); Freeroll und VIP stecken im Turnier-Typ. Mit Ausweichen in - /// Fuellfolge, mit Pfeil nach vorn. - private void FormatKarten(Spielplan w) - { - var folge = w.Folge(); - var reihe = (w.Ziel == null ? Formate.Alle.ToList() : folge.Concat(Formate.Alle.Where(f => !folge.Contains(f))).ToList()) - .Where(f => f is not (SpielFormat.Freeroll or SpielFormat.Vip)).ToList(); - if (!w.Cash) reihe.RemoveAll(f => !w.Gemessen.Contains(f) && w.Anzahl(f) == 0); - var abdruck = string.Join(",", reihe.Select(f => $"{f}:{w.Anzahl(f)}:{folge.IndexOf(f)}:{w.Gemessen.Contains(f)}:{w.Spielbar.Contains(f)}")) + $"|{w.Tische}|{w.Ziel}"; - if ((string?)_formate.Tag == abdruck) return; - _formate.Tag = abdruck; - _formate.Children.Clear(); - _formate.RowDefinitions.Clear(); - for (int i = 0; i < reihe.Count; i++) - { - if (i % 2 == 0) _formate.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - var karte = FormatKarte(w, reihe[i], w.Ziel == null ? -1 : folge.IndexOf(reihe[i])); - Grid.SetRow(karte, i / 2); - Grid.SetColumn(karte, i % 2); - _formate.Children.Add(karte); - } - } - - private Border FormatKarte(Spielplan w, SpielFormat f, int rang) - { - int anzahl = w.Anzahl(f); - bool an = anzahl > 0; - bool voll = w.Ziel == null ? w.Tische >= Spielplan.Hoechstens : anzahl >= Spielplan.Hoechstens; - string? hinweis = !w.Gemessen.Contains(f) ? "ungemessen" - : !w.Spielbar.Contains(f) ? "Menü nicht gemessen" - : f == SpielFormat.Bombpot ? "PLO5 · Engine schwächer" : null; - - var g = new Grid { ColumnSpacing = 4, Height = 38, Padding = new Thickness(8, 0, 2, 0) }; - g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(20) }); - g.ColumnDefinitions.Add(new ColumnDefinition()); - g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - g.Children.Add(Ui.Zeichen(f.Zeichen(), 13, an ? "blau" : "grau").Mit(z => z.VerticalAlignment = VerticalAlignment.Center)); - var namen = Ui.Spalte(0, Ui.Text(f.Name(), 12, fett: true)); - if (hinweis != null) namen.Children.Add(Ui.Text(hinweis, 9.5, "orange")); - namen.VerticalAlignment = VerticalAlignment.Center; - g.Children.Add(namen.Spalte(1)); - var rechts = Ui.Reihe(0); - rechts.VerticalAlignment = VerticalAlignment.Center; - if (rang > 0) rechts.Children.Add(Ui.Symbolknopf("", $"In der Füllfolge nach vorn (jetzt Platz {rang + 1})", () => _z.Eingabe(p => p.Vorziehen(f)), 10, "")); - if (an) - { - rechts.Children.Add(Ui.Symbolknopf("", "eins weniger", () => _z.Eingabe(p => p.Setzen(f, anzahl - 1)), 10, "")); - rechts.Children.Add(Ui.Gross($"{anzahl}", 14).Mit(t => { t.MinWidth = 12; t.TextAlignment = TextAlignment.Center; t.VerticalAlignment = VerticalAlignment.Center; })); - } - var plus = Ui.Symbolknopf("", "eins mehr", () => _z.Eingabe(p => p.Setzen(f, anzahl + 1)), 10, ""); - plus.IsEnabled = !voll; - rechts.Children.Add(plus); - g.Children.Add(rechts.Spalte(2)); - - var karte = new Border - { - Background = an ? Ui.Pinsel("blau", 0.14) : Ui.Weiss(0.05), - BorderBrush = an ? Ui.Pinsel("blau", 0.5) : null, - BorderThickness = new Thickness(an ? 1 : 0), - CornerRadius = new CornerRadius(10), - Child = g, - }; - ToolTipService.SetToolTip(karte, !w.Gemessen.Contains(f) - ? $"{f.Name()}: der Weg in der Lobby ist noch nicht gemessen - der Läufer öffnet hier nichts" - : !w.Spielbar.Contains(f) - ? $"{f.Name()}: gelistet, aber das Einsatz-Menü ist noch nicht gemessen - der Läufer kann dort nicht klicken" - : $"{f.Name()}: {anzahl} Tisch{(anzahl == 1 ? "" : "e")}"); - return karte; - } -} - -/// Not-Aus (Wurzel.swift `NotAusKnopf`): runder roter Knopf, ein Klick haelt sofort an. -public sealed class NotAusKnopf : Grid -{ - public const string Hand = ""; - - public NotAusKnopf(double d, Action tun) - { - Width = d; - Height = d; - var kreis = new Ellipse - { - Fill = new LinearGradientBrush - { - StartPoint = new Windows.Foundation.Point(0, 0), - EndPoint = new Windows.Foundation.Point(0, 1), - GradientStops = - { - new GradientStop { Color = Color.FromArgb(255, 255, 82, 77), Offset = 0 }, - new GradientStop { Color = Color.FromArgb(255, 191, 20, 26), Offset = 1 }, - }, - }, - Stroke = Ui.Weiss(0.35), - StrokeThickness = 1, - }; - var schein = new Ellipse { Fill = Ui.Pinsel("rot", 0.30), Margin = new Thickness(-4) }; - Children.Add(schein); - Children.Add(kreis); - Children.Add(Ui.Zeichen(Hand, d * 0.38, "").Mit(z => { z.HorizontalAlignment = HorizontalAlignment.Center; z.VerticalAlignment = VerticalAlignment.Center; })); - Background = Ui.Weiss(0); - CenterPoint = new System.Numerics.Vector3((float)d / 2, (float)d / 2, 0); - PointerPressed += (_, _) => { Scale = new System.Numerics.Vector3(0.92f); schein.Margin = new Thickness(-1); }; - PointerReleased += (_, _) => { Scale = new System.Numerics.Vector3(1); schein.Margin = new Thickness(-4); }; - PointerExited += (_, _) => { Scale = new System.Numerics.Vector3(1); schein.Margin = new Thickness(-4); }; - Tapped += (_, _) => tun(); - ToolTipService.SetToolTip(this, "Not-Aus - sofort anhalten"); - Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(this, "Not-Aus"); - } -} - -/// Gedrueckt halten (1 s) loest den Not-Aus - der Ring fuellt sich dabei (Wurzel.swift `LoesenKnopf`). -/// So wird der Laeufer nie aus Versehen wieder scharf. -public sealed class LoesenKnopf : Grid -{ - private static readonly TimeSpan Dauer = TimeSpan.FromSeconds(1); - private readonly ProgressRing _ring = new() { IsIndeterminate = false, Minimum = 0, Maximum = 1, Value = 0, Foreground = Ui.Pinsel("gruen") }; - private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer _uhr; - private DateTime? _seit; - - public LoesenKnopf(double d, Action tun) - { - Width = d; - Height = d; - Children.Add(new Ellipse { Fill = Ui.Weiss(0.10) }); - _ring.Width = d; - _ring.Height = d; - Children.Add(_ring); - Children.Add(Ui.Zeichen("", d * 0.34, "gruen").Mit(z => { z.HorizontalAlignment = HorizontalAlignment.Center; z.VerticalAlignment = VerticalAlignment.Center; })); - Background = Ui.Weiss(0); - _uhr = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread().CreateTimer(); - _uhr.Interval = TimeSpan.FromMilliseconds(30); - _uhr.Tick += (_, _) => - { - if (_seit is not DateTime s) return; - var anteil = (DateTime.Now - s) / Dauer; - _ring.Value = Math.Min(1, anteil); - if (anteil >= 1) { Ende(); tun(); } - }; - PointerPressed += (_, e) => { _seit = DateTime.Now; CapturePointer(e.Pointer); _uhr.Start(); }; - PointerReleased += (_, _) => Ende(); - PointerCaptureLost += (_, _) => Ende(); - ToolTipService.SetToolTip(this, "Gedrückt halten, um den Not-Aus zu lösen"); - Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(this, "Not-Aus lösen, gedrückt halten"); - } - - private void Ende() - { - _seit = null; - _uhr.Stop(); - _ring.Value = 0; - } -} - -public static class HauptknopfHilfe -{ - public static string Hilfe(this HauptArt a) => a switch - { - HauptArt.Unbekannt => "wartet auf den Server", - HauptArt.NotAusLoesen => "Not-Aus lösen - der Läufer darf wieder klicken", - HauptArt.HoertAuf => "Er spielt die laufenden Hände zu Ende und schließt dann die Tische - sofort: Not-Aus", - HauptArt.Aufhoeren => "Bei nächster Gelegenheit: ab der nächsten Hand aussetzen, laufende Hände zu Ende spielen, dann Tische zu - sofort: Not-Aus", - HauptArt.ZuschauenBeenden => "Zuschauer stoppen - danach wählst du Übung oder Echtgeld", - HauptArt.EchtgeldStarten => "Spielplan auf Echtgeld setzen und den Läufer starten - er öffnet selbst Tische bis zur Tischzahl", - HauptArt.UebungStarten => "Spielplan Übung setzen und den Läufer starten - er öffnet selbst Übungstische bis zur Tischzahl", - HauptArt.BudgetFehlt => "Echtgeld braucht ein Guthaben: Budget eintragen, sonst wählte die Lobby blind", - HauptArt.FreigabeFehlt => "Das Cockpit kann die Tischfenster nicht lesen - ein Läufer von hier wäre blind", - HauptArt.ClientStarten => "CoinPoker mit Debug-Port starten - danach anmelden", - HauptArt.ClientNeuStarten => "CoinPoker läuft ohne Debug-Port - beenden und mit Port neu starten, danach anmelden", - HauptArt.PortFehlt => "CoinPoker läuft ohne Debug-Port, aber Tische sind offen - erst die Tische schließen, dann neu starten", - _ => "", - }; -} +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Shapes; +using Pokerfreak.Cockpit.Kern; +using Windows.UI; + +namespace Pokerfreak.Cockpit.Seiten; + +/// +/// Der Reiter "Cash" nach der Mac-App (Wurzel.swift `Kopfzeile` + Tische.swift `LiveAnsicht`): oben der +/// Kopf (Modus als Kapsel, Instrument-Kacheln, Tischzahl/-form, "Was spielen", Status, Hauptknopf mit +/// rundem Not-Aus), darunter die Rueckmeldungen, dann die Live-Ansicht zum Scrollen. +/// Die Steuerelemente bleiben stehen; `Zeichnen` setzt ihre Werte, Listen bauen nur bei neuem Abdruck. +/// +public sealed class CashSeite : UserControl, ISeite +{ + private readonly CockpitZustand _z; + private bool _zeichnet; + + // Modus + private readonly Border[] _modusTeil = new Border[3]; + private readonly TextBlock[] _modusText = new TextBlock[3]; + private readonly Tippflaeche[] _modusTipp = new Tippflaeche[3]; + private static readonly string[] ModusTon = { "teal", "blau", "rot" }; + private readonly Border _cashFrage; + + // Kacheln + private readonly TextBlock _tischeWert = Ui.Gross("", 24), _tischeFuss = Ui.Winzig(""); + private readonly TextBlock _geldTitel = Ui.Winzig(""), _geldWert = Ui.Gross("Chips", 20, "grau"), _geldFuss = Ui.Winzig(""); + private readonly TextBox _budget = new() + { + PlaceholderText = "alles", + FontSize = 20, + FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, + BorderThickness = new Thickness(0), + Padding = new Thickness(0), + MinHeight = 0, + Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), + }; + private readonly TextBlock _planWert = Ui.Text("", 14, fett: true), _planFuss = Ui.Winzig(""); + private readonly UIElement[] _nurLaeufer; + + // Zeilen + private readonly ComboBox _sitzungArt = new() { FontSize = 12, MinWidth = 0, Padding = new Thickness(8, 2, 4, 2) }; + private readonly TextBlock _stepperText = Ui.Text("", 12); + private readonly Tippflaeche _minus, _plus; + private readonly ComboBox _form = new() { FontSize = 12, MinWidth = 0, Padding = new Thickness(8, 2, 4, 2) }; + private readonly ToggleSwitch _micro = new() { OnContent = "", OffContent = "", MinWidth = 0, Width = 44 }; + + // Was spielen + private readonly TextBlock _zusammen = Ui.Winzig(""); + private readonly ToggleButton _ausweichen = new() { Content = "Ausweichen", FontSize = 11, Padding = new Thickness(8, 1, 8, 2), MinHeight = 0 }; + private readonly StackPanel _zielZeile = Ui.Reihe(6); + private readonly TextBlock _zielText = Ui.Winzig(""); + private readonly Grid _formate = new() { ColumnSpacing = 6, RowSpacing = 6 }; + + // Status und Knoepfe + private readonly Border _phase = Ui.Flaeche(null, 10, 0.06, 0); + private readonly Ellipse _statusPunkt = Ui.Punkt("grau", 10); + private readonly TextBlock _statusSatz = Ui.Text("", 14, fett: true, umbruch: true); + private readonly Grid _statusZeile; + private readonly StackPanel _konto = Ui.Spalte(4); + private readonly Grid _knoepfe = new() { ColumnSpacing = 10 }; + private readonly Border _hauptknopf = new() { CornerRadius = new CornerRadius(22), Height = 44 }; + private readonly Tippflaeche _hauptTipp; + private readonly FontIcon _hauptZeichen = Ui.Zeichen("", 15, ""); + private readonly ProgressRing _hauptRing = new() { Width = 16, Height = 16, IsActive = false, Foreground = Ui.Pinsel("") }; + private readonly TextBlock _hauptTitel = Ui.Text("…", 15, "", fett: true); + private readonly Grid _notAusBand; + private readonly TextBlock _portWarnung; + + // Rueckmeldungen + private readonly Border _wartet, _meldung; + private readonly TextBlock _wartetText = Ui.Text("", 13, umbruch: true), _meldungText = Ui.Text("", 13, umbruch: true); + private readonly FontIcon _meldungZeichen = Ui.Zeichen("", 14); + + private readonly LiveTeil _live; + private readonly ZuschauerTeil _zuschauer; + + public CashSeite(CockpitZustand z) + { + _z = z; + _live = new LiveTeil(z); + _zuschauer = new ZuschauerTeil(z); + + // ---- Modus: Zuschauer | Übung | Echtgeld als Kapsel --------------------------------------- + var modus = new Grid(); + string[] titel = { "Zuschauer", "Übung", "Echtgeld" }; + for (int i = 0; i < 3; i++) + { + int n = i; + modus.ColumnDefinitions.Add(new ColumnDefinition()); + _modusText[i] = Ui.Text(titel[i], 14, fett: true); + _modusText[i].HorizontalAlignment = HorizontalAlignment.Center; + _modusTeil[i] = new Border { CornerRadius = new CornerRadius(16), Padding = new Thickness(0, 6, 0, 7), Child = _modusText[i] }; + _modusTipp[i] = _modusTeil[i].Tippen(() => _z.ModusWaehlen(n), 16); + modus.Children.Add(_modusTipp[i].Spalte(i)); + } + var modusKapsel = new Border { Background = Ui.Weiss(0.07), CornerRadius = new CornerRadius(19), Padding = new Thickness(3), Child = modus }; + ToolTipService.SetToolTip(modusKapsel, "Zuschauer: liest nur, klickt nie · Übung: Claim Chips · Echtgeld: Geld"); + + var abbrechen = new Button { Content = "Abbrechen", FontSize = 12 }; + abbrechen.Click += (_, _) => _z.CashAbbrechen(); + var einschalten = new Button { Content = "Echtgeld einschalten", FontSize = 12, Background = Ui.Pinsel("rot"), Foreground = Ui.Pinsel("") }; + einschalten.Click += (_, _) => _z.CashBestaetigen(); + _cashFrage = Ui.Getoent(Ui.Spalte(8, + Ui.Reihe(6, Ui.Zeichen("", 13, "rot"), Ui.Text("Echtgeld heißt echtes Geld", 14, "rot", fett: true)), + Ui.Klein("Der Läufer öffnet selbst Tische und setzt Geld.", true), + Ui.Zeile(abbrechen, einschalten)), "rot", 0.12, 12); + + // ---- Kacheln: Tische | Budget/Geld | Plan -------------------------------------------------- + _budget.KeyDown += (_, e) => { if (e.Key == Windows.System.VirtualKey.Enter) BudgetUebernehmen(); }; + _budget.LostFocus += (_, _) => BudgetUebernehmen(); + var budgetFeld = new Grid(); + budgetFeld.Children.Add(_geldWert); + budgetFeld.Children.Add(_budget); + var kacheln = new Grid { ColumnSpacing = 8 }; + for (int i = 0; i < 3; i++) kacheln.ColumnDefinitions.Add(new ColumnDefinition()); + kacheln.Children.Add(Kachel(Ui.Winzig("Tische"), _tischeWert, _tischeFuss)); + kacheln.Children.Add(Kachel(_geldTitel, budgetFeld, _geldFuss).Spalte(1)); + kacheln.Children.Add(Kachel(Ui.Winzig("Plan"), _planWert, _planFuss).Spalte(2)); + + // ---- Tische je Sitzung, Tischform, Micro only ---------------------------------------------- + _sitzungArt.Items.Add("immer 1"); + _sitzungArt.Items.Add("ausgelost"); + _sitzungArt.SelectionChanged += (_, _) => + { + if (_zeichnet || _sitzungArt.SelectedIndex < 0) return; + _z.Eingabe(w => w.TischeBisSetzen(_sitzungArt.SelectedIndex == 1 ? Math.Min(Spielplan.Hoechstens, w.Tische + 2) : null)); + }; + _minus = Stufe("", () => _z.Eingabe(w => { if (w.TischeBis is int b) w.TischeBisSetzen(b - 1); else w.TischeSetzen(w.Tische - 1); })); + _plus = Stufe("", () => _z.Eingabe(w => { if (w.TischeBis is int b) w.TischeBisSetzen(b + 1); else w.TischeSetzen(w.Tische + 1); })); + var stepper = Ui.Reihe(6, _stepperText.Mit(t => t.VerticalAlignment = VerticalAlignment.Center), Stepper(_minus, _plus)); + var zahlZeile = Ui.Reihe(8, Ui.Text("Tische je Sitzung", 12, fett: true).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _sitzungArt, stepper); + + foreach (var f in new[] { "Multiway", "Heads-Up", "Beide" }) _form.Items.Add(f); + _form.SelectionChanged += (_, _) => + { + if (_zeichnet || _form.SelectedIndex < 0) return; + _z.Eingabe(w => w.Tischform = (Tischform)_form.SelectedIndex); + }; + ToolTipService.SetToolTip(_form, "Multiway = Ring-Tische (Engine-Stärke). Heads-Up = nur 2-Platz-Tische. Beide = egal."); + _micro.Toggled += (_, _) => { if (!_zeichnet) _z.Eingabe(w => w.MicroOnly = _micro.IsOn); }; + ToolTipService.SetToolTip(_micro, "Nur die kleinsten Stakes (Big Blind ≤ 0.10) - schnelles Testen. Kappt das Einsatz-Band nach oben."); + var formZeile = Ui.Zeile( + Ui.Reihe(8, Ui.Text("Tischform", 12, fett: true).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _form), + Ui.Reihe(6, Ui.Text("Micro only", 12).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _micro)); + + // ---- Was spielen --------------------------------------------------------------------------- + _ausweichen.Click += (_, _) => _z.Eingabe(w => w.Ausweichen(_ausweichen.IsChecked == true)); + ToolTipService.SetToolTip(_ausweichen, "Ein Tischziel: gibt es von einem Format zu wenig freie Tische, nimmt er das nächste"); + var wasKopf = Ui.Zeile(Ui.Winzig("Was spielen", fett: true).Mit(t => t.VerticalAlignment = VerticalAlignment.Center), + Ui.Reihe(8, _zusammen.Mit(t => t.VerticalAlignment = VerticalAlignment.Center), _ausweichen)); + _zielZeile.Children.Add(_zielText.Mit(t => t.VerticalAlignment = VerticalAlignment.Center)); + _zielZeile.Children.Add(Stepper(Stufe("", () => _z.Eingabe(w => w.ZielSetzen((w.Ziel ?? 1) - 1))), + Stufe("", () => _z.Eingabe(w => w.ZielSetzen((w.Ziel ?? 1) + 1))))); + _formate.ColumnDefinitions.Add(new ColumnDefinition()); + _formate.ColumnDefinitions.Add(new ColumnDefinition()); + var wasSpielen = Ui.Spalte(6, wasKopf, _zielZeile, _formate); + + // ---- Status, Konto, Hauptknopf + Not-Aus --------------------------------------------------- + _statusZeile = new Grid { ColumnSpacing = 8 }; + _statusZeile.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + _statusZeile.ColumnDefinitions.Add(new ColumnDefinition()); + _statusPunkt.VerticalAlignment = VerticalAlignment.Top; + _statusPunkt.Margin = new Thickness(0, 5, 0, 0); + _statusZeile.Children.Add(_statusPunkt); + _statusZeile.Children.Add(_statusSatz.Spalte(1)); + + var hauptInhalt = Ui.Reihe(7, _hauptZeichen, _hauptRing, _hauptTitel); + hauptInhalt.HorizontalAlignment = HorizontalAlignment.Center; + hauptInhalt.VerticalAlignment = VerticalAlignment.Center; + _hauptknopf.Child = hauptInhalt; + _hauptTipp = _hauptknopf.Tippen(() => _z.HauptknopfDruecken(), 22); + var notAus = new NotAusKnopf(44, () => _z.NotAusSetzen()); + _knoepfe.ColumnDefinitions.Add(new ColumnDefinition()); + _knoepfe.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + _knoepfe.Children.Add(_hauptTipp); + _knoepfe.Children.Add(notAus.Spalte(1)); + + var loesen = new LoesenKnopf(44, () => _z.NotAusLoesen()); + _notAusBand = new Grid { ColumnSpacing = 10, Padding = new Thickness(10), CornerRadius = new CornerRadius(14) }; + _notAusBand.Background = new LinearGradientBrush + { + StartPoint = new Windows.Foundation.Point(0, 0.5), + EndPoint = new Windows.Foundation.Point(1, 0.5), + GradientStops = + { + new GradientStop { Color = Color.FromArgb(255, 0xD9, 0x1F, 0x24), Offset = 0 }, + new GradientStop { Color = Color.FromArgb(255, 0x8C, 0x0D, 0x14), Offset = 1 }, + }, + }; + _notAusBand.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + _notAusBand.ColumnDefinitions.Add(new ColumnDefinition()); + _notAusBand.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + _notAusBand.Children.Add(Ui.Zeichen(NotAusKnopf.Hand, 18, "").Mit(f => f.VerticalAlignment = VerticalAlignment.Center)); + _notAusBand.Children.Add(Ui.Spalte(1, Ui.Text("Not-Aus aktiv", 14, "", fett: true), + Ui.Text("Es wird nichts geklickt. Zum Lösen den grünen Knopf gedrückt halten.", 11, pinsel: Ui.Weiss(0.85), umbruch: true)) + .Mit(s => s.VerticalAlignment = VerticalAlignment.Center).Spalte(1)); + _notAusBand.Children.Add(loesen.Spalte(2)); + + _portWarnung = Ui.Text("CoinPoker läuft ohne Debug-Port: Tische öffnen und Selbstheilen gehen nicht. Aufhören, dann neu starten.", + 12, "orange", umbruch: true); + + // ---- Rueckmeldungen ------------------------------------------------------------------------ + var wartetRing = new ProgressRing { IsActive = true, Width = 14, Height = 14 }; + _wartet = Ui.Getoent(Ui.Reihe(8, wartetRing, _wartetText), "blau", 0.12, 10); + var weg = Ui.Symbolknopf("", "Ausblenden", () => _z.MeldungWeg(), 10); + var meldungInhalt = new Grid { ColumnSpacing = 8 }; + meldungInhalt.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + meldungInhalt.ColumnDefinitions.Add(new ColumnDefinition()); + meldungInhalt.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + meldungInhalt.Children.Add(_meldungZeichen); + meldungInhalt.Children.Add(_meldungText.Mit(t => t.IsTextSelectionEnabled = true).Spalte(1)); + meldungInhalt.Children.Add(weg.Spalte(2)); + _meldung = Ui.Getoent(meldungInhalt, "gruen", 0.14, 10); + + // ---- Aufbau -------------------------------------------------------------------------------- + _nurLaeufer = new UIElement[] { kacheln, zahlZeile, formZeile, wasSpielen }; + var kopf = Ui.Spalte(10, modusKapsel, _cashFrage, kacheln, zahlZeile, formZeile, wasSpielen, + _phase, _statusZeile, _konto, _knoepfe, _notAusBand, _portWarnung); + kopf.Padding = new Thickness(12, 6, 12, 10); + var rueck = Ui.Spalte(6, _wartet, _meldung); + rueck.Padding = new Thickness(12, 0, 12, 0); + + var scroll = new ScrollViewer + { + Content = Ui.Spalte(0, _live, _zuschauer), + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, + Padding = new Thickness(12, 10, 12, 12), + }; + var seite = new Grid(); + seite.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + seite.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + seite.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + seite.RowDefinitions.Add(new RowDefinition()); + seite.Children.Add(kopf); + seite.Children.Add(rueck.Zeile(1)); + seite.Children.Add(new Rectangle { Height = 1, Fill = Ui.Weiss(0.12), Margin = new Thickness(0, 8, 0, 0) }.Zeile(2)); + seite.Children.Add(scroll.Zeile(3)); + Content = seite; + } + + /// Eine Instrument-Kachel (Spielplan.swift `Kachel`): Titel klein, Inhalt 30 hoch, Fuss klein. + private static Border Kachel(TextBlock titel, FrameworkElement inhalt, TextBlock fuss) + { + inhalt.Height = 30; + inhalt.VerticalAlignment = VerticalAlignment.Center; + return Ui.Flaeche(Ui.Spalte(2, titel, inhalt, fuss), 14, 0.06, 10); + } + + private static Tippflaeche Stufe(string glyph, Action tun) + { + var z = Ui.Zeichen(glyph, 9, ""); + z.HorizontalAlignment = HorizontalAlignment.Center; + z.VerticalAlignment = VerticalAlignment.Center; + var b = new Border { Width = 24, Height = 22, Child = z, Background = Ui.Weiss(0) }; + return b.Tippen(tun, 6); + } + + /// Ein Stepper wie am Mac: zwei kleine Knoepfe in einer Kapsel. + private static Border Stepper(Tippflaeche minus, Tippflaeche plus) => new() + { + Background = Ui.Weiss(0.12), + CornerRadius = new CornerRadius(6), + Child = Ui.Reihe(0, minus, new Rectangle { Width = 1, Fill = Ui.Weiss(0.15), Margin = new Thickness(0, 4, 0, 4) }, plus), + VerticalAlignment = VerticalAlignment.Center, + }; + + private void BudgetUebernehmen() + { + if (_zeichnet) return; + var roh = _budget.Text.Replace(".", "").Replace(",", ".").Trim(); + double? neu = double.TryParse(roh, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var v) && v > 0 ? v : null; + if (neu == _z.Wahl.Budget) { _budget.Text = neu is double n ? Format.Zahl(n) : ""; return; } + _z.Eingabe(w => w.Budget = neu); + } + + // ---- Zeichnen ------------------------------------------------------------------------------- + + public void Takt() => _live.Takt(); + + public void Zeichnen() + { + _zeichnet = true; + try { Werte(); } + finally { _zeichnet = false; } + // Solange der Zuschauer laeuft, steht seine Sicht an Stelle der Live-Ansicht (Wurzel.swift) + var zuschauen = _z.Ansicht.Zuschauen; + _live.Visibility = zuschauen ? Visibility.Collapsed : Visibility.Visible; + _zuschauer.Visibility = zuschauen ? Visibility.Visible : Visibility.Collapsed; + if (zuschauen) _zuschauer.Zeichnen(); + else _live.Zeichnen(); + } + + private static Visibility Sichtbar(bool b) => b ? Visibility.Visible : Visibility.Collapsed; + + private void Werte() + { + var a = _z.Ansicht; + var w = _z.Wahl; + var k = a.Kopf; + bool laeuft = a.Laeuft, zuschauen = a.Zuschauen, cash = w.Cash && !zuschauen; + + // Modus + int an = zuschauen ? 0 : cash ? 2 : 1; + for (int i = 0; i < 3; i++) + { + _modusTeil[i].Background = i == an ? Ui.Pinsel(ModusTon[i]) : null; + _modusText[i].Foreground = i == an ? Ui.Pinsel("") : Ui.Zweit; + _modusTipp[i].An = !laeuft && _z.Verbunden; + _modusTipp[i].Opacity = 1; + } + _cashFrage.Visibility = Sichtbar(_z.CashFragen); + + // Der Spielplan gilt nur fuer den Laeufer + foreach (var e in _nurLaeufer) e.Visibility = Sichtbar(!zuschauen); + + // Tische-Kachel: die Summe (die Zahl je Format steht unter "Was spielen") + int tische = w.Tische; + _tischeWert.Text = w.TischeBis is int b ? $"{tische}–{b}" : $"{tische}"; + _tischeWert.FontSize = w.TischeBis == null ? 24 : 20; + var offen = (int?)k.Zahl("tische_offen") ?? 0; + _tischeFuss.Text = laeuft ? $"{offen} von {tische} offen" : "füllt der Läufer auf"; + + // Geld-Kachel: Echtgeld = Budget (eintippbar), sonst Chips mit dem Buy-in + _geldTitel.Text = w.Cash ? "Budget" : "Geld"; + _budget.Visibility = Sichtbar(w.Cash); + _geldWert.Visibility = Sichtbar(!w.Cash); + _geldFuss.Text = w.Cash ? $"{w.ReserveBuyins} Buy-ins/Tisch" : $"Buy-in {(w.KaufMax ? "Max" : "Min")}"; + if (w.Cash && _budget.FocusState == FocusState.Unfocused) + _budget.Text = w.Budget is double bu ? Format.Zahl(bu) : ""; + + var (pt, pf) = w.PlanText(); + _planWert.Text = pt; + _planFuss.Text = pf; + + // Tische je Sitzung + _sitzungArt.Items[0] = $"immer {tische}"; + _sitzungArt.SelectedIndex = w.TischeBis != null ? 1 : 0; + _stepperText.Text = w.TischeBis is int bis ? $"{tische} bis {bis}" : $"{tische} {(tische == 1 ? "Tisch" : "Tische")}"; + _minus.An = w.TischeBis is int b2 ? b2 > tische + 1 : tische > 1; + _plus.An = (w.TischeBis ?? tische) < Spielplan.Hoechstens; + _form.SelectedIndex = (int)w.Tischform; + _micro.IsOn = w.MicroOnly; + + // Was spielen + _zusammen.Text = tische == 0 ? "nichts gewählt" : $"{tische} Tisch{(tische == 1 ? "" : "e")} zusammen"; + _ausweichen.IsChecked = w.Ziel != null; + _zielZeile.Visibility = Sichtbar(w.Ziel != null); + if (w.Ziel is int zz) _zielText.Text = $"Ziel: {zz} Tisch{(zz == 1 ? "" : "e")} · Zahlen unten sind Obergrenzen"; + FormatKarten(w); + + // Phase des Zeitplans + if (laeuft && k.Obj("phase") is { } ph) + { + var art = ph.Text("art"); + string glyph = art switch { "pause" => "", "ausserhalb" => "", "fertig" => "", "spielen" => "", _ => "" }; + string? ton = art == "spielen" ? null : "orange"; + _phase.Child = Ui.Reihe(8, Ui.Zeichen(glyph, 12, ton), Ui.Text(ph.T("text"), 12, ton, fett: true, umbruch: true)) + .Mit(r => r.Margin = new Thickness(10, 6, 10, 6)); + _phase.Visibility = Visibility.Visible; + } + else _phase.Visibility = Visibility.Collapsed; + + // Status: was gerade passiert (ohne Verbindung steht dort, was los ist) + string satz, ton2; + if (!_z.Verbunden) { satz = _z.JemalsVerbunden ? $"Server weg - {_z.Getrennt}" : _z.Getrennt; ton2 = "grau"; } + else + { + satz = k.Obj("status").Text("satz") ?? k.Text("text") ?? "liest …"; + ton2 = k.Obj("status").Text("farbe") ?? "grau"; + } + _statusPunkt.Fill = Ui.Pinsel(ton2); + _statusSatz.Text = satz; + bool notAus = _z.NotAus; + _statusZeile.Visibility = Sichtbar(!(notAus && _z.Verbunden)); + + // Konto-Alarme: Verdacht, Sperre, laufende Ruhezeit + var alarme = k.Obj("konto").Texte("felder") + .Where(f => f.StartsWith("Verdacht: ja") || f.StartsWith("Gesperrt: ja") || f.Contains("(JETZT)")).ToList(); + var abdruck = string.Join("|", alarme); + if ((string?)_konto.Tag != abdruck) + { + _konto.Tag = abdruck; + _konto.Children.Clear(); + foreach (var f in alarme) + { + var t = f.Contains("(JETZT)") ? "orange" : "rot"; + _konto.Children.Add(Ui.Getoent(Ui.Text(f, 11, t, umbruch: true), t, 0.12, 9, 4) + .Mit(x => x.HorizontalAlignment = HorizontalAlignment.Left)); + } + } + _konto.Visibility = Sichtbar(alarme.Count > 0); + + // Hauptknopf oder Not-Aus-Band + _knoepfe.Visibility = Sichtbar(!notAus); + _notAusBand.Visibility = Sichtbar(notAus); + var knopf = _z.Knopf; + bool beschaeftigt = _z.Laufend.Count > 0; + _hauptTitel.Text = knopf.Titel(); + _hauptZeichen.Glyph = knopf.Zeichen(); + _hauptZeichen.Visibility = Sichtbar(!beschaeftigt); + _hauptRing.IsActive = beschaeftigt; + _hauptRing.Visibility = Sichtbar(beschaeftigt); + var farbe = Ui.Farbe(knopf.Ton()); + _hauptknopf.Background = knopf.Ton() == "grau" ? Ui.Weiss(0.14) : new LinearGradientBrush + { + StartPoint = new Windows.Foundation.Point(0, 0), + EndPoint = new Windows.Foundation.Point(0, 1), + GradientStops = + { + new GradientStop { Color = farbe, Offset = 0 }, + new GradientStop { Color = Color.FromArgb(255, (byte)(farbe.R * 0.8), (byte)(farbe.G * 0.8), (byte)(farbe.B * 0.8)), Offset = 1 }, + }, + }; + _hauptTipp.An = knopf.Wirksam() && !beschaeftigt; + ToolTipService.SetToolTip(_hauptTipp, knopf.Hilfe()); + + _portWarnung.Visibility = Sichtbar(laeuft && k.WahrOderNull("client_port") == false); + + // Rueckmeldungen + _wartet.Visibility = Sichtbar(beschaeftigt); + _wartetText.Text = "läuft: " + string.Join(", ", _z.Laufend.Select(x => x.Replace('_', ' '))); + if (_z.Meldung is { } m) + { + _meldung.Visibility = Visibility.Visible; + _meldung.Background = Ui.Pinsel(m.Ok ? "gruen" : "orange", 0.14); + _meldungZeichen.Glyph = m.Ok ? "" : ""; + _meldungZeichen.Foreground = Ui.Pinsel(m.Ok ? "gruen" : "orange"); + _meldungText.Text = m.Text; + } + else _meldung.Visibility = Visibility.Collapsed; + } + + /// "Was spielen" (FormatWahl.swift): je Format eine Karte im Zweierraster. In Uebung nur + /// Gemessenes (oder schon Gewaehltes); Freeroll und VIP stecken im Turnier-Typ. Mit Ausweichen in + /// Fuellfolge, mit Pfeil nach vorn. + private void FormatKarten(Spielplan w) + { + var folge = w.Folge(); + var reihe = (w.Ziel == null ? Formate.Alle.ToList() : folge.Concat(Formate.Alle.Where(f => !folge.Contains(f))).ToList()) + .Where(f => f is not (SpielFormat.Freeroll or SpielFormat.Vip)).ToList(); + if (!w.Cash) reihe.RemoveAll(f => !w.Gemessen.Contains(f) && w.Anzahl(f) == 0); + var abdruck = string.Join(",", reihe.Select(f => $"{f}:{w.Anzahl(f)}:{folge.IndexOf(f)}:{w.Gemessen.Contains(f)}:{w.Spielbar.Contains(f)}")) + $"|{w.Tische}|{w.Ziel}"; + if ((string?)_formate.Tag == abdruck) return; + _formate.Tag = abdruck; + _formate.Children.Clear(); + _formate.RowDefinitions.Clear(); + for (int i = 0; i < reihe.Count; i++) + { + if (i % 2 == 0) _formate.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var karte = FormatKarte(w, reihe[i], w.Ziel == null ? -1 : folge.IndexOf(reihe[i])); + Grid.SetRow(karte, i / 2); + Grid.SetColumn(karte, i % 2); + _formate.Children.Add(karte); + } + } + + private Border FormatKarte(Spielplan w, SpielFormat f, int rang) + { + int anzahl = w.Anzahl(f); + bool an = anzahl > 0; + bool voll = w.Ziel == null ? w.Tische >= Spielplan.Hoechstens : anzahl >= Spielplan.Hoechstens; + string? hinweis = !w.Gemessen.Contains(f) ? "ungemessen" + : !w.Spielbar.Contains(f) ? "Menü nicht gemessen" + : f == SpielFormat.Bombpot ? "PLO5 · Engine schwächer" : null; + + var g = new Grid { ColumnSpacing = 4, Height = 38, Padding = new Thickness(8, 0, 2, 0) }; + g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(20) }); + g.ColumnDefinitions.Add(new ColumnDefinition()); + g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + g.Children.Add(Ui.Zeichen(f.Zeichen(), 13, an ? "blau" : "grau").Mit(z => z.VerticalAlignment = VerticalAlignment.Center)); + var namen = Ui.Spalte(0, Ui.Text(f.Name(), 12, fett: true)); + if (hinweis != null) namen.Children.Add(Ui.Text(hinweis, 9.5, "orange")); + namen.VerticalAlignment = VerticalAlignment.Center; + g.Children.Add(namen.Spalte(1)); + var rechts = Ui.Reihe(0); + rechts.VerticalAlignment = VerticalAlignment.Center; + if (rang > 0) rechts.Children.Add(Ui.Symbolknopf("", $"In der Füllfolge nach vorn (jetzt Platz {rang + 1})", () => _z.Eingabe(p => p.Vorziehen(f)), 10, "")); + if (an) + { + rechts.Children.Add(Ui.Symbolknopf("", "eins weniger", () => _z.Eingabe(p => p.Setzen(f, anzahl - 1)), 10, "")); + rechts.Children.Add(Ui.Gross($"{anzahl}", 14).Mit(t => { t.MinWidth = 12; t.TextAlignment = TextAlignment.Center; t.VerticalAlignment = VerticalAlignment.Center; })); + } + var plus = Ui.Symbolknopf("", "eins mehr", () => _z.Eingabe(p => p.Setzen(f, anzahl + 1)), 10, ""); + plus.IsEnabled = !voll; + rechts.Children.Add(plus); + g.Children.Add(rechts.Spalte(2)); + + var karte = new Border + { + Background = an ? Ui.Pinsel("blau", 0.14) : Ui.Weiss(0.05), + BorderBrush = an ? Ui.Pinsel("blau", 0.5) : null, + BorderThickness = new Thickness(an ? 1 : 0), + CornerRadius = new CornerRadius(10), + Child = g, + }; + ToolTipService.SetToolTip(karte, !w.Gemessen.Contains(f) + ? $"{f.Name()}: der Weg in der Lobby ist noch nicht gemessen - der Läufer öffnet hier nichts" + : !w.Spielbar.Contains(f) + ? $"{f.Name()}: gelistet, aber das Einsatz-Menü ist noch nicht gemessen - der Läufer kann dort nicht klicken" + : $"{f.Name()}: {anzahl} Tisch{(anzahl == 1 ? "" : "e")}"); + return karte; + } +} + +/// Not-Aus (Wurzel.swift `NotAusKnopf`): runder roter Knopf, ein Klick haelt sofort an. +public sealed class NotAusKnopf : Grid +{ + public const string Hand = ""; + + public NotAusKnopf(double d, Action tun) + { + Width = d; + Height = d; + var kreis = new Ellipse + { + Fill = new LinearGradientBrush + { + StartPoint = new Windows.Foundation.Point(0, 0), + EndPoint = new Windows.Foundation.Point(0, 1), + GradientStops = + { + new GradientStop { Color = Color.FromArgb(255, 255, 82, 77), Offset = 0 }, + new GradientStop { Color = Color.FromArgb(255, 191, 20, 26), Offset = 1 }, + }, + }, + Stroke = Ui.Weiss(0.35), + StrokeThickness = 1, + }; + var schein = new Ellipse { Fill = Ui.Pinsel("rot", 0.30), Margin = new Thickness(-4) }; + Children.Add(schein); + Children.Add(kreis); + Children.Add(Ui.Zeichen(Hand, d * 0.38, "").Mit(z => { z.HorizontalAlignment = HorizontalAlignment.Center; z.VerticalAlignment = VerticalAlignment.Center; })); + Background = Ui.Weiss(0); + CenterPoint = new System.Numerics.Vector3((float)d / 2, (float)d / 2, 0); + PointerPressed += (_, _) => { Scale = new System.Numerics.Vector3(0.92f); schein.Margin = new Thickness(-1); }; + PointerReleased += (_, _) => { Scale = new System.Numerics.Vector3(1); schein.Margin = new Thickness(-4); }; + PointerExited += (_, _) => { Scale = new System.Numerics.Vector3(1); schein.Margin = new Thickness(-4); }; + Tapped += (_, _) => tun(); + ToolTipService.SetToolTip(this, "Not-Aus - sofort anhalten"); + Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(this, "Not-Aus"); + } +} + +/// Gedrueckt halten (1 s) loest den Not-Aus - der Ring fuellt sich dabei (Wurzel.swift `LoesenKnopf`). +/// So wird der Laeufer nie aus Versehen wieder scharf. +public sealed class LoesenKnopf : Grid +{ + private static readonly TimeSpan Dauer = TimeSpan.FromSeconds(1); + private readonly ProgressRing _ring = new() { IsIndeterminate = false, Minimum = 0, Maximum = 1, Value = 0, Foreground = Ui.Pinsel("gruen") }; + private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer _uhr; + private DateTime? _seit; + + public LoesenKnopf(double d, Action tun) + { + Width = d; + Height = d; + Children.Add(new Ellipse { Fill = Ui.Weiss(0.10) }); + _ring.Width = d; + _ring.Height = d; + Children.Add(_ring); + Children.Add(Ui.Zeichen("", d * 0.34, "gruen").Mit(z => { z.HorizontalAlignment = HorizontalAlignment.Center; z.VerticalAlignment = VerticalAlignment.Center; })); + Background = Ui.Weiss(0); + _uhr = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread().CreateTimer(); + _uhr.Interval = TimeSpan.FromMilliseconds(30); + _uhr.Tick += (_, _) => + { + if (_seit is not DateTime s) return; + var anteil = (DateTime.Now - s) / Dauer; + _ring.Value = Math.Min(1, anteil); + if (anteil >= 1) { Ende(); tun(); } + }; + PointerPressed += (_, e) => { _seit = DateTime.Now; CapturePointer(e.Pointer); _uhr.Start(); }; + PointerReleased += (_, _) => Ende(); + PointerCaptureLost += (_, _) => Ende(); + ToolTipService.SetToolTip(this, "Gedrückt halten, um den Not-Aus zu lösen"); + Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(this, "Not-Aus lösen, gedrückt halten"); + } + + private void Ende() + { + _seit = null; + _uhr.Stop(); + _ring.Value = 0; + } +} + +public static class HauptknopfHilfe +{ + public static string Hilfe(this HauptArt a) => a switch + { + HauptArt.Unbekannt => "wartet auf den Server", + HauptArt.NotAusLoesen => "Not-Aus lösen - der Läufer darf wieder klicken", + HauptArt.HoertAuf => "Er spielt die laufenden Hände zu Ende und schließt dann die Tische - sofort: Not-Aus", + HauptArt.Aufhoeren => "Bei nächster Gelegenheit: ab der nächsten Hand aussetzen, laufende Hände zu Ende spielen, dann Tische zu - sofort: Not-Aus", + HauptArt.ZuschauenBeenden => "Zuschauer stoppen - danach wählst du Übung oder Echtgeld", + HauptArt.EchtgeldStarten => "Spielplan auf Echtgeld setzen und den Läufer starten - er öffnet selbst Tische bis zur Tischzahl", + HauptArt.UebungStarten => "Spielplan Übung setzen und den Läufer starten - er öffnet selbst Übungstische bis zur Tischzahl", + HauptArt.BudgetFehlt => "Echtgeld braucht ein Guthaben: Budget eintragen, sonst wählte die Lobby blind", + HauptArt.FreigabeFehlt => "Das Cockpit kann die Tischfenster nicht lesen - ein Läufer von hier wäre blind", + HauptArt.ClientStarten => "CoinPoker mit Debug-Port starten - danach anmelden", + HauptArt.ClientNeuStarten => "CoinPoker läuft ohne Debug-Port - beenden und mit Port neu starten, danach anmelden", + HauptArt.PortFehlt => "CoinPoker läuft ohne Debug-Port, aber Tische sind offen - erst die Tische schließen, dann neu starten", + _ => "", + }; +} diff --git a/winui/Seiten/ZuschauerTeil.cs b/winui/Seiten/ZuschauerTeil.cs new file mode 100644 index 00000000..ee6fc4bd --- /dev/null +++ b/winui/Seiten/ZuschauerTeil.cs @@ -0,0 +1,149 @@ +using System.Text.Json.Nodes; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Pokerfreak.Cockpit.Kern; + +namespace Pokerfreak.Cockpit.Seiten; + +/// +/// Zuschauer (ZuschauerAnsicht.swift): was der Laeufer sieht und taete. Der Lauf liest nur das Log und +/// kann nicht klicken. Je Tisch eine Karte (Board, Topf, wer dran ist, die Plaetze), dazu der eigene Zug +/// mit Empfehlung, EV je Linie und Reads; darunter der Abgleich "du gegen den Kern". +/// Steht im Cash-Reiter an Stelle der Live-Ansicht, solange der Zuschauer laeuft. +/// +public sealed class ZuschauerTeil : UserControl +{ + private readonly CockpitZustand _z; + private readonly StackPanel _inhalt = Ui.Spalte(10); + private string _abdruck = ""; + + public ZuschauerTeil(CockpitZustand z) + { + _z = z; + Content = _inhalt; + } + + public void Zeichnen() + { + var zu = _z.Ansicht.Zuschauer; + var abdruck = zu.Abdruck(); + if (abdruck == _abdruck) return; + _abdruck = abdruck; + _inhalt.Children.Clear(); + if (zu.Text("leer") is string leer) _inhalt.Children.Add(Ui.Klein(leer, true)); + var tische = zu.Objekte("tische").ToList(); + foreach (var p in tische) + { + if (p.Obj("tisch") is JsonObject t) _inhalt.Children.Add(TischKarte(t, p.T("raum"), tische.Count == 1)); + if (p.Obj("zug") is JsonObject a) _inhalt.Children.Add(ZugKarte(a)); + } + var abgleich = zu.Objekte("abgleich").ToList(); + if (abgleich.Count > 0) + { + _inhalt.Children.Add(Ui.Abschnitt("Abgleich", "du gegen den Kern, nur Chips")); + foreach (var x in abgleich.Take(100)) _inhalt.Children.Add(AbgleichZeile(x)); + } + } + + private static Border TischKarte(JsonObject t, string raum, bool mitGegnern) + { + var modus = t.Text("modus"); + var kopf = Ui.Reihe(6, Ui.Text(t.Text("raum") ?? (raum.Length > 0 ? raum : "Tisch"), 14, fett: true), + Ui.Abzeichen(modus == "uebung" ? "Übung" : modus == "cash" ? "Echtgeld" : "Modus unbekannt", modus == "uebung" ? "blau" : "rot")); + var s = Ui.Spalte(7, kopf); + + var board = t.Texte("board").ToList(); + var mitte = Ui.Reihe(3); + for (var i = 0; i < 5; i++) mitte.Children.Add(i < board.Count ? Ui.Spielkarte(board[i]) : Ui.Kartenplatz()); + if (t.Zahl("topf") is double topf) + { + mitte.Children.Add(new Border { Width = 8 }); + mitte.Children.Add(new Border + { + Background = Ui.Schwarz(0.45), + CornerRadius = new CornerRadius(9), + Padding = new Thickness(8, 2, 8, 3), + VerticalAlignment = VerticalAlignment.Center, + Child = Ui.Text("Topf " + Format.Auto(topf), 11, "gelb", true, zahlen: true), + }); + } + s.Children.Add(Ui.Flaeche(mitte, 12, 0.04, 8)); + + if (t.Obj("am_zug") is JsonObject az && az.Text("name") is string n) + s.Children.Add(Ui.Klein("Am Zug: " + n + (az.Zahl("frist_s") is double f ? $" · Frist {f:0} s" : ""))); + if (t.Text("hinweis") is string h) s.Children.Add(Ui.Klein(h, true)); + + // Die Plaetze: Name, Stack in bb, letzte Aktion; der eigene halbfett. Die Reads nur bei einem Tisch. + foreach (var sp in t.Objekte("spieler").OrderBy(x => x.Zahl("sitz") ?? 0)) + { + var ich = sp.Wahr("ich"); + var g = new Grid { ColumnSpacing = 6, Opacity = sp.Wahr("draussen") ? 0.45 : 1 }; + foreach (var w in new[] { new GridLength(30), new GridLength(1, GridUnitType.Star), GridLength.Auto, GridLength.Auto }) + g.ColumnDefinitions.Add(new ColumnDefinition { Width = w }); + g.Children.Add(Ui.Text(sp.Text("rolle") ?? "", 10, "gelb", true).Mit(x => x.VerticalAlignment = VerticalAlignment.Center)); + g.Children.Add(Ui.Text(sp.Text("name") ?? $"Sitz {sp.Zahl("sitz"):0}", 12, fett: ich, pinsel: ich ? Ui.Pinsel("gruen") : null).Spalte(1)); + if (sp.Text("aktion") is string ak) + g.Children.Add(Ui.Winzig(HaendeSeite.MitBetrag(ak, sp.Zahl("betrag_bb"))).Spalte(2).Mit(x => x.VerticalAlignment = VerticalAlignment.Center)); + g.Children.Add(Ui.Text(sp.Zahl("stack_bb") is double bb ? Format.Auto(bb) + " bb" : Format.Auto(sp.Zahl("stack")), 12, zahlen: true).Spalte(3)); + s.Children.Add(g); + if (mitGegnern && !ich && sp.Obj("einschaetzung") is JsonObject e) + s.Children.Add(Ui.Winzig($" {e.T("stil_text")} · {e.T("satz")}", Ui.Dritt).Mit(x => x.TextWrapping = TextWrapping.Wrap)); + } + return Ui.Flaeche(s, 16, 0.05, 10); + } + + private static Border ZugKarte(JsonObject a) + { + var karten = Ui.Reihe(4); + foreach (var k in a.Texte("karten")) karten.Children.Add(Ui.Spielkarte(k, true)); + var s = Ui.Spalte(7, Ui.Zeile(karten, a.Text("strasse") is string st ? Ui.Winzig(st, Ui.Dritt) : null)); + if (a.Obj("empfehlung") is JsonObject e) + { + var zeile = Ui.Reihe(6, Ui.Text(HaendeSeite.MitBetrag(e.Text("aktion"), e.Zahl("betrag_bb")), 14, fett: true)); + if (a.Zahl("equity") is double q) zeile.Children.Add(Ui.Klein("Equity " + Format.Prozent(q)).Mit(x => x.VerticalAlignment = VerticalAlignment.Center)); + s.Children.Add(zeile); + if ((e.Text("klartext") ?? e.Text("grund")) is { Length: > 0 } t) s.Children.Add(Ui.Klein(t, true)); + } + if (a.Text("hinweis") is string h) s.Children.Add(Ui.Klein(h, true)); + var kenn = new List(); + if (a.Zahl("topf_bb") is double tb) kenn.Add($"Topf {Format.Zahl(tb, 1)} bb"); + if (a.Zahl("zu_zahlen_bb") is double zz) kenn.Add($"zu zahlen {Format.Zahl(zz, 1)} bb"); + if (a.Zahl("stack_bb") is double sb) kenn.Add($"Stack {Format.Zahl(sb, 1)} bb"); + if (a.Zahl("takt_s") is double ts) kenn.Add($"Takt {ts:0} s"); + if (kenn.Count > 0) s.Children.Add(Ui.Winzig(string.Join(" · ", kenn), Ui.Dritt)); + var linien = a.Objekte("evs_bb").ToList(); + if (linien.Count > 0) + { + s.Children.Add(new Border { Height = 1, Background = Ui.Weiss(0.08) }); + s.Children.Add(Ui.Winzig("EV je Linie", fett: true)); + foreach (var l in linien) + s.Children.Add(Ui.Zeile(Ui.Text(HaendeSeite.MitBetrag(l.Text("aktion"), l.Zahl("betrag_bb")), 12), + Ui.Text(l.Zahl("ev_bb") is double ev ? (ev >= 0 ? "+" : "−") + Format.Zahl(Math.Abs(ev), 2) + " bb" : "–", 12, Teile.Ton(l.Zahl("ev_bb")), zahlen: true))); + } + var reads = a.Objekte("reads").ToList(); + if (reads.Count > 0) + { + s.Children.Add(new Border { Height = 1, Background = Ui.Weiss(0.08) }); + s.Children.Add(Ui.Winzig("Reads", fett: true)); + foreach (var r in reads) s.Children.Add(Ui.Text($"Sitz {r.Zahl("sitz") ?? 0:0}: {r.T("stil_text")} · {r.T("satz")}", 12, umbruch: true)); + } + return Ui.Flaeche(s, 16, 0.05, 10); + } + + private static Border AbgleichZeile(JsonObject a) + { + var abw = (int)(a.Zahl("abweichungen") ?? 0); + var rechts = abw == 0 ? Ui.Text("wie der Kern", 12, "gruen") + : Ui.Text(a.Zahl("kosten_bb") is double k ? $"kostet {Format.Zahl(k, 2)} bb" : "", 12, "orange", zahlen: true); + var s = Ui.Spalte(3, Ui.Zeile(Ui.Text(a.Text("hand") ?? "Hand", 12, fett: true), rechts)); + foreach (var z in a.Objekte("zuege")) + { + var du = z.Obj("bediener").Text("aktion") ?? "?"; + var kern = z.Obj("kern").Text("aktion") ?? "?"; + s.Children.Add(Ui.Winzig($"{z.T("strasse")}: du {du}, Kern {kern}" + (z.Text("warum") is string w ? " - " + w : "")) + .Mit(x => x.TextWrapping = TextWrapping.Wrap)); + } + if (a.Zahl("unbewertet") is double u && u > 0) s.Children.Add(Ui.Winzig($"{u:0} Züge unbewertet", Ui.Dritt)); + return Ui.Flaeche(s, 10, 0.05, 8); + } +}