tray-hintergrundbetrieb, favoriten, neustart-fix

- Desktop-App läuft beim Schließen als Symbol neben der Uhr weiter
  (automatisches Backup auch ohne Fenster, Windows-Hinweise), nur eine
  Instanz, optional mit Windows starten (--background)
- Favoriten: Stern an Projekten, eigene Reihe in der einfachen Ansicht,
  immer zuerst sortiert, Filter "Favoriten"
- Fix: geerbtes DASHBOARD_WORKER ließ ein aus dem Dashboard gestartetes
  Dashboard ohne Supervisor laufen ("Neu starten" beendete es)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 21:18:02 +01:00
parent d6f5b1672c
commit f2d0cd1df9
6 changed files with 313 additions and 23 deletions

View File

@@ -10,11 +10,22 @@ namespace ProjectDashboard;
static class Program
{
// --background: start only the server and the tray icon (Windows autostart)
[STAThread]
static void Main()
static void Main(string[] args)
{
// one dashboard per port: a second start brings the running one to the front
var name = $"ProjectDashboard-{MainForm.Port}";
using var mutex = new Mutex(true, name, out var first);
if (!first)
{
try { EventWaitHandle.OpenExisting(name + "-show").Set(); } catch { }
return;
}
using var show = new EventWaitHandle(false, EventResetMode.AutoReset, name + "-show");
ApplicationConfiguration.Initialize();
Application.Run(new MainForm());
Application.Run(new MainForm(args.Contains("--background"), show));
GC.KeepAlive(mutex);
}
}
@@ -30,7 +41,7 @@ static class Program
sealed class MainForm : Form
{
// DASHBOARD_PORT (also read by server.js) allows a second instance, e.g. for tests
static readonly int Port = int.TryParse(Environment.GetEnvironmentVariable("DASHBOARD_PORT"), out var p) ? p : 4848;
internal static readonly int Port = int.TryParse(Environment.GetEnvironmentVariable("DASHBOARD_PORT"), out var p) ? p : 4848;
static readonly string BaseUrl = $"http://127.0.0.1:{Port}/";
// DASHBOARD_HOME moves everything (window state, WebView2, unpacked app, data) - used for tests
static readonly string DataDir = Environment.GetEnvironmentVariable("DASHBOARD_HOME") is { Length: > 0 } home
@@ -51,37 +62,151 @@ sealed class MainForm : Form
Process? server; // only set when this window started the server
StreamWriter? serverLog;
public MainForm()
// tray: closing the window keeps the dashboard (and the automatic backup) running
readonly NotifyIcon tray = new() { Text = "Projekt-Dashboard" };
readonly System.Windows.Forms.Timer poll = new() { Interval = 20000 };
AppPrefs prefs = AppPrefs.Load();
bool startHidden; // --background: the first Show() is skipped
bool exiting; // "Beenden" in the tray menu: really close
string? lastAutoAt; // last automatic backup result seen (notifications)
string? lastPhase;
bool polledOnce;
public MainForm(bool background = false, EventWaitHandle? showSignal = null)
{
Text = "Projekte";
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
MinimumSize = new Size(900, 560);
RestoreWindow();
startHidden = background;
SetupTray();
if (showSignal != null)
{
new Thread(() => { while (showSignal.WaitOne()) { try { BeginInvoke(() => ShowFromTray()); } catch { } } }) { IsBackground = true }.Start();
}
FormClosing += (_, e) =>
{
if (!exiting && prefs.Tray && e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
SaveWindow();
Hide();
if (!prefs.HintShown)
{
tray.ShowBalloonTip(5000, "Projekt-Dashboard läuft weiter",
"Im Hintergrund – das automatische Backup läuft weiter. Rechtsklick auf das Symbol → Beenden.", ToolTipIcon.Info);
prefs.HintShown = true;
prefs.Save();
}
return;
}
if (server != null && BackupRunning() &&
MessageBox.Show(this, "Das Backup läuft noch.\n\nBeim Schließen wird es abgebrochen (bereits kopierte Dateien bleiben). Trotzdem schließen?",
"Projekte", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
{
e.Cancel = true;
exiting = false;
return;
}
SaveWindow();
if (Visible) SaveWindow();
};
BackColor = Color.FromArgb(245, 246, 250);
status.Text = "Starte Dashboard …";
Controls.Add(web);
Controls.Add(status);
Shown += async (_, _) => await StartAsync();
FormClosed += (_, _) => StopServer();
FormClosed += (_, _) => { poll.Stop(); tray.Visible = false; tray.Dispose(); StopServer(); };
}
async Task StartAsync()
// --background: the window is not shown at start; the server starts anyway
protected override void SetVisibleCore(bool value)
{
if (startHidden)
{
startHidden = false;
value = false;
if (!IsHandleCreated) CreateHandle();
BeginInvoke(async () =>
{
try { await EnsureServerAsync(); }
catch (Exception ex) { tray.ShowBalloonTip(8000, "Projekt-Dashboard", "Konnte nicht starten: " + ex.Message, ToolTipIcon.Error); }
});
}
base.SetVisibleCore(value);
}
void SetupTray()
{
tray.Icon = Icon;
var menu = new ContextMenuStrip();
menu.Items.Add("Öffnen", null, (_, _) => ShowFromTray());
menu.Items.Add("Backup …", null, (_, _) => ShowFromTray("backup"));
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add("Beenden", null, (_, _) => { exiting = true; Close(); });
tray.ContextMenuStrip = menu;
tray.DoubleClick += (_, _) => ShowFromTray();
tray.BalloonTipClicked += (_, _) => ShowFromTray();
tray.Visible = true;
poll.Tick += async (_, _) => await PollBackup();
poll.Start();
}
// Brings the window back (from the tray, or for a second start of the exe).
void ShowFromTray(string? hash = null)
{
if (!Visible) Show(); // the first Show() also starts the web view (Shown event)
if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal;
Activate();
BringToFront();
if (hash == "backup")
{
if (web.CoreWebView2 != null) _ = web.CoreWebView2.ExecuteScriptAsync("typeof openBackup === 'function' && openBackup()");
else pendingHash = "#backup";
}
}
string pendingHash = "";
// While the window is hidden: a balloon when a backup finished or failed.
async Task PollBackup()
{
try
{
Directory.CreateDirectory(DataDir);
if (!await IsServerUp())
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(3) };
using var doc = JsonDocument.Parse(await http.GetStringAsync(BaseUrl + "api/backup"));
var r = doc.RootElement;
var phase = r.TryGetProperty("phase", out var ph) ? ph.GetString() : null;
var auto = r.TryGetProperty("auto", out var au) && au.ValueKind == JsonValueKind.True;
string? at = null; bool ok = true; string detail = "";
if (r.TryGetProperty("schedule", out var sc) && sc.TryGetProperty("lastResult", out var lr) && lr.ValueKind == JsonValueKind.Object)
{
at = lr.TryGetProperty("at", out var a) ? a.GetString() : null;
ok = lr.TryGetProperty("ok", out var o) && o.ValueKind == JsonValueKind.True;
if (lr.TryGetProperty("targets", out var ts) && ts.ValueKind == JsonValueKind.Array)
detail = string.Join(", ", ts.EnumerateArray().Select(t =>
(t.TryGetProperty("name", out var n) ? n.GetString() : "") +
(t.TryGetProperty("error", out var er) && er.ValueKind == JsonValueKind.String ? ": " + er.GetString() : "")));
}
if (polledOnce && !Visible)
{
if (at != null && at != lastAutoAt)
tray.ShowBalloonTip(6000, ok ? "Automatisches Backup fertig" : "Automatisches Backup fehlgeschlagen",
detail.Length > 0 ? detail : (ok ? "Alle Projekte gesichert." : "Details im Dashboard."), ok ? ToolTipIcon.Info : ToolTipIcon.Warning);
else if (!auto && lastPhase is "checking" or "copying" && phase is "done" or "error")
tray.ShowBalloonTip(6000, phase == "done" ? "Backup fertig" : "Backup fehlgeschlagen",
phase == "done" ? "Alles gesichert." : (r.TryGetProperty("error", out var e) ? e.GetString() ?? "" : ""), phase == "done" ? ToolTipIcon.Info : ToolTipIcon.Warning);
}
lastAutoAt = at;
lastPhase = phase;
polledOnce = true;
}
catch { }
}
// Starts the Node server unless one is already running (also used by --background).
async Task EnsureServerAsync()
{
Directory.CreateDirectory(DataDir);
if (!await IsServerUp())
{
string node;
if (File.Exists(Path.Combine(appDir, "server.js")))
@@ -110,7 +235,13 @@ sealed class MainForm : Form
await Task.Delay(300);
}
}
}
async Task StartAsync()
{
try
{
await EnsureServerAsync();
var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2"));
await web.EnsureCoreWebView2Async(env);
var core = web.CoreWebView2;
@@ -125,7 +256,8 @@ sealed class MainForm : Form
core.DocumentTitleChanged += (_, _) => Text = core.DocumentTitle;
core.WebMessageReceived += OnWebMessage;
if (savedZoom is > 0.3 and < 3) web.ZoomFactor = savedZoom;
web.Source = new Uri(BaseUrl);
web.Source = new Uri(BaseUrl + pendingHash);
pendingHash = "";
web.Visible = true;
status.Visible = false;
}
@@ -162,6 +294,18 @@ sealed class MainForm : Form
var m = doc.RootElement;
if (m.ValueKind != JsonValueKind.Object) return;
var type = m.GetProperty("type").GetString();
// window options from Einstellungen → Allgemein → Fenster
if (type == "getAppSettings" || type == "appSettings")
{
if (type == "appSettings")
{
if (m.TryGetProperty("tray", out var tr) && tr.ValueKind is JsonValueKind.True or JsonValueKind.False) prefs.Tray = tr.GetBoolean();
if (m.TryGetProperty("autostart", out var au) && au.ValueKind is JsonValueKind.True or JsonValueKind.False) AppPrefs.SetAutostart(au.GetBoolean());
prefs.Save();
}
web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "appSettings", tray = prefs.Tray, autostart = AppPrefs.Autostart() }));
return;
}
if (type != "pickFolder" && type != "pickFile") return;
var id = m.GetProperty("id").GetString() ?? "";
var title = m.TryGetProperty("title", out var t) ? t.GetString() : null;
@@ -361,4 +505,42 @@ sealed class MainForm : Form
{
try { Process.Start(new ProcessStartInfo(uri) { UseShellExecute = true }); } catch { }
}
internal static string Home => DataDir;
}
// Window options (only the desktop app can do these): <DataDir>\app.json.
// Autostart lives in the registry (HKCU ...\Run); a test home (DASHBOARD_HOME)
// uses its own value name so it never touches the real one.
sealed class AppPrefs
{
public bool Tray { get; set; } = true;
public bool HintShown { get; set; }
static string File_ => Path.Combine(MainForm.Home, "app.json");
const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
static string RunValue => Environment.GetEnvironmentVariable("DASHBOARD_HOME") is { Length: > 0 } ? "ProjectDashboard-Test" : "ProjectDashboard";
public static AppPrefs Load()
{
try { return JsonSerializer.Deserialize<AppPrefs>(File.ReadAllText(File_)) ?? new AppPrefs(); } catch { return new AppPrefs(); }
}
public void Save()
{
try { Directory.CreateDirectory(MainForm.Home); File.WriteAllText(File_, JsonSerializer.Serialize(this)); } catch { }
}
public static bool Autostart()
{
try { using var k = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RunKey); return k?.GetValue(RunValue) is string; } catch { return false; }
}
public static void SetAutostart(bool on)
{
try
{
using var k = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(RunKey);
if (on) k.SetValue(RunValue, $"\"{Application.ExecutablePath}\" --background");
else k.DeleteValue(RunValue, false);
}
catch { }
}
}