From 40160da2eac55abb76502dd3ed3f20d73d09feae Mon Sep 17 00:00:00 2001 From: uye <99072975+ABA2396@users.noreply.github.com> Date: Mon, 9 Oct 2023 14:44:23 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=EF=BC=8C=E6=B6=88=E9=99=A4=E8=AD=A6=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MaaWpfGui/Configuration/ConfigFactory.cs | 2 +- src/MaaWpfGui/Configuration/SpecificConfig.cs | 2 +- src/MaaWpfGui/Helper/Instances.cs | 2 + src/MaaWpfGui/Helper/LocalizationHelper.cs | 12 +- src/MaaWpfGui/Models/ResourceUpdater.cs | 35 ++-- .../RemoteControl/RemoteControlService.cs | 161 +++++++++--------- .../ViewModels/UI/AnnouncementViewModel.cs | 2 +- .../ViewModels/UI/CopilotViewModel.cs | 2 +- .../ViewModels/UI/RecognizerViewModel.cs | 29 +--- .../ViewModels/UI/SettingsViewModel.cs | 16 +- .../ViewModels/UI/VersionUpdateViewModel.cs | 3 + 11 files changed, 139 insertions(+), 127 deletions(-) diff --git a/src/MaaWpfGui/Configuration/ConfigFactory.cs b/src/MaaWpfGui/Configuration/ConfigFactory.cs index 37c878f8a8..deb298dee4 100644 --- a/src/MaaWpfGui/Configuration/ConfigFactory.cs +++ b/src/MaaWpfGui/Configuration/ConfigFactory.cs @@ -131,7 +131,7 @@ namespace MaaWpfGui.Configuration }; } - public static Root Root => _rootConfig.Value; + private static Root Root => _rootConfig.Value; public static readonly SpecificConfig CurrentConfig = Root.CurrentConfig; diff --git a/src/MaaWpfGui/Configuration/SpecificConfig.cs b/src/MaaWpfGui/Configuration/SpecificConfig.cs index bc2b8bc6cd..4f796070f3 100644 --- a/src/MaaWpfGui/Configuration/SpecificConfig.cs +++ b/src/MaaWpfGui/Configuration/SpecificConfig.cs @@ -15,7 +15,7 @@ namespace MaaWpfGui.Configuration { public class SpecificConfig { - // ReSharper disable once UnusedAutoPropertyAccessor.Global + // ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global public GUI GUI { get; set; } = new GUI(); } } diff --git a/src/MaaWpfGui/Helper/Instances.cs b/src/MaaWpfGui/Helper/Instances.cs index 0c068f40b6..e6b50eb1ae 100644 --- a/src/MaaWpfGui/Helper/Instances.cs +++ b/src/MaaWpfGui/Helper/Instances.cs @@ -75,6 +75,8 @@ namespace MaaWpfGui.Helper public static IMaaHotKeyActionHandler MaaHotKeyActionHandler { get; private set; } + // 别的地方有用到这个吗? + // ReSharper disable once UnusedAutoPropertyAccessor.Global public static RemoteControlService RemoteControlService { get; private set; } public static IMainWindowManager MainWindowManager { get; private set; } diff --git a/src/MaaWpfGui/Helper/LocalizationHelper.cs b/src/MaaWpfGui/Helper/LocalizationHelper.cs index b1dcad9c12..5e4a34c339 100644 --- a/src/MaaWpfGui/Helper/LocalizationHelper.cs +++ b/src/MaaWpfGui/Helper/LocalizationHelper.cs @@ -14,6 +14,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Windows; @@ -53,13 +54,12 @@ namespace MaaWpfGui.Helper return local; } - foreach (var lang in SupportedLanguages) + foreach (var lang in from lang in SupportedLanguages + let key = lang.Key.Contains("-") ? lang.Key.Split('-')[0] : lang.Key + where local.StartsWith(key) || key.StartsWith(local) + select lang) { - var key = lang.Key.Contains("-") ? lang.Key.Split('-')[0] : lang.Key; - if (local.StartsWith(key) || key.StartsWith(local)) - { - return lang.Key; - } + return lang.Key; } return "en-us"; diff --git a/src/MaaWpfGui/Models/ResourceUpdater.cs b/src/MaaWpfGui/Models/ResourceUpdater.cs index 79f070937e..018dd379c4 100644 --- a/src/MaaWpfGui/Models/ResourceUpdater.cs +++ b/src/MaaWpfGui/Models/ResourceUpdater.cs @@ -43,6 +43,8 @@ namespace MaaWpfGui.Models NotModified, } + // 只有 Release 版本才会检查更新 + // ReSharper disable once UnusedMember.Global public static async void UpdateAndToast() { var ret = await Update(); @@ -86,13 +88,18 @@ namespace MaaWpfGui.Models { var sRet = await UpdateFileWithETag(MaaUrls.MaaResourceApi, file, file); - if (sRet == UpdateResult.Failed) + switch (sRet) { - ret = UpdateResult.Failed; - } - else if (sRet == UpdateResult.Success) - { - ETagCache.Save(); + case UpdateResult.Failed: + ret = UpdateResult.Failed; + break; + case UpdateResult.Success: + ETagCache.Save(); + break; + case UpdateResult.NotModified: + break; + default: + throw new ArgumentOutOfRangeException(); } if (ret == UpdateResult.NotModified && sRet == UpdateResult.Success) @@ -109,13 +116,17 @@ namespace MaaWpfGui.Models private static async Task UpdateFilesWithIndex() { var indexSRet = await UpdateFileWithETag(MaaUrls.MaaResourceApi, MaaDynamicFilesIndex, MaaDynamicFilesIndex); - if (indexSRet == UpdateResult.Failed) + switch (indexSRet) { - return UpdateResult.Failed; - } - else if (indexSRet == UpdateResult.Success) - { - ETagCache.Save(); + case UpdateResult.Failed: + return UpdateResult.Failed; + case UpdateResult.Success: + ETagCache.Save(); + break; + case UpdateResult.NotModified: + break; + default: + throw new ArgumentOutOfRangeException(); } var indexPath = Path.Combine(Environment.CurrentDirectory, MaaDynamicFilesIndex); diff --git a/src/MaaWpfGui/Services/RemoteControl/RemoteControlService.cs b/src/MaaWpfGui/Services/RemoteControl/RemoteControlService.cs index 5f4c53b904..df66b78c3b 100644 --- a/src/MaaWpfGui/Services/RemoteControl/RemoteControlService.cs +++ b/src/MaaWpfGui/Services/RemoteControl/RemoteControlService.cs @@ -9,20 +9,20 @@ using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; -using System.Windows.Threading; using MaaWpfGui.Constants; using MaaWpfGui.Helper; -using MaaWpfGui.Services.Web; using MaaWpfGui.States; -using MaaWpfGui.ViewModels.UI; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Serilog; -using Windows.Media.Protection.PlayReady; -using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace MaaWpfGui.Services.RemoteControl { + /// + /// The view model of remote control. + /// + // 通过 container.Get(); 实例化或获取实例 + // ReSharper disable once ClassNeverInstantiated.Global public class RemoteControlService { private readonly Task _pollJobTask = Task.CompletedTask; @@ -33,7 +33,7 @@ namespace MaaWpfGui.Services.RemoteControl public RemoteControlService() { - _pollJobTask = _pollJobTask.ContinueWith(async (_) => + _pollJobTask = _pollJobTask.ContinueWith(async _ => { while (true) { @@ -51,7 +51,7 @@ namespace MaaWpfGui.Services.RemoteControl // ReSharper disable once FunctionNeverReturns }); - _executeJobTask = _executeJobTask.ContinueWith(async (_) => + _executeJobTask = _executeJobTask.ContinueWith(async _ => { while (true) { @@ -204,7 +204,7 @@ namespace MaaWpfGui.Services.RemoteControl var uid = Instances.SettingsViewModel.RemoteControlUserIdentity; var did = Instances.SettingsViewModel.RemoteControlDeviceIdentity; - var response = await Instances.HttpService.PostAsJsonAsync(new Uri(endpoint), new { user=uid, device = did}); + var response = await Instances.HttpService.PostAsJsonAsync(new Uri(endpoint), new { user = uid, device = did }); if (response == null) { Log.Logger.Error("RemoteControlService endpoint failed."); @@ -219,17 +219,20 @@ namespace MaaWpfGui.Services.RemoteControl foreach (var task in tasks.OfType()) { var type = task.GetValue("type")?.Value(); - if (!string.IsNullOrWhiteSpace(type)) + if (string.IsNullOrWhiteSpace(type)) { - // It is a valid task - var id = task.GetValue("id")?.Value(); - if (!_executedTaskIds.Contains(id)) - { - _executedTaskIds.Add(id); - - _taskQueue.Enqueue(task); - } + continue; } + + // It is a valid task + var id = task.GetValue("id")?.Value(); + if (_executedTaskIds.Contains(id)) + { + continue; + } + + _executedTaskIds.Add(id); + _taskQueue.Enqueue(task); } } } @@ -247,25 +250,25 @@ namespace MaaWpfGui.Services.RemoteControl switch (type) { case "LinkStart": - { - // 一键长草特殊任务 - await _runningState.UntilIdleAsync(); - var startLogStr = string.Format(LocalizationHelper.GetString("RemoteControlReceivedTask"), type, id); - - Application.Current.Dispatcher.Invoke(() => { - Instances.TaskQueueViewModel.AddLog(startLogStr); - Instances.TaskQueueViewModel.LinkStart(); - }); - await _runningState.UntilIdleAsync(); + // 一键长草特殊任务 + await _runningState.UntilIdleAsync(); + var startLogStr = string.Format(LocalizationHelper.GetString("RemoteControlReceivedTask"), type, id); - var stopLogStr = string.Format(LocalizationHelper.GetString("RemoteControlCompletedTask"), type, id); - Application.Current.Dispatcher.Invoke(() => - { - Instances.TaskQueueViewModel.AddLog(stopLogStr); - }); - break; - } + Application.Current.Dispatcher.Invoke(() => + { + Instances.TaskQueueViewModel.AddLog(startLogStr); + Instances.TaskQueueViewModel.LinkStart(); + }); + await _runningState.UntilIdleAsync(); + + var stopLogStr = string.Format(LocalizationHelper.GetString("RemoteControlCompletedTask"), type, id); + Application.Current.Dispatcher.Invoke(() => + { + Instances.TaskQueueViewModel.AddLog(stopLogStr); + }); + break; + } case "LinkStart-Base": case "LinkStart-WakeUp": @@ -275,66 +278,64 @@ namespace MaaWpfGui.Services.RemoteControl case "LinkStart-Mission": case "LinkStart-AutoRoguelike": case "LinkStart-ReclamationAlgorithm": - { - await LinkStart(new[] { type.Split('-')[1] }); - break; - } + { + await LinkStart(new[] { type.Split('-')[1] }); + break; + } case "Toolbox-GachaOnce": - { - await _runningState.UntilIdleAsync(); - Instances.RecognizerViewModel.GachaOnce(); - while (!Instances.RecognizerViewModel.GachaDone) { - await Task.Delay(100); // 暂停100毫秒以避免密集循环 - } + await _runningState.UntilIdleAsync(); + Instances.RecognizerViewModel.GachaOnce(); + while (!Instances.RecognizerViewModel.GachaDone) + { + await Task.Delay(100); // 暂停100毫秒以避免密集循环 + } - break; - } + break; + } case "Toolbox-GachaTenTimes": - { - await _runningState.UntilIdleAsync(); - Instances.RecognizerViewModel.GachaTenTimes(); - while (!Instances.RecognizerViewModel.GachaDone) { - await Task.Delay(100); // 暂停100毫秒以避免密集循环 + await _runningState.UntilIdleAsync(); + Instances.RecognizerViewModel.GachaTenTimes(); + while (!Instances.RecognizerViewModel.GachaDone) + { + await Task.Delay(100); // 暂停100毫秒以避免密集循环 + } + + break; } - break; - } - case "CaptureImage": - { - string errMsg = string.Empty; - bool connected = await Task.Run(() => Instances.AsstProxy.AsstConnect(ref errMsg)); - if (connected) { - var image = Instances.AsstProxy.AsstGetImage(); - if (image == null) + string errMsg = string.Empty; + bool connected = await Task.Run(() => Instances.AsstProxy.AsstConnect(ref errMsg)); + if (connected) { - status = "FAILED"; + var image = Instances.AsstProxy.AsstGetImage(); + if (image == null) + { + status = "FAILED"; + break; + } + + byte[] bytes; + using (MemoryStream stream = new MemoryStream()) + { + PngBitmapEncoder encoder = new PngBitmapEncoder(); + encoder.Frames.Add(BitmapFrame.Create(image)); + encoder.Save(stream); + bytes = stream.ToArray(); + } + + payload = Convert.ToBase64String(bytes); break; } - byte[] bytes; - using (MemoryStream stream = new MemoryStream()) - { - PngBitmapEncoder encoder = new PngBitmapEncoder(); - encoder.Frames.Add(BitmapFrame.Create(image)); - encoder.Save(stream); - bytes = stream.ToArray(); - } - - payload = Convert.ToBase64String(bytes); - break; - } - else - { status = "FAILED"; break; } - } case "Settings-ConnectAddress": // ConfigurationHelper.SetValue(type.Split('-')[1], data); @@ -345,6 +346,7 @@ namespace MaaWpfGui.Services.RemoteControl break; + // ReSharper disable once RedundantEmptySwitchSection default: // 未知的Type统一直接发给MAACore // No! 未知的任务一概不处理 @@ -360,9 +362,9 @@ namespace MaaWpfGui.Services.RemoteControl { user = uid, device = did, - status = status, + status, task = id, - payload = payload, + payload, }); if (response == null) { @@ -385,7 +387,8 @@ namespace MaaWpfGui.Services.RemoteControl /// /// 指定的任务列表。 /// 异步任务,无返回结果。 - public async Task LinkStart(IEnumerable originalNames) + // 这个是不是可以直接做到 TaskQueueViewModel 里面去? + private async Task LinkStart(IEnumerable originalNames) { await _runningState.UntilIdleAsync(); diff --git a/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs b/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs index c115ecf40e..73b3a83481 100644 --- a/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/AnnouncementViewModel.cs @@ -26,7 +26,7 @@ namespace MaaWpfGui.ViewModels.UI /// /// The view model of version update. /// - // 通过 container.Get(); 实例化或获取实例 + // 通过 container.Get(); 实例化或获取实例 // ReSharper disable once ClassNeverInstantiated.Global public class AnnouncementViewModel : Screen { diff --git a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs index 44547c4e64..e5d04ae8b7 100644 --- a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs @@ -38,7 +38,7 @@ namespace MaaWpfGui.ViewModels.UI /// /// The view model of copilot. /// - // 通过 container.Get(); 实例化或获取实例,需要添加 qodana ignore rule + // 通过 container.Get(); 实例化或获取实例 // ReSharper disable once ClassNeverInstantiated.Global public class CopilotViewModel : Screen { diff --git a/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs b/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs index 7d78722388..355738e23e 100644 --- a/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/RecognizerViewModel.cs @@ -604,29 +604,14 @@ namespace MaaWpfGui.ViewModels.UI List> operHave = new List>(); List> operNotHave = new List>(); - string localizedName; - switch (ConfigurationHelper.GetValue(ConfigurationKeys.Localization, string.Empty)) + string localizedName = ConfigurationHelper.GetValue(ConfigurationKeys.Localization, string.Empty) switch { - case "zh-cn": - localizedName = "name"; - break; - - case "ja-jp": - localizedName = "name_jp"; - break; - - case "ko-kr": - localizedName = "name_kr"; - break; - - case "zh-tw": - localizedName = "name_tw"; - break; - - default: - localizedName = "name_en"; - break; - } + "zh-cn" => "name", + "ja-jp" => "name_jp", + "ko-kr" => "name_kr", + "zh-tw" => "name_tw", + _ => "name_en" + }; foreach (JObject operBox in operBoxes.Cast()) { diff --git a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs index eead67838f..79f32322b3 100644 --- a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs @@ -127,12 +127,14 @@ namespace MaaWpfGui.ViewModels.UI public void Sober() { - if (Cheers && Language == PallasLangKey) + if (!Cheers || Language != PallasLangKey) { - ConfigurationHelper.SetValue(ConfigurationKeys.Localization, SoberLanguage); - Hangover = true; - Cheers = false; + return; } + + ConfigurationHelper.SetValue(ConfigurationKeys.Localization, SoberLanguage); + Hangover = true; + Cheers = false; } protected override void OnInitialActivate() @@ -148,11 +150,15 @@ namespace MaaWpfGui.ViewModels.UI #region Remote Control + // UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public async void RemoteControlConnectionTest() { await RemoteControlService.ConnectionTest(); } + // UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void RemoteControlRegenerateDeviceIdentity() { RemoteControlService.RegenerateDeviceIdentity(); @@ -3394,6 +3400,8 @@ namespace MaaWpfGui.ViewModels.UI case DarkModeType.SyncWithOs: ThemeHelper.SwitchToSyncWithOsMode(); break; + default: + throw new ArgumentOutOfRangeException(); } } diff --git a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs index 2f73692316..636023ee9d 100644 --- a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs @@ -406,6 +406,9 @@ namespace MaaWpfGui.ViewModels.UI { AskToRestart(); } +#else + // 跑个空任务避免 async warning + await Task.Run(() => {}); #endif } }