WinUI-Cockpit: Server-Autostart mit Tisch-Desktop, cockpit.json, an alle Desktops, Tray, Zuschauer

Was das Rust-Cockpit am Windows-Client tut, jetzt auch hier:
- Kern/Dienst.cs: startet sicht/start.py --client selbst, wenn der lokale Port tot ist, mit
  COINPOKER_DESKTOP (Vorgabe 1, erbt der Laeufer); Job-Objekt KILL_ON_JOB_CLOSE raeumt ihn am Ende weg.
- Kern/Ort.cs: meldet jede Sekunde den Fensterrahmen als cockpit.json im Treffpunkt (Kacheln daneben),
  versteckt/minimiert/Ende -> Datei weg; bei Tisch-Desktop `fensterdienst anheften` (alle Desktops).
- Kern/Schale.cs: Tray-Symbol, Minimieren versteckt ins Tray, Klick holt zurueck, Menue Zeigen/Beenden.
- Seiten/ZuschauerTeil.cs: Zuschauer-Sicht (Tisch, eigener Zug mit Empfehlung/EV/Reads, Abgleich)
  an Stelle der Live-Ansicht, solange der Zuschauer laeuft (ZuschauerAnsicht.swift).
- Wurzel.Finden auch vom Arbeitsverzeichnis aus (wie dienst.rs).

Live geprueft: Server auf leerem Port gestartet, cockpit.json folgt dem Fenster, angeheftet
(fensterdienst: geaendert=false beim zweiten Aufruf), minimiert -> versteckt + Datei weg,
Schliessen beendet den Server und loescht die Datei.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:32:30 +01:00
co-authored by Claude Opus 5.5
parent 9b33942394
commit 08250ead87
7 changed files with 1324 additions and 686 deletions
+152
View File
@@ -0,0 +1,152 @@
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace Pokerfreak.Cockpit.Kern;
/// <summary>
/// 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.
/// </summary>
public sealed class Dienst : IDisposable
{
private Process? _kind;
private IntPtr _job;
/// <summary>Der Desktop-Schalter: leer/fehlend -> "1".</summary>
public static string DesktopSchalter(string? vorhanden) =>
string.IsNullOrWhiteSpace(vorhanden) ? "1" : vorhanden.Trim();
public static string Desktop => DesktopSchalter(Environment.GetEnvironmentVariable("COINPOKER_DESKTOP"));
public static List<string> ServerArgumente(int port, bool klon)
{
var a = new List<string> { 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";
}
/// <summary>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.</summary>
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<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>();
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);
}
+159
View File
@@ -0,0 +1,159 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.UI.Dispatching;
namespace Pokerfreak.Cockpit.Kern;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Wie client/umgebung.py `treffpunkt`: SCRATCH, sonst betrieb/scratch, ohne betrieb/ scratch/.</summary>
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");
}
/// <summary>`form: "fenster"`: das Kacheln nimmt die Flaeche neben dem Rahmen (kein Leisten-Ziel).</summary>
public static string CockpitJson(int x, int y, int w, int h) =>
$"{{\"rect\": [{x}, {y}, {w}, {h}], \"form\": \"fenster\", \"quelle\": \"windows-cockpit\"}}";
/// <summary>Der Fensterdienst, release vor debug (hand/winfenster.py `_bin`).</summary>
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();
}
/// <summary>Ist das Fenster an alle Desktops geheftet (oder braucht es das nicht)?</summary>
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));
}
}
/// <summary>Einmal `fensterdienst anheften {"id":hwnd}` - im Hintergrund (COM, ~100 ms).</summary>
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<RECT>()) == 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);
}
+136
View File
@@ -0,0 +1,136 @@
using System.Runtime.InteropServices;
namespace Pokerfreak.Cockpit.Kern;
/// <summary>
/// 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).
/// </summary>
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);
}
/// <summary>Den Hinweistext am Symbol aendern (z. B. Laeufer-Zustand).</summary>
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<NOTIFYICONDATAW>(),
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);
}
+87 -83
View File
@@ -1,83 +1,87 @@
namespace Pokerfreak.Cockpit.Kern;
/// <summary>
/// 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).
/// </summary>
public static class Wurzel
{
/// <summary>Der Projektordner: POKERFREAK_WURZEL, sonst aufwaerts vom Programm bis zu einem Ordner mit lesen/ und sicht/.</summary>
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<string> 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);
/// <summary>Pause setzen oder loesen; die Rueckmeldung sagt, ob es geklappt hat.</summary>
public static Rueckmeldung PauseSetzen(bool an)
{
var pfade = PausePfade().ToList();
var fehler = new List<string>();
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");
/// <summary>Nur ein ausdrueckliches "echt" gibt Echtgeld, alles andere Uebung.</summary>
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;
/// <summary>
/// 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).
/// </summary>
public static class Wurzel
{
/// <summary>Der Projektordner: POKERFREAK_WURZEL, sonst aufwaerts vom Programm bis zu einem Ordner mit lesen/ und sicht/.</summary>
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<string> 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);
/// <summary>Pause setzen oder loesen; die Rueckmeldung sagt, ob es geklappt hat.</summary>
public static Rueckmeldung PauseSetzen(bool an)
{
var pfade = PausePfade().ToList();
var fehler = new List<string>();
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");
/// <summary>Nur ein ausdrueckliches "echt" gibt Echtgeld, alles andere Uebung.</summary>
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 { }
}
}
+31
View File
@@ -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();
}
/// <summary>Aus dem Tray zurueck: zeigen, wiederherstellen, nach vorn.</summary>
private void Hervorholen()
{
AppWindow.Show();
if (AppWindow.Presenter is OverlappedPresenter op && op.State == OverlappedPresenterState.Minimized) op.Restore();
Activate();
}
}
/// <summary>Ein Reiter: zeichnet sich aus dem Zustand neu; `Takt` jede Sekunde fuer laufende Zeit.</summary>
@@ -140,4 +170,5 @@ public interface ISeite
{
void Zeichnen();
void Takt() { }
}
+610 -603
View File
File diff suppressed because it is too large Load Diff
+149
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<string>();
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);
}
}