Files
TTSDream/desktop/src/LanUps.Desktop/MainWindow.axaml.cs
T

307 lines
11 KiB
C#

using Avalonia.Controls;
using Avalonia.Interactivity;
using LanUps.Core;
namespace LanUps.Desktop;
public sealed partial class MainWindow : Window
{
private readonly AgentClient _agent = new();
private readonly CancellationTokenSource _lifetime = new();
private CancellationTokenSource? _discovery;
private DesktopOptions _options = DesktopSettings.Load();
private AgentState? _agentState;
private ShutdownDialog? _shutdownDialog;
private bool _savingSettings;
private string? _previousStatus;
private bool _logFailed;
private bool _closeDialogOpen;
private bool _exitConfirmed;
private readonly bool _startMinimized;
public MainWindow() : this(false) { }
internal MainWindow(bool startMinimized)
{
_startMinimized = startMinimized;
InitializeComponent();
LogLocation.Text = DesktopSettings.LogPath;
Closing += ConfirmClose;
Opened += StartMonitoring;
Closed += (_, _) =>
{
_lifetime.Cancel();
_discovery?.Cancel();
_agent.Dispose();
WriteLog("桌面端退出");
};
}
private void StartMonitoring(object? sender, EventArgs args)
{
Opened -= StartMonitoring;
if (_startMinimized) Minimize();
_ = ObserveAgentAsync();
}
internal void Restore()
{
if (!IsVisible)
Show();
WindowState = WindowState.Normal;
if (OwnedWindows.FirstOrDefault(window => window.IsVisible) is { } dialog)
dialog.Activate();
else
Activate();
}
private void Minimize()
{
// Linux desktops may lack a tray host. Keep their taskbar entry reachable.
if (OperatingSystem.IsLinux())
WindowState = WindowState.Minimized;
else
Hide();
}
private async void ConfirmClose(object? sender, WindowClosingEventArgs args)
{
if (_exitConfirmed || args.CloseReason is WindowCloseReason.OSShutdown or WindowCloseReason.ApplicationShutdown ||
_options.CloseAction == CloseAction.Exit)
return;
args.Cancel = true;
if (_closeDialogOpen)
return;
if (_options.CloseAction == CloseAction.Minimize)
{
Minimize();
return;
}
_closeDialogOpen = true;
CloseAction? choice;
try
{
choice = await new CloseDialog(_options).ShowDialog<CloseAction?>(this);
}
finally
{
_closeDialogOpen = false;
}
_options = DesktopSettings.Load();
if (choice == CloseAction.Minimize)
Minimize();
else if (choice == CloseAction.Exit)
{
_exitConfirmed = true;
Close();
}
}
private void OpenSettings(object? sender, RoutedEventArgs args)
{
var endpoint = _agentState?.Endpoint ?? _options.Endpoint;
HostBox.Text = endpoint.Host;
PortBox.Text = endpoint.Port.ToString();
NameBox.Text = endpoint.Name;
AskOnClose.IsChecked = _options.CloseAction is null;
MinimizeOnClose.IsChecked = _options.CloseAction == CloseAction.Minimize;
ExitOnClose.IsChecked = _options.CloseAction == CloseAction.Exit;
SettingsStatus.IsVisible = false;
DiscoveredUps.IsVisible = false;
LogWarning.IsVisible = _logFailed;
DashboardPage.IsVisible = false;
SettingsPage.IsVisible = true;
}
private void BackToDashboard(object? sender, RoutedEventArgs args) => ShowDashboard();
private void ShowDashboard()
{
_discovery?.Cancel();
SettingsPage.IsVisible = false;
DashboardPage.IsVisible = true;
}
private async void SaveSettings(object? sender, RoutedEventArgs args)
{
if (_savingSettings) return;
if (!NutEndpoint.TryParse(HostBox.Text, PortBox.Text, NameBox.Text, out var endpoint))
{
SettingsMessage("请输入有效的服务器地址、端口和 UPS 名称。");
return;
}
var close = MinimizeOnClose.IsChecked == true ? CloseAction.Minimize :
ExitOnClose.IsChecked == true ? CloseAction.Exit : (CloseAction?)null;
var options = new DesktopOptions(endpoint, close);
_savingSettings = true;
try
{
await _agent.SaveAsync(endpoint, _lifetime.Token);
DesktopSettings.Save(options);
_options = options;
WriteLog("已保存桌面端和后台服务设置");
ShowDashboard();
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { }
catch (Exception ex) when (IsAgentError(ex))
{
SettingsMessage($"设置保存失败:{ex.Message}");
}
finally { _savingSettings = false; }
}
private async void RefreshUps(object? sender, RoutedEventArgs args)
{
if (!NutEndpoint.TryServer(HostBox.Text, PortBox.Text, out var host, out var port))
{
SettingsMessage("请先输入有效的 NUT 服务器地址和端口。");
return;
}
using var discovery = new CancellationTokenSource();
_discovery = discovery;
RefreshUpsButton.IsEnabled = false;
DiscoveredUps.IsVisible = false;
SettingsMessage("正在获取 UPS 名称…");
try
{
var names = await _agent.DiscoverAsync(host, port, discovery.Token);
discovery.Token.ThrowIfCancellationRequested();
if (!NutEndpoint.TryServer(HostBox.Text, PortBox.Text, out var currentHost, out var currentPort) ||
currentHost != host || currentPort != port)
{
SettingsMessage("服务器地址已变更,请重新更新 UPS 名称。");
return;
}
WriteLog($"NUT {host}:{port} 发现 {names.Length} 台 UPS");
if (names.Length == 1)
NameBox.Text = names[0];
else if (names.Length > 1)
{
DiscoveredUps.ItemsSource = names;
DiscoveredUps.SelectedItem = names.Contains(NameBox.Text) ? NameBox.Text : null;
DiscoveredUps.IsVisible = true;
}
SettingsMessage(names.Length switch { 0 => "服务器没有发布可用的 UPS 名称。", 1 => "已填入 UPS 名称,保存后生效。", _ => "请选择要监控的 UPS。" });
}
catch (OperationCanceledException) when (discovery.IsCancellationRequested) { }
catch (Exception ex) when (IsAgentError(ex))
{
if (!discovery.IsCancellationRequested)
{
var error = ex is OperationCanceledException ? "连接或读取超时" : ex.Message;
SettingsMessage($"更新失败:{error}");
WriteLog($"读取 UPS 名称失败 {host}:{port} {error}");
}
}
finally
{
_discovery = null;
RefreshUpsButton.IsEnabled = true;
}
}
private void SettingsMessage(string message)
{
SettingsStatus.Text = message;
SettingsStatus.IsVisible = true;
}
private void SelectDiscoveredUps(object? sender, SelectionChangedEventArgs args)
{
if (DiscoveredUps.SelectedItem is string name) NameBox.Text = name;
}
private static bool IsAgentError(Exception ex) => ex is HttpRequestException or IOException or UnauthorizedAccessException or OperationCanceledException or System.Text.Json.JsonException;
private async Task ObserveAgentAsync()
{
try
{
while (!_lifetime.IsCancellationRequested)
{
try
{
var state = await _agent.StatusAsync(_lifetime.Token);
_agentState = state;
var endpoint = state.Endpoint;
CurrentEndpoint.Text = $"{endpoint.Name} @ {endpoint.Host}:{endpoint.Port}";
ShutdownModeLabel.Text = state.DryRun ? "关机信号 · 模拟模式" : "关机信号";
ShutdownSignal.Text = state.Pending is not null ? "关机倒计时进行中" : state.LastAction ?? "尚未收到关机信号";
Render(state.Update);
UpdateShutdownDialog(state.Pending, state.DryRun);
}
catch (Exception ex) when (IsAgentError(ex) && !_lifetime.IsCancellationRequested)
{
Render(new(_agentState?.Update.LastReading, $"本机后台服务不可用:{ex.Message}", false));
}
await Task.Delay(TimeSpan.FromSeconds(1), _lifetime.Token);
}
}
catch (Exception ex) when (_lifetime.IsCancellationRequested && (IsAgentError(ex) || ex is ObjectDisposedException)) { }
}
private void UpdateShutdownDialog(ShutdownNotice? notice, bool dryRun)
{
if (_shutdownDialog?.Notice.Id == notice?.Id) return;
_shutdownDialog?.Dismiss();
_shutdownDialog = null;
if (notice is null) return;
if (OwnedWindows.FirstOrDefault(window => window is CloseDialog) is CloseDialog closeDialog)
closeDialog.Close(null);
Restore();
var dialog = new ShutdownDialog(notice, dryRun, _agent);
_shutdownDialog = dialog;
WriteLog("后台服务收到 FSD,显示关机确认");
_ = dialog.ShowDialog(this);
}
private void Render(UpsUpdate update)
{
var reading = update.LastReading;
if (reading is null && update.Error is null)
{
Supply.Text = "等待后台服务读取 UPS";
Updated.Text = "等待首次读数";
ConnectionError.IsVisible = false;
ShowMetrics(null);
return;
}
var live = update.Error is null && reading is not null;
Supply.Text = !live ? "通讯中断" : reading!.Has("FSD") ? "收到关机信号" :
reading.Has("LB") ? "电池电量低" : reading.Has("OB") ? "电池供电" :
reading.Has("OL") ? "市电供电" : $"UPS 状态 {reading.Get("ups.status")}";
Updated.Text = reading is null ? "等待首次读数" :
$"{(live ? "更新时间" : "历史读数 · 最后读取")} {reading.At.LocalDateTime:G}";
ConnectionError.Text = update.Error;
ConnectionError.IsVisible = update.Error is not null;
ShowMetrics(reading);
var status = live ? $"UPS 状态 {reading!.Get("ups.status")}" : $"通讯中断 {update.Error}";
if (status != _previousStatus)
{
WriteLog(status);
_previousStatus = status;
}
}
private void WriteLog(string message)
{
_logFailed = !DesktopSettings.Log(message);
LogWarning.IsVisible = _logFailed;
}
private void ShowMetrics(UpsReading? reading)
{
Charge.Text = Metric(reading, "battery.charge", "%");
Load.Text = Metric(reading, "ups.load", "%");
InputVoltage.Text = Metric(reading, "input.voltage", " V");
OutputVoltage.Text = Metric(reading, "output.voltage", " V");
}
private static string Metric(UpsReading? reading, string key, string unit) =>
reading?.Get(key) is { Length: > 0 } value ? value + unit : "—";
}