From 1cf6af0617013df1b745af44fe5a4f8208be4bba Mon Sep 17 00:00:00 2001 From: Dynesshely Date: Fri, 10 Jan 2025 02:01:28 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=BE=20=F0=9F=8E=87=20Feat,=20Style(Ste?= =?UTF-8?q?p=201):=20All-round=20optimization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- KitX Dashboard/App.axaml.cs | 14 +- KitX Dashboard/AppFramework.cs | 105 ++++---- KitX Dashboard/Configuration/ConfigFetcher.cs | 3 +- KitX Dashboard/Converters/Base64Converters.cs | 2 +- .../Converters/WindowAttributesConverter.cs | 11 +- .../Generators/GreetingTextGenerator.cs | 36 ++- KitX Dashboard/Instances.cs | 12 +- KitX Dashboard/KitX.Dashboard.csproj | 49 ++-- KitX Dashboard/Managers/ActivityManager.cs | 4 +- .../Managers/AnnouncementManager.cs | 102 ++++++++ KitX Dashboard/Managers/AnouncementManager.cs | 80 ------ KitX Dashboard/Managers/ConfigManager.cs | 97 ++++--- KitX Dashboard/Managers/FileWatcherManager.cs | 4 +- KitX Dashboard/Managers/ManagerBase.cs | 4 +- KitX Dashboard/Managers/PluginsManager.cs | 2 +- KitX Dashboard/Managers/StatisticsManager.cs | 2 +- KitX Dashboard/Managers/WebManager.cs | 4 +- KitX Dashboard/Models/DeviceCase.cs | 141 +++++----- .../DevicesNetwork/DevicesDiscoveryServer.cs | 10 +- .../DevicesNetwork/DevicesOrganizer.cs | 36 ++- .../Network/DevicesNetwork/DevicesServer.cs | 42 ++- KitX Dashboard/Network/NetworkHelper.cs | 133 +++++----- .../Network/PluginsNetwork/PluginConnector.cs | 2 +- .../Network/PluginsNetwork/PluginsServer.cs | 15 +- KitX Dashboard/Program.cs | 20 +- KitX Dashboard/Services/EventService.cs | 62 ++--- KitX Dashboard/Utils/WindowsUtils.cs | 46 +++- ...del.cs => AnnouncementsWindowViewModel.cs} | 99 ++++---- KitX Dashboard/ViewModels/AppViewModel.cs | 15 +- .../ExchangeDeviceKeyWindowViewModel.cs | 25 +- .../ViewModels/MainWindowViewModel.cs | 19 +- .../Maintain/DebugOptionsWindowViewModel.cs | 14 + .../Controls/Home_ActivityLogViewModel.cs | 7 +- .../Pages/Controls/Home_CountViewModel.cs | 37 +-- .../Pages/Controls/PluginBarViewModel.cs | 53 ++-- .../Pages/Controls/Settings_AboutViewModel.cs | 28 +- .../Controls/Settings_GeneralViewModel.cs | 21 +- .../Controls/Settings_PerformenceViewModel.cs | 121 ++++----- .../Controls/Settings_PersonaliseViewModel.cs | 102 ++++---- .../Controls/Settings_UpdateViewModel.cs | 240 +++++++++--------- ...geViewModel.cs => DevicesPageViewModel.cs} | 8 +- .../ViewModels/Pages/HomePageViewModel.cs | 21 +- .../ViewModels/Pages/LibPageViewModel.cs | 10 +- .../ViewModels/Pages/RepoPageViewModel.cs | 27 +- .../ViewModels/Pages/SettingsPageViewModel.cs | 21 +- .../ViewModels/PluginDetailWindowViewModel.cs | 45 ++-- .../PluginsLaunchWindowViewModel.cs | 79 +++--- KitX Dashboard/ViewModels/ViewModelBase.cs | 31 +-- ...Window.axaml => AnnouncementsWindow.axaml} | 2 +- ....axaml.cs => AnnouncementsWindow.axaml.cs} | 47 ++-- KitX Dashboard/Views/MainWindow.axaml | 2 - KitX Dashboard/Views/MainWindow.axaml.cs | 175 +++++++------ .../Views/Maintain/DebugOptionsWindow.axaml | 9 + .../Maintain/DebugOptionsWindow.axaml.cs | 18 ++ .../Pages/Controls/Settings_General.axaml | 8 + .../{DevicePage.axaml => DevicesPage.axaml} | 2 +- ...vicePage.axaml.cs => DevicesPage.axaml.cs} | 6 +- KitX Dashboard/Views/Pages/HomePage.axaml.cs | 2 +- KitX Dashboard/Views/Pages/RepoPage.axaml.cs | 2 +- .../Views/PluginDetailWindow.axaml.cs | 2 +- 60 files changed, 1235 insertions(+), 1101 deletions(-) create mode 100644 KitX Dashboard/Managers/AnnouncementManager.cs delete mode 100644 KitX Dashboard/Managers/AnouncementManager.cs rename KitX Dashboard/ViewModels/{AnouncementsWindowViewModel.cs => AnnouncementsWindowViewModel.cs} (53%) create mode 100644 KitX Dashboard/ViewModels/Maintain/DebugOptionsWindowViewModel.cs rename KitX Dashboard/ViewModels/Pages/{DevicePageViewModel.cs => DevicesPageViewModel.cs} (92%) rename KitX Dashboard/Views/{AnouncementsWindow.axaml => AnnouncementsWindow.axaml} (98%) rename KitX Dashboard/Views/{AnouncementsWindow.axaml.cs => AnnouncementsWindow.axaml.cs} (51%) create mode 100644 KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml create mode 100644 KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml.cs rename KitX Dashboard/Views/Pages/{DevicePage.axaml => DevicesPage.axaml} (99%) rename KitX Dashboard/Views/Pages/{DevicePage.axaml.cs => DevicesPage.axaml.cs} (58%) diff --git a/KitX Dashboard/App.axaml.cs b/KitX Dashboard/App.axaml.cs index 5cb73fa4..f9218685 100644 --- a/KitX Dashboard/App.axaml.cs +++ b/KitX Dashboard/App.axaml.cs @@ -172,7 +172,7 @@ private static void InitializeLiveCharts() public override void OnFrameworkInitializationCompleted() { - var location = $"{nameof(App)}.{nameof(OnFrameworkInitializationCompleted)}"; + const string location = $"{nameof(App)}.{nameof(OnFrameworkInitializationCompleted)}"; if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { @@ -180,17 +180,7 @@ public override void OnFrameworkInitializationCompleted() } if (ConfigManager.Instance.AppConfig.App.ShowAnnouncementWhenStart) - new Thread(async () => - { - try - { - await AnouncementManager.CheckNewAnnouncements(); - } - catch (Exception ex) - { - Log.Error(ex, $"In {location}: {ex.Message}"); - } - }).Start(); + new Thread(async () => await AnnouncementManager.CheckNewAnnouncements()).Start(); base.OnFrameworkInitializationCompleted(); } diff --git a/KitX Dashboard/AppFramework.cs b/KitX Dashboard/AppFramework.cs index df0c3833..6ab17d38 100644 --- a/KitX Dashboard/AppFramework.cs +++ b/KitX Dashboard/AppFramework.cs @@ -23,22 +23,27 @@ namespace KitX.Dashboard; public static class AppFramework { - private readonly static Queue actionsInInitialization = []; + private static readonly Queue actionsInInitialization = []; public static void ProcessStartupArguments() { - Parser.Default.ParseArguments(Environment.GetCommandLineArgs()) + Parser + .Default.ParseArguments(Environment.GetCommandLineArgs()) .WithParsed(opt => { ConstantTable.IsSingleProcessStartMode = !opt.DisableSingleProcessCheck; ConstantTable.EnabledConfigFileHotReload = !opt.DisableConfigHotReload; ConstantTable.SkipNetworkSystemOnStartup = opt.DisableNetworkSystemOnStartup; - TasksManager.RunTask(() => - { - if (opt.PluginPath is not null) - ImportPlugin(opt.PluginPath); - }, $"{nameof(ImportPlugin)}", catchException: true); + TasksManager.RunTask( + () => + { + if (opt.PluginPath is not null) + ImportPlugin(opt.PluginPath); + }, + $"{nameof(ImportPlugin)}", + catchException: true + ); }); } @@ -55,9 +60,12 @@ public static void RunFramework() { var waitCount = 0; - while (Process.GetProcesses().Count(x => x.ProcessName.StartsWith("KitX.Dashboard")) >= 2) + while ( + Process.GetProcesses().Count(x => x.ProcessName.StartsWith("KitX.Dashboard")) >= 2 + ) { - if (waitCount > 10) Environment.Exit(ExitCodes.WaitRestartingLockFileTooLong); + if (waitCount > 10) + Environment.Exit(ExitCodes.WaitRestartingLockFileTooLong); ++waitCount; @@ -74,11 +82,13 @@ public static void RunFramework() ProcessStartupArguments(); if (ConstantTable.IsSingleProcessStartMode) - Process.GetProcesses().WhenCount( - count => count >= 2, - item => item.ProcessName.StartsWith("KitX.Dashboard"), - _ => Environment.Exit(ExitCodes.MultiProcessesStarted) - ); + Process + .GetProcesses() + .WhenCount( + count => count >= 2, + item => item.ProcessName.StartsWith("KitX.Dashboard"), + _ => Environment.Exit(ExitCodes.MultiProcessesStarted) + ); LoadResource(); @@ -97,11 +107,7 @@ public static void RunFramework() rollingInterval: RollingInterval.Hour, fileSizeLimitBytes: config.Log.LogFileSingleMaxSize, buffered: true, - flushToDiskInterval: new( - 0, - 0, - config.Log.LogFileFlushInterval - ), + flushToDiskInterval: new(0, 0, config.Log.LogFileFlushInterval), restrictedToMinimumLevel: config.Log.LogLevel, rollOnFileSizeLimit: true, retainedFileCountLimit: config.Log.LogFileMaxCount @@ -142,20 +148,21 @@ public static void RunFramework() #region Initialize WebManager - Instances.SignalTasksManager!.SignalRun(nameof(SignalsNames.MainWindowInitSignal), () => - { - new Thread(async () => + Instances.SignalTasksManager!.SignalRun( + nameof(SignalsNames.MainWindowInitSignal), + () => { - Thread.Sleep( - Convert.ToInt32(config.Web.DelayStartSeconds * 1000) - ); + new Thread(async () => + { + Thread.Sleep(Convert.ToInt32(config.Web.DelayStartSeconds * 1000)); - if (ConstantTable.SkipNetworkSystemOnStartup) - Instances.WebManager = new(); - else - Instances.WebManager = await new WebManager().RunAsync(new()); - }).Start(); - }); + if (ConstantTable.SkipNetworkSystemOnStartup) + Instances.WebManager = new(); + else + Instances.WebManager = await new WebManager().RunAsync(new()); + }).Start(); + } + ); #endregion @@ -167,13 +174,16 @@ public static void RunFramework() #region Initialize persistent windows - Instances.SignalTasksManager.SignalRun(nameof(SignalsNames.MainWindowInitSignal), () => - { - Dispatcher.UIThread.Post(() => + Instances.SignalTasksManager.SignalRun( + nameof(SignalsNames.MainWindowInitSignal), + () => { - ViewInstances.PluginsLaunchWindow = new(); - }); - }); + Dispatcher.UIThread.Post(() => + { + ViewInstances.PluginsLaunchWindow = new(); + }); + } + ); #endregion @@ -182,13 +192,14 @@ public static void RunFramework() private static void InitDataBase() { - var location = $"{nameof(AppFramework)}.{nameof(InitDataBase)}"; + const string location = $"{nameof(AppFramework)}.{nameof(InitDataBase)}"; try { var dir = ConstantTable.DataPath.GetFullPath(); - if (!Directory.Exists(dir)) _ = Directory.CreateDirectory(dir); + if (!Directory.Exists(dir)) + _ = Directory.CreateDirectory(dir); var dbfile = ConstantTable.ActivitiesDataBaseFilePath.GetFullPath(); @@ -206,7 +217,7 @@ private static void InitDataBase() private static async void LoadResource() { - var location = $"{nameof(AppFramework)}.{nameof(LoadResource)}"; + const string location = $"{nameof(AppFramework)}.{nameof(LoadResource)}"; try { @@ -220,11 +231,12 @@ private static async void LoadResource() } } - public static void AfterInitailization(Action action) => actionsInInitialization.Enqueue(action); + public static void AfterInitailization(Action action) => + actionsInInitialization.Enqueue(action); private static void ImportPlugin(string kxpPath) { - var location = $"{nameof(AppFramework)}.{nameof(ImportPlugin)}"; + const string location = $"{nameof(AppFramework)}.{nameof(ImportPlugin)}"; try { @@ -247,11 +259,10 @@ private static void ImportPlugin(string kxpPath) public static void EnsureExit() { - if (Design.IsDesignMode) return; - var location = $"{nameof(AppFramework)}.{nameof(EnsureExit)}"; + const string location = $"{nameof(AppFramework)}.{nameof(EnsureExit)}"; ConstantTable.EnsureExiting = true; @@ -281,7 +292,8 @@ public static void EnsureExit() var path = Process.GetCurrentProcess().MainModule?.FileName; - if (path is not null) Process.Start(path); + if (path is not null) + Process.Start(path); } Thread.Sleep(ConfigManager.Instance.AppConfig.App.LastBreakAfterExit); @@ -294,7 +306,8 @@ public static void EnsureExit() } }).Start(); - while (ConstantTable.EnsureExiting) ; + while (ConstantTable.EnsureExiting) + ; Environment.Exit(0); } diff --git a/KitX Dashboard/Configuration/ConfigFetcher.cs b/KitX Dashboard/Configuration/ConfigFetcher.cs index 223ae304..938e0668 100644 --- a/KitX Dashboard/Configuration/ConfigFetcher.cs +++ b/KitX Dashboard/Configuration/ConfigFetcher.cs @@ -6,7 +6,8 @@ public class ConfigFetcher { public static AppConfig AppConfig => ConfigManager.Instance.AppConfig; - public static AnnouncementConfig AnnouncementConfig => ConfigManager.Instance.AnnouncementConfig; + public static AnnouncementConfig AnnouncementConfig => + ConfigManager.Instance.AnnouncementConfig; public static MarketConfig MarketConfig => ConfigManager.Instance.MarketConfig; diff --git a/KitX Dashboard/Converters/Base64Converters.cs b/KitX Dashboard/Converters/Base64Converters.cs index 682df884..62b6e980 100644 --- a/KitX Dashboard/Converters/Base64Converters.cs +++ b/KitX Dashboard/Converters/Base64Converters.cs @@ -11,7 +11,7 @@ public class Base64ToIconConverter : IValueConverter { public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { - var location = $"{nameof(Base64ToIconConverter)}.{nameof(Convert)}"; + const string location = $"{nameof(Base64ToIconConverter)}.{nameof(Convert)}"; try { diff --git a/KitX Dashboard/Converters/WindowAttributesConverter.cs b/KitX Dashboard/Converters/WindowAttributesConverter.cs index 415946f8..a3ca1f18 100644 --- a/KitX Dashboard/Converters/WindowAttributesConverter.cs +++ b/KitX Dashboard/Converters/WindowAttributesConverter.cs @@ -7,11 +7,14 @@ internal class WindowAttributesConverter { internal static Distances PositionCameCenter(Distances location, Screen? screen, Resolution win) { - if (location.Left == -1) - location.Left = ((screen?.WorkingArea.Width ?? 2560) - (int)win.Width!) / 2; + if (screen is null) + return location; - if (location.Top == -1) - location.Top = (screen?.WorkingArea.Height ?? 1440 - (int)win.Height!) / 2; + if (location.Left - -1.0 < 0.1) + location.Left = (double)((screen.WorkingArea.Width - win.Width!) / 2.0); + + if (location.Top - -1.0 < 0.1) + location.Top = (double)((screen.WorkingArea.Height - win.Height!) / 2.0); return location; } diff --git a/KitX Dashboard/Generators/GreetingTextGenerator.cs b/KitX Dashboard/Generators/GreetingTextGenerator.cs index 5548e129..22e58a4d 100644 --- a/KitX Dashboard/Generators/GreetingTextGenerator.cs +++ b/KitX Dashboard/Generators/GreetingTextGenerator.cs @@ -16,37 +16,31 @@ internal static string GetKey() var time = DateTime.Now.Hour; if (time >= 6 && time < 12) - key = key.Replace("%Step%", "Morning").Replace( - "%Index%", - GenerateRandomIndex(Step.Morning).ToString() - ); + key = key.Replace("%Step%", "Morning") + .Replace("%Index%", GenerateRandomIndex(Step.Morning).ToString()); else if (time >= 12 && time < 14) - key = key.Replace("%Step%", "Noon").Replace( - "%Index%", - GenerateRandomIndex(Step.Noon).ToString() - ); + key = key.Replace("%Step%", "Noon") + .Replace("%Index%", GenerateRandomIndex(Step.Noon).ToString()); else if (time >= 14 && time < 18) - key = key.Replace("%Step%", "AfterNoon").Replace( - "%Index%", - GenerateRandomIndex(Step.AfterNoon).ToString() - ); + key = key.Replace("%Step%", "AfterNoon") + .Replace("%Index%", GenerateRandomIndex(Step.AfterNoon).ToString()); else if (time >= 18 && time < 24) - key = key.Replace("%Step%", "Evening").Replace( - "%Index%", - GenerateRandomIndex(Step.Evening).ToString() - ); + key = key.Replace("%Step%", "Evening") + .Replace("%Index%", GenerateRandomIndex(Step.Evening).ToString()); else - key = key.Replace("%Step%", "Night").Replace( - "%Index%", - GenerateRandomIndex(Step.Night).ToString() - ); + key = key.Replace("%Step%", "Night") + .Replace("%Index%", GenerateRandomIndex(Step.Night).ToString()); return key; } internal enum Step { - Morning, Noon, AfterNoon, Evening, Night + Morning, + Noon, + AfterNoon, + Evening, + Night, } internal static int GenerateRandomIndex(Step step) diff --git a/KitX Dashboard/Instances.cs b/KitX Dashboard/Instances.cs index 4827dc78..f9195d92 100644 --- a/KitX Dashboard/Instances.cs +++ b/KitX Dashboard/Instances.cs @@ -22,7 +22,7 @@ public static class Instances internal static void Initialize() { - var location = $"{nameof(Instances)}.{nameof(Initialize)}"; + const string location = $"{nameof(Instances)}.{nameof(Initialize)}"; TasksManager.RunTask(() => { @@ -32,11 +32,11 @@ internal static void Initialize() catchException: true ); - TasksManager.RunTask( - () => KeyHookManager = new KeyHookManager().Hook(), - location.Append("." + nameof(KeyHookManager)), - catchException: true - ); + //TasksManager.RunTask( + // () => KeyHookManager = new KeyHookManager().Hook(), + // location.Append("." + nameof(KeyHookManager)), + // catchException: true + //); TasksManager.RunTask( () => SecurityManager = SecurityManager.Instance, diff --git a/KitX Dashboard/KitX.Dashboard.csproj b/KitX Dashboard/KitX.Dashboard.csproj index b2231595..0756cbba 100644 --- a/KitX Dashboard/KitX.Dashboard.csproj +++ b/KitX Dashboard/KitX.Dashboard.csproj @@ -83,8 +83,7 @@ Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration --> - + @@ -97,8 +96,7 @@ - + @@ -107,37 +105,32 @@ - - - - + + + + - - + + - - - - + + + + + + + + + AnnouncementsWindow.axaml + + + DevicesPage.axaml + \ No newline at end of file diff --git a/KitX Dashboard/Managers/ActivityManager.cs b/KitX Dashboard/Managers/ActivityManager.cs index 5dc5c2c2..a5ca3288 100644 --- a/KitX Dashboard/Managers/ActivityManager.cs +++ b/KitX Dashboard/Managers/ActivityManager.cs @@ -30,7 +30,7 @@ public static List ReadActivities() public static void Record(Activity activity, Expression> keySelector) { - var location = $"{nameof(ActivityManager)}.{nameof(Record)}"; + const string location = $"{nameof(ActivityManager)}.{nameof(Record)}"; TasksManager.RunTask(() => { @@ -54,7 +54,7 @@ public static void Record(Activity activity, Expression> key public static void Update(Activity activity) { - var location = $"{nameof(ActivityManager)}.{nameof(Update)}"; + const string location = $"{nameof(ActivityManager)}.{nameof(Update)}"; TasksManager.RunTask(() => { diff --git a/KitX Dashboard/Managers/AnnouncementManager.cs b/KitX Dashboard/Managers/AnnouncementManager.cs new file mode 100644 index 00000000..f68681f8 --- /dev/null +++ b/KitX Dashboard/Managers/AnnouncementManager.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using Avalonia.Threading; +using KitX.Dashboard.Views; +using MsBox.Avalonia; +using MsBox.Avalonia.Enums; +using Serilog; + +namespace KitX.Dashboard.Managers; + +internal class AnnouncementManager +{ + public static async Task CheckNewAnnouncements() + { + const string location = $"{nameof(AnnouncementsWindow)}.{nameof(CheckNewAnnouncements)}"; + + var appConfig = ConfigManager.Instance.AppConfig; + + var linkBase = new StringBuilder() + .Append("https://") + .Append(appConfig.Web.ApiServer) + .Append(appConfig.Web.ApiPath) + .ToString(); + + var link = new StringBuilder() + .Append(linkBase) + .Append(ConstantTable.Api_Get_Announcements) + .ToString(); + + try + { + using var client = new HttpClient(); + + client.DefaultRequestHeaders.Accept.Clear(); + + var msg = await client.GetStringAsync(link); + + var list = JsonSerializer.Deserialize>(msg); + + var accepted = ConfigManager.Instance.AnnouncementConfig.Accepted; + + if (list is null) + return; + + var unreads = ( + from item in list + where !accepted.Contains(item) + select DateTime.Parse(item) + ).ToList(); + + var src = new Dictionary(); + + foreach (var item in unreads) + { + var apiLink = new StringBuilder() + .Append($"{linkBase}{ConstantTable.Api_Get_Announcement}") + .Append('?') + .Append($"lang={ConfigManager.Instance.AppConfig.App.AppLanguage}") + .Append('&') + .Append($"date={item:yyyy-MM-dd HH-mm}") + .ToString(); + + var md = JsonSerializer.Deserialize(await client.GetStringAsync(apiLink)); + + if (md is not null) + src.Add(item.ToString("yyyy-MM-dd HH:mm"), md); + } + + if (unreads.Count > 0) + { + Dispatcher.UIThread.Post(() => + { + var toast = new AnnouncementsWindow().UpdateSource(src); + + ViewInstances.ShowWindow(toast); + }); + } + } + catch (Exception ex) + { + Log.Error(ex, $"In {location}: {ex.Message}"); + + Dispatcher.UIThread.Post(() => + { + var content = new StringBuilder() + .AppendLine($"GET: {link}") + .AppendLine() + .AppendLine(ex.StackTrace) + .ToString(); + + var box = MessageBoxManager + .GetMessageBoxStandard(ex.Message, content, icon: Icon.Error) + .ShowWindowAsync(); + }); + } + } +} diff --git a/KitX Dashboard/Managers/AnouncementManager.cs b/KitX Dashboard/Managers/AnouncementManager.cs deleted file mode 100644 index 3ccaa091..00000000 --- a/KitX Dashboard/Managers/AnouncementManager.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; -using Avalonia.Threading; -using KitX.Dashboard.Views; - -namespace KitX.Dashboard.Managers; - -internal class AnouncementManager -{ - public static async Task CheckNewAnnouncements() - { - using var client = new HttpClient(); - - client.DefaultRequestHeaders.Accept.Clear(); - - var appConfig = ConfigManager.Instance.AppConfig; - - var linkBase = new StringBuilder() - .Append("https://") - .Append(appConfig.Web.ApiServer) - .Append(appConfig.Web.ApiPath) - .ToString() - ; - - var link = new StringBuilder() - .Append(linkBase) - .Append(ConstantTable.Api_Get_Announcements) - .ToString() - ; - - var msg = await client.GetStringAsync(link); - - var list = JsonSerializer.Deserialize>(msg); - - var accepted = ConfigManager.Instance.AnnouncementConfig.Accepted; - - var unreads = new List(); - - if (list is null || accepted is null) return; - - foreach (var item in list) - if (!accepted.Contains(item)) - unreads.Add(DateTime.Parse(item)); - - var src = new Dictionary(); - - foreach (var item in unreads) - { - var apiLink = new StringBuilder() - .Append($"{linkBase}{ConstantTable.Api_Get_Announcement}") - .Append('?') - .Append($"lang={ConfigManager.Instance.AppConfig.App.AppLanguage}") - .Append('&') - .Append($"date={item:yyyy-MM-dd HH-mm}") - .ToString() - ; - - var md = JsonSerializer.Deserialize( - await client.GetStringAsync(apiLink) - ); - - if (md is not null) - src.Add(item.ToString("yyyy-MM-dd HH:mm"), md); - } - - if (unreads.Count > 0) - { - Dispatcher.UIThread.Post(() => - { - var toast = new AnouncementsWindow().UpdateSource(src); - - ViewInstances.ShowWindow(toast); - }); - } - } -} diff --git a/KitX Dashboard/Managers/ConfigManager.cs b/KitX Dashboard/Managers/ConfigManager.cs index 6ba41392..8c4a848e 100644 --- a/KitX Dashboard/Managers/ConfigManager.cs +++ b/KitX Dashboard/Managers/ConfigManager.cs @@ -13,7 +13,8 @@ public class ConfigManager { private static ConfigManager? _instance; - public static ConfigManager Instance => _instance ??= new ConfigManager().SetLocation("./Config/").Load(); + public static ConfigManager Instance => + _instance ??= new ConfigManager().SetLocation("./Config/").Load(); internal class ConfigManagerInfo { @@ -49,26 +50,31 @@ public ConfigManager() private void InitEvents() { - var location = $"{nameof(ConfigManager)}.{nameof(InitEvents)}"; + const string location = $"{nameof(ConfigManager)}.{nameof(InitEvents)}"; - TasksManager.RunTask(() => - { - - EventService.AppConfigChanged += () => - { - Instances.FileWatcherManager!.IncreaseExceptCount(AppConfig.ConfigFileWatcherName!); - - AppConfig.Save(AppConfig.ConfigFileLocation!); - }; - - EventService.PluginsConfigChanged += () => + TasksManager.RunTask( + () => { - Instances.FileWatcherManager!.IncreaseExceptCount(PluginsConfig.ConfigFileWatcherName!); + EventService.AppConfigChanged += () => + { + Instances.FileWatcherManager!.IncreaseExceptCount( + AppConfig.ConfigFileWatcherName! + ); - PluginsConfig.Save(PluginsConfig.ConfigFileLocation!); - }; + AppConfig.Save(AppConfig.ConfigFileLocation!); + }; - }, location); + EventService.PluginsConfigChanged += () => + { + Instances.FileWatcherManager!.IncreaseExceptCount( + PluginsConfig.ConfigFileWatcherName! + ); + + PluginsConfig.Save(PluginsConfig.ConfigFileLocation!); + }; + }, + location + ); } public ConfigManager SetLocation(string location) @@ -79,7 +85,8 @@ public ConfigManager SetLocation(string location) return this; } - private void RegisterFileWatcher(T config) where T : ConfigBase, new() + private void RegisterFileWatcher(T config) + where T : ConfigBase, new() { var name = "ConfigFileWatcher".Append(typeof(T).Name); @@ -94,7 +101,7 @@ public ConfigManager SetLocation(string location) path, (_, y) => { - var location = $"{nameof(ConfigManager)}.{nameof(RegisterFileWatcher)}"; + const string location = $"{nameof(ConfigManager)}.{nameof(RegisterFileWatcher)}"; Log.Information($"FileChanged: {name} | {y.Name}, {y.ChangeType}"); @@ -110,7 +117,8 @@ public ConfigManager SetLocation(string location) ); } - public ConfigManager LoadConfigFile() where T : ConfigBase, new() + public ConfigManager LoadConfigFile() + where T : ConfigBase, new() { var name = typeof(T).Name; @@ -136,37 +144,48 @@ public ConfigManager SetLocation(string location) public ConfigManager Load() { - var location = $"{nameof(ConfigManager)}.{nameof(Load)}"; + const string location = $"{nameof(ConfigManager)}.{nameof(Load)}"; - TasksManager.RunTask(() => - { - LoadConfigFile(); - LoadConfigFile(); - LoadConfigFile(); - LoadConfigFile(); - LoadConfigFile(); - }, location, catchException: false); + TasksManager.RunTask( + () => + { + LoadConfigFile(); + LoadConfigFile(); + LoadConfigFile(); + LoadConfigFile(); + LoadConfigFile(); + }, + location, + catchException: false + ); return this; } public ConfigManager SaveAll() { - var location = $"{nameof(ConfigManager)}.{nameof(SaveAll)}"; + const string location = $"{nameof(ConfigManager)}.{nameof(SaveAll)}"; - TasksManager.RunTask(() => - { - foreach (var config in _configs.Values) - config.Save(config.ConfigFileLocation ?? throw new InvalidOperationException( - $"Saving config requires `{nameof(ConfigBase.ConfigFileLocation)}` property not null." - )); - - }, location, catchException: true); + TasksManager.RunTask( + () => + { + foreach (var config in _configs.Values) + config.Save( + config.ConfigFileLocation + ?? throw new InvalidOperationException( + $"Saving config requires `{nameof(ConfigBase.ConfigFileLocation)}` property not null." + ) + ); + }, + location, + catchException: true + ); return this; } - private T GetConfig() where T : ConfigBase + private T GetConfig() + where T : ConfigBase { var name = typeof(T).Name; diff --git a/KitX Dashboard/Managers/FileWatcherManager.cs b/KitX Dashboard/Managers/FileWatcherManager.cs index 2fe01779..c3931b53 100644 --- a/KitX Dashboard/Managers/FileWatcherManager.cs +++ b/KitX Dashboard/Managers/FileWatcherManager.cs @@ -27,7 +27,7 @@ public FileWatcherManager RegisterWatcher( string filePath, Action onchange) { - var location = $"{nameof(FileWatcherManager)}.{nameof(RegisterWatcher)}"; + const string location = $"{nameof(FileWatcherManager)}.{nameof(RegisterWatcher)}"; if (!Watchers.ContainsKey(name)) { @@ -89,7 +89,7 @@ public FileWatcher( Action onchanged, NotifyFilters? notifyFilters = NotifyFilters.LastWrite) { - var location = $"{nameof(FileWatcherManager)}.{nameof(FileWatcher)}"; + const string location = $"{nameof(FileWatcherManager)}.{nameof(FileWatcher)}"; var filepath = filename.GetFullPath(); diff --git a/KitX Dashboard/Managers/ManagerBase.cs b/KitX Dashboard/Managers/ManagerBase.cs index 03685324..566e7643 100644 --- a/KitX Dashboard/Managers/ManagerBase.cs +++ b/KitX Dashboard/Managers/ManagerBase.cs @@ -2,6 +2,4 @@ namespace KitX.Dashboard.Managers; -public class ManagerBase : ConfigFetcher -{ -} +public class ManagerBase : ConfigFetcher { } diff --git a/KitX Dashboard/Managers/PluginsManager.cs b/KitX Dashboard/Managers/PluginsManager.cs index b136ad0a..8eae27b7 100644 --- a/KitX Dashboard/Managers/PluginsManager.cs +++ b/KitX Dashboard/Managers/PluginsManager.cs @@ -19,7 +19,7 @@ internal class PluginsManager internal static void ImportPlugin(string[] kxpfiles, bool inGraphic = false) { - var location = $"{nameof(PluginsManager)}.{nameof(ImportPlugin)}"; + const string location = $"{nameof(PluginsManager)}.{nameof(ImportPlugin)}"; var processPath = Environment.ProcessPath ?? throw new Exception("Can not get path of `KitX.Dashboard` process."); diff --git a/KitX Dashboard/Managers/StatisticsManager.cs b/KitX Dashboard/Managers/StatisticsManager.cs index fba42df6..2c9f1ea1 100644 --- a/KitX Dashboard/Managers/StatisticsManager.cs +++ b/KitX Dashboard/Managers/StatisticsManager.cs @@ -91,7 +91,7 @@ internal static async void RecoverPreviousStatistics() internal static void BeginRecord() { - var location = $"{nameof(StatisticsManager)}.{nameof(BeginRecord)}"; + const string location = $"{nameof(StatisticsManager)}.{nameof(BeginRecord)}"; var use_timer = new Timer() { diff --git a/KitX Dashboard/Managers/WebManager.cs b/KitX Dashboard/Managers/WebManager.cs index 81024bf2..d2fc6b13 100644 --- a/KitX Dashboard/Managers/WebManager.cs +++ b/KitX Dashboard/Managers/WebManager.cs @@ -18,7 +18,7 @@ public class WebManager public async Task RunAsync(WebManagerOperationInfo info) { - var location = $"{nameof(WebManager)}.{nameof(RunAsync)}"; + const string location = $"{nameof(WebManager)}.{nameof(RunAsync)}"; await TasksManager.RunTaskAsync(async () => { @@ -44,7 +44,7 @@ await TasksManager.RunTaskAsync(async () => public async Task CloseAsync(WebManagerOperationInfo info) { - var location = $"{nameof(WebManager)}.{nameof(CloseAsync)}"; + const string location = $"{nameof(WebManager)}.{nameof(CloseAsync)}"; try { diff --git a/KitX Dashboard/Models/DeviceCase.cs b/KitX Dashboard/Models/DeviceCase.cs index fefca7af..01db8e97 100644 --- a/KitX Dashboard/Models/DeviceCase.cs +++ b/KitX Dashboard/Models/DeviceCase.cs @@ -30,7 +30,7 @@ public DeviceCase(DeviceInfo deviceInfo) InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { AuthorizeAndExchangeDeviceKeyCommand = ReactiveCommand.Create( async info => @@ -38,8 +38,8 @@ public override void InitCommands() if (ConstantTable.IsExchangingDeviceKey) { var box = MessageBoxManager.GetMessageBoxStandard( - Translate("Text_Log_Warning"), - Translate("Text_Device_Tip_ExchangingDeviceKey"), + Translate("Text_Log_Warning") ?? "Null", + Translate("Text_Device_Tip_ExchangingDeviceKey") ?? "Null", ButtonEnum.Ok, Icon.Warning ); @@ -61,8 +61,8 @@ public override void InitCommands() if (SecurityManager.Instance.LocalDeviceKey is null) { var box = MessageBoxManager.GetMessageBoxStandard( - Translate("Text_Log_Error"), - Translate("Text_Device_Tip_SecuritySystemFailed"), + Translate("Text_Log_Error") ?? "Null", + Translate("Text_Device_Tip_SecuritySystemFailed") ?? "Null", ButtonEnum.Ok, Icon.Error ); @@ -88,7 +88,8 @@ public override void InitCommands() var sha1 = SecurityManager.GetSHA1(key); - var url = $"http://{target}/Api/V1/Device/{nameof(DeviceController.ExchangeKey)}?verifyCodeSHA1={sha1}&address={address}"; + var url = + $"http://{target}/Api/V1/Device/{nameof(DeviceController.ExchangeKey)}?verifyCodeSHA1={sha1}&address={address}"; ConstantTable.ExchangeDeviceKeyCode = key; @@ -100,18 +101,22 @@ public override void InitCommands() ConstantTable.IsExchangingDeviceKey = false; - var url = $"http://{target}/Api/V1/Device/{nameof(DeviceController.CancelExchangingKey)}"; + var url = + $"http://{target}/Api/V1/Device/{nameof(DeviceController.CancelExchangingKey)}"; using var http = new HttpClient(); var response = await http.PostAsync(url, null); - Log.Information($"In {nameof(DeviceController)}: Requested {url} with responsed {response.StatusCode} - {response}"); + Log.Information( + $"In {nameof(DeviceController)}: Requested {url} with responsed {response.StatusCode} - {response}" + ); }); ViewInstances.ShowWindow(window); - EventService.OnReceiveCancelExchangingDeviceKey += () => Dispatcher.UIThread.Post(() => window.Canceled()); + EventService.OnReceiveCancelExchangingDeviceKey += () => + Dispatcher.UIThread.Post(() => window.Canceled()); using var http = new HttpClient(); @@ -124,19 +129,17 @@ public override void InitCommands() ) ); - if (response.IsSuccessStatusCode) - { - - } + if (response.IsSuccessStatusCode) { } else { var box = MessageBoxManager.GetMessageBoxStandard( - Translate("Text_Log_Error"), + Translate("Text_Log_Error") ?? "Null", new StringBuilder() .AppendLine($"Requested: {url}") - .AppendLine($"Responsed: {response.StatusCode} - {response.RequestMessage}") - .ToString() - , + .AppendLine( + $"Responsed: {response.StatusCode} - {response.RequestMessage}" + ) + .ToString(), ButtonEnum.Ok, Icon.Error ); @@ -157,8 +160,8 @@ public override void InitCommands() if (info.IsCurrentDevice()) { var box = MessageBoxManager.GetMessageBoxStandard( - Translate("Text_Log_Error"), - Translate("Text_Device_Tip_DeleteYourSelfError"), + Translate("Text_Log_Error") ?? "Null", + Translate("Text_Device_Tip_DeleteYourSelfError") ?? "Null", ButtonEnum.Ok, Icon.Forbidden ); @@ -174,10 +177,7 @@ public override void InitCommands() ); } - public override void InitEvents() - { - - } + public sealed override void InitEvents() { } private DeviceInfo deviceInfo; @@ -205,68 +205,79 @@ private void Update() private void Connect() { - TasksManager.RunTask(async () => - { - using var http = new HttpClient(); - - var targetKey = SecurityManager.SearchDeviceKey(DeviceInfo.Device); + TasksManager.RunTask( + async () => + { + using var http = new HttpClient(); - if (targetKey is null) return; + var targetKey = SecurityManager.SearchDeviceKey(DeviceInfo.Device); - var local = SecurityManager.Instance.GetPrivateDeviceKey(); + if (targetKey is null) + return; - if (local is null) return; + var local = SecurityManager.Instance.GetPrivateDeviceKey(); - var deviceName = local.Device.DeviceName; + if (local is null) + return; - var deviceNameEncrypted = SecurityManager.Instance.EncryptString(deviceName); + var deviceName = local.Device.DeviceName; - var address = $"{DeviceInfo.Device.IPv4}:{DeviceInfo.DevicesServerPort}"; + var deviceNameEncrypted = SecurityManager.Instance.EncryptString(deviceName); - var deviceJson = JsonSerializer.Serialize(local.Device); + var address = $"{DeviceInfo.Device.IPv4}:{DeviceInfo.DevicesServerPort}"; - deviceJson = Convert.ToBase64String(deviceJson.FromUTF8()); + var deviceJson = JsonSerializer.Serialize(local.Device); - var url = $"http://{address}/Api/V1/Device/{nameof(DeviceController.Connect)}?deviceBase64={deviceJson}"; + deviceJson = Convert.ToBase64String(deviceJson.FromUTF8()); - var response = await http.PostAsync( - url, - new StringContent( - JsonSerializer.Serialize(deviceNameEncrypted), - Encoding.UTF8, - "application/json" - ) - ); + var url = + $"http://{address}/Api/V1/Device/{nameof(DeviceController.Connect)}?deviceBase64={deviceJson}"; - if (response.IsSuccessStatusCode) - { - Log.Information($"Connected to {DeviceInfo.Device.DeviceName} with response {response}"); + var response = await http.PostAsync( + url, + new StringContent( + JsonSerializer.Serialize(deviceNameEncrypted), + Encoding.UTF8, + "application/json" + ) + ); - var body = await response.Content.ReadAsStringAsync(); + if (response.IsSuccessStatusCode) + { + Log.Information( + $"Connected to {DeviceInfo.Device.DeviceName} with response {response}" + ); - if (body is null) return; + var body = await response.Content.ReadAsStringAsync(); - ConnectionToken = SecurityManager.RsaDecryptString(targetKey, body); + if (body is null) + return; - Update(); - } - else - { - Log.Warning( - new StringBuilder() - .AppendLine($"Requested: {url}") - .AppendLine($"Responsed: {response.StatusCode} - {response.ReasonPhrase}") - .AppendLine(response.RequestMessage?.ToString()) - .ToString() - ); - } + ConnectionToken = SecurityManager.RsaDecryptString(targetKey, body); - }, $"Connecting {DeviceInfo.Device.DeviceName}"); + Update(); + } + else + { + Log.Warning( + new StringBuilder() + .AppendLine($"Requested: {url}") + .AppendLine( + $"Responsed: {response.StatusCode} - {response.ReasonPhrase}" + ) + .AppendLine(response.RequestMessage?.ToString()) + .ToString() + ); + } + }, + $"Connecting {DeviceInfo.Device.DeviceName}" + ); } public bool IsAuthorized => SecurityManager.IsDeviceAuthorized(DeviceInfo.Device); - public bool IsConnected => DevicesServer.Instance.IsDeviceSignedIn(DeviceInfo.Device) || ConnectionToken is not null; + public bool IsConnected => + DevicesServer.Instance.IsDeviceSignedIn(DeviceInfo.Device) || ConnectionToken is not null; public bool IsCurrentDevice => DeviceInfo.IsCurrentDevice(); diff --git a/KitX Dashboard/Network/DevicesNetwork/DevicesDiscoveryServer.cs b/KitX Dashboard/Network/DevicesNetwork/DevicesDiscoveryServer.cs index 916ce5a7..c6408903 100644 --- a/KitX Dashboard/Network/DevicesNetwork/DevicesDiscoveryServer.cs +++ b/KitX Dashboard/Network/DevicesNetwork/DevicesDiscoveryServer.cs @@ -113,7 +113,7 @@ await TasksManager.RunTaskAsync(() => } catch (Exception ex) { - var location = $"{nameof(DevicesServer)}.{nameof(RunAsync)}"; + const string location = $"{nameof(DevicesServer)}.{nameof(RunAsync)}"; Log.Warning(ex, $"In {location}: {ex.Message}"); } }, nameof(FindSupportNetworkInterfaces)); @@ -196,7 +196,7 @@ private void FindSupportNetworkInterfaces(List clients, IPAddress mul } catch (Exception ex) { - var location = $"{nameof(DevicesServer)}.{nameof(FindSupportNetworkInterfaces)}"; + const string location = $"{nameof(DevicesServer)}.{nameof(FindSupportNetworkInterfaces)}"; Log.Error(ex, $"In {location}: {ex.Message}"); } @@ -227,7 +227,7 @@ private void UpdateDefaultDeviceInfo() if (LastTimeToOSVersionUpdated > ConfigManager.Instance.AppConfig.IO.OperatingSystemVersionUpdateInterval) { LastTimeToOSVersionUpdated = 0; - DefaultDeviceInfo.DeviceOSVersion = NetworkHelper.TryGetOSVersionString() ?? ""; + DefaultDeviceInfo.DeviceOSVersion = NetworkHelper.TryGetOsVersionString() ?? ""; } ++DeviceInfoUpdatedTimes; @@ -238,7 +238,7 @@ private void UpdateDefaultDeviceInfo() private void MultiDevicesBroadCastSend() { - var location = $"{nameof(DevicesDiscoveryServer)}.{nameof(MultiDevicesBroadCastSend)}"; + const string location = $"{nameof(DevicesDiscoveryServer)}.{nameof(MultiDevicesBroadCastSend)}"; var multicast = new IPEndPoint( IPAddress.Parse(ConfigManager.Instance.AppConfig.Web.UdpBroadcastAddress), @@ -334,7 +334,7 @@ private void MultiDevicesBroadCastSend() private void MultiDevicesBroadCastReceive() { - var location = $"{nameof(DevicesDiscoveryServer)}.{nameof(MultiDevicesBroadCastReceive)}"; + const string location = $"{nameof(DevicesDiscoveryServer)}.{nameof(MultiDevicesBroadCastReceive)}"; var multicast = new IPEndPoint(IPAddress.Any, 0); diff --git a/KitX Dashboard/Network/DevicesNetwork/DevicesOrganizer.cs b/KitX Dashboard/Network/DevicesNetwork/DevicesOrganizer.cs index cd4f8c53..d732fe3f 100644 --- a/KitX Dashboard/Network/DevicesNetwork/DevicesOrganizer.cs +++ b/KitX Dashboard/Network/DevicesNetwork/DevicesOrganizer.cs @@ -44,7 +44,7 @@ public void Initialize() KeepCheckAndRemove(); - Watch4MainDevice(); + ObserveMainDevice(); } private void InitEvents() @@ -58,16 +58,21 @@ private void InitEvents() receivedDeviceInfo4Watch?.Add(deviceInfo); } - if (deviceInfo.IsMainDevice && deviceInfo.DevicesServerBuildTime < ConstantTable.ServerBuildTime) + if ( + deviceInfo.IsMainDevice + && deviceInfo.DevicesServerBuildTime < ConstantTable.ServerBuildTime + ) { ConstantTable.IsMainMachine = false; - Watch4MainDevice(); + ObserveMainDevice(); Log.Information( new StringBuilder() .AppendLine("Watched earlier built server.") - .AppendLine($"DevicesServerAddress: {deviceInfo.Device.IPv4}:{deviceInfo.DevicesServerPort} ") + .AppendLine( + $"DevicesServerAddress: {deviceInfo.Device.IPv4}:{deviceInfo.DevicesServerPort} " + ) .AppendLine($"DevicesServerBuildTime: {deviceInfo.DevicesServerBuildTime}") .ToString() ); @@ -87,7 +92,8 @@ private void UpdateSourceAndAddCards() var findThis = thisTurnAdded.Contains(hashCode); - if (findThis) continue; + if (findThis) + continue; foreach (var item in ViewInstances.DeviceCases) { @@ -140,12 +146,12 @@ private static void MoveSelfCardToFirst() private void KeepCheckAndRemove() { - var location = $"{nameof(DevicesOrganizer)}.{nameof(KeepCheckAndRemove)}"; + const string location = $"{nameof(DevicesOrganizer)}.{nameof(KeepCheckAndRemove)}"; var timer = new Timer() { Interval = AppConfig.Web.DevicesViewRefreshDelay, - AutoReset = true + AutoReset = true, }; timer.Elapsed += (_, _) => @@ -182,9 +188,9 @@ private void KeepCheckAndRemove() }; } - internal void Watch4MainDevice(CancellationToken token = default) + internal void ObserveMainDevice(CancellationToken token = default) { - var location = $"{nameof(DevicesOrganizer)}.{nameof(Watch4MainDevice)}"; + const string location = $"{nameof(DevicesOrganizer)}.{nameof(ObserveMainDevice)}"; new Thread(() => { @@ -200,7 +206,8 @@ internal void Watch4MainDevice(CancellationToken token = default) { try { - if (receivedDeviceInfo4Watch is null) continue; + if (receivedDeviceInfo4Watch is null) + continue; lock (_receivedDeviceInfo4WatchLock) { @@ -208,7 +215,10 @@ internal void Watch4MainDevice(CancellationToken token = default) { if (item.IsMainDevice) { - if (item.DevicesServerBuildTime.ToUniversalTime() < earliestBuiltServerTime) + if ( + item.DevicesServerBuildTime.ToUniversalTime() + < earliestBuiltServerTime + ) { serverPort = item.DevicesServerPort; serverAddress = item.Device.IPv4; @@ -241,7 +251,7 @@ internal void Watch4MainDevice(CancellationToken token = default) Log.Error(e, $"In {location}: {e.Message} Rewatch."); if (token.IsCancellationRequested == false) - Watch4MainDevice(); + ObserveMainDevice(); break; } @@ -251,7 +261,7 @@ internal void Watch4MainDevice(CancellationToken token = default) private void WatchingOver(bool foundMainDevice, string serverAddress, int serverPort) { - var location = $"{nameof(DevicesOrganizer)}.{nameof(WatchingOver)}"; + const string location = $"{nameof(DevicesOrganizer)}.{nameof(WatchingOver)}"; Log.Information( new StringBuilder() diff --git a/KitX Dashboard/Network/DevicesNetwork/DevicesServer.cs b/KitX Dashboard/Network/DevicesNetwork/DevicesServer.cs index 4fab2d0e..83222e89 100644 --- a/KitX Dashboard/Network/DevicesNetwork/DevicesServer.cs +++ b/KitX Dashboard/Network/DevicesNetwork/DevicesServer.cs @@ -37,13 +37,19 @@ public async Task RunAsync() new Thread(host.Run).Start(); - var addresses = host.Services.GetService()?.Features.Get()?.Addresses; + var addresses = host + .Services.GetService() + ?.Features.Get() + ?.Addresses; while (addresses is null || addresses.Count == 0) { await Task.Delay(500); - addresses = host.Services.GetService()?.Features.Get()?.Addresses; + addresses = host + .Services.GetService() + ?.Features.Get() + ?.Addresses; } if (addresses is not null && addresses.Count != 0) @@ -70,21 +76,23 @@ private IHostBuilder CreateHostBuilder(string[] args) => { webBuilder.UseStartup(); webBuilder.UseUrls($"http://0.0.0.0:{port}"); - }) - ; + }); internal bool IsDeviceTokenExist(string token) => SignedDeviceTokens.ContainsValue(token); internal DeviceLocator? SearchDeviceByToken(string token) { - if (IsDeviceTokenExist(token) == false) return null; + if (IsDeviceTokenExist(token) == false) + return null; return SignedDeviceTokens.First(x => x.Value.Equals(token)).Key; } - internal bool IsDeviceSignedIn(DeviceLocator locator) => SignedDeviceTokens.ContainsKey(locator); + internal bool IsDeviceSignedIn(DeviceLocator locator) => + SignedDeviceTokens.ContainsKey(locator); - internal void AddDeviceToken(DeviceLocator locator, string token) => SignedDeviceTokens.Add(locator, token); + internal void AddDeviceToken(DeviceLocator locator, string token) => + SignedDeviceTokens.Add(locator, token); internal string SignInDevice(DeviceLocator locator) { @@ -102,7 +110,10 @@ internal string SignInDevice(DeviceLocator locator) public class Startup { - private readonly List apiVersions = [.. typeof(DevicesServerApiVersions).GetEnumNames()]; + private readonly List apiVersions = + [ + .. typeof(DevicesServerApiVersions).GetEnumNames(), + ]; public void ConfigureServices(IServiceCollection services) { @@ -114,12 +125,15 @@ public void ConfigureServices(IServiceCollection services) { apiVersions.ForEach(version => { - options.SwaggerDoc(version, new OpenApiInfo - { - Title = "KitX Dashboard DevicesServer API", - Version = version, - Description = $"Version: {version}" - }); + options.SwaggerDoc( + version, + new OpenApiInfo + { + Title = "KitX Dashboard DevicesServer API", + Version = version, + Description = $"Version: {version}", + } + ); }); }); } diff --git a/KitX Dashboard/Network/NetworkHelper.cs b/KitX Dashboard/Network/NetworkHelper.cs index 19b9ee5a..0d73caac 100644 --- a/KitX Dashboard/Network/NetworkHelper.cs +++ b/KitX Dashboard/Network/NetworkHelper.cs @@ -16,8 +16,7 @@ namespace KitX.Dashboard.Network; internal static class NetworkHelper { - internal static bool CheckNetworkInterface - ( + internal static bool CheckNetworkInterface( NetworkInterface adapter, IPInterfaceProperties adapterProperties ) @@ -25,24 +24,25 @@ IPInterfaceProperties adapterProperties var userPointed = ConfigManager.Instance.AppConfig.Web.AcceptedNetworkInterfaces; if (userPointed is not null) - if (userPointed.Contains(adapter.Name)) - return true; - else return false; - - if (adapter.NetworkInterfaceType != NetworkInterfaceType.Ethernet && - adapter.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 - && - ( - adapterProperties.MulticastAddresses.Count == 0 || + return userPointed.Contains(adapter.Name); + + var noNetworkConnection = + adapter.NetworkInterfaceType != NetworkInterfaceType.Ethernet + && adapter.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 + && ( + adapterProperties.MulticastAddresses.Count == 0 + || // most of VPN adapters will be skipped - !adapter.SupportsMulticast || + !adapter.SupportsMulticast + || // multicast is meaningless for this type of connection - OperationalStatus.Up != adapter.OperationalStatus || + OperationalStatus.Up != adapter.OperationalStatus + || // this adapter is off or not connected !adapter.Supports(NetworkInterfaceComponent.IPv4) - ) - ) return false; - return true; + ); + + return !noNetworkConnection; } internal static bool IsInterNetworkAddressV4(IPAddress address) @@ -60,19 +60,22 @@ internal static bool IsInterNetworkAddressV4(IPAddress address) internal static string GetInterNetworkIPv4() { - var location = $"{nameof(NetworkHelper)}.{nameof(GetInterNetworkIPv4)}"; + const string location = $"{nameof(NetworkHelper)}.{nameof(GetInterNetworkIPv4)}"; try { var search = from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList - where ip.AddressFamily == AddressFamily.InterNetwork + where + ip.AddressFamily == AddressFamily.InterNetwork && IsInterNetworkAddressV4(ip) && !ip.ToString().Equals("127.0.0.1") && ip.ToString().StartsWith(ConfigManager.Instance.AppConfig.Web.IPFilter) select ip; - Log.Information($"IPv4 addresses: {search.Print(print: false)}"); + Log.Information( + $"IPv4 addresses: {search.Print(print: false, separateWithNewLine: false)}" + ); var result = search.FirstOrDefault()?.ToString(); @@ -88,17 +91,19 @@ from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList internal static string GetInterNetworkIPv6() { - var location = $"{nameof(NetworkHelper)}.{nameof(GetInterNetworkIPv6)}"; + const string location = $"{nameof(NetworkHelper)}.{nameof(GetInterNetworkIPv6)}"; try { var search = from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList - where ip.AddressFamily == AddressFamily.InterNetworkV6 - && !ip.ToString().Equals("::1") + where + ip.AddressFamily == AddressFamily.InterNetworkV6 && !ip.ToString().Equals("::1") select ip; - Log.Information($"IPv6 addresses: {search.Print(print: false)}"); + Log.Information( + $"IPv6 addresses: {search.Print(print: false, separateWithNewLine: false)}" + ); var result = search.FirstOrDefault()?.ToString(); @@ -114,21 +119,21 @@ from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList internal static string? TryGetDeviceMacAddress() { - var location = $"{nameof(NetworkHelper)}.{nameof(TryGetDeviceMacAddress)}"; + const string location = $"{nameof(NetworkHelper)}.{nameof(TryGetDeviceMacAddress)}"; try { var mac = from nic in NetworkInterface.GetAllNetworkInterfaces() - where CheckNetworkInterface(nic, nic.GetIPProperties()) && - nic.GetIPProperties().UnicastAddresses.Any( - x => x.Address.ToString().Equals(GetInterNetworkIPv4()) - ) + where + CheckNetworkInterface(nic, nic.GetIPProperties()) + && nic.GetIPProperties() + .UnicastAddresses.Any(x => + x.Address.ToString().Equals(GetInterNetworkIPv4()) + ) select nic.GetPhysicalAddress().ToString(); - var result = mac.FirstOrDefault()?.SeparateGroup( - 2, sb => sb.Append(':') - ); + var result = mac.FirstOrDefault()?.SeparateGroup(2, sb => sb.Append(':')); return result; } @@ -140,9 +145,9 @@ where CheckNetworkInterface(nic, nic.GetIPProperties()) && } } - internal static string? TryGetOSVersionString() + internal static string? TryGetOsVersionString() { - var location = $"{nameof(NetworkHelper)}.{nameof(TryGetOSVersionString)}"; + const string location = $"{nameof(NetworkHelper)}.{nameof(TryGetOsVersionString)}"; var result = Environment.OSVersion.VersionString; @@ -152,28 +157,27 @@ where CheckNetworkInterface(nic, nic.GetIPProperties()) && { case OperatingSystems.Linux: - var versionFilePath = "/etc/os-release"; - var versionSegament = "PRETTY_NAME"; + const string versionFilePath = "/etc/os-release"; + const string versionSegment = "PRETTY_NAME"; + var needFindInIssue = false; if (File.Exists(versionFilePath)) { var osRelease = File.ReadAllLines(versionFilePath) .Select(line => line.Split('=')) - .ToDictionary - ( - parts => parts[0], - parts => parts[1].Trim('"') - ); + .ToDictionary(parts => parts[0], parts => parts[1].Trim('"')); - if (osRelease.TryGetValue(versionSegament, out var version)) + if (osRelease.TryGetValue(versionSegment, out var version)) result = version; - else needFindInIssue = true; + else + needFindInIssue = true; } if (needFindInIssue) { - var issueFilePath = "/etc/issue"; + const string issueFilePath = "/etc/issue"; + if (File.Exists(issueFilePath)) { var issue = File.ReadAllText(issueFilePath); @@ -185,17 +189,13 @@ where CheckNetworkInterface(nic, nic.GetIPProperties()) && break; case OperatingSystems.MacOS: - var command = "sw_vers"; + const string command = "sw_vers"; var productName = command.ExecuteAsCommand("-productName"); var productVersion = command.ExecuteAsCommand("-productVersion"); var buildVersion = command.ExecuteAsCommand("-buildVersion"); - if (productName is null || productVersion is null || buildVersion is null) - break; - - result = $"{productName} {productVersion} {buildVersion}" - .Replace("\n", ""); + result = $"{productName} {productVersion} {buildVersion}".Replace("\n", ""); break; } @@ -208,22 +208,23 @@ where CheckNetworkInterface(nic, nic.GetIPProperties()) && return result; } - internal static DeviceInfo GetDeviceInfo() => new() - { - Device = new() + internal static DeviceInfo GetDeviceInfo() => + new() { - DeviceName = Environment.MachineName, - MacAddress = TryGetDeviceMacAddress() ?? "", - IPv4 = GetInterNetworkIPv4(), - IPv6 = GetInterNetworkIPv6(), - }, - IsMainDevice = ConstantTable.IsMainMachine, - SendTime = DateTime.UtcNow, - DeviceOSType = OperatingSystemUtils.GetOSType(), - DeviceOSVersion = TryGetOSVersionString() ?? "", - PluginsServerPort = ConstantTable.PluginsServerPort, - DevicesServerPort = ConstantTable.DevicesServerPort, - DevicesServerBuildTime = new(), - PluginsCount = ViewInstances.PluginInfos.Count, - }; + Device = new() + { + DeviceName = Environment.MachineName, + MacAddress = TryGetDeviceMacAddress() ?? "", + IPv4 = GetInterNetworkIPv4(), + IPv6 = GetInterNetworkIPv6(), + }, + IsMainDevice = ConstantTable.IsMainMachine, + SendTime = DateTime.UtcNow, + DeviceOSType = OperatingSystemUtils.GetOSType(), + DeviceOSVersion = TryGetOsVersionString() ?? "", + PluginsServerPort = ConstantTable.PluginsServerPort, + DevicesServerPort = ConstantTable.DevicesServerPort, + DevicesServerBuildTime = new(), + PluginsCount = ViewInstances.PluginInfos.Count, + }; } diff --git a/KitX Dashboard/Network/PluginsNetwork/PluginConnector.cs b/KitX Dashboard/Network/PluginsNetwork/PluginConnector.cs index 8baac1f2..d2cf9165 100644 --- a/KitX Dashboard/Network/PluginsNetwork/PluginConnector.cs +++ b/KitX Dashboard/Network/PluginsNetwork/PluginConnector.cs @@ -100,7 +100,7 @@ public PluginConnector Run() if (_initialized == false) Initialize(); - var location = $"{nameof(PluginConnector)}.{nameof(Run)}"; + const string location = $"{nameof(PluginConnector)}.{nameof(Run)}"; _connection!.OnOpen = () => { diff --git a/KitX Dashboard/Network/PluginsNetwork/PluginsServer.cs b/KitX Dashboard/Network/PluginsNetwork/PluginsServer.cs index d118a3a9..59e2f5ec 100644 --- a/KitX Dashboard/Network/PluginsNetwork/PluginsServer.cs +++ b/KitX Dashboard/Network/PluginsNetwork/PluginsServer.cs @@ -63,8 +63,8 @@ public PluginsServer Run() public PluginConnector? FindConnector(PluginInfo info) { - var query = PluginConnectors.Where( - x => x.PluginInfo is not null && x.PluginInfo.Equals(info) + var query = PluginConnectors.Where(x => + x.PluginInfo is not null && x.PluginInfo.Equals(info) ); if (query.Any()) @@ -73,19 +73,14 @@ public PluginsServer Run() return null; } - public PluginConnector? FindConnector(string connectionId) => PluginConnectors.FirstOrDefault( - x => x.ConnectionId?.Equals(connectionId) ?? false - ); + public PluginConnector? FindConnector(string connectionId) => + PluginConnectors.FirstOrDefault(x => x.ConnectionId?.Equals(connectionId) ?? false); public async Task Close() { await Task.Run(() => { - Task.WaitAll( - _connectors.Select( - c => c.CloseAsync() - ).ToArray() - ); + Task.WaitAll(_connectors.Select(c => c.CloseAsync()).ToArray()); _connectors.Clear(); diff --git a/KitX Dashboard/Program.cs b/KitX Dashboard/Program.cs index e8c9780d..58325c20 100644 --- a/KitX Dashboard/Program.cs +++ b/KitX Dashboard/Program.cs @@ -1,7 +1,6 @@ using System; using System.IO; using Avalonia; -using Avalonia.Controls; using Avalonia.ReactiveUI; using Common.BasicHelper.Utils.Extensions; @@ -51,22 +50,13 @@ public static void Main(string[] args) /// /// Avalonia AppBuilder /// Do not remove this, it also used by visual designer. - public static AppBuilder BuildAvaloniaApp() - => AppBuilder.Configure() + public static AppBuilder BuildAvaloniaApp() => + AppBuilder + .Configure() .UsePlatformDetect() .WithInterFont() .LogToTrace() .UseReactiveUI() - .With( - new MacOSPlatformOptions - { - ShowInDock = true, - } - ) - .With( - new X11PlatformOptions - { - EnableMultiTouch = true, - } - ); + .With(new MacOSPlatformOptions { ShowInDock = true }) + .With(new X11PlatformOptions { EnableMultiTouch = true }); } diff --git a/KitX Dashboard/Services/EventService.cs b/KitX Dashboard/Services/EventService.cs index df887951..e6b505e1 100644 --- a/KitX Dashboard/Services/EventService.cs +++ b/KitX Dashboard/Services/EventService.cs @@ -14,7 +14,10 @@ public static void Invoke(string eventName, object[]? objects = null) if (eventField is null || !typeof(Delegate).IsAssignableFrom(eventField.FieldType)) { - throw new ArgumentException($"No event found with the name '{eventName}'.", nameof(eventName)); + throw new ArgumentException( + $"No event found with the name '{eventName}'.", + nameof(eventName) + ); } var @delegate = eventField.GetValue(null) as Delegate; @@ -22,87 +25,78 @@ public static void Invoke(string eventName, object[]? objects = null) @delegate?.DynamicInvoke(objects); } - public delegate void LanguageChangedHandler(); +#pragma warning disable CS0067 // Event is never used - public static event LanguageChangedHandler LanguageChanged = new(() => { }); + public delegate void LanguageChangedHandler(); + public static event LanguageChangedHandler LanguageChanged = () => { }; public delegate void GreetingTextIntervalUpdatedHandler(); - public static event GreetingTextIntervalUpdatedHandler GreetingTextIntervalUpdated = new(() => { }); - + public static event GreetingTextIntervalUpdatedHandler GreetingTextIntervalUpdated = () => { }; public delegate void AppConfigChangedHandler(); - public static event AppConfigChangedHandler AppConfigChanged = new(() => { }); - + public static event AppConfigChangedHandler AppConfigChanged = () => { }; public delegate void PluginsConfigChangedHandler(); - public static event PluginsConfigChangedHandler PluginsConfigChanged = new(() => { }); - + public static event PluginsConfigChangedHandler PluginsConfigChanged = () => { }; public delegate void MicaOpacityChangedHandler(); - public static event MicaOpacityChangedHandler MicaOpacityChanged = new(() => { }); - + public static event MicaOpacityChangedHandler MicaOpacityChanged = () => { }; public delegate void DevelopSettingsChangedHandler(); - public static event DevelopSettingsChangedHandler DevelopSettingsChanged = new(() => { }); - + public static event DevelopSettingsChangedHandler DevelopSettingsChanged = () => { }; public delegate void LogConfigUpdatedHandler(); - public static event LogConfigUpdatedHandler LogConfigUpdated = new(() => { }); - + public static event LogConfigUpdatedHandler LogConfigUpdated = () => { }; public delegate void ThemeConfigChangedHandler(); - public static event ThemeConfigChangedHandler ThemeConfigChanged = new(() => { }); - + public static event ThemeConfigChangedHandler ThemeConfigChanged = () => { }; public delegate void UseStatisticsChangedHandler(); - public static event UseStatisticsChangedHandler UseStatisticsChanged = new(() => { }); - + public static event UseStatisticsChangedHandler UseStatisticsChanged = () => { }; public delegate void DevicesServerPortChangedHandler(int port); - public static event DevicesServerPortChangedHandler DevicesServerPortChanged = new(port => ConstantTable.DevicesServerPort = port); - + public static event DevicesServerPortChangedHandler DevicesServerPortChanged = port => + ConstantTable.DevicesServerPort = port; public delegate void PluginsServerPortChangedHandler(int port); - public static event PluginsServerPortChangedHandler PluginsServerPortChanged = new(port => ConstantTable.PluginsServerPort = port); - + public static event PluginsServerPortChangedHandler PluginsServerPortChanged = port => + ConstantTable.PluginsServerPort = port; public delegate void OnActivitiesUpdatedHandler(); - public static event OnActivitiesUpdatedHandler OnActivitiesUpdated = new(() => { }); - + public static event OnActivitiesUpdatedHandler OnActivitiesUpdated = () => { }; public delegate void OnReceiveCancelExchangingDeviceKeyHandler(); - public static event OnReceiveCancelExchangingDeviceKeyHandler OnReceiveCancelExchangingDeviceKey = new(() => ConstantTable.IsExchangingDeviceKey = false); - + public static event OnReceiveCancelExchangingDeviceKeyHandler OnReceiveCancelExchangingDeviceKey = + () => ConstantTable.IsExchangingDeviceKey = false; public delegate void OnExitingHandler(); - public static event OnExitingHandler OnExiting = new(() => { }); - + public static event OnExitingHandler OnExiting = () => { }; public delegate void OnReceivingDeviceInfoHandler(DeviceInfo dis); - public static event OnReceivingDeviceInfoHandler OnReceivingDeviceInfo = new(_ => { }); - + public static event OnReceivingDeviceInfoHandler OnReceivingDeviceInfo = _ => { }; public delegate void OnConfigHotReloadedHandler(); - public static event OnConfigHotReloadedHandler OnConfigHotReloaded = new(() => { }); - + public static event OnConfigHotReloadedHandler OnConfigHotReloaded = () => { }; public delegate void OnAcceptingDeviceKeyHandler(string code); - public static event OnAcceptingDeviceKeyHandler OnAcceptingDeviceKey = new(_ => { }); + public static event OnAcceptingDeviceKeyHandler OnAcceptingDeviceKey = _ => { }; + +#pragma warning restore CS0067 // Event is never used } diff --git a/KitX Dashboard/Utils/WindowsUtils.cs b/KitX Dashboard/Utils/WindowsUtils.cs index 2353cae2..d25fe270 100644 --- a/KitX Dashboard/Utils/WindowsUtils.cs +++ b/KitX Dashboard/Utils/WindowsUtils.cs @@ -1,23 +1,51 @@ -using Avalonia.Platform; +using System; +using System.Runtime.InteropServices; +using Avalonia.Platform; using Common.BasicHelper.Graphics.Screen; namespace KitX.Dashboard.Utils; internal static class WindowsUtils { - internal static Resolution SuggestResolution(this Resolution res, Screen? screen) + [DllImport("user32.dll")] + private static extern int GetDpiForSystem(); + + private const int DefaultDpi = 96; + + internal static Resolution SuggestResolution( + this Resolution res, + Screen? screen, + out Resolution? notScaled + ) { - if (res.Width == 1280 && res.Height == 720 && screen is not null) - { - var suggest = Resolution.Suggest( + notScaled = null; + + var condition = res.Width - 1280.0 < 0.1 && res.Height - 720.0 < 0.1 && screen is not null; + + if (!condition) + return res.Integerization(); + + var suggest = Resolution + .Suggest( Resolution.Parse("2560x1440"), Resolution.Parse("1280x720"), - Resolution.Parse($"{screen.WorkingArea.Width}x{screen.WorkingArea.Height}") - ).Integerization(); + Resolution.Parse($"{screen!.Bounds.Width}x{screen.Bounds.Height}") + ) + .Integerization(); + + if (OperatingSystem.IsWindows()) + { + notScaled = suggest.Clone(); + + int dpi = GetDpiForSystem(); + float scale = (float)dpi / DefaultDpi; + + suggest.Width /= scale; + suggest.Height /= scale; - return suggest; + suggest = suggest.Integerization(); } - return res; + return suggest; } } diff --git a/KitX Dashboard/ViewModels/AnouncementsWindowViewModel.cs b/KitX Dashboard/ViewModels/AnnouncementsWindowViewModel.cs similarity index 53% rename from KitX Dashboard/ViewModels/AnouncementsWindowViewModel.cs rename to KitX Dashboard/ViewModels/AnnouncementsWindowViewModel.cs index 4c64bd70..b3fda21a 100644 --- a/KitX Dashboard/ViewModels/AnouncementsWindowViewModel.cs +++ b/KitX Dashboard/ViewModels/AnnouncementsWindowViewModel.cs @@ -8,16 +8,16 @@ namespace KitX.Dashboard.ViewModels; -internal class AnouncementsWindowViewModel : ViewModelBase +internal class AnnouncementsWindowViewModel : ViewModelBase { - public AnouncementsWindowViewModel() + public AnnouncementsWindowViewModel() { InitCommands(); InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { ConfirmReceivedCommand = ReactiveCommand.Create(() => { @@ -25,34 +25,36 @@ public override void InitCommands() var accepted = config.Accepted; - if (SelectedMenuItem is null || accepted is null) return; + if (SelectedMenuItem is null) + return; var key = SelectedMenuItem.Content!.ToString(); - if (key is null) return; + if (key is null) + return; if (!accepted.Contains(key)) accepted.Add(key); config.Save(config.ConfigFileLocation!); - var finded = false; + var found = false; var navView = Window?.AnouncementsNavigationView; - if (navView is not null) + if (navView is null) + return; + + foreach (NavigationViewItem item in navView.MenuItems.Cast()) { - foreach (NavigationViewItem item in navView.MenuItems.Cast()) + if (found) { - if (finded) - { - SelectedMenuItem = item; - break; - } - - if (item == SelectedMenuItem) - finded = true; + SelectedMenuItem = item; + break; } + + if (item == SelectedMenuItem) + found = true; } }); @@ -64,29 +66,27 @@ public override void InitCommands() var navView = Window?.AnouncementsNavigationView; - if (navView is not null) + if (navView is null) + return; + + foreach (NavigationViewItem item in navView.MenuItems.Cast()) { - foreach (NavigationViewItem item in navView.MenuItems.Cast()) - { - var key = item.Content?.ToString(); + var key = item.Content?.ToString(); - if (key is null) continue; + if (key is null) + continue; - if (!accepted.Contains(key)) - accepted.Add(key); - } + if (!accepted.Contains(key)) + accepted.Add(key); + } - config.Save(config.ConfigFileLocation!); + config.Save(config.ConfigFileLocation!); - Window?.Close(); - } + Window?.Close(); }); } - public override void InitEvents() - { - - } + public sealed override void InitEvents() { } internal static double Window_Width { @@ -100,43 +100,45 @@ internal static double Window_Height set => AppConfig.Windows.AnnouncementWindow.Size.Height = value; } - private NavigationViewItem? selectedMenuItem; + private NavigationViewItem? _selectedMenuItem; internal NavigationViewItem? SelectedMenuItem { - get => selectedMenuItem; + get => _selectedMenuItem; set { - selectedMenuItem = value; + _selectedMenuItem = value; - if (SelectedMenuItem is null) return; + if (_selectedMenuItem is null) + return; - var key = SelectedMenuItem.Content?.ToString(); + var key = SelectedMenuItem!.Content?.ToString(); - if (key is null) return; + if (key is null) + return; Markdown = Sources[key]; - this.RaiseAndSetIfChanged(ref selectedMenuItem, value); + this.RaiseAndSetIfChanged(ref _selectedMenuItem, value); } } - private string markdown = string.Empty; + private string _markdown = string.Empty; internal string Markdown { - get => markdown; - set => this.RaiseAndSetIfChanged(ref markdown, value); + get => _markdown; + set => this.RaiseAndSetIfChanged(ref _markdown, value); } - private Dictionary sources = []; + private Dictionary _sources = []; internal Dictionary Sources { - get => sources; + get => _sources; set { - sources = value; + _sources = value; var navView = Window?.AnouncementsNavigationView; @@ -144,18 +146,15 @@ internal Dictionary Sources foreach (var item in Sources.Reverse()) { - navView?.MenuItems?.Add(new NavigationViewItem() - { - Content = item.Key - }); + navView?.MenuItems?.Add(new NavigationViewItem() { Content = item.Key }); } if (navView is not null) - SelectedMenuItem = navView.MenuItems.First() as NavigationViewItem; + SelectedMenuItem = navView.MenuItems?.First() as NavigationViewItem; } } - internal AnouncementsWindow? Window { get; set; } + internal AnnouncementsWindow? Window { get; set; } internal ReactiveCommand? ConfirmReceivedCommand { get; set; } diff --git a/KitX Dashboard/ViewModels/AppViewModel.cs b/KitX Dashboard/ViewModels/AppViewModel.cs index 559ddd69..198f1726 100644 --- a/KitX Dashboard/ViewModels/AppViewModel.cs +++ b/KitX Dashboard/ViewModels/AppViewModel.cs @@ -21,7 +21,7 @@ public AppViewModel() UpdateTrayIconText(); } - public override void InitCommands() + public sealed override void InitCommands() { TrayIconClickedCommand = ReactiveCommand.Create(() => { @@ -41,7 +41,7 @@ public override void InitCommands() ViewLatestAnnouncementsCommand = ReactiveCommand.Create(async () => { - await AnouncementManager.CheckNewAnnouncements(); + await AnnouncementManager.CheckNewAnnouncements(); }); OpenDebugToolCommand = ReactiveCommand.Create(() => @@ -77,7 +77,7 @@ public override void InitCommands() ExitCommand = ReactiveCommand.Create(Exit); } - public override void InitEvents() + public sealed override void InitEvents() { ViewInstances.DeviceCases.CollectionChanged += (_, _) => UpdateTrayIconText(); @@ -104,8 +104,7 @@ private void UpdateTrayIconText() .Append(ViewInstances.PluginInfos.Count + " ") .AppendLine(Translate("Text_Lib_Tip_Connected")) .AppendLine() - .Append("Hello, World!") - ; + .Append("Hello, World!"); TrayIconText = sb.ToString(); } @@ -130,11 +129,7 @@ public static void Exit() internal string TrayIconText { get => trayIconText; - set => this.RaiseAndSetIfChanged( - ref trayIconText, - value, - nameof(TrayIconText) - ); + set => this.RaiseAndSetIfChanged(ref trayIconText, value, nameof(TrayIconText)); } internal ReactiveCommand? TrayIconClickedCommand { get; set; } diff --git a/KitX Dashboard/ViewModels/ExchangeDeviceKeyWindowViewModel.cs b/KitX Dashboard/ViewModels/ExchangeDeviceKeyWindowViewModel.cs index fceb29fd..a74b66f3 100644 --- a/KitX Dashboard/ViewModels/ExchangeDeviceKeyWindowViewModel.cs +++ b/KitX Dashboard/ViewModels/ExchangeDeviceKeyWindowViewModel.cs @@ -18,7 +18,7 @@ public ExchangeDeviceKeyWindowViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { CancelCommand = ReactiveCommand.Create(() => { @@ -26,10 +26,7 @@ public override void InitCommands() }); } - public override void InitEvents() - { - - } + public sealed override void InitEvents() { } private int updatingIndex = 0; @@ -59,7 +56,8 @@ public string VerificationCodeString get => string.Join(null, VerificationCode); set { - if (value.Length != verificationCode.Length) throw new InvalidCastException(); + if (value.Length != verificationCode.Length) + throw new InvalidCastException(); for (var i = 0; i < verificationCode.Length; ++i) verificationCode[i] = value[i].ToString(); @@ -99,28 +97,33 @@ private void Update() internal bool NextCode(char code) { - if (updatingIndex == VerificationCode.Length) return false; + if (updatingIndex == VerificationCode.Length) + return false; verificationCode[updatingIndex++] = code.ToString(); Update(); - if (updatingIndex == VerificationCode.Length) return false; + if (updatingIndex == VerificationCode.Length) + return false; return true; } internal bool Backspace(bool clear = true) { - if (updatingIndex == 0) return false; + if (updatingIndex == 0) + return false; if (clear) { if (verificationCode[updatingIndex].Equals("0") == false) verificationCode[updatingIndex] = "0"; - else verificationCode[--updatingIndex] = "0"; + else + verificationCode[--updatingIndex] = "0"; } - else --updatingIndex; + else + --updatingIndex; Update(); diff --git a/KitX Dashboard/ViewModels/MainWindowViewModel.cs b/KitX Dashboard/ViewModels/MainWindowViewModel.cs index d4c0964a..2668f740 100644 --- a/KitX Dashboard/ViewModels/MainWindowViewModel.cs +++ b/KitX Dashboard/ViewModels/MainWindowViewModel.cs @@ -14,7 +14,7 @@ public MainWindowViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { RefreshGreetingCommand = ReactiveCommand.Create(mainWindow => { @@ -24,22 +24,7 @@ public override void InitCommands() }); } - public override void InitEvents() - { - - } - - internal static double Window_Width - { - get => AppConfig.Windows.MainWindow.Size.Width!.Value; - set => AppConfig.Windows.MainWindow.Size.Width = value; - } - - internal static double Window_Height - { - get => AppConfig.Windows.MainWindow.Size.Height!.Value; - set => AppConfig.Windows.MainWindow.Size.Height = value; - } + public sealed override void InitEvents() { } internal ReactiveCommand? RefreshGreetingCommand { get; set; } } diff --git a/KitX Dashboard/ViewModels/Maintain/DebugOptionsWindowViewModel.cs b/KitX Dashboard/ViewModels/Maintain/DebugOptionsWindowViewModel.cs new file mode 100644 index 00000000..9dcdcf07 --- /dev/null +++ b/KitX Dashboard/ViewModels/Maintain/DebugOptionsWindowViewModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace KitX.Dashboard.ViewModels.Maintain; + +internal class DebugOptionsWindowViewModel : ViewModelBase +{ + public override void InitCommands() { } + + public override void InitEvents() { } +} diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Home_ActivityLogViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Home_ActivityLogViewModel.cs index b1aae7c1..f0804216 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Home_ActivityLogViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Home_ActivityLogViewModel.cs @@ -34,12 +34,9 @@ public Home_ActivityLogViewModel() Activities.Add(item); } - public override void InitCommands() - { - - } + public sealed override void InitCommands() { } - public override void InitEvents() + public sealed override void InitEvents() { Activities.CollectionChanged += (_, _) => { diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Home_CountViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Home_CountViewModel.cs index c5e8285b..33cf392f 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Home_CountViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Home_CountViewModel.cs @@ -21,7 +21,7 @@ public Home_CountViewModel() public override void InitCommands() => throw new System.NotImplementedException(); - public override void InitEvents() + public sealed override void InitEvents() { EventService.UseStatisticsChanged += RecoveryUseCount; } @@ -30,13 +30,7 @@ internal void RecoveryUseCount() { var use = StatisticsManager.UseStatistics; - Use_XAxes = - [ - new Axis - { - Labels = use?.Keys.ToList() - } - ]; + Use_XAxes = [new Axis { Labels = use?.Keys.ToList() }]; Use_Series = [ @@ -44,8 +38,9 @@ internal void RecoveryUseCount() { Values = use?.Values.ToArray(), Fill = null, - XToolTipLabelFormatter = x => $"{use?.Keys.ToArray()[(int)x.Coordinate.SecondaryValue]}: {x.Coordinate.PrimaryValue} h" - } + XToolTipLabelFormatter = x => + $"{use?.Keys.ToArray()[(int)x.Coordinate.SecondaryValue]}: {x.Coordinate.PrimaryValue} h", + }, ]; } @@ -72,11 +67,7 @@ internal bool UseAreaExpanded private ISeries[] useSeries = [ - new LineSeries - { - Values = new double[] { 2, 1, 3, 5, 3, 4, 6 }, - Fill = null - } + new LineSeries { Values = new double[] { 2, 1, 3, 5, 3, 4, 6 }, Fill = null }, ]; public ISeries[] Use_Series @@ -85,13 +76,7 @@ public ISeries[] Use_Series set => this.RaiseAndSetIfChanged(ref useSeries, value); } - private List use_xAxes = - [ - new Axis - { - Labeler = Labelers.Default - } - ]; + private List use_xAxes = [new Axis { Labeler = Labelers.Default }]; public List Use_XAxes { @@ -99,13 +84,7 @@ public List Use_XAxes set => this.RaiseAndSetIfChanged(ref use_xAxes, value); } - private List use_yAxes = - [ - new Axis - { - Labeler = (value) => $"{value} h" - } - ]; + private List use_yAxes = [new Axis { Labeler = (value) => $"{value} h" }]; public List Use_YAxes { diff --git a/KitX Dashboard/ViewModels/Pages/Controls/PluginBarViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/PluginBarViewModel.cs index 8d804d41..ea3e42e5 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/PluginBarViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/PluginBarViewModel.cs @@ -25,17 +25,17 @@ public PluginBarViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { ViewDetailsCommand = ReactiveCommand.Create(() => { if (Plugin is not null && ViewInstances.MainWindow is not null) new PluginDetailWindow() { - WindowStartupLocation = WindowStartupLocation.CenterOwner + WindowStartupLocation = WindowStartupLocation.CenterOwner, } - .SetPluginInfo(Plugin.PluginInfo) - .Show(ViewInstances.MainWindow); + .SetPluginInfo(Plugin.PluginInfo) + .Show(ViewInstances.MainWindow); }); RemoveCommand = ReactiveCommand.Create(() => @@ -59,9 +59,10 @@ public override void InitCommands() LaunchCommand = ReactiveCommand.Create(() => { - var location = $"{nameof(PluginBarViewModel)}.{nameof(LaunchCommand)}"; + const string location = $"{nameof(PluginBarViewModel)}.{nameof(LaunchCommand)}"; - if (Plugin?.LoaderInfo is null) return; + if (Plugin?.LoaderInfo is null) + return; new Thread(() => { @@ -73,19 +74,22 @@ public override void InitCommands() var pluginPath = $"{Plugin?.InstallPath}/{pd?.RootStartupFileName}"; var pluginFile = pluginPath.GetFullPath(); - var connectStr = "ws://" + - $"{DevicesDiscoveryServer.Instance.DefaultDeviceInfo.Device.IPv4}" + - $":" + - $"{ConstantTable.PluginsServerPort}/"; + var connectStr = + "ws://" + + $"{DevicesDiscoveryServer.Instance.DefaultDeviceInfo.Device.IPv4}" + + $":" + + $"{ConstantTable.PluginsServerPort}/"; - if (Plugin is null) return; + if (Plugin is null) + return; if (Plugin.LoaderInfo.SelfLoad) Process.Start(pluginFile, $"--connect {connectStr}"); else { - var loaderFile = $"{AppConfig.Loaders.InstallPath}/" + - $"{loaderName}/{loaderVersion}/{loaderName}"; + var loaderFile = + $"{AppConfig.Loaders.InstallPath}/" + + $"{loaderName}/{loaderVersion}/{loaderName}"; if (OperatingSystem.IsWindows()) loaderFile += ".exe"; @@ -112,7 +116,7 @@ public override void InitCommands() }); } - public override void InitEvents() + public sealed override void InitEvents() { EventService.LanguageChanged += () => this.RaisePropertyChanged(nameof(DisplayName)); } @@ -125,11 +129,15 @@ internal string? DisplayName { get { - if (Plugin is null) return null; + if (Plugin is null) + return null; return Plugin.PluginInfo.DisplayName.TryGetValue( - AppConfig.App.AppLanguage, out var lang - ) ? lang : Plugin.PluginInfo.DisplayName.Values.GetEnumerator().Current; + AppConfig.App.AppLanguage, + out var lang + ) + ? lang + : Plugin.PluginInfo.DisplayName.Values.GetEnumerator().Current; } } @@ -143,11 +151,12 @@ internal Bitmap IconDisplay { get { - var location = $"{nameof(PluginBarViewModel)}.{nameof(IconDisplay)}.getter"; + const string location = $"{nameof(PluginBarViewModel)}.{nameof(IconDisplay)}.getter"; try { - if (Plugin is null) return App.DefaultIcon; + if (Plugin is null) + return App.DefaultIcon; var src = Convert.FromBase64String(Plugin.PluginInfo.IconInBase64); @@ -159,9 +168,9 @@ internal Bitmap IconDisplay { Log.Warning( e, - $"In {location}: " + - $"Failed to transform icon from base64 to byte[] " + - $"or create bitmap from `MemoryStream`. {e.Message}" + $"In {location}: " + + $"Failed to transform icon from base64 to byte[] " + + $"or create bitmap from `MemoryStream`. {e.Message}" ); return App.DefaultIcon; diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Settings_AboutViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Settings_AboutViewModel.cs index 70264ad1..56ac207c 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Settings_AboutViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Settings_AboutViewModel.cs @@ -17,26 +17,22 @@ internal Settings_AboutViewModel() InitCommands(); } - public override void InitCommands() + public sealed override void InitCommands() { - AppNameButtonClickedCommand = ReactiveCommand.Create( - () => - { - if (AppLogo is not null) - { - if (AppLogo.IsAnimating) - AppLogo.StopAnimations(); - else - AppLogo.InitAnimations(); - } - } - ); + AppNameButtonClickedCommand = ReactiveCommand.Create(() => + { + if (AppLogo is null) + return; + + if (AppLogo.IsAnimating) + AppLogo.StopAnimations(); + else + AppLogo.InitAnimations(); + }); LoadThirdPartyLicenseCommand = ReactiveCommand.Create(async () => { - var license = await FileHelper.ReadAllAsync( - ConstantTable.ThirdPartLicenseFilePath - ); + var license = await FileHelper.ReadAllAsync(ConstantTable.ThirdPartLicenseFilePath); ThirdPartyLicenseString = license; }); diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Settings_GeneralViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Settings_GeneralViewModel.cs index 1054e9bb..cf13e844 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Settings_GeneralViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Settings_GeneralViewModel.cs @@ -18,21 +18,11 @@ internal Settings_GeneralViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { ShowAnnouncementsInstantlyCommand = ReactiveCommand.Create(() => { - Task.Run(async () => - { - try - { - await AnouncementManager.CheckNewAnnouncements(); - } - catch (Exception ex) - { - Log.Error(ex, $"辣鸡公告系统又双叒叕崩了 ! {ex.Message}"); - } - }); + Task.Run(async () => await AnnouncementManager.CheckNewAnnouncements()); }); OpenDebugToolCommand = ReactiveCommand.Create(() => @@ -41,11 +31,10 @@ public override void InitCommands() }); } - public override void InitEvents() + public sealed override void InitEvents() { - EventService.DevelopSettingsChanged += () => this.RaisePropertyChanged( - nameof(DeveloperSettingEnabled) - ); + EventService.DevelopSettingsChanged += () => + this.RaisePropertyChanged(nameof(DeveloperSettingEnabled)); } internal static string LocalPluginsFileDirectory diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Settings_PerformenceViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Settings_PerformenceViewModel.cs index 0cb0e50c..b55ae0a9 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Settings_PerformenceViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Settings_PerformenceViewModel.cs @@ -25,17 +25,16 @@ internal Settings_PerformenceViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { EmptyLogsCommand = ReactiveCommand.Create(() => { - var location = $"{nameof(Settings_PerformenceViewModel)}.{nameof(EmptyLogsCommand)}"; + const string location = + $"{nameof(Settings_PerformenceViewModel)}.{nameof(EmptyLogsCommand)}"; Task.Run(() => { - var dir = new DirectoryInfo( - AppConfig.Log.LogFilePath.GetFullPath() - ); + var dir = new DirectoryInfo(AppConfig.Log.LogFilePath.GetFullPath()); foreach (var file in dir.GetFiles()) { @@ -58,7 +57,7 @@ public override void InitCommands() ); } - public override void InitEvents() + public sealed override void InitEvents() { EventService.LogConfigUpdated += () => { @@ -72,11 +71,7 @@ public override void InitEvents() rollingInterval: RollingInterval.Hour, fileSizeLimitBytes: AppConfig.Log.LogFileSingleMaxSize, buffered: true, - flushToDiskInterval: new( - 0, - 0, - AppConfig.Log.LogFileFlushInterval - ), + flushToDiskInterval: new(0, 0, AppConfig.Log.LogFileFlushInterval), restrictedToMinimumLevel: AppConfig.Log.LogLevel, rollOnFileSizeLimit: true, retainedFileCountLimit: AppConfig.Log.LogFileMaxCount @@ -92,9 +87,11 @@ public override void InitEvents() this.RaisePropertyChanged(nameof(SupportedLogLevels)); }; - EventService.DevicesServerPortChanged += _ => this.RaisePropertyChanged(nameof(DevicesServerPort)); + EventService.DevicesServerPortChanged += _ => + this.RaisePropertyChanged(nameof(DevicesServerPort)); - EventService.PluginsServerPortChanged += _ => this.RaisePropertyChanged(nameof(PluginsServerPort)); + EventService.PluginsServerPortChanged += _ => + this.RaisePropertyChanged(nameof(PluginsServerPort)); Instances.SignalTasksManager?.SignalRun( nameof(SignalsNames.FinishedFindingNetworkInterfacesSignal), @@ -108,9 +105,11 @@ public override void InitEvents() var anin = AcceptedNetworkInterfacesNames; - if (anin is null || anin.Equals("Auto")) return; + if (anin is null || anin.Equals("Auto")) + return; - if (AvailableNetworkInterfaces is null) return; + if (AvailableNetworkInterfaces is null) + return; foreach (var item in anin.Split(';')) if (AvailableNetworkInterfaces.Contains(item)) @@ -219,7 +218,8 @@ internal static string AcceptedNetworkInterfacesNames } } - internal static ObservableCollection? AvailableNetworkInterfaces => Instances.WebManager?.NetworkInterfaceRegistered; + internal static ObservableCollection? AvailableNetworkInterfaces => + Instances.WebManager?.NetworkInterfaceRegistered; internal static ObservableCollection? SelectedNetworkInterfaces { get; } = []; @@ -291,8 +291,8 @@ internal static bool UpdateRelatedAreaExpanded } } - internal static int LogFileSizeUsage - => (int)(AppConfig.Log.LogFilePath.GetTotalSize() / 1000 / 1024); + internal static int LogFileSizeUsage => + (int)(AppConfig.Log.LogFilePath.GetTotalSize() / 1000 / 1024); internal static int LogFileSizeLimit { @@ -344,50 +344,51 @@ internal static int CheckerPerThreadFilesCountLimit } } - private static string GetLogLevelDisplayText(string key) => Translate(key, prefix: "Text_Log_") ?? string.Empty; + private static string GetLogLevelDisplayText(string key) => + Translate(key, prefix: "Text_Log_") ?? string.Empty; internal static List SupportedLogLevels { get; } = - [ - new() - { - LogEventLevel = LogEventLevel.Verbose, - LogLevelName = "Verbose", - LogLevelDisplayName = GetLogLevelDisplayText("Verbose") - }, - new() - { - LogEventLevel = LogEventLevel.Debug, - LogLevelName = "Debug", - LogLevelDisplayName = GetLogLevelDisplayText("Debug") - }, - new() - { - LogEventLevel = LogEventLevel.Information, - LogLevelName = "Information", - LogLevelDisplayName = GetLogLevelDisplayText("Information") - }, - new() - { - LogEventLevel = LogEventLevel.Warning, - LogLevelName = "Warning", - LogLevelDisplayName = GetLogLevelDisplayText("Warning") - }, - new() - { - LogEventLevel = LogEventLevel.Error, - LogLevelName = "Error", - LogLevelDisplayName = GetLogLevelDisplayText("Error") - }, - new() - { - LogEventLevel = LogEventLevel.Fatal, - LogLevelName = "Fatal", - LogLevelDisplayName = GetLogLevelDisplayText("Fatal") - }, - ]; - - private SupportedLogLevel? _currentLogLevel = SupportedLogLevels.Find( - x => x.LogEventLevel == AppConfig.Log.LogLevel + [ + new() + { + LogEventLevel = LogEventLevel.Verbose, + LogLevelName = "Verbose", + LogLevelDisplayName = GetLogLevelDisplayText("Verbose"), + }, + new() + { + LogEventLevel = LogEventLevel.Debug, + LogLevelName = "Debug", + LogLevelDisplayName = GetLogLevelDisplayText("Debug"), + }, + new() + { + LogEventLevel = LogEventLevel.Information, + LogLevelName = "Information", + LogLevelDisplayName = GetLogLevelDisplayText("Information"), + }, + new() + { + LogEventLevel = LogEventLevel.Warning, + LogLevelName = "Warning", + LogLevelDisplayName = GetLogLevelDisplayText("Warning"), + }, + new() + { + LogEventLevel = LogEventLevel.Error, + LogLevelName = "Error", + LogLevelDisplayName = GetLogLevelDisplayText("Error"), + }, + new() + { + LogEventLevel = LogEventLevel.Fatal, + LogLevelName = "Fatal", + LogLevelDisplayName = GetLogLevelDisplayText("Fatal"), + }, + ]; + + private SupportedLogLevel? _currentLogLevel = SupportedLogLevels.Find(x => + x.LogEventLevel == AppConfig.Log.LogLevel ); internal SupportedLogLevel? CurrentLogLevel diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Settings_PersonaliseViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Settings_PersonaliseViewModel.cs index ba080aae..6e38c5a6 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Settings_PersonaliseViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Settings_PersonaliseViewModel.cs @@ -30,7 +30,7 @@ internal Settings_PersonaliseViewModel() InitData(); } - public override void InitCommands() + public sealed override void InitCommands() { ColorConfirmedCommand = ReactiveCommand.Create(async () => { @@ -38,7 +38,8 @@ public override void InitCommands() await Dispatcher.UIThread.InvokeAsync(() => { - if (Application.Current is null) return; + if (Application.Current is null) + return; Application.Current.Resources["ThemePrimaryAccent"] = new SolidColorBrush( new Color(c.A, c.R, c.G, c.B) @@ -46,15 +47,11 @@ await Dispatcher.UIThread.InvokeAsync(() => for (char i = 'A'; i <= 'E'; ++i) Application.Current.Resources[$"ThemePrimaryAccentTransparent{i}{i}"] = - new SolidColorBrush( - new Color((byte)(170 + (i - 'A') * 17), c.R, c.G, c.B) - ); + new SolidColorBrush(new Color((byte)(170 + (i - 'A') * 17), c.R, c.G, c.B)); for (int i = 1; i <= 9; ++i) Application.Current.Resources[$"ThemePrimaryAccentTransparent{i}{i}"] = - new SolidColorBrush( - new Color((byte)(i * 10 + i), c.R, c.G, c.B) - ); + new SolidColorBrush(new Color((byte)(i * 10 + i), c.R, c.G, c.B)); }); AppConfig.App.ThemeColor = themeColor.ToHexString(); @@ -63,16 +60,14 @@ await Dispatcher.UIThread.InvokeAsync(() => }); } - public override void InitEvents() + public sealed override void InitEvents() { EventService.LanguageChanged += () => { foreach (var item in SupportedThemes) item.ThemeDisplayName = GetThemeDisplayText(item.ThemeName); - _currentAppTheme = SupportedThemes.Find( - x => x.ThemeName.Equals(AppConfig.App.Theme) - ); + _currentAppTheme = SupportedThemes.Find(x => x.ThemeName.Equals(AppConfig.App.Theme)); this.RaisePropertyChanged(nameof(CurrentAppTheme)); @@ -85,14 +80,12 @@ private void InitData() SupportedLanguages.Clear(); foreach (var item in AppConfig.App.SurpportLanguages) - SupportedLanguages.Add(new SupportedLanguage() - { - LanguageCode = item.Key, - LanguageName = item.Value - }); + SupportedLanguages.Add( + new SupportedLanguage() { LanguageCode = item.Key, LanguageName = item.Value } + ); - LanguageSelected = SupportedLanguages.FindIndex( - x => x.LanguageCode.Equals(AppConfig.App.AppLanguage) + LanguageSelected = SupportedLanguages.FindIndex(x => + x.LanguageCode.Equals(AppConfig.App.AppLanguage) ); } @@ -104,36 +97,34 @@ internal Color2 ThemeColor { var obj = Application.Current?.Resources["ThemePrimaryAccent"]; - if (obj is not SolidColorBrush brush) return new(); + if (obj is not SolidColorBrush brush) + return new(); return new(brush.Color); } set => themeColor = value; } - private static string GetThemeDisplayText(string key) => Translate(key, prefix: "Text_Settings_Personalise_Theme_") ?? string.Empty; + private static string GetThemeDisplayText(string key) => + Translate(key, prefix: "Text_Settings_Personalise_Theme_") ?? string.Empty; internal static List SupportedThemes => - [ - new() - { - ThemeName = FluentAvaloniaTheme.LightModeString, - ThemeDisplayName = GetThemeDisplayText(FluentAvaloniaTheme.LightModeString), - }, - new() - { - ThemeName = FluentAvaloniaTheme.DarkModeString, - ThemeDisplayName = GetThemeDisplayText(FluentAvaloniaTheme.DarkModeString), - }, - new() - { - ThemeName = "Follow", - ThemeDisplayName = GetThemeDisplayText("Follow"), - } - ]; - - private SupportedTheme? _currentAppTheme = SupportedThemes.Find( - x => x.ThemeName.Equals(AppConfig.App.Theme) + [ + new() + { + ThemeName = FluentAvaloniaTheme.LightModeString, + ThemeDisplayName = GetThemeDisplayText(FluentAvaloniaTheme.LightModeString), + }, + new() + { + ThemeName = FluentAvaloniaTheme.DarkModeString, + ThemeDisplayName = GetThemeDisplayText(FluentAvaloniaTheme.DarkModeString), + }, + new() { ThemeName = "Follow", ThemeDisplayName = GetThemeDisplayText("Follow") }, + ]; + + private SupportedTheme? _currentAppTheme = SupportedThemes.Find(x => + x.ThemeName.Equals(AppConfig.App.Theme) ); internal SupportedTheme? CurrentAppTheme @@ -143,11 +134,13 @@ internal SupportedTheme? CurrentAppTheme { _currentAppTheme = value; - if (value is null) return; + if (value is null) + return; AppConfig.App.Theme = value.ThemeName; - if (Application.Current is null) return; + if (Application.Current is null) + return; Application.Current.RequestedThemeVariant = value.ThemeName switch { @@ -166,11 +159,12 @@ internal SupportedTheme? CurrentAppTheme internal static void LoadLanguage() { - var location = $"{nameof(Settings_PersonaliseViewModel)}.{nameof(LoadLanguage)}"; + const string location = $"{nameof(Settings_PersonaliseViewModel)}.{nameof(LoadLanguage)}"; var lang = AppConfig.App.AppLanguage; - if (Application.Current is null) return; + if (Application.Current is null) + return; try { @@ -179,16 +173,19 @@ internal static void LoadLanguage() Application.Current.Resources.MergedDictionaries.Add( AvaloniaRuntimeXamlLoader.Load( File.ReadAllText($"{ConstantTable.LanguageFilePath}/{lang}.axaml") - ) as ResourceDictionary ?? [] + ) as ResourceDictionary + ?? [] ); } catch (Exception ex) { - MessageBoxManager.GetMessageBoxStandard( - "Error", - "No this language file.", - icon: MsBox.Avalonia.Enums.Icon.Error - ).ShowWindowAsync(); + MessageBoxManager + .GetMessageBoxStandard( + "Error", + "No this language file.", + icon: MsBox.Avalonia.Enums.Icon.Error + ) + .ShowWindowAsync(); Log.Warning(ex, $"In {location}: Language File {lang}.axaml not found."); } @@ -207,7 +204,8 @@ internal int LanguageSelected { AppConfig.App.AppLanguage = SupportedLanguages[value].LanguageCode; - if (languageSelected != -1) LoadLanguage(); + if (languageSelected != -1) + LoadLanguage(); languageSelected = value; diff --git a/KitX Dashboard/ViewModels/Pages/Controls/Settings_UpdateViewModel.cs b/KitX Dashboard/ViewModels/Pages/Controls/Settings_UpdateViewModel.cs index a2597d8c..d0fa119d 100644 --- a/KitX Dashboard/ViewModels/Pages/Controls/Settings_UpdateViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/Controls/Settings_UpdateViewModel.cs @@ -35,14 +35,14 @@ internal Settings_UpdateViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { CheckUpdateCommand = ReactiveCommand.Create(CheckUpdate); UpdateCommand = ReactiveCommand.Create(Update); } - public override void InitEvents() + public sealed override void InitEvents() { Components.CollectionChanged += (_, _) => { @@ -63,7 +63,10 @@ internal int CanUpdateCount set => this.RaiseAndSetIfChanged(ref canUpdateCount, value); } - internal static int ComponentsCount { get => Components.Count; } + internal static int ComponentsCount + { + get => Components.Count; + } internal static ObservableCollection Components { get; } = []; @@ -85,13 +88,14 @@ internal string DiskUseStatus public static int UpdateChannel { - get => AppConfig.Web.UpdateChannel switch - { - "stable" => 0, - "beta" => 1, - "alpha" => 2, - _ => 0 - }; + get => + AppConfig.Web.UpdateChannel switch + { + "stable" => 0, + "beta" => 1, + "alpha" => 2, + _ => 0, + }; set { AppConfig.Web.UpdateChannel = value switch @@ -99,14 +103,15 @@ public static int UpdateChannel 0 => "stable", 1 => "beta", 2 => "alpha", - _ => "stable" + _ => "stable", }; SaveAppConfigChanges(); } } - private static string GetUpdateTip(string key) => Translate(key, prefix: "Text_Settings_Update_Tip_") ?? string.Empty; + private static string GetUpdateTip(string key) => + Translate(key, prefix: "Text_Settings_Update_Tip_") ?? string.Empty; private static async void DownloadNewComponent(string url, string to, HttpClient client) { @@ -127,9 +132,12 @@ private static async void DownloadNewComponent(string url, string to, HttpClient private static string GetDisplaySize(long size) { - if (size / (1024 * 1024) > 2000) return $"{size / (1024 * 1024 * 1024)} GB"; - else if (size / 1024 > 1200) return $"{size / (1024 * 1024)} MB"; - else return $"{size / 1024} KB"; + if (size / (1024 * 1024) > 2000) + return $"{size / (1024 * 1024 * 1024)} GB"; + else if (size / 1024 > 1200) + return $"{size / (1024 * 1024)} MB"; + else + return $"{size / 1024} KB"; } private Checker ScanComponents(string workbase) @@ -164,27 +172,23 @@ private Checker ScanComponents(string workbase) private void CalculateComponentsHash(Checker checker) { - var location = $"{nameof(Settings_UpdateViewModel)}.{nameof(CalculateComponentsHash)}"; + const string location = + $"{nameof(Settings_UpdateViewModel)}.{nameof(CalculateComponentsHash)}"; var _calculateFinished = false; - var timer = new Timer() - { - Interval = 10, - AutoReset = true - }; + var timer = new Timer() { Interval = 10, AutoReset = true }; timer.Elapsed += (_, _) => { try { var progress = checker.GetProgress(); - Tip = GetUpdateTip("Calculate").Replace( - "%Progress%", - $"({progress.Item1}/{progress.Item2})" - ); + Tip = GetUpdateTip("Calculate") + .Replace("%Progress%", $"({progress.Item1}/{progress.Item2})"); - if (_calculateFinished) timer.Stop(); + if (_calculateFinished) + timer.Stop(); } catch (Exception e) { @@ -205,41 +209,38 @@ private void CalculateComponentsHash(Checker checker) PropertyNamingPolicy = new UpdateHashNamePolicy(), }; - private static async Task?> GetLatestComponentsAsync - ( + private static async Task?> GetLatestComponentsAsync( HttpClient client ) { - client.DefaultRequestHeaders.Accept.Clear(); // 清除请求头部 + client.DefaultRequestHeaders.Accept.Clear(); // 清除请求头部 - var link = "https://" + - AppConfig.Web.UpdateServer + - AppConfig.Web.UpdatePath.Replace( + var link = + "https://" + + AppConfig.Web.UpdateServer + + AppConfig.Web.UpdatePath.Replace( "%platform%", DevicesDiscoveryServer.Instance.DefaultDeviceInfo.DeviceOSType switch { OperatingSystems.Windows => "win", OperatingSystems.Linux => "linux", OperatingSystems.MacOS => "mac", - _ => "" + _ => "", } - ) + - $"{AppConfig.Web.UpdateChannel}/" + - AppConfig.Web.UpdateSource; + ) + + $"{AppConfig.Web.UpdateChannel}/" + + AppConfig.Web.UpdateSource; var json = await client.GetStringAsync(link); - var latestComponents = JsonSerializer - .Deserialize>( - json, - JsonSerializerOptions - ); + var latestComponents = JsonSerializer.Deserialize< + Dictionary + >(json, JsonSerializerOptions); return latestComponents; } - private void AddLocalComponentsToView - ( + private void AddLocalComponentsToView( Dictionary result, string wd, ref long localComponentsTotalSize @@ -253,14 +254,16 @@ ref long localComponentsTotalSize localComponentsTotalSize += size; - localComponents.Add(new() - { - CanUpdate = false, - Name = item.Key, - MD5 = item.Value.Item1.ToUpper(), - SHA1 = item.Value.Item2.ToUpper(), - Size = GetDisplaySize(size), - }); + localComponents.Add( + new() + { + CanUpdate = false, + Name = item.Key, + MD5 = item.Value.Item1.ToUpper(), + SHA1 = item.Value.Item2.ToUpper(), + Size = GetDisplaySize(size), + } + ); } Dispatcher.UIThread.Post(() => @@ -271,7 +274,8 @@ ref long localComponentsTotalSize { ++index; - if (index == localComponents.Count) _canUpdateDataGridView = true; + if (index == localComponents.Count) + _canUpdateDataGridView = true; Components.Add(item); } @@ -279,11 +283,10 @@ ref long localComponentsTotalSize Tip = GetUpdateTip("Compare"); - while (Components.Count != result.Count) { } // 阻塞直到前台加载完毕 + while (Components.Count != result.Count) { } // 阻塞直到前台加载完毕 } - private static object CompareDifferentComponents - ( + private static object CompareDifferentComponents( ref string wd, ref Dictionary latestComponents, ref Dictionary result, @@ -298,8 +301,10 @@ ref long latestComponentsTotalSize { if (result.TryGetValue(component.Key, out var current)) { - if (!current.Item1.ToUpper().Equals(component.Value.Item1.ToUpper()) || - !current.Item2.ToUpper().Equals(component.Value.Item2.ToUpper())) + if ( + !current.Item1.ToUpper().Equals(component.Value.Item1.ToUpper()) + || !current.Item2.ToUpper().Equals(component.Value.Item2.ToUpper()) + ) updatedComponents.Add(component.Key, component.Value.Item3); } else @@ -314,16 +319,13 @@ ref long latestComponentsTotalSize if (!latestComponents.ContainsKey(item.Key)) tdeleteComponents.Add( item.Key, - new FileInfo( - $"{wd}/{item.Key}".GetFullPath() - ).Length + new FileInfo($"{wd}/{item.Key}".GetFullPath()).Length ); return (updatedComponents, new2addComponents, tdeleteComponents); } - private void UpdateFrontendViewAfterCompare - ( + private void UpdateFrontendViewAfterCompare( Dictionary updatedComponents, Dictionary new2addComponents, Dictionary tdeleteComponents, @@ -337,7 +339,8 @@ private void UpdateFrontendViewAfterCompare foreach (var item in Components) { - if (item.Name is null) continue; + if (item.Name is null) + continue; if (updatedComponents.ContainsKey(item.Name)) { @@ -355,15 +358,17 @@ private void UpdateFrontendViewAfterCompare foreach (var item in new2addComponents) { - newComponents.Add(new Component() - { - Name = item.Key, - CanUpdate = true, - MD5 = latestComponents[item.Key].Item1, - SHA1 = latestComponents[item.Key].Item2, - Task = Translate("Text_Public_Add"), - Size = GetDisplaySize(item.Value) - }); + newComponents.Add( + new Component() + { + Name = item.Key, + CanUpdate = true, + MD5 = latestComponents[item.Key].Item1, + SHA1 = latestComponents[item.Key].Item2, + Task = Translate("Text_Public_Add"), + Size = GetDisplaySize(item.Value), + } + ); } Dispatcher.UIThread.Post(() => @@ -374,7 +379,8 @@ private void UpdateFrontendViewAfterCompare { ++index; - if (index == new2addComponents.Count) _canUpdateDataGridView = true; + if (index == new2addComponents.Count) + _canUpdateDataGridView = true; Components.Add(item); } @@ -391,15 +397,11 @@ private void UpdateFrontendViewAfterCompare DiskUseStatus = localComponentsTotalSize > latestComponentsTotalSize - ? - $"- {GetDisplaySize(localComponentsTotalSize - latestComponentsTotalSize)}" - : - $"+ {GetDisplaySize(latestComponentsTotalSize - localComponentsTotalSize)}" - ; + ? $"- {GetDisplaySize(localComponentsTotalSize - latestComponentsTotalSize)}" + : $"+ {GetDisplaySize(latestComponentsTotalSize - localComponentsTotalSize)}"; } - private void DownloadNewComponents - ( + private void DownloadNewComponents( ref Dictionary updatedComponents, ref HttpClient client ) @@ -407,18 +409,20 @@ ref HttpClient client Tip = GetUpdateTip("Download"); //TODO: 下载有变更的文件 - var downloadLinkBase = "https://" + - AppConfig.Web.UpdateServer + - AppConfig.Web.UpdateDownloadPath.Replace( + var downloadLinkBase = + "https://" + + AppConfig.Web.UpdateServer + + AppConfig.Web.UpdateDownloadPath.Replace( "%platform%", DevicesDiscoveryServer.Instance.DefaultDeviceInfo.DeviceOSType switch { OperatingSystems.Windows => "win", OperatingSystems.Linux => "linux", OperatingSystems.MacOS => "mac", - _ => "" - }) + - $"{AppConfig.Web.UpdateChannel}/"; + _ => "", + } + ) + + $"{AppConfig.Web.UpdateChannel}/"; if (!Directory.Exists(ConstantTable.UpdateSavePath.GetFullPath())) Directory.CreateDirectory(ConstantTable.UpdateSavePath.GetFullPath()); @@ -441,7 +445,7 @@ internal bool IsCheckingOrUpdating public void CheckUpdate() { - var location = $"{nameof(Settings_UpdateViewModel)}.{nameof(CheckUpdate)}"; + const string location = $"{nameof(Settings_UpdateViewModel)}.{nameof(CheckUpdate)}"; Components.Clear(); @@ -461,12 +465,14 @@ public void CheckUpdate() { Dispatcher.UIThread.Post(async () => { - await MessageBoxManager.GetMessageBoxStandard( - "Error", - "Can't get working directory!", - ButtonEnum.Ok, - Icon.Warning - ).ShowAsync(); + await MessageBoxManager + .GetMessageBoxStandard( + "Error", + "Can't get working directory!", + ButtonEnum.Ok, + Icon.Warning + ) + .ShowAsync(); }); IsCheckingOrUpdating = false; @@ -478,15 +484,10 @@ await MessageBoxManager.GetMessageBoxStandard( CalculateComponentsHash(checker); - var result = checker.GetCalculateResult() - .OrderBy( - x => - x.Key.Contains('/') || - x.Key.Contains('\\') ? $"0{x.Key}" : x.Key - ).ToDictionary( - x => x.Key, - x => x.Value - ); + var result = checker + .GetCalculateResult() + .OrderBy(x => x.Key.Contains('/') || x.Key.Contains('\\') ? $"0{x.Key}" : x.Key) + .ToDictionary(x => x.Key, x => x.Value); checker.CleanMemoryUsage(); @@ -497,20 +498,18 @@ await MessageBoxManager.GetMessageBoxStandard( var client = new HttpClient(); - var latestComponents - = await GetLatestComponentsAsync(client); + var latestComponents = await GetLatestComponentsAsync(client); if (latestComponents is not null) { - var difference = - (( + var difference = (( Dictionary, Dictionary, Dictionary - )) - CompareDifferentComponents - ( - ref wd, ref latestComponents, ref result, + ))CompareDifferentComponents( + ref wd, + ref latestComponents, + ref result, ref latestComponentsTotalSize ); @@ -518,8 +517,7 @@ ref latestComponentsTotalSize var new2addComponents = difference.Item2; var tdeleteComponents = difference.Item3; - UpdateFrontendViewAfterCompare - ( + UpdateFrontendViewAfterCompare( updatedComponents, new2addComponents, tdeleteComponents, @@ -548,12 +546,14 @@ ref result Dispatcher.UIThread.Post(async () => { - await MessageBoxManager.GetMessageBoxStandard( - GetUpdateTip("Failed"), - e.Message, - ButtonEnum.Ok, - Icon.Error - ).ShowAsync(); + await MessageBoxManager + .GetMessageBoxStandard( + GetUpdateTip("Failed"), + e.Message, + ButtonEnum.Ok, + Icon.Error + ) + .ShowAsync(); }); Log.Error(e, $"In {location}: {e.Message}"); @@ -564,9 +564,7 @@ await MessageBoxManager.GetMessageBoxStandard( [DependsOn(nameof(IsCheckingOrUpdating))] internal bool CanCheckUpdate(object _) => !IsCheckingOrUpdating; - public void Update() - { - } + public void Update() { } [DependsOn(nameof(CanUpdateCount))] [DependsOn(nameof(IsCheckingOrUpdating))] diff --git a/KitX Dashboard/ViewModels/Pages/DevicePageViewModel.cs b/KitX Dashboard/ViewModels/Pages/DevicesPageViewModel.cs similarity index 92% rename from KitX Dashboard/ViewModels/Pages/DevicePageViewModel.cs rename to KitX Dashboard/ViewModels/Pages/DevicesPageViewModel.cs index 41b67208..8e788dad 100644 --- a/KitX Dashboard/ViewModels/Pages/DevicePageViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/DevicesPageViewModel.cs @@ -7,16 +7,16 @@ namespace KitX.Dashboard.ViewModels.Pages; -internal class DevicePageViewModel : ViewModelBase +internal class DevicesPageViewModel : ViewModelBase { - public DevicePageViewModel() + public DevicesPageViewModel() { InitCommands(); InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { RestartDevicesServerCommand = ReactiveCommand.Create(async () => { @@ -54,7 +54,7 @@ await Instances.WebManager.CloseAsync( }); } - public override void InitEvents() + public sealed override void InitEvents() { DeviceCases.CollectionChanged += (_, _) => { diff --git a/KitX Dashboard/ViewModels/Pages/HomePageViewModel.cs b/KitX Dashboard/ViewModels/Pages/HomePageViewModel.cs index 7c5cfe10..87bf51ad 100644 --- a/KitX Dashboard/ViewModels/Pages/HomePageViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/HomePageViewModel.cs @@ -13,7 +13,7 @@ public HomePageViewModel() InitCommands(); } - public override void InitCommands() + public sealed override void InitCommands() { ResetToAutoCommand = ReactiveCommand.Create(() => { @@ -44,15 +44,16 @@ internal static bool IsPaneOpen } } - internal Thickness FirstItemMargin => NavigationViewPaneDisplayMode switch - { - NavigationViewPaneDisplayMode.Auto => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.Left => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.LeftCompact => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.LeftMinimal => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.Top => new(0, 0, 0, 0), - _ => new(0, 0, 0, 0) - }; + internal Thickness FirstItemMargin => + NavigationViewPaneDisplayMode switch + { + NavigationViewPaneDisplayMode.Auto => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.Left => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.LeftCompact => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.LeftMinimal => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.Top => new(0, 0, 0, 0), + _ => new(0, 0, 0, 0), + }; internal NavigationViewPaneDisplayMode NavigationViewPaneDisplayMode { diff --git a/KitX Dashboard/ViewModels/Pages/LibPageViewModel.cs b/KitX Dashboard/ViewModels/Pages/LibPageViewModel.cs index da051cfb..22bf2f5f 100644 --- a/KitX Dashboard/ViewModels/Pages/LibPageViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/LibPageViewModel.cs @@ -16,21 +16,21 @@ public LibPageViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { ViewDetailsCommand = ReactiveCommand.Create(info => { if (ViewInstances.MainWindow is not null) new PluginDetailWindow() { - WindowStartupLocation = WindowStartupLocation.CenterOwner + WindowStartupLocation = WindowStartupLocation.CenterOwner, } - .SetPluginInfo(info) - .Show(ViewInstances.MainWindow); + .SetPluginInfo(info) + .Show(ViewInstances.MainWindow); }); } - public override void InitEvents() + public sealed override void InitEvents() { PluginInfos.CollectionChanged += (_, args) => { diff --git a/KitX Dashboard/ViewModels/Pages/RepoPageViewModel.cs b/KitX Dashboard/ViewModels/Pages/RepoPageViewModel.cs index 0c6a2a04..ab9d7628 100644 --- a/KitX Dashboard/ViewModels/Pages/RepoPageViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/RepoPageViewModel.cs @@ -35,21 +35,26 @@ public RepoPageViewModel() RefreshPluginsCommand?.Execute(new()); } - public override void InitCommands() + public sealed override void InitCommands() { ImportPluginCommand = ReactiveCommand.Create(async win => { - if (win is not Window window) return; + if (win is not Window window) + return; var topLevel = TopLevel.GetTopLevel(CurrentPage!); - if (topLevel is null) return; + if (topLevel is null) + return; - var files = (await topLevel.StorageProvider.OpenFilePickerAsync(new() - { - Title = "Open KitX Extensions Package File", - AllowMultiple = true, - })).Select(x => x.Path.LocalPath).ToList().ToArray(); + var files = ( + await topLevel.StorageProvider.OpenFilePickerAsync( + new() { Title = "Open KitX Extensions Package File", AllowMultiple = true } + ) + ) + .Select(x => x.Path.LocalPath) + .ToList() + .ToArray(); if (files is not null && files?.Length > 0) { @@ -95,7 +100,7 @@ public override void InitCommands() Path.GetFullPath($"{item.InstallPath}/LoaderInfo.json") ) ), - InstalledDevices = [] + InstalledDevices = [], }; PluginBars.Add(new(plugin, ref pluginBars)); @@ -114,12 +119,10 @@ internal RepoPageViewModel SetControl(RepoPage control) return this; } - public override void InitEvents() + public sealed override void InitEvents() { EventService.AppConfigChanged += () => - { ImportButtonVisibility = ConfigManager.Instance.AppConfig.App.DeveloperSetting; - }; PluginBars.CollectionChanged += (_, _) => { diff --git a/KitX Dashboard/ViewModels/Pages/SettingsPageViewModel.cs b/KitX Dashboard/ViewModels/Pages/SettingsPageViewModel.cs index 25c62021..083eb6cf 100644 --- a/KitX Dashboard/ViewModels/Pages/SettingsPageViewModel.cs +++ b/KitX Dashboard/ViewModels/Pages/SettingsPageViewModel.cs @@ -12,7 +12,7 @@ internal SettingsPageViewModel() InitCommands(); } - public override void InitCommands() + public sealed override void InitCommands() { ResetToAutoCommand = ReactiveCommand.Create(() => { @@ -43,15 +43,16 @@ internal static bool IsPaneOpen } } - internal Thickness FirstItemMargin => NavigationViewPaneDisplayMode switch - { - NavigationViewPaneDisplayMode.Auto => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.Left => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.LeftCompact => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.LeftMinimal => new(0, 5, 0, 0), - NavigationViewPaneDisplayMode.Top => new(0, 0, 0, 0), - _ => new(0, 0, 0, 0) - }; + internal Thickness FirstItemMargin => + NavigationViewPaneDisplayMode switch + { + NavigationViewPaneDisplayMode.Auto => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.Left => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.LeftCompact => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.LeftMinimal => new(0, 5, 0, 0), + NavigationViewPaneDisplayMode.Top => new(0, 0, 0, 0), + _ => new(0, 0, 0, 0), + }; internal NavigationViewPaneDisplayMode NavigationViewPaneDisplayMode { diff --git a/KitX Dashboard/ViewModels/PluginDetailWindowViewModel.cs b/KitX Dashboard/ViewModels/PluginDetailWindowViewModel.cs index a61e9fd0..2d8473d3 100644 --- a/KitX Dashboard/ViewModels/PluginDetailWindowViewModel.cs +++ b/KitX Dashboard/ViewModels/PluginDetailWindowViewModel.cs @@ -20,14 +20,12 @@ public PluginDetailWindowViewModel() InitEvents(); } - public override void InitCommands() + public sealed override void InitCommands() { - FinishCommand = ReactiveCommand.Create( - parent => (parent as Window)?.Close() - ); + FinishCommand = ReactiveCommand.Create(parent => (parent as Window)?.Close()); } - public override void InitEvents() + public sealed override void InitEvents() { EventService.ThemeConfigChanged += () => this.RaisePropertyChanged(nameof(TintColor)); } @@ -42,23 +40,30 @@ internal PluginInfo? PluginDetail internal string? PublishDate => PluginDetail?.PublishDate.ToLocalTime().ToString("yyyy.MM.dd"); - internal string? LastUpdateDate => PluginDetail?.LastUpdateDate.ToLocalTime().ToString("yyyy.MM.dd"); + internal string? LastUpdateDate => + PluginDetail?.LastUpdateDate.ToLocalTime().ToString("yyyy.MM.dd"); - internal static Color TintColor => AppConfig.App.Theme switch - { - "Light" => Colors.WhiteSmoke, - "Dark" => Colors.Black, - "Follow" => Application.Current?.ActualThemeVariant == ThemeVariant.Light ? Colors.WhiteSmoke : Colors.Black, - _ => Color.Parse(AppConfig.App.ThemeColor), - }; + internal static Color TintColor => + AppConfig.App.Theme switch + { + "Light" => Colors.WhiteSmoke, + "Dark" => Colors.Black, + "Follow" => Application.Current?.ActualThemeVariant == ThemeVariant.Light + ? Colors.WhiteSmoke + : Colors.Black, + _ => Color.Parse(AppConfig.App.ThemeColor), + }; internal void InitFunctionsAndTags() { - if (PluginDetail is null) return; + if (PluginDetail is null) + return; - if (PluginDetail?.Functions is null) return; + if (PluginDetail?.Functions is null) + return; - if (PluginDetail?.Tags is null) return; + if (PluginDetail?.Tags is null) + return; foreach (var func in PluginDetail.Functions) { @@ -66,17 +71,13 @@ internal void InitFunctionsAndTags() .Append(func.ReturnValueType) .Append(' ') .Append(func.Name) - .Append('(') - ; + .Append('('); var index = 0; foreach (var param in func.Parameters) { - sb.Append(param.Type) - .Append(' ') - .Append(param.Name) - ; + sb.Append(param.Type).Append(' ').Append(param.Name); if (index != func.Parameters.Count - 1) sb.Append(", "); diff --git a/KitX Dashboard/ViewModels/PluginsLaunchWindowViewModel.cs b/KitX Dashboard/ViewModels/PluginsLaunchWindowViewModel.cs index 3e2534d6..c5d0c640 100644 --- a/KitX Dashboard/ViewModels/PluginsLaunchWindowViewModel.cs +++ b/KitX Dashboard/ViewModels/PluginsLaunchWindowViewModel.cs @@ -22,12 +22,9 @@ public PluginsLaunchWindowViewModel() InitEvents(); } - public override void InitCommands() - { - - } + public sealed override void InitCommands() { } - public override void InitEvents() + public sealed override void InitEvents() { PluginInfos.CollectionChanged += (_, _) => { @@ -73,7 +70,8 @@ public PluginInfo? SelectedPluginInfo get => PluginIndexInRange(SelectedPluginIndex) ? PluginInfos[SelectedPluginIndex] : null; set { - if (value is null) return; + if (value is null) + return; var index = PluginInfos.IndexOf(value); @@ -87,11 +85,11 @@ public Function? SelectedFunction { get { - if (SelectedPluginInfo is null) selectedFunction = null; + if (SelectedPluginInfo is null) + selectedFunction = null; return selectedFunction; } - set { this.RaiseAndSetIfChanged(ref selectedFunction, value); @@ -135,7 +133,6 @@ public bool IsSelectingFunction this.RaiseAndSetIfChanged(ref isSelectingFunction, value); - if (value) { SearchingText = SelectedFunction?.Name; @@ -149,7 +146,8 @@ public bool HavingParameters { get { - if (SelectedFunction is null) return false; + if (SelectedFunction is null) + return false; return SelectedFunction.Value.Parameters.Count != 0; } @@ -167,7 +165,8 @@ public IEnumerable SearchItems { return SelectedPluginInfo?.Functions.Select(f => f.Name) ?? []; } - else return []; + else + return []; } } @@ -176,10 +175,7 @@ public IEnumerable SearchItems public string? SearchingText { get => searchingText; - set - { - this.RaiseAndSetIfChanged(ref searchingText, value); - } + set { this.RaiseAndSetIfChanged(ref searchingText, value); } } private Vector scrollViewerOffset = new(0, 0); @@ -198,7 +194,11 @@ public bool IsInDirectSelectingMode set => this.RaiseAndSetIfChanged(ref isInDirectSelectingMode, value); } - private void BringSelectedButtonIntoView(int perLineButtonsCount, double scrollviewerHeight, double scrollviewerOffsetY) + private void BringSelectedButtonIntoView( + int perLineButtonsCount, + double scrollviewerHeight, + double scrollviewerOffsetY + ) { var viewerHeight = (int)Math.Floor(scrollviewerHeight); @@ -233,7 +233,11 @@ private void CheckPluginIndex() } } - internal void SelectLeftOne(int perLineCount, double scrollviewerHeight, double scrollviewerOffsetY) + internal void SelectLeftOne( + int perLineCount, + double scrollviewerHeight, + double scrollviewerOffsetY + ) { if (PluginIndexInRange(selectedPluginIndex - 1)) { @@ -243,7 +247,11 @@ internal void SelectLeftOne(int perLineCount, double scrollviewerHeight, double } } - internal void SelectRightOne(int perLineCount, double scrollviewerHeight, double scrollviewerOffsetY) + internal void SelectRightOne( + int perLineCount, + double scrollviewerHeight, + double scrollviewerOffsetY + ) { if (PluginIndexInRange(SelectedPluginIndex + 1)) { @@ -253,7 +261,11 @@ internal void SelectRightOne(int perLineCount, double scrollviewerHeight, double } } - internal void SelectUpOne(int perLineCount, double scrollviewerHeight, double scrollviewerOffsetY) + internal void SelectUpOne( + int perLineCount, + double scrollviewerHeight, + double scrollviewerOffsetY + ) { var targetIndex = SelectedPluginIndex - perLineCount; @@ -265,7 +277,11 @@ internal void SelectUpOne(int perLineCount, double scrollviewerHeight, double sc } } - internal void SelectDownOne(int perLineCount, double scrollviewerHeight, double scrollviewerOffsetY) + internal void SelectDownOne( + int perLineCount, + double scrollviewerHeight, + double scrollviewerOffsetY + ) { var targetIndex = SelectedPluginIndex + perLineCount; @@ -326,7 +342,8 @@ internal void SubmitSearchingText() { SelectedPluginIndex = index; - if (SelectedFunction is not null) SelectedFunction = null; + if (SelectedFunction is not null) + SelectedFunction = null; IsSelectingFunction = true; } @@ -342,7 +359,11 @@ internal void SubmitSearchingText() break; } - if (SelectedPluginInfo is not null && SelectedFunction is not null && (HavingParameters == false)) + if ( + SelectedPluginInfo is not null + && SelectedFunction is not null + && (HavingParameters == false) + ) { var plugConnector = PluginsServer.Instance.FindConnector(SelectedPluginInfo); @@ -350,10 +371,10 @@ internal void SubmitSearchingText() { var connector = new Connector() .SetSerializer(x => JsonSerializer.Serialize(x)) - .SetSender(plugConnector.Request) - ; + .SetSender(plugConnector.Request); - var request = connector.Request() + var request = connector + .Request() .ReceiveCommand() .UpdateCommand(cmd => { @@ -361,14 +382,10 @@ internal void SubmitSearchingText() return cmd; }) - .Send() - ; + .Send(); } } } - else - { - - } + else { } } } diff --git a/KitX Dashboard/ViewModels/ViewModelBase.cs b/KitX Dashboard/ViewModels/ViewModelBase.cs index ea03f97e..1a690298 100644 --- a/KitX Dashboard/ViewModels/ViewModelBase.cs +++ b/KitX Dashboard/ViewModels/ViewModelBase.cs @@ -9,32 +9,32 @@ namespace KitX.Dashboard.ViewModels; public abstract class ViewModelBase : ReactiveObject { - protected static string? Translate - ( + protected static string? Translate( string key = "", string prefix = "", string suffix = "", - string seperator = "", + string separator = "", Application? app = null ) { app ??= Application.Current; - if (app is null) return null; + if (app is null) + return null; - var res_key = $"{prefix}{seperator}{key}{seperator}{suffix}"; + var resKey = $"{prefix}{separator}{key}{separator}{suffix}"; - if (app.TryFindResource(res_key, out var found)) - { - if (found is string text) return text; - else return null; - } - else return null; + if (!app.TryFindResource(resKey, out var found)) + return null; + + if (found is string text) + return text; + + return null; } - protected static void SaveAppConfigChanges() => EventService.Invoke( - nameof(EventService.AppConfigChanged) - ); + protected static void SaveAppConfigChanges() => + EventService.Invoke(nameof(EventService.AppConfigChanged)); public abstract void InitCommands(); @@ -42,5 +42,6 @@ protected static void SaveAppConfigChanges() => EventService.Invoke( internal static AppConfig AppConfig => ConfigManager.Instance.AppConfig; - internal static AnnouncementConfig AnnouncementConfig => ConfigManager.Instance.AnnouncementConfig; + internal static AnnouncementConfig AnnouncementConfig => + ConfigManager.Instance.AnnouncementConfig; } diff --git a/KitX Dashboard/Views/AnouncementsWindow.axaml b/KitX Dashboard/Views/AnnouncementsWindow.axaml similarity index 98% rename from KitX Dashboard/Views/AnouncementsWindow.axaml rename to KitX Dashboard/Views/AnnouncementsWindow.axaml index 27f61363..c95629e0 100644 --- a/KitX Dashboard/Views/AnouncementsWindow.axaml +++ b/KitX Dashboard/Views/AnnouncementsWindow.axaml @@ -1,4 +1,4 @@ - ConfigManager.Instance.AppConfig; - public AnouncementsWindow() + public AnnouncementsWindow() { InitializeComponent(); - viewModel.Window = this; + _viewModel.Window = this; - DataContext = viewModel; + DataContext = _viewModel; + } - var config = appConfig.Windows.AnnouncementWindow; + internal AnnouncementsWindow UpdateSource(Dictionary src) + { + _viewModel.Sources = src; - var screen = Screens.ScreenFromWindow(this); + return this; + } - var nowRes = config.Size.SuggestResolution(screen); + protected override void OnOpened(EventArgs e) + { + var config = AppConfig.Windows.AnnouncementWindow; - var centerPos = config.Location.BringToCenter(screen, nowRes); + var screen = Screens.ScreenFromWindow(this); - ClientSize = new(nowRes.Width!.Value, nowRes.Height!.Value); + config.Size = config.Size.SuggestResolution(screen, out var notScaled); - Position = new((int)centerPos.Left, (int)centerPos.Top); + var centerPos = config.Location.BringToCenter(screen, notScaled ?? config.Size); - ClientSizeProperty.Changed.Subscribe(size => + SizeChanged += (_, _) => { if (WindowState != WindowState.Maximized) - config.Size = new Resolution(ClientSize.Width, ClientSize.Height); - }); + config.Size = new(Width, Height); + }; - PositionChanged += (_, args) => + PositionChanged += (_, _) => { if (WindowState == WindowState.Normal) config.Location = new(left: Position.X, top: Position.Y); }; - } - internal AnouncementsWindow UpdateSource(Dictionary src) - { - viewModel.Sources = src; + ClientSize = new(config.Size.Width!.Value, config.Size.Height!.Value); - return this; + Position = new((int)centerPos.Left, (int)centerPos.Top); + + base.OnOpened(e); } protected override void OnClosing(WindowClosingEventArgs e) diff --git a/KitX Dashboard/Views/MainWindow.axaml b/KitX Dashboard/Views/MainWindow.axaml index 8e579373..ae2639e9 100644 --- a/KitX Dashboard/Views/MainWindow.axaml +++ b/KitX Dashboard/Views/MainWindow.axaml @@ -9,8 +9,6 @@ xmlns:vm="using:KitX.Dashboard.ViewModels" x:Name="MainWindowInstance" Title="{DynamicResource Text_MainWindow_Title}" - Width="{Binding Window_Width}" - Height="{Binding Window_Height}" MinWidth="800" MinHeight="600" d:DesignHeight="450" diff --git a/KitX Dashboard/Views/MainWindow.axaml.cs b/KitX Dashboard/Views/MainWindow.axaml.cs index 78dcc9e3..eb441006 100644 --- a/KitX Dashboard/Views/MainWindow.axaml.cs +++ b/KitX Dashboard/Views/MainWindow.axaml.cs @@ -3,7 +3,6 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Threading; -using Common.BasicHelper.Graphics.Screen; using FluentAvalonia.UI.Controls; using KitX.Dashboard.Configuration; using KitX.Dashboard.Converters; @@ -25,7 +24,7 @@ public partial class MainWindow : Window, IView public MainWindow() { - var location = $"{nameof(MainWindow)}"; + const string location = $"{nameof(MainWindow)}"; InitializeComponent(); @@ -33,47 +32,71 @@ public MainWindow() DataContext = viewModel; - var config = AppConfig.Windows.MainWindow; + Instances.SignalTasksManager?.SignalRun( + nameof(SignalsNames.MainWindowOpenedSignal), + () => + { + var config = AppConfig.Windows.MainWindow; - var screen = Screens.ScreenFromWindow(this); + var screen = Screens.ScreenFromWindow(this); - var nowRes = config.Size.SuggestResolution(screen); + config.Size = config.Size.SuggestResolution(screen, out var notScaled); - var centerPos = config.Location.BringToCenter(screen, nowRes); + var centerPos = config.Location.BringToCenter(screen, notScaled ?? config.Size); - ClientSize = new(nowRes.Width!.Value, nowRes.Height!.Value); + try + { + Instances.SignalTasksManager.SignalRun( + nameof(SignalsNames.MainWindowOpenedSignal), + () => WindowState = config.WindowState + ); + + if (config.IsHidden) + Instances.SignalTasksManager.SignalRun( + nameof(SignalsNames.MainWindowOpenedSignal), + Hide + ); + } + catch (Exception e) + { + Log.Error(e, $"In {location}: {e.Message}"); + } - Position = new((int)centerPos.Left, (int)centerPos.Top); + SizeChanged += (_, _) => + { + if (WindowState == WindowState.Maximized) + return; - try - { - Instances.SignalTasksManager?.SignalRun( - nameof(SignalsNames.MainWindowOpenedSignal), - () => WindowState = config.WindowState - ); - - if (config.IsHidden) - Instances.SignalTasksManager?.SignalRun( - nameof(SignalsNames.MainWindowOpenedSignal), - Hide - ); - } - catch (Exception e) - { - Log.Error(e, $"In {location}: {e.Message}"); - } + config.Size.Width = ClientSize.Width; + config.Size.Height = ClientSize.Height; + }; - ClientSizeProperty.Changed.Subscribe(size => - { - if (WindowState != WindowState.Maximized) - config.Size = new Resolution(ClientSize.Width, ClientSize.Height); - }); + //ClientSizeProperty.Changed.Subscribe(_ => + //{ + // if (WindowState == WindowState.Maximized) + // return; - PositionChanged += (_, args) => - { - if (WindowState == WindowState.Normal) - config.Location = new(left: Position.X, top: Position.Y); - }; + // config.Size.Width = ClientSize.Width; + // config.Size.Height = ClientSize.Height; + //}); + + PositionChanged += (_, _) => + { + if (WindowState != WindowState.Normal) + return; + + config.Location.Left = Position.X; + config.Location.Top = Position.Y; + }; + + if (WindowState != WindowState.Normal) + return; + + ClientSize = new(config.Size.Width!.Value, config.Size.Height!.Value); + + Position = new((int)centerPos.Left, (int)centerPos.Top); + } + ); InitMainWindow(); } @@ -84,14 +107,14 @@ private void InitMainWindow() UpdateGreetingText(); - EventService.LanguageChanged += () => UpdateGreetingText(); + EventService.LanguageChanged += UpdateGreetingText; - EventService.GreetingTextIntervalUpdated += () => UpdateGreetingText(); + EventService.GreetingTextIntervalUpdated += UpdateGreetingText; var timer = new Timer() { AutoReset = true, - Interval = 1000 * 60 * AppConfig.Windows.MainWindow.GreetingUpdateInterval + Interval = 1000 * 60 * AppConfig.Windows.MainWindow.GreetingUpdateInterval, }; timer.Elapsed += (_, _) => UpdateGreetingText(); @@ -105,15 +128,21 @@ internal void UpdateGreetingText() { try { - if (Application.Current is null) return; + if (Application.Current is null) + return; Dispatcher.UIThread.Invoke(() => { - Application.Current.Resources.MergedDictionaries[0].TryGetResource( - GreetingTextGenerator.GetKey(), ActualThemeVariant, out object? text - ); + Application + .Current.Resources.MergedDictionaries[0] + .TryGetResource( + GreetingTextGenerator.GetKey(), + ActualThemeVariant, + out object? text + ); - if (text is null) return; + if (text is null) + return; Dispatcher.UIThread.Post(() => { @@ -127,17 +156,18 @@ internal void UpdateGreetingText() } } - private static Type GetPageTypeFromName(string name) => name switch - { - "Page_Home" => typeof(Pages.HomePage), - "Page_Lib" => typeof(Pages.LibPage), - "Page_Repo" => typeof(Pages.RepoPage), - "Page_Account" => typeof(Pages.AccountPage), - "Page_Settings" => typeof(Pages.SettingsPage), - "Page_Market" => typeof(Pages.MarketPage), - "Page_Device" => typeof(Pages.DevicePage), - _ => typeof(Pages.HomePage), - }; + private static Type GetPageTypeFromName(string name) => + name switch + { + "Page_Home" => typeof(Pages.HomePage), + "Page_Lib" => typeof(Pages.LibPage), + "Page_Repo" => typeof(Pages.RepoPage), + "Page_Account" => typeof(Pages.AccountPage), + "Page_Settings" => typeof(Pages.SettingsPage), + "Page_Market" => typeof(Pages.MarketPage), + "Page_Device" => typeof(Pages.DevicesPage), + _ => typeof(Pages.HomePage), + }; private static string SelectedPageName { @@ -157,15 +187,18 @@ NavigationViewSelectionChangedEventArgs e { try { - if (sender is null) return; + if (sender is null) + return; var navView = sender as NavigationView; - if (navView?.SelectedItem is not Control control || control.Tag is null) return; + if (navView?.SelectedItem is not Control control || control.Tag is null) + return; var pageName = control.Tag.ToString(); - if (pageName is null) return; + if (pageName is null) + return; SelectedPageName = pageName; @@ -177,26 +210,26 @@ NavigationViewSelectionChangedEventArgs e } } - protected override void OnClosing(WindowClosingEventArgs e) + protected override void OnOpened(EventArgs e) { - base.OnClosing(e); + base.OnOpened(e); - if (!ConstantTable.Exiting) - { - e.Cancel = true; + Instances.SignalTasksManager?.RaiseSignal(nameof(SignalsNames.MainWindowOpenedSignal)); + } - Hide(); + protected override void OnClosing(WindowClosingEventArgs e) + { + if (ConstantTable.Exiting) + return; - AppConfig.Windows.MainWindow.IsHidden = true; + e.Cancel = true; - IView.SaveAppConfigChanges(); - } - } + Hide(); - protected override void OnOpened(EventArgs e) - { - base.OnOpened(e); + AppConfig.Windows.MainWindow.IsHidden = true; - Instances.SignalTasksManager?.RaiseSignal(nameof(SignalsNames.MainWindowOpenedSignal)); + IView.SaveAppConfigChanges(); + + base.OnClosing(e); } } diff --git a/KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml b/KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml new file mode 100644 index 00000000..b63069b3 --- /dev/null +++ b/KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml @@ -0,0 +1,9 @@ + + Welcome to Avalonia! + diff --git a/KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml.cs b/KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml.cs new file mode 100644 index 00000000..8f56b65d --- /dev/null +++ b/KitX Dashboard/Views/Maintain/DebugOptionsWindow.axaml.cs @@ -0,0 +1,18 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Markup.Xaml; +using KitX.Dashboard.ViewModels.Maintain; + +namespace KitX.Dashboard; + +public partial class DebugOptionsWindow : Window +{ + private readonly DebugOptionsWindowViewModel viewModel = new(); + + public DebugOptionsWindow() + { + InitializeComponent(); + + DataContext = viewModel; + } +} diff --git a/KitX Dashboard/Views/Pages/Controls/Settings_General.axaml b/KitX Dashboard/Views/Pages/Controls/Settings_General.axaml index 97891ab0..b4181842 100644 --- a/KitX Dashboard/Views/Pages/Controls/Settings_General.axaml +++ b/KitX Dashboard/Views/Pages/Controls/Settings_General.axaml @@ -108,6 +108,14 @@ IsVisible="{Binding DeveloperSettingEnabled}"/> + +