From bae78d87c53e9a75bf21d878c97369a26a68e05a Mon Sep 17 00:00:00 2001 From: zzyyyl Date: Sun, 24 Sep 2023 01:09:52 +0800 Subject: [PATCH 1/3] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E9=83=A8?= =?UTF-8?q?=E5=88=86=20WPF=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MaaWpfGui/Helper/WindowManager.cs | 2 +- src/MaaWpfGui/Main/AsstProxy.cs | 23 ++++++------------- src/MaaWpfGui/Main/Bootstrapper.cs | 19 --------------- src/MaaWpfGui/Models/ResourceUpdater.cs | 7 +++--- .../ViewModels/UI/CopilotViewModel.cs | 16 ++++++------- 5 files changed, 19 insertions(+), 48 deletions(-) diff --git a/src/MaaWpfGui/Helper/WindowManager.cs b/src/MaaWpfGui/Helper/WindowManager.cs index 273a012f1b..50d8ccd70b 100644 --- a/src/MaaWpfGui/Helper/WindowManager.cs +++ b/src/MaaWpfGui/Helper/WindowManager.cs @@ -115,7 +115,7 @@ namespace MaaWpfGui.Helper return false; } - private bool GetConfiguration(out WindowPlacement wp) + private static bool GetConfiguration(out WindowPlacement wp) { wp = default; var jsonStr = ConfigurationHelper.GetValue(ConfigurationKeys.WindowPlacement, string.Empty); diff --git a/src/MaaWpfGui/Main/AsstProxy.cs b/src/MaaWpfGui/Main/AsstProxy.cs index 3e004af57d..65f95f119d 100644 --- a/src/MaaWpfGui/Main/AsstProxy.cs +++ b/src/MaaWpfGui/Main/AsstProxy.cs @@ -618,13 +618,13 @@ namespace MaaWpfGui.Main TimeSpan timeDiff = TimeSpan.Zero; do { - if (sanity_report?.Count() != 2 || !sanity_report[0].Contains("/")) + if (sanity_report?.Length != 2 || !sanity_report[0].Contains("/")) { break; } int[] sanity = sanity_report[0].Split('/').Select(i => Convert.ToInt32(i)).ToArray(); - if (sanity?.Length != 2 || sanity[1] <= 1) + if (sanity.Length != 2 || sanity[1] <= 1) { break; } @@ -1231,7 +1231,7 @@ namespace MaaWpfGui.Main /// /// 连接地址。 /// 是否有效。 - public bool IfPortEstablished(string address) + private static bool IfPortEstablished(string address) { if (string.IsNullOrEmpty(address) || !address.Contains(":")) { @@ -1259,11 +1259,9 @@ namespace MaaWpfGui.Main client.EndConnect(result); return true; } - else - { - client.Close(); - return false; - } + + client.Close(); + return false; } catch (Exception) { @@ -1906,14 +1904,7 @@ namespace MaaWpfGui.Main }; AsstTaskId id = AsstAppendTaskWithEncoding(type, task_params); _latestTaskId[TaskType.Copilot] = id; - if (asst_start) - { - return id != 0 && AsstStart(); - } - else - { - return id != 0; - } + return id != 0 && (!asst_start || AsstStart()); } public bool AsstStartVideoRec(string filename) diff --git a/src/MaaWpfGui/Main/Bootstrapper.cs b/src/MaaWpfGui/Main/Bootstrapper.cs index 4e91392e56..ad612c360b 100644 --- a/src/MaaWpfGui/Main/Bootstrapper.cs +++ b/src/MaaWpfGui/Main/Bootstrapper.cs @@ -227,25 +227,6 @@ namespace MaaWpfGui.Main base.OnExit(e); } - /// - /// 会带参数重启,切换配置等操作会切换回去 - /// - public static void RestartApplication() - { - //// 释放互斥量 - /* - _mutex?.ReleaseMutex(); - _mutex?.Dispose(); - - // 避免 OnExit 时再次释放 - _mutex = null; - */ - - // 有时候软件自重启时 gui.log 会无法正常写入 - Log.CloseAndFlush(); - System.Windows.Forms.Application.Restart(); - } - /// /// 重启,不带参数 /// diff --git a/src/MaaWpfGui/Models/ResourceUpdater.cs b/src/MaaWpfGui/Models/ResourceUpdater.cs index 19d32af627..451382e20d 100644 --- a/src/MaaWpfGui/Models/ResourceUpdater.cs +++ b/src/MaaWpfGui/Models/ResourceUpdater.cs @@ -36,7 +36,7 @@ namespace MaaWpfGui.Models "resource/global/YoStarKR/resource/version.json", }; - private static readonly string MaaDynamicFilesIndex = "resource/dynamic_list.txt"; + private const string MaaDynamicFilesIndex = "resource/dynamic_list.txt"; public enum UpdateResult { @@ -71,7 +71,8 @@ namespace MaaWpfGui.Models { return UpdateResult.Failed; } - else if (ret1 == UpdateResult.Success || ret2 == UpdateResult.Success) + + if (ret1 == UpdateResult.Success || ret2 == UpdateResult.Success) { return UpdateResult.Success; } @@ -145,7 +146,7 @@ namespace MaaWpfGui.Models private static bool _updating; - public static async Task UpdateFileWithETag(string baseUrl, string file, string saveTo) + private static async Task UpdateFileWithETag(string baseUrl, string file, string saveTo) { saveTo = Path.Combine(Environment.CurrentDirectory, saveTo); var url = baseUrl + file; diff --git a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs index 9188031b5e..b899945c48 100644 --- a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs @@ -71,7 +71,7 @@ namespace MaaWpfGui.ViewModels.UI JArray jArray = JArray.Parse(copilotTaskList); foreach (var item in jArray) { - if ((item as JObject).TryGetValue("file_path", out var token) && File.Exists(token.ToString())) + if (((item as JObject)?.TryGetValue("file_path", out var token) ?? false) && File.Exists(token.ToString())) { CopilotItemViewModels.Add(new CopilotItemViewModel((string)item["name"], (string)item["file_path"], (bool)item["is_checked"])); } @@ -593,7 +593,7 @@ namespace MaaWpfGui.ViewModels.UI } } - public void AddCopilotTaskToList(string stage_name) + private void AddCopilotTaskToList(string stage_name) { var jsonPath = $"{CopilotJsonDir}/{stage_name}.json"; @@ -603,6 +603,7 @@ namespace MaaWpfGui.ViewModels.UI } catch (Exception) { + Log.Warning("Failed to create directory {0}", CopilotJsonDir); } try @@ -663,13 +664,10 @@ namespace MaaWpfGui.ViewModels.UI { Application.Current.Dispatcher.InvokeAsync(() => { - for (int i = 0; i < CopilotItemViewModels.Count; i++) + foreach (var item in CopilotItemViewModels.Where(item => item.IsChecked)) { - if (CopilotItemViewModels[i].IsChecked) - { - CopilotItemViewModels[i].IsChecked = false; - break; - } + item.IsChecked = false; + break; } SaveCopilotTask(); @@ -679,7 +677,7 @@ namespace MaaWpfGui.ViewModels.UI /// /// 更新任务顺序 /// - public void CopilotItemIndexChanged() + private void CopilotItemIndexChanged() { Application.Current.Dispatcher.InvokeAsync(() => { From f13e93b04205a426abcfdf6b82c3f29bd309256f Mon Sep 17 00:00:00 2001 From: uye <99072975+ABA2396@users.noreply.github.com> Date: Sun, 24 Sep 2023 13:44:07 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20=E5=BC=80=E6=9C=BA=E8=87=AA=E5=90=AF?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5/=E5=A4=9A=E5=AE=9E=E4=BE=8B=E8=87=AA?= =?UTF-8?q?=E5=90=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix #6474 fix #5721 fix #6291 --- src/MaaWpfGui/Utilities/AutoStart.cs | 32 ++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/MaaWpfGui/Utilities/AutoStart.cs b/src/MaaWpfGui/Utilities/AutoStart.cs index e10d6d34f6..bab40dfa5f 100644 --- a/src/MaaWpfGui/Utilities/AutoStart.cs +++ b/src/MaaWpfGui/Utilities/AutoStart.cs @@ -11,8 +11,9 @@ // but WITHOUT ANY WARRANTY // +using System; using System.Diagnostics; -using Microsoft.Win32; +using System.IO; namespace MaaWpfGui.Utilities { @@ -21,7 +22,17 @@ namespace MaaWpfGui.Utilities /// public static class AutoStart { - private static readonly string fileValue = Process.GetCurrentProcess().MainModule?.FileName; + private static readonly string _fileValue = Process.GetCurrentProcess().MainModule?.FileName; + private static readonly string _uniqueIdentifier = GetUniqueIdentifierFromPath(_fileValue); + + private static readonly string _startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); + private static readonly string _startupShortcutPath = Path.Combine(_startupFolderPath, $"MAA_{_uniqueIdentifier}.lnk"); + + static string GetUniqueIdentifierFromPath(string path) + { + int hash = path.GetHashCode(); + return hash.ToString("X"); + } /// /// Checks whether this program starts up with OS. @@ -31,8 +42,7 @@ namespace MaaWpfGui.Utilities { try { - using var key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", false); - return key.GetValue("MeoAsst") != null; + return File.Exists(_startupShortcutPath); } catch { @@ -49,14 +59,22 @@ namespace MaaWpfGui.Utilities { try { - using var key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (set) { - key.SetValue("MeoAsst", "\"" + fileValue + "\""); + // 创建启动文件夹的快捷方式 + var shell = new IWshRuntimeLibrary.WshShell(); + var shortcut = shell.CreateShortcut(_startupShortcutPath); + shortcut.TargetPath = _fileValue; + shortcut.WorkingDirectory = Path.GetDirectoryName(_fileValue); + shortcut.Save(); } else { - key.DeleteValue("MeoAsst"); + // 删除启动文件夹的快捷方式 + if (File.Exists(_startupShortcutPath)) + { + File.Delete(_startupShortcutPath); + } } return set == CheckStart(); From 2f5b58c6f5eeea751fc3ee40a106fa507f0b12c4 Mon Sep 17 00:00:00 2001 From: uye <99072975+ABA2396@users.noreply.github.com> Date: Sun, 24 Sep 2023 13:48:51 +0800 Subject: [PATCH 3/3] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E9=83=A8?= =?UTF-8?q?=E5=88=86=20WPF=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MAA.sln.DotSettings | 4 + src/MaaWpfGui/Helper/ConfigurationHelper.cs | 1 + src/MaaWpfGui/MaaWpfGui.csproj | 12 ++ src/MaaWpfGui/Main/AsstProxy.cs | 4 +- src/MaaWpfGui/Models/ResourceUpdater.cs | 25 ++-- .../ServerChanNotificationProvider.cs | 3 + .../ViewModels/CopilotItemViewModel.cs | 69 ++--------- .../ViewModels/UI/CopilotViewModel.cs | 70 +++++++---- .../ViewModels/UI/SettingsViewModel.cs | 113 ++++++++---------- .../ViewModels/UI/TaskQueueViewModel.cs | 5 +- .../ViewModels/UI/VersionUpdateViewModel.cs | 2 +- .../ConnectSettingsOnWakeUpUserControl.xaml | 2 +- 12 files changed, 142 insertions(+), 168 deletions(-) diff --git a/MAA.sln.DotSettings b/MAA.sln.DotSettings index ec9bfce50c..012b9d3acd 100644 --- a/MAA.sln.DotSettings +++ b/MAA.sln.DotSettings @@ -8,12 +8,15 @@ True True True + True + True True True True True True True + True True True True @@ -27,5 +30,6 @@ True True True + True True True \ No newline at end of file diff --git a/src/MaaWpfGui/Helper/ConfigurationHelper.cs b/src/MaaWpfGui/Helper/ConfigurationHelper.cs index 7b2cd8f9a6..1c8ee2c676 100644 --- a/src/MaaWpfGui/Helper/ConfigurationHelper.cs +++ b/src/MaaWpfGui/Helper/ConfigurationHelper.cs @@ -157,6 +157,7 @@ namespace MaaWpfGui.Helper /// /// The configuration key. /// The return value of . + // ReSharper disable once UnusedMember.Global public static bool DeleteValue(string key) { lock (_lock) diff --git a/src/MaaWpfGui/MaaWpfGui.csproj b/src/MaaWpfGui/MaaWpfGui.csproj index ac241134ef..5e63b070fd 100644 --- a/src/MaaWpfGui/MaaWpfGui.csproj +++ b/src/MaaWpfGui/MaaWpfGui.csproj @@ -41,6 +41,18 @@ + + + + tlbimp + 0 + 1 + f935dc20-1cf0-11d0-adb9-00c04fd58a0b + 0 + false + true + + diff --git a/src/MaaWpfGui/Main/AsstProxy.cs b/src/MaaWpfGui/Main/AsstProxy.cs index 65f95f119d..895a62d768 100644 --- a/src/MaaWpfGui/Main/AsstProxy.cs +++ b/src/MaaWpfGui/Main/AsstProxy.cs @@ -1909,11 +1909,11 @@ namespace MaaWpfGui.Main public bool AsstStartVideoRec(string filename) { - var task_params = new JObject + var taskParams = new JObject { ["filename"] = filename, }; - AsstTaskId id = AsstAppendTaskWithEncoding("VideoRecognition", task_params); + AsstTaskId id = AsstAppendTaskWithEncoding("VideoRecognition", taskParams); _latestTaskId[TaskType.Copilot] = id; return id != 0 && AsstStart(); } diff --git a/src/MaaWpfGui/Models/ResourceUpdater.cs b/src/MaaWpfGui/Models/ResourceUpdater.cs index 451382e20d..b0e81b1616 100644 --- a/src/MaaWpfGui/Models/ResourceUpdater.cs +++ b/src/MaaWpfGui/Models/ResourceUpdater.cs @@ -9,11 +9,11 @@ using Stylet; namespace MaaWpfGui.Models { - public class ResourceUpdater + public static class ResourceUpdater { private const string MaaResourceApi = "https://ota.maa.plus/MaaAssistantArknights/MaaAssistantArknights/"; - private static readonly List MaaSingleFiles = new List + private static readonly List _maaSingleFiles = new List { "resource/Arknights-Tile-Pos/overview.json", "resource/battle_data.json", @@ -63,8 +63,8 @@ namespace MaaWpfGui.Models { _updating = false; - var ret1 = await updateSingleFiles(); - var ret2 = await updateFilesWithIndex(); + var ret1 = await UpdateSingleFiles(); + var ret2 = await UpdateFilesWithIndex(); ETagCache.Save(); if (ret1 == UpdateResult.Failed || ret2 == UpdateResult.Failed) @@ -80,11 +80,11 @@ namespace MaaWpfGui.Models return UpdateResult.NotModified; } - private static async Task updateSingleFiles() + private static async Task UpdateSingleFiles() { UpdateResult ret = UpdateResult.NotModified; - foreach (var file in MaaSingleFiles) + foreach (var file in _maaSingleFiles) { var sRet = await UpdateFileWithETag(MaaResourceApi, file, file); @@ -104,7 +104,7 @@ namespace MaaWpfGui.Models // 地图文件、掉落材料的图片、基建技能图片 // 这些文件数量不固定,需要先获取索引文件,再根据索引文件下载 - private static async Task updateFilesWithIndex() + private static async Task UpdateFilesWithIndex() { var indexSRet = await UpdateFileWithETag(MaaResourceApi, MaaDynamicFilesIndex, MaaDynamicFilesIndex); if (indexSRet == UpdateResult.Failed || indexSRet == UpdateResult.NotModified) @@ -115,7 +115,12 @@ namespace MaaWpfGui.Models var ret = UpdateResult.NotModified; var context = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, MaaDynamicFilesIndex)); - context.Split('\n').ToList().ForEach(async file => + context.Split('\n').ToList().ForEach(Action); + + return ret; + + // lambda 避免使用异步,任何未被 lambda 处理的异常都可能导致进程崩溃 + async void Action(string file) { if (string.IsNullOrEmpty(file)) { @@ -139,9 +144,7 @@ namespace MaaWpfGui.Models { ret = UpdateResult.Success; } - }); - - return ret; + } } private static bool _updating; diff --git a/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs b/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs index fa72faf301..dffb5cea2d 100644 --- a/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs +++ b/src/MaaWpfGui/Services/Notification/ServerChanNotificationProvider.cs @@ -68,10 +68,13 @@ namespace MaaWpfGui.Services.Notification private class ServerChanPostContent { + // 这两个没用过,不知道有没有用,之后再看看 [JsonPropertyName("title")] + // ReSharper disable once UnusedAutoPropertyAccessor.Local public string Title { get; set; } [JsonPropertyName("desp")] + // ReSharper disable once UnusedAutoPropertyAccessor.Local public string Content { get; set; } } } diff --git a/src/MaaWpfGui/ViewModels/CopilotItemViewModel.cs b/src/MaaWpfGui/ViewModels/CopilotItemViewModel.cs index 07fc2e22d7..4252d5b2b2 100644 --- a/src/MaaWpfGui/ViewModels/CopilotItemViewModel.cs +++ b/src/MaaWpfGui/ViewModels/CopilotItemViewModel.cs @@ -13,32 +13,20 @@ namespace MaaWpfGui.ViewModels /// isChecked public CopilotItemViewModel(string name, string filePath, bool isChecked = true) { - _name = name; - _filePath = filePath; + Name = name; + FilePath = filePath; _isChecked = isChecked; } - private string _filePath; + /// + /// Gets the original_name. + /// + public string FilePath { get; } /// - /// Gets or sets the original_name. + /// Gets the name. /// - public string FilePath - { - get => _filePath; - set => SetAndNotify(ref _filePath, value); - } - - private string _name; - - /// - /// Gets or sets the name. - /// - public string Name - { - get => _name; - set => SetAndNotify(ref _name, value); - } + public string Name { get; } private bool _isChecked; @@ -55,51 +43,12 @@ namespace MaaWpfGui.ViewModels } } - // 换成图标的话要这个,暂时没用 - private string _iconPath; - - /// - /// Gets or sets the icon path. - /// - // ReSharper disable once UnusedMember.Global - public string IconPath - { - get => _iconPath; - set => SetAndNotify(ref _iconPath, value); - } - - private string _token; - - /// - /// Gets or sets the token. - /// - // ReSharper disable once UnusedMember.Global - public string Token - { - get => _token; - set => SetAndNotify(ref _token, value); - } - - private string _runStatus; - - /// - /// Gets or sets the running status. - /// - // ReSharper disable once UnusedMember.Global - public string RunStatus - { - get => _runStatus; - set => SetAndNotify(ref _runStatus, value); - } - - private int _index = 0; + private int _index; public int Index { get => _index; set => SetAndNotify(ref _index, value); } - - public int GetIndex() => Index; } } diff --git a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs index b899945c48..e81833b616 100644 --- a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs @@ -66,19 +66,21 @@ namespace MaaWpfGui.ViewModels.UI _runningState.IdleChanged += RunningState_IdleChanged; var copilotTaskList = ConfigurationHelper.GetValue(ConfigurationKeys.CopilotTaskList, string.Empty); - if (!string.IsNullOrEmpty(copilotTaskList)) + if (string.IsNullOrEmpty(copilotTaskList)) { - JArray jArray = JArray.Parse(copilotTaskList); - foreach (var item in jArray) - { - if (((item as JObject)?.TryGetValue("file_path", out var token) ?? false) && File.Exists(token.ToString())) - { - CopilotItemViewModels.Add(new CopilotItemViewModel((string)item["name"], (string)item["file_path"], (bool)item["is_checked"])); - } - } - - CopilotItemIndexChanged(); + return; } + + JArray jArray = JArray.Parse(copilotTaskList); + foreach (var item in jArray) + { + if (((JObject)item).TryGetValue("file_path", out var token) && File.Exists(token.ToString())) + { + CopilotItemViewModels.Add(new CopilotItemViewModel((string)item["name"], (string)item["file_path"], (bool)item["is_checked"])); + } + } + + CopilotItemIndexChanged(); } private void RunningState_IdleChanged(object sender, bool e) @@ -570,32 +572,36 @@ namespace MaaWpfGui.ViewModels.UI private const string CopilotJsonDir = "cache/copilot"; + //UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void AddCopilotTask() { - var stage_name = CopilotTaskName.Trim().Replace("突袭", "-Adverse"); - if (!stage_name.IsNullOrEmpty()) + var stageName = CopilotTaskName.Trim().Replace("突袭", "-Adverse"); + if (!stageName.IsNullOrEmpty()) { - AddCopilotTaskToList(stage_name); + AddCopilotTaskToList(stageName); } } + //UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void AddCopilotTask_Adverse() { - var stage_name = CopilotTaskName.Trim().Replace("突袭", "-Adverse"); - if (!stage_name.EndsWith("-Adverse")) + var stageName = CopilotTaskName.Trim().Replace("突袭", "-Adverse"); + if (!stageName.EndsWith("-Adverse")) { - stage_name += "-Adverse"; + stageName += "-Adverse"; } - if (!stage_name.IsNullOrEmpty()) + if (!stageName.IsNullOrEmpty()) { - AddCopilotTaskToList(stage_name); + AddCopilotTaskToList(stageName); } } - private void AddCopilotTaskToList(string stage_name) + private void AddCopilotTaskToList(string stageName) { - var jsonPath = $"{CopilotJsonDir}/{stage_name}.json"; + var jsonPath = $"{CopilotJsonDir}/{stageName}.json"; try { @@ -603,17 +609,18 @@ namespace MaaWpfGui.ViewModels.UI } catch (Exception) { - Log.Warning("Failed to create directory {0}", CopilotJsonDir); + // ignored } try { if (jsonPath != (IsDataFromWeb ? TempCopilotFile : Filename)) - {// 相同路径跳拷贝 + { + // 相同路径跳拷贝 File.Copy(IsDataFromWeb ? TempCopilotFile : Filename, jsonPath, true); } - var item = new CopilotItemViewModel(stage_name, jsonPath) + var item = new CopilotItemViewModel(stageName, jsonPath) { Index = CopilotItemViewModels.Count, }; @@ -638,12 +645,16 @@ namespace MaaWpfGui.ViewModels.UI ConfigurationHelper.SetValue(ConfigurationKeys.CopilotTaskList, JsonConvert.SerializeObject(jArray)); } + //UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void DeleteCopilotTask(int index) { CopilotItemViewModels.RemoveAt(index); CopilotItemIndexChanged(); } + //UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void CleanUnableCopilotTask() { foreach (var item in CopilotItemViewModels.Where(model => !model.IsChecked).ToList()) @@ -654,6 +665,8 @@ namespace MaaWpfGui.ViewModels.UI CopilotItemIndexChanged(); } + //UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void ClearCopilotTask() { CopilotItemViewModels.Clear(); @@ -664,9 +677,14 @@ namespace MaaWpfGui.ViewModels.UI { Application.Current.Dispatcher.InvokeAsync(() => { - foreach (var item in CopilotItemViewModels.Where(item => item.IsChecked)) + foreach (var model in CopilotItemViewModels) { - item.IsChecked = false; + if (!model.IsChecked) + { + continue; + } + + model.IsChecked = false; break; } diff --git a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs index baab5b1ecb..bf6e0a936f 100644 --- a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs @@ -152,6 +152,8 @@ namespace MaaWpfGui.ViewModels.UI #region External Notifications + // UI 绑定的方法 + // ReSharper disable once UnusedMember.Global public void ExternalNotificationSendTest() { ExternalNotificationService.Send( @@ -160,7 +162,7 @@ namespace MaaWpfGui.ViewModels.UI true); } - public List ExternalNotificationProviders => new List + public static List ExternalNotificationProviders => new List { new CombinedData { Display = LocalizationHelper.GetString("Off"), Value = "Off" }, new CombinedData { Display = "Server Chan", Value = "ServerChan" }, @@ -560,7 +562,9 @@ namespace MaaWpfGui.ViewModels.UI } } - public void AccountSwitchMannualRun() + // UI 绑定的方法 + // ReSharper disable once UnusedMember.Global + public void AccountSwitchManualRun() { Instances.TaskQueueViewModel.QuickSwitchAccount(); } @@ -968,33 +972,34 @@ namespace MaaWpfGui.ViewModels.UI // This allows for SQL injection, but since it is not on a real database nothing horrible would happen. // The following query string does what I want, but WMI does not accept it. // var wmiQueryString = string.Format("SELECT ProcessId, CommandLine FROM Win32_Process WHERE ExecutablePath='{0}'", adbPath); - var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process"; - using (var searcher = new ManagementObjectSearcher(wmiQueryString)) - using (var results = searcher.Get()) - { - var query = from p in Process.GetProcesses() - join mo in results.Cast() + const string WmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process"; + using var searcher = new ManagementObjectSearcher(WmiQueryString); + using var results = searcher.Get(); + var query = from p in Process.GetProcesses() + join mo in results.Cast() on p.Id equals (int)(uint)mo["ProcessId"] - select new - { - Process = p, - Path = (string)mo["ExecutablePath"], - }; - foreach (var item in query) + select new + { + Process = p, + Path = (string)mo["ExecutablePath"], + }; + foreach (var item in query) + { + if (item.Path != adbPath) { - if (item.Path == adbPath) - { - // Some emulators start their adb with administrator privilege. - // Not sure if this is necessary - try - { - item.Process.Kill(); - item.Process.WaitForExit(); - } - catch - { - } - } + continue; + } + + // Some emulators start their adb with administrator privilege. + // Not sure if this is necessary + try + { + item.Process.Kill(); + item.Process.WaitForExit(); + } + catch + { + // ignored } } } @@ -1598,7 +1603,7 @@ namespace MaaWpfGui.ViewModels.UI ConfigurationHelper.SetValue(ConfigurationKeys.RoguelikeMode, value); // 烧开水模式可选项 - this.RoguelikeStartWithEliteTwoEnable = mapRoguelikeStartWithEliteTwoEnable(value); + this.RoguelikeStartWithEliteTwoEnable = MapRoguelikeStartWithEliteTwoEnable(value); } } @@ -1661,7 +1666,7 @@ namespace MaaWpfGui.ViewModels.UI public ObservableCollection RoguelikeCoreCharList { get => _roguelikeCoreCharList; - set => SetAndNotify(ref _roguelikeCoreCharList, value); + private set => SetAndNotify(ref _roguelikeCoreCharList, value); } private string _roguelikeStartWithEliteTwo = ConfigurationHelper.GetValue(ConfigurationKeys.RoguelikeStartWithEliteTwo, false.ToString()); @@ -1674,7 +1679,7 @@ namespace MaaWpfGui.ViewModels.UI get => bool.Parse(_roguelikeStartWithEliteTwo); set { - if (value == true && RoguelikeUseSupportUnit == true) + if (value && RoguelikeUseSupportUnit) { RoguelikeUseSupportUnit = false; } @@ -1684,7 +1689,7 @@ namespace MaaWpfGui.ViewModels.UI } } - private string _roguelikeStartWithEliteTwoEnable = mapRoguelikeStartWithEliteTwoEnable(ConfigurationHelper.GetValue(ConfigurationKeys.RoguelikeMode, "0")); + private string _roguelikeStartWithEliteTwoEnable = MapRoguelikeStartWithEliteTwoEnable(ConfigurationHelper.GetValue(ConfigurationKeys.RoguelikeMode, "0")); public string RoguelikeStartWithEliteTwoEnable { @@ -1699,14 +1704,9 @@ namespace MaaWpfGui.ViewModels.UI } } - private static string mapRoguelikeStartWithEliteTwoEnable(string mode) + private static string MapRoguelikeStartWithEliteTwoEnable(string mode) { - if (mode == "4") - { - return "Visible"; - } - - return "Collapsed"; + return mode == "4" ? "Visible" : "Collapsed"; } private string _roguelikeUseSupportUnit = ConfigurationHelper.GetValue(ConfigurationKeys.RoguelikeUseSupportUnit, false.ToString()); @@ -1719,7 +1719,7 @@ namespace MaaWpfGui.ViewModels.UI get => bool.Parse(_roguelikeUseSupportUnit); set { - if (value == true && RoguelikeStartWithEliteTwo == true) + if (value && RoguelikeStartWithEliteTwo) { RoguelikeStartWithEliteTwo = false; } @@ -2720,9 +2720,9 @@ namespace MaaWpfGui.ViewModels.UI /// /// RegisterKey of Bluestacks_Nxt /// - public static string BluestacksNxtRegistryKey = @"SOFTWARE\BlueStacks_nxt"; + private const string BluestacksNxtRegistryKey = @"SOFTWARE\BlueStacks_nxt"; - public static string BluestacksNxtValueName = "UserDefinedDir"; + private const string BluestacksNxtValueName = "UserDefinedDir"; /// /// Refreshes ADB config. @@ -2795,7 +2795,7 @@ namespace MaaWpfGui.ViewModels.UI /// Get the path of bluestacks.conf /// /// path - public static string GetBluestacksConfig() + private static string GetBluestacksConfig() { var conf = ConfigurationHelper.GetValue(ConfigurationKeys.BluestacksConfigPath, string.Empty); if (!string.IsNullOrEmpty(conf)) @@ -2803,16 +2803,11 @@ namespace MaaWpfGui.ViewModels.UI return conf; } - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(BluestacksNxtRegistryKey)) + using RegistryKey key = Registry.LocalMachine.OpenSubKey(BluestacksNxtRegistryKey); + object value = key?.GetValue(BluestacksNxtValueName); + if (value != null) { - if (key != null) - { - object value = key.GetValue(BluestacksNxtValueName); - if (value != null) - { - return (string)value + "\\bluestacks.conf"; - } - } + return (string)value + "\\bluestacks.conf"; } return null; @@ -3576,19 +3571,11 @@ namespace MaaWpfGui.ViewModels.UI return true; } - var wine_list = new[] { "酒", "drink", "wine", "beer", "술", "🍷", "🍸", "🍺", "🍻", "🥃", "🍶" }; - foreach (var wine in wine_list) - { - if (CreditFirstList.Contains(wine)) - { - return true; - } - } - - return false; + var wineList = new[] { "酒", "drink", "wine", "beer", "술", "🍷", "🍸", "🍺", "🍻", "🥃", "🍶" }; + return wineList.Any(wine => CreditFirstList.Contains(wine)); } - public void UpdateRoguelikeSquadList() + private void UpdateRoguelikeSquadList() { var roguelikeSquad = RoguelikeSquad; @@ -3665,7 +3652,7 @@ namespace MaaWpfGui.ViewModels.UI _roguelikeSquad = RoguelikeSquadList.Any(x => x.Value == roguelikeSquad) ? roguelikeSquad : string.Empty; } - public void UpdateRoguelikeCoreCharList() + private void UpdateRoguelikeCoreCharList() { var filePath = $"resource/roguelike/{RoguelikeTheme}/recruitment.json"; if (File.Exists(filePath) is false) diff --git a/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs b/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs index 90127bc6fb..9c7761f493 100644 --- a/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs @@ -977,9 +977,6 @@ namespace MaaWpfGui.ViewModels.UI AddLog(LocalizationHelper.GetString("AdbReplacementTips"), UiLogColor.Info); } - string errMsg = string.Empty; - bool connected = await Task.Run(() => Instances.AsstProxy.AsstConnect(ref errMsg)); - // 一般是点了“停止”按钮了 if (Stopping) { @@ -1190,7 +1187,7 @@ namespace MaaWpfGui.ViewModels.UI Instances.SettingsViewModel.CreditForceShoppingIfCreditFull); } - private bool AppendAward() + private static bool AppendAward() { var receiveAward = Instances.SettingsViewModel.ReceiveAward; var receiveMail = Instances.SettingsViewModel.ReceiveMail; diff --git a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs index abb6225760..98db4dd43b 100644 --- a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs @@ -449,7 +449,7 @@ namespace MaaWpfGui.ViewModels.UI /// 检查更新,并下载更新包。 /// /// 操作成功返回 ,反之则返回 - public async Task CheckAndDownloadVersionUpdate() + private async Task CheckAndDownloadVersionUpdate() { var checkResult = await CheckUpdateInner(); diff --git a/src/MaaWpfGui/Views/UserControl/ConnectSettingsOnWakeUpUserControl.xaml b/src/MaaWpfGui/Views/UserControl/ConnectSettingsOnWakeUpUserControl.xaml index 83e382604b..b6a402b8a5 100644 --- a/src/MaaWpfGui/Views/UserControl/ConnectSettingsOnWakeUpUserControl.xaml +++ b/src/MaaWpfGui/Views/UserControl/ConnectSettingsOnWakeUpUserControl.xaml @@ -34,7 +34,7 @@ VerticalAlignment="Bottom" hc:BorderElement.CornerRadius="0,4,4,0" BorderThickness="0,1,1,1" - Command="{s:Action AccountSwitchMannualRun}" + Command="{s:Action AccountSwitchManualRun}" Content="{DynamicResource AccountSwitchManualRun}" />