using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml.Styling; using YZWater.Avalonia.Controls; using YZWater.Avalonia.Views; using YZWater.Core.Services; namespace YZWater.Avalonia; public partial class App : Application { private ResourceInclude? _darkTheme; private ResourceInclude? _lightTheme; public override void Initialize() { AvaloniaXamlLoader.Load(this); _darkTheme = new ResourceInclude(new Uri("avares://YZWater.Avalonia/Themes/IndustrialTheme.axaml")) { Source = new Uri("avares://YZWater.Avalonia/Themes/IndustrialTheme.axaml") }; _lightTheme = new ResourceInclude(new Uri("avares://YZWater.Avalonia/Themes/IndustrialThemeLight.axaml")) { Source = new Uri("avares://YZWater.Avalonia/Themes/IndustrialThemeLight.axaml") }; ThemeService.Instance.ThemeChanged += ApplyTheme; // 全局异常处理 AppDomain.CurrentDomain.UnhandledException += (s, e) => { Serilog.Log.Fatal(e.ExceptionObject as Exception, "未处理的异常"); }; TaskScheduler.UnobservedTaskException += (s, e) => { Serilog.Log.Error(e.Exception, "未观察的任务异常"); e.SetObserved(); }; } public override void OnFrameworkInitializationCompleted() { // 初始化服务 DatabaseService.Initialize(); PlcService.Initialize(); // 加载主题和语言偏好 ThemeService.Instance.LoadFromConfig(); LanguageService.Instance.LoadFromConfig(); // 应用当前主题 ThemeHelper.SetTheme(ThemeService.Instance.IsDarkTheme); // 初始化轮询和报警服务 PlcPollingService.Instance.Start(); AlarmService.Instance.Start(); // 启动数据日志 var dataLogger = new DataLoggingService(PlcPollingService.Instance); dataLogger.Start(); if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new MainWindow(); // 窗口关闭时清理 desktop.ShutdownRequested += (_, _) => { PlcPollingService.Instance.Dispose(); AlarmService.Instance.Dispose(); dataLogger.Dispose(); PlcService.Dispose(); DatabaseService.Dispose(); }; } base.OnFrameworkInitializationCompleted(); } private void ApplyTheme() { var resources = Resources.MergedDictionaries; if (resources.Count == 0) return; var targetTheme = ThemeService.Instance.IsDarkTheme ? _darkTheme : _lightTheme; if (targetTheme == null) return; resources.Clear(); resources.Add(targetTheme); ThemeHelper.SetTheme(ThemeService.Instance.IsDarkTheme); } }