Redesign the stats panel after the developer's feedback on v1 and add limit forecasts, daily week use and token-based estimates (D7, D8). - Panel: a fixed header with range and provider controls, limit tiles with pace chips, meters and forecasts, week use per day, token KPIs and charts, one burn-up chart per limit window with past instances, and a sortable breakdown whose "Other" row expands. One tooltip component for every chart, tile and table. - Core (D7): average and recent-rate forecasts, the reach date whenever use is over pace, days of a long window with even pace and daily budget, window instances derived from resets with a 15-minute tolerance, and estimates from price-weighted tokens where samples are missing. Forecasts start at 10 % of a window, or as soon as it is ahead, so a Codex week far ahead right after its reset warns too. - Settings, popups and the version (1.1.0) follow the new design. Closes #5 Closes #7
194 lines
9.8 KiB
C#
194 lines
9.8 KiB
C#
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Controls.ApplicationLifetimes;
|
|
using Avalonia.Media;
|
|
using Avalonia.Media.Imaging;
|
|
using Avalonia.Themes.Fluent;
|
|
using Avalonia.Threading;
|
|
using FinalToken.Core;
|
|
using FinalToken.Core.StreamDeck;
|
|
|
|
namespace FinalToken.App;
|
|
|
|
public sealed class DesktopApp : Application
|
|
{
|
|
private readonly PanelViewModel model = new();
|
|
private IClassicDesktopStyleApplicationLifetime? desktop;
|
|
private PanelWindow? panel;
|
|
private PopupStack? popups;
|
|
private TrayIcon? tray;
|
|
private DispatcherTimer? ageTimer;
|
|
private SettingsWindow? settingsWindow;
|
|
private Task settingsSave = Task.CompletedTask;
|
|
private PopupWindow? pluginAsk;
|
|
private RefreshEngine? engine;
|
|
private readonly SemaphoreSlim pluginGate = new(1, 1);
|
|
private int historyRequest;
|
|
private bool quitting;
|
|
private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
|
|
public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault();
|
|
public override void Initialize() => Styles.Add(Ui.NeutralTheme());
|
|
public override void OnFrameworkInitializationCompleted()
|
|
{
|
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
|
|
{
|
|
desktop = lifetime; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
|
engine = Program.Engine;
|
|
if (Program.StartupError is { } error)
|
|
{
|
|
var window = new Window { Title = "FinalToken — history error", Width = 560, Height = 240,
|
|
Content = Ui.Card(Ui.Stack(Ui.Text("History cannot be loaded", 22), Ui.Text(error), Ui.Button("Quit", () => desktop.Shutdown(1)))) };
|
|
desktop.MainWindow = window; window.Show();
|
|
window.Closed += (_, _) => desktop.Shutdown(1);
|
|
}
|
|
else
|
|
{
|
|
panel = new PanelWindow(model, () => Run(Refresh), OpenSettings, () => Run(Quit), () => Run(LoadHistory));
|
|
desktop.MainWindow = panel; popups = new(OpenPanel);
|
|
panel.Closing += (_, e) => { if (!quitting && engine?.Settings.CloseToTray != false) { e.Cancel = true; panel.Hide(); } else if (!quitting) { e.Cancel = true; Run(Quit); } };
|
|
CreateTray(); panel.Show();
|
|
if (engine is not null)
|
|
{
|
|
engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); });
|
|
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
|
|
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
|
|
model.Snapshot = engine.CurrentSnapshot;
|
|
model.ProbeInterval = engine.Settings.ProbeInterval;
|
|
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
|
|
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
|
|
ageTimer.Start();
|
|
Run(Start);
|
|
}
|
|
}
|
|
desktop.ShutdownRequested += (_, e) => { if (!quitting && engine is not null) { e.Cancel = true; Run(Quit); } };
|
|
}
|
|
base.OnFrameworkInitializationCompleted();
|
|
}
|
|
private async Task Start()
|
|
{
|
|
await engine!.StartAsync();
|
|
if (engine.Settings.StartWithOs) await OsStartup.ApplyAsync(true);
|
|
await CheckPlugin();
|
|
}
|
|
private void CreateTray()
|
|
{
|
|
var menu = new NativeMenu();
|
|
foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) })
|
|
{ var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); }
|
|
using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32));
|
|
using (var context = bitmap.CreateDrawingContext())
|
|
{ context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); }
|
|
using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0;
|
|
tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
|
|
tray.Clicked += (_, _) => OpenPanel();
|
|
TrayIcon.SetIcons(this, [tray]);
|
|
}
|
|
private void OpenPanel()
|
|
{
|
|
if (panel is null || quitting) return;
|
|
panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
|
|
if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel);
|
|
}
|
|
private async Task Refresh()
|
|
{
|
|
if (engine is null) return;
|
|
await model.RefreshAsync(() => engine.RefreshNowAsync());
|
|
}
|
|
private async Task LoadHistory()
|
|
{
|
|
if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
|
|
var request = ++historyRequest; var range = model.Range; var filter = model.ProviderFilter;
|
|
var history = await Task.Run(() => PanelViewModel.QueryHistory(engine.History, snapshot, range, filter, DateTimeOffset.UtcNow));
|
|
if (request == historyRequest && !quitting) model.History = history;
|
|
}
|
|
private void OpenSettings()
|
|
{
|
|
if (engine is null) return;
|
|
if (settingsWindow is not null) { settingsWindow.Activate(); return; }
|
|
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit));
|
|
settingsWindow.Closed += (_, _) => settingsWindow = null;
|
|
settingsWindow.Show();
|
|
}
|
|
private async Task SaveSettings(Settings value)
|
|
{
|
|
if (engine is null || quitting) return;
|
|
var previous = engine.Settings;
|
|
await OsStartup.ApplyAsync(value.StartWithOs);
|
|
if (quitting) { await OsStartup.ApplyAsync(previous.StartWithOs); return; }
|
|
try { await engine.UpdateSettingsAsync(value); }
|
|
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
|
|
if (quitting) return;
|
|
model.ProbeInterval = value.ProbeInterval;
|
|
await CheckPlugin();
|
|
if (!quitting) await engine.RefreshNowAsync();
|
|
}
|
|
private async Task CheckPlugin()
|
|
{
|
|
if (engine is null || quitting) return;
|
|
await pluginGate.WaitAsync();
|
|
try
|
|
{
|
|
if (quitting) return;
|
|
pluginAsk?.Close(); pluginAsk = null;
|
|
pluginStatus = await PluginInstaller.GetStatusAsync();
|
|
var action = InstallPolicy.Decide(engine.Settings.StreamDeckInstallMode, pluginStatus, engine.Settings.DismissedPluginVersion);
|
|
if (action == InstallAction.Install) await InstallPlugin();
|
|
else if (action == InstallAction.Ask)
|
|
{
|
|
var version = pluginStatus.ShippedVersion;
|
|
pluginAsk = new PopupWindow("Stream Deck plugin", $"Version {version} is ready.", OpenPanel,
|
|
pluginStatus.State == PluginInstallState.Outdated ? "Update" : "Install", () => Run(() => AcceptPlugin(version)),
|
|
() => Run(() => DismissPlugin(version)));
|
|
popups!.Show(pluginAsk);
|
|
}
|
|
}
|
|
finally { pluginGate.Release(); }
|
|
}
|
|
private async Task DismissPlugin(string? version)
|
|
{
|
|
await pluginGate.WaitAsync();
|
|
try { if (!quitting && engine is not null) await engine.UpdateSettingsAsync(engine.Settings with { DismissedPluginVersion = version }); }
|
|
finally { pluginGate.Release(); }
|
|
}
|
|
private async Task AcceptPlugin(string? version)
|
|
{
|
|
await pluginGate.WaitAsync();
|
|
try
|
|
{
|
|
if (quitting || engine?.Settings.StreamDeckInstallMode == InstallMode.Off) return;
|
|
var current = await PluginInstaller.GetStatusAsync();
|
|
if (current.ShippedVersion == version && current.State is PluginInstallState.NotInstalled or PluginInstallState.Outdated)
|
|
await InstallPlugin();
|
|
}
|
|
finally { pluginGate.Release(); }
|
|
}
|
|
private async Task InstallPlugin()
|
|
{
|
|
try { await PluginInstaller.InstallOrUpdateAsync(); pluginStatus = await PluginInstaller.GetStatusAsync(); if (!quitting) popups!.Show(new PopupWindow("Stream Deck", pluginStatus.State == PluginInstallState.UpToDate ? "Plugin installed successfully." : $"Plugin status: {pluginStatus.State}", OpenPanel)); }
|
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException)
|
|
{ if (!quitting) popups!.Show(new PopupWindow("Stream Deck", "Install failed: " + e.Message, OpenPanel)); }
|
|
}
|
|
private async Task Quit()
|
|
{
|
|
if (quitting) return; quitting = true;
|
|
ageTimer?.Stop(); tray?.Dispose(); popups?.Dispose(); settingsWindow?.Close();
|
|
var stopping = engine?.StopAsync() ?? Task.CompletedTask;
|
|
await pluginGate.WaitAsync(); pluginGate.Release();
|
|
try { await settingsSave; }
|
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or OperationCanceledException)
|
|
{ engine?.Diagnostics.Add(null, "settings-shutdown", "Settings could not finish applying before shutdown."); }
|
|
await stopping;
|
|
desktop?.Shutdown();
|
|
}
|
|
private async void Run(Func<Task> work)
|
|
{
|
|
try { await work(); }
|
|
catch (OperationCanceledException) { }
|
|
catch (Exception)
|
|
{
|
|
engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed.");
|
|
model.Message = "Operation failed. See diagnostics.";
|
|
}
|
|
}
|
|
}
|