diff --git a/MAA.sln.DotSettings b/MAA.sln.DotSettings index ad5e7ea01f..3cc5f38486 100644 --- a/MAA.sln.DotSettings +++ b/MAA.sln.DotSettings @@ -28,6 +28,7 @@ WSA XYAZ True + True True True True @@ -39,21 +40,28 @@ True True True + True True True True + True + True True True + True True True True True + True True True True True + True True + True True True True @@ -62,20 +70,30 @@ True True True + True True + True True + True True True True True + True True True True True True + True + True + True True + True True True True True + True + True True diff --git a/src/MaaWpfGui/Constants/ConfigurationKeys.cs b/src/MaaWpfGui/Constants/ConfigurationKeys.cs index a0d3f386d1..a87b6142e7 100644 --- a/src/MaaWpfGui/Constants/ConfigurationKeys.cs +++ b/src/MaaWpfGui/Constants/ConfigurationKeys.cs @@ -22,7 +22,11 @@ namespace MaaWpfGui.Constants public const string DefaultConfiguration = "Default"; public const string GlobalConfiguration = "Global"; public const string ConfigurationMap = "Configurations"; + + // ReSharper disable once UnusedMember.Global public const string ConfigurationData = "Data"; + + // ReSharper disable once UnusedMember.Global public const string ConfigurationCron = "Cron"; public const string Localization = "GUI.Localization"; @@ -137,7 +141,11 @@ namespace MaaWpfGui.Constants public const string VersionType = "VersionUpdate.VersionType"; public const string UpdateCheck = "VersionUpdate.UpdateCheck"; public const string UpdateAutoCheck = "VersionUpdate.ScheduledUpdateCheck"; + + // 这个已经废弃了,还要留着吗? + // ReSharper disable once UnusedMember.Global public const string UseAria2 = "VersionUpdate.UseAria2"; + public const string AutoDownloadUpdatePackage = "VersionUpdate.AutoDownloadUpdatePackage"; public const string AutoInstallUpdatePackage = "VersionUpdate.AutoInstallUpdatePackage"; diff --git a/src/MaaWpfGui/Constants/UILogColor.cs b/src/MaaWpfGui/Constants/UILogColor.cs index e3ff2b1015..1df990e750 100644 --- a/src/MaaWpfGui/Constants/UILogColor.cs +++ b/src/MaaWpfGui/Constants/UILogColor.cs @@ -59,6 +59,6 @@ namespace MaaWpfGui.Constants public const string Download = "DownloadLogBrush"; // 颜色在MaaWpfGui\Res\Themes中定义 - // Brushs are defined in MaaWpfGui\Res\Themes + // Brush are defined in MaaWpfGui\Res\Themes } } diff --git a/src/MaaWpfGui/Extensions/DateTimeExtension.cs b/src/MaaWpfGui/Extensions/DateTimeExtension.cs index 86f0cfde6c..57c39e3b5a 100644 --- a/src/MaaWpfGui/Extensions/DateTimeExtension.cs +++ b/src/MaaWpfGui/Extensions/DateTimeExtension.cs @@ -53,7 +53,7 @@ namespace MaaWpfGui.Extensions public static bool IsAprilFoolsDay(this DateTime dt) { - return dt.Month == 4 && dt.Day == 1; + return dt is { Month: 4, Day: 1 }; } } } diff --git a/src/MaaWpfGui/Helper/BitmapImageExtensions.cs b/src/MaaWpfGui/Helper/BitmapImageExtensions.cs index d57f03fbc6..70cc0c3dd3 100644 --- a/src/MaaWpfGui/Helper/BitmapImageExtensions.cs +++ b/src/MaaWpfGui/Helper/BitmapImageExtensions.cs @@ -11,7 +11,6 @@ // but WITHOUT ANY WARRANTY // -using System; using System.IO; using System.Linq; using System.Windows.Media.Imaging; @@ -32,24 +31,25 @@ namespace MaaWpfGui.Helper public static byte[] ToBytes(this BitmapImage image) { - byte[] data = new byte[] { }; - if (image != null) + byte[] data = { }; + if (image == null) { - try - { - var encoder = new BmpBitmapEncoder(); - encoder.Frames.Add(BitmapFrame.Create(image)); - using (MemoryStream ms = new MemoryStream()) - { - encoder.Save(ms); - data = ms.ToArray(); - } + return data; + } - return data; - } - catch (Exception) - { - } + try + { + var encoder = new BmpBitmapEncoder(); + encoder.Frames.Add(BitmapFrame.Create(image)); + using MemoryStream ms = new MemoryStream(); + encoder.Save(ms); + data = ms.ToArray(); + + return data; + } + catch + { + // ignored } return data; diff --git a/src/MaaWpfGui/Helper/ConfigurationHelper.cs b/src/MaaWpfGui/Helper/ConfigurationHelper.cs index 1c8ee2c676..1eebe0994b 100644 --- a/src/MaaWpfGui/Helper/ConfigurationHelper.cs +++ b/src/MaaWpfGui/Helper/ConfigurationHelper.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Windows.Input; using MaaWpfGui.Constants; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -76,7 +75,7 @@ namespace MaaWpfGui.Helper hasValue = _kvs.TryGetValue(key, out value); if (hasValue) { - _logger.Information("Read global configuration key {Key} with current configuration value {Value}, configuration hit: {HasValue}, configuration value {Value}", key, value, hasValue, value); + _logger.Information("Read global configuration key {Key} with current configuration value {Value}, configuration hit: {HasValue}, configuration value {Value}", key, value, true, value); SetGlobalValue(key, value); return value; } @@ -224,8 +223,10 @@ namespace MaaWpfGui.Helper if (parsed.ContainsKey(ConfigurationKeys.ConfigurationMap)) { // new version - _kvsMap = parsed[ConfigurationKeys.ConfigurationMap].ToObject>>(); - _current = parsed[ConfigurationKeys.CurrentConfiguration].ToString(); + _kvsMap = parsed[ConfigurationKeys.ConfigurationMap]?.ToObject>>() + ?? new Dictionary>(); + _current = parsed[ConfigurationKeys.CurrentConfiguration]?.ToString() + ?? ConfigurationKeys.DefaultConfiguration; _kvs = _kvsMap[_current]; } else @@ -239,14 +240,9 @@ namespace MaaWpfGui.Helper _kvs = _kvsMap[_current]; } - if (parsed.ContainsKey(ConfigurationKeys.GlobalConfiguration)) - { - _globalKvs = parsed[ConfigurationKeys.GlobalConfiguration].ToObject>(); - } - else - { - _globalKvs = new Dictionary(); - } + _globalKvs = parsed.ContainsKey(ConfigurationKeys.GlobalConfiguration) + ? parsed[ConfigurationKeys.GlobalConfiguration]?.ToObject>() + : new Dictionary(); return true; } diff --git a/src/MaaWpfGui/Helper/ItemListHelper.cs b/src/MaaWpfGui/Helper/ItemListHelper.cs index eb946380fd..fba9fd05e1 100644 --- a/src/MaaWpfGui/Helper/ItemListHelper.cs +++ b/src/MaaWpfGui/Helper/ItemListHelper.cs @@ -78,8 +78,8 @@ namespace MaaWpfGui.Helper public static string GetItemName(string itemId) { - return ArkItems.ContainsKey(itemId) - ? ArkItems[itemId].Name + return ArkItems.TryGetValue(itemId, out var item) + ? item.Name : itemId; } } diff --git a/src/MaaWpfGui/Helper/MessageBoxHelper.cs b/src/MaaWpfGui/Helper/MessageBoxHelper.cs index 0f2fb8b104..221506952a 100644 --- a/src/MaaWpfGui/Helper/MessageBoxHelper.cs +++ b/src/MaaWpfGui/Helper/MessageBoxHelper.cs @@ -33,6 +33,7 @@ namespace MaaWpfGui.Helper /// /// OK text /// + // ReSharper disable once InconsistentNaming public static string OK = "OK"; /// @@ -200,9 +201,9 @@ namespace MaaWpfGui.Helper config.mainIcon = (IntPtr)ComCtl32.TaskDialogIcon.TD_WARNING_ICON; break; case MessageBoxImage.Question: - var iconinfo = new Shell32.SHSTOCKICONINFO() { cbSize = (uint)Marshal.SizeOf() }; - Shell32.SHGetStockIconInfo(Shell32.SHSTOCKICONID.SIID_HELP, Shell32.SHGSI.SHGSI_ICON, ref iconinfo).ThrowIfFailed(); - config.mainIcon = iconinfo.hIcon.DangerousGetHandle(); + var iconInfo = new Shell32.SHSTOCKICONINFO { cbSize = (uint)Marshal.SizeOf() }; + Shell32.SHGetStockIconInfo(Shell32.SHSTOCKICONID.SIID_HELP, Shell32.SHGSI.SHGSI_ICON, ref iconInfo).ThrowIfFailed(); + config.mainIcon = iconInfo.hIcon.DangerousGetHandle(); config.dwFlags |= ComCtl32.TASKDIALOG_FLAGS.TDF_USE_HICON_MAIN; break; } @@ -228,6 +229,8 @@ namespace MaaWpfGui.Helper hasYes = true; hasNo = true; break; + default: + throw new ArgumentOutOfRangeException(nameof(buttons), buttons, null); } if (hasOk) diff --git a/src/MaaWpfGui/Helper/ThemeHelper.cs b/src/MaaWpfGui/Helper/ThemeHelper.cs index 20892a01ff..5e9a47ba23 100644 --- a/src/MaaWpfGui/Helper/ThemeHelper.cs +++ b/src/MaaWpfGui/Helper/ThemeHelper.cs @@ -106,33 +106,33 @@ namespace MaaWpfGui.Helper return $"#FF{color.R:X2}{color.G:X2}{color.B:X2}"; } + // ReSharper disable once UnusedMember.Global public static string Brush2HexString(SolidColorBrush brush, bool keepAlpha = false) { - if (brush != null) - { - return Color2HexString(brush.Color, keepAlpha); - } - - return DefaultHexString; + return brush != null + ? Color2HexString(brush.Color, keepAlpha) + : DefaultHexString; } public static Color String2Color(string str) { - if (!string.IsNullOrWhiteSpace(str)) + if (string.IsNullOrWhiteSpace(str)) { - try + return DefaultColor; + } + + try + { + object obj = ColorConverter.ConvertFromString(str); + if (obj is Color color) { - object obj = ColorConverter.ConvertFromString(str); - if (obj is Color color) - { - return color; - } - } - catch - { - return DefaultColor; + return color; } } + catch + { + return DefaultColor; + } return DefaultColor; } diff --git a/src/MaaWpfGui/Helper/ToastNotification.cs b/src/MaaWpfGui/Helper/ToastNotification.cs index b3461faee4..5c2b730b68 100644 --- a/src/MaaWpfGui/Helper/ToastNotification.cs +++ b/src/MaaWpfGui/Helper/ToastNotification.cs @@ -13,6 +13,7 @@ using System; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Media; using System.Runtime.InteropServices; @@ -42,6 +43,8 @@ namespace MaaWpfGui.Helper /// public class ToastNotification : IDisposable { + // 这玩意有用吗? + // ReSharper disable once UnusedMember.Local private ToastNotification() { if (!CheckToastSystem()) @@ -50,8 +53,8 @@ namespace MaaWpfGui.Helper } } - private static bool _systemToastChecked = false; - private static bool _systemToastCheckInited = false; + private static bool _systemToastChecked; + private static bool _systemToastCheckInited; private static readonly ILogger _logger = Log.ForContext(); @@ -100,13 +103,13 @@ namespace MaaWpfGui.Helper /// /// 应用图标资源 /// - private ImageSource GetAppIcon() + private static ImageSource GetAppIcon() { try { var icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); var imageSource = Imaging.CreateBitmapSourceFromHIcon( - icon.Handle, + icon!.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); @@ -123,7 +126,7 @@ namespace MaaWpfGui.Helper /// /// 通知标题 /// - /// Toast通知,基于 实现,方便管理通知样式。 + /// Toast通知,基于 实现,方便管理通知样式。 /// 建议使用 调用,如果不使用 调用,建议手动调用 方法释放。 /// 在线程中必须使用 Dispatcher.Invoke 相关方法调用。 /// @@ -266,24 +269,24 @@ namespace MaaWpfGui.Helper #region 通知按钮变量 // 左边按钮 - private string _buttonLeftText = null; + private string _buttonLeftText; - private Action _buttonLeftAction = null; + private Action _buttonLeftAction; // 右边按钮 - private string _buttonRightText = null; + private string _buttonRightText; - private Action _buttonRightAction = null; + private Action _buttonRightAction; // 系统按钮 - private string _buttonSystemText = null; + private string _buttonSystemText; /// /// Gets or sets the button system URL. /// public string ButtonSystemUrl { get; set; } = string.Empty; - private bool _buttonSystemEnabled = false; + private bool _buttonSystemEnabled; #endregion 通知按钮变量 @@ -308,6 +311,7 @@ namespace MaaWpfGui.Helper /// 按钮标题 /// 按钮执行方法 /// 返回类本身,可继续调用其它方法 + // ReSharper disable once UnusedMember.Global public ToastNotification AddButtonRight(string text, Action action) { _buttonRightText = text; @@ -403,7 +407,7 @@ namespace MaaWpfGui.Helper { if (CheckToastSystem()) { - Execute.OnUIThread(() => + Execute.OnUIThreadAsync(() => { if (_buttonSystemEnabled) { @@ -539,6 +543,9 @@ namespace MaaWpfGui.Helper /// /// 闪烁信息 /// + // ReSharper disable once InconsistentNaming + [SuppressMessage("ReSharper", "InconsistentNaming")] + [SuppressMessage("ReSharper", "NotAccessedField.Local")] private struct FLASHWINFO { /// @@ -572,6 +579,9 @@ namespace MaaWpfGui.Helper /// /// 闪烁类型。 /// + [SuppressMessage("ReSharper", "InconsistentNaming")] + [SuppressMessage("ReSharper", "IdentifierTypo")] + [SuppressMessage("ReSharper", "UnusedMember.Global")] public enum FlashType : uint { /// diff --git a/src/MaaWpfGui/Helper/WinAdapter.cs b/src/MaaWpfGui/Helper/WinAdapter.cs index 3ca32aeaa1..993d9686c7 100644 --- a/src/MaaWpfGui/Helper/WinAdapter.cs +++ b/src/MaaWpfGui/Helper/WinAdapter.cs @@ -78,19 +78,19 @@ namespace MaaWpfGui.Helper var emulators = new List(); foreach (var process in allProcess) { - if (_emulatorIdDict.Keys.Contains(process.ProcessName)) + if (!_emulatorIdDict.Keys.Contains(process.ProcessName)) { - var emulatorId = _emulatorIdDict[process.ProcessName]; - emulators.Add(emulatorId); - var processPath = process.MainModule.FileName; - foreach (var path in _adbRelativePathDict[emulatorId]) - { - var adbPath = Path.GetDirectoryName(processPath) + "\\" + path; - if (File.Exists(adbPath)) - { - _adbAbsolutePathDict[emulatorId] = adbPath; - } - } + continue; + } + + var emulatorId = _emulatorIdDict[process.ProcessName]; + emulators.Add(emulatorId); + var processPath = process.MainModule?.FileName; + foreach (string adbPath in _adbRelativePathDict[emulatorId] + .Select(path => Path.GetDirectoryName(processPath) + "\\" + path) + .Where(File.Exists)) + { + _adbAbsolutePathDict[emulatorId] = adbPath; } } @@ -119,35 +119,26 @@ namespace MaaWpfGui.Helper /// The list of ADB addresses. public List GetAdbAddresses(string adbPath) { - var addresses = new List(); - using (Process process = new Process()) - { - process.StartInfo.FileName = adbPath; - process.StartInfo.Arguments = "devices"; + using Process process = new Process(); + process.StartInfo.FileName = adbPath; + process.StartInfo.Arguments = "devices"; - // 禁用操作系统外壳程序 - process.StartInfo.UseShellExecute = false; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.RedirectStandardOutput = true; - process.Start(); - var output = process.StandardOutput.ReadToEnd(); - _logger.Information(adbPath + " devices | output:\n" + output); - var outLines = output.Split(new[] { '\r', '\n' }); - foreach (var line in outLines) - { - if (line.StartsWith("List of devices attached") || - line.Length == 0 || - !line.Contains("device")) - { - continue; - } + // 禁用操作系统外壳程序 + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.RedirectStandardOutput = true; + process.Start(); + var output = process.StandardOutput.ReadToEnd(); + _logger.Information(adbPath + " devices | output:\n" + output); + var outLines = output.Split('\r', '\n'); - var address = line.Split('\t')[0]; - addresses.Add(address); - } - } - - return addresses; + return + (from line in outLines + where !line.StartsWith("List of devices attached") + && line.Length != 0 + && line.Contains("device") + select line.Split('\t')[0]) + .ToList(); } } } diff --git a/src/MaaWpfGui/Helper/WindowManager.cs b/src/MaaWpfGui/Helper/WindowManager.cs index 50d8ccd70b..b6ae54845d 100644 --- a/src/MaaWpfGui/Helper/WindowManager.cs +++ b/src/MaaWpfGui/Helper/WindowManager.cs @@ -41,16 +41,18 @@ namespace MaaWpfGui.Helper /// /// Center other windows in MaaWpfGui.RootView /// - private void MoveWindowToDisplay(Window window) + private static void MoveWindowToDisplay(Window window) { var mainWindow = Application.Current.MainWindow; - if (mainWindow.WindowState == WindowState.Normal) + if (!(mainWindow is { WindowState: WindowState.Normal })) { - // In Stylet, CreateWindow().WindowStartupLocation is CenterScreen or CenterOwner (if w.WSLoc == Manual && w.Left == NaN && w.Top == NaN && ...) - window.WindowStartupLocation = WindowStartupLocation.Manual; - window.Left = mainWindow!.Left + ((mainWindow.Width - window.Width) / 2); - window.Top = mainWindow.Top + ((mainWindow.Height - window.Height) / 2); + return; } + + // In Stylet, CreateWindow().WindowStartupLocation is CenterScreen or CenterOwner (if w.WSLoc == Manual && w.Left == NaN && w.Top == NaN && ...) + window.WindowStartupLocation = WindowStartupLocation.Manual; + window.Left = mainWindow!.Left + ((mainWindow.Width - window.Width) / 2); + window.Top = mainWindow.Top + ((mainWindow.Height - window.Height) / 2); } /// @@ -72,8 +74,14 @@ namespace MaaWpfGui.Helper { window.Closing += (s, e) => { - GetWindowPlacement(window, out WindowPlacement wp); - SetConfiguration(wp); + if (!GetWindowPlacement(window, out WindowPlacement windowPlacement)) + { + _logger.Error("Failed to get window placement"); + } + if (!SetConfiguration(windowPlacement)) + { + _logger.Error("Failed to save window placement"); + } }; } @@ -82,6 +90,7 @@ namespace MaaWpfGui.Helper window.WindowState = WindowState.Minimized; } + // ReSharper disable once InvertIf if (_minimizeDirectly && _minimizeToTray) { window.ShowInTaskbar = false; @@ -163,38 +172,43 @@ namespace MaaWpfGui.Helper } } - private bool GetWindowPlacement(WindowHandle window, out WindowPlacement wp) + private static bool GetWindowPlacement(WindowHandle window, out WindowPlacement wp) { - if (GetWindowPlacement(window.Handle, out wp)) + if (!GetWindowPlacement(window.Handle, out wp)) { - // get the aero snap position of the window - if (wp.ShowCmd == SwShownormal && GetWindowRect(window.Handle, out Rect rect)) - { - wp.NormalPosition = rect; - - // rect is screen coordinates, wp is workspace coordinates - if (SetWindowPlacement(window.Handle, ref wp) - && GetWindowPlacement(window.Handle, out WindowPlacement currentWp) - && GetWindowRect(window.Handle, out Rect currentRect)) - { - var taskbarWidth = currentRect.Left - currentWp.NormalPosition.Left; - var taskbarHeight = currentRect.Top - currentWp.NormalPosition.Top; - if (taskbarWidth != 0 || taskbarHeight != 0) - { - rect.Left -= taskbarWidth; - rect.Right -= taskbarWidth; - rect.Top -= taskbarHeight; - rect.Bottom -= taskbarHeight; - wp.NormalPosition = rect; - SetWindowPlacement(window.Handle, ref wp); - } - } - } + return false; + } + // get the Aero Snap position of the window + if (wp.ShowCmd != SwShownormal || !GetWindowRect(window.Handle, out Rect rect)) + { return true; } - return false; + wp.NormalPosition = rect; + + // rect is screen coordinates, wp is workspace coordinates + if (!SetWindowPlacement(window.Handle, ref wp) || !GetWindowPlacement(window.Handle, out WindowPlacement currentWp) || !GetWindowRect(window.Handle, out Rect currentRect)) + { + return true; + } + + var taskBarWidth = currentRect.Left - currentWp.NormalPosition.Left; + var taskBarHeight = currentRect.Top - currentWp.NormalPosition.Top; + if (taskBarWidth == 0 && taskBarHeight == 0) + { + return true; + } + + rect.Left -= taskBarWidth; + rect.Right -= taskBarWidth; + rect.Top -= taskBarHeight; + rect.Bottom -= taskBarHeight; + wp.NormalPosition = rect; + SetWindowPlacement(window.Handle, ref wp); + + return true; + } #region Win32 API declarations to set and get window placement diff --git a/src/MaaWpfGui/Main/AsstProxy.cs b/src/MaaWpfGui/Main/AsstProxy.cs index dd78ec5623..271dd8894c 100644 --- a/src/MaaWpfGui/Main/AsstProxy.cs +++ b/src/MaaWpfGui/Main/AsstProxy.cs @@ -295,7 +295,7 @@ namespace MaaWpfGui.Main if (loaded == false || _handle == IntPtr.Zero) { - Execute.OnUIThread(() => + Execute.OnUIThreadAsync(() => { MessageBoxHelper.Show(LocalizationHelper.GetString("ResourceBroken"), LocalizationHelper.GetString("Error"), iconKey: ResourceToken.FatalGeometry, iconBrushKey: ResourceToken.DangerBrush); Application.Current.Shutdown(); @@ -307,6 +307,7 @@ namespace MaaWpfGui.Main this.AsstSetInstanceOption(InstanceOptionKey.TouchMode, Instances.SettingsViewModel.TouchMode); this.AsstSetInstanceOption(InstanceOptionKey.DeploymentWithPause, Instances.SettingsViewModel.DeploymentWithPause ? "1" : "0"); this.AsstSetInstanceOption(InstanceOptionKey.AdbLiteEnabled, Instances.SettingsViewModel.AdbLiteEnabled ? "1" : "0"); + // TODO: 之后把这个 OnUIThread 拆出来 Execute.OnUIThread(async () => { if (Instances.SettingsViewModel.RunDirectly) @@ -324,6 +325,7 @@ namespace MaaWpfGui.Main return; } + // ReSharper disable once InvertIf if (Instances.SettingsViewModel.RunDirectly) { // 重置按钮状态,不影响LinkStart判断 @@ -470,17 +472,20 @@ namespace MaaWpfGui.Main _logger.Warning("Failed to stop Asst"); } + // TODO: 之后把这个 OnUIThread 拆出来 Execute.OnUIThread(async () => { - if (Instances.SettingsViewModel.RetryOnDisconnected) + if (!Instances.SettingsViewModel.RetryOnDisconnected) { - Instances.TaskQueueViewModel.AddLog(LocalizationHelper.GetString("TryToStartEmulator"), UiLogColor.Error); - TaskQueueViewModel.KillEmulator(); - await Task.Delay(3000); - await Instances.TaskQueueViewModel.Stop(); - Instances.TaskQueueViewModel.SetStopped(); - Instances.TaskQueueViewModel.LinkStart(); + return; } + + Instances.TaskQueueViewModel.AddLog(LocalizationHelper.GetString("TryToStartEmulator"), UiLogColor.Error); + TaskQueueViewModel.KillEmulator(); + await Task.Delay(3000); + await Instances.TaskQueueViewModel.Stop(); + Instances.TaskQueueViewModel.SetStopped(); + Instances.TaskQueueViewModel.LinkStart(); }); break; @@ -1382,7 +1387,7 @@ namespace MaaWpfGui.Main return false; } - Execute.OnUIThread(() => + Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification("Auto Reload"); toast.Show(); diff --git a/src/MaaWpfGui/Models/ArkItem.cs b/src/MaaWpfGui/Models/ArkItem.cs index 1b67cd37f9..b76df9d5c0 100644 --- a/src/MaaWpfGui/Models/ArkItem.cs +++ b/src/MaaWpfGui/Models/ArkItem.cs @@ -18,6 +18,7 @@ namespace MaaWpfGui.Models public class ArkItem { [JsonPropertyName("classifyType")] + // ReSharper disable once UnusedMember.Global public string ClassifyType { get; set; } [JsonPropertyName("description")] diff --git a/src/MaaWpfGui/Services/HotKeys/IMaaHotKeyManager.cs b/src/MaaWpfGui/Services/HotKeys/IMaaHotKeyManager.cs index 5ba2bfd580..3b102e2f6f 100644 --- a/src/MaaWpfGui/Services/HotKeys/IMaaHotKeyManager.cs +++ b/src/MaaWpfGui/Services/HotKeys/IMaaHotKeyManager.cs @@ -17,7 +17,7 @@ namespace MaaWpfGui.Services.HotKeys { bool TryRegister(MaaHotKeyAction action, MaaHotKey hotKey); - void Unregister(MaaHotKeyAction action); + void UnRegister(MaaHotKeyAction action); MaaHotKey GetOrNull(MaaHotKeyAction action); } diff --git a/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs b/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs index d5423e640c..4d5a1143fc 100644 --- a/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs +++ b/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs @@ -39,7 +39,7 @@ namespace MaaWpfGui.Services.HotKeys public bool TryRegister(MaaHotKeyAction action, MaaHotKey hotKey) { - InternalUnregister(action); + InternalUnRegister(action); var hotKeyOwner = _actionHotKeyMapping.FirstOrDefault(x => x.Value != null && x.Value.Equals(hotKey)); @@ -70,9 +70,9 @@ namespace MaaWpfGui.Services.HotKeys return true; } - public void Unregister(MaaHotKeyAction action) + public void UnRegister(MaaHotKeyAction action) { - InternalUnregister(action); + InternalUnRegister(action); try { @@ -84,7 +84,7 @@ namespace MaaWpfGui.Services.HotKeys } } - protected void InternalUnregister(MaaHotKeyAction action) + protected void InternalUnRegister(MaaHotKeyAction action) { if (!_actionHotKeyMapping.ContainsKey(action) || _actionHotKeyMapping[action] == null) { @@ -97,7 +97,7 @@ namespace MaaWpfGui.Services.HotKeys public MaaHotKey GetOrNull(MaaHotKeyAction action) { - return _actionHotKeyMapping.ContainsKey(action) ? _actionHotKeyMapping[action] : null; + return _actionHotKeyMapping.TryGetValue(action, out var value) ? value : null; } private void HotKeyManagerPressed(object sender, KeyPressedEventArgs e) @@ -108,11 +108,11 @@ namespace MaaWpfGui.Services.HotKeys private Dictionary GetPersistentHotKeys() { - var hotkeysString = ConfigurationHelper.GetValue(HotKeyConfigName, null); + var hotKeysString = ConfigurationHelper.GetValue(HotKeyConfigName, null); - return hotkeysString is null + return hotKeysString is null ? CreateInitialHotKeys() - : JsonConvert.DeserializeObject>(hotkeysString); + : JsonConvert.DeserializeObject>(hotKeysString); } private Dictionary CreateInitialHotKeys() diff --git a/src/MaaWpfGui/Services/Managers/IMainWindowManager.cs b/src/MaaWpfGui/Services/Managers/IMainWindowManager.cs index efa8ac48c0..5111c68ff3 100644 --- a/src/MaaWpfGui/Services/Managers/IMainWindowManager.cs +++ b/src/MaaWpfGui/Services/Managers/IMainWindowManager.cs @@ -47,15 +47,15 @@ namespace MaaWpfGui.Services.Managers WindowState GetWindowState(); /// - /// Sets whether to minimize to taskbar. + /// Sets whether to minimize to taskBar. /// - /// Whether to minimize to taskbar. - void SetMinimizeToTaskbar(bool shouldMinimizeToTaskbar); + /// Whether to minimize to taskBar. + void SetMinimizeToTaskBar(bool shouldMinimizeToTaskBar); /// /// Get the main window if it is visible. /// - /// The if it is visible, or . + /// The if it is visible, or null. Window GetWindowIfVisible(); } } diff --git a/src/MaaWpfGui/Services/Managers/MainWindowManager.cs b/src/MaaWpfGui/Services/Managers/MainWindowManager.cs index 651d004e13..022646f8fe 100644 --- a/src/MaaWpfGui/Services/Managers/MainWindowManager.cs +++ b/src/MaaWpfGui/Services/Managers/MainWindowManager.cs @@ -19,31 +19,31 @@ using MaaWpfGui.Helper; namespace MaaWpfGui.Services.Managers { /// - public class MainWindowManager : IMainWindowManager + public sealed class MainWindowManager : IMainWindowManager { /// /// Gets the main window object /// - protected static Window MainWindow => Application.Current.MainWindow; + private static Window MainWindow => Application.Current.MainWindow; /// /// Gets or sets a value indicating whether whether minimize to tray. /// - protected bool ShouldMinimizeToTaskbar { get; set; } + private bool ShouldMinimizeToTaskBar { get; set; } /// /// Initializes a new instance of the class. /// public MainWindowManager() { - MainWindow.StateChanged += MainWindow_StateChanged; + MainWindow.StateChanged += MainWindowStateChanged; bool minimizeToTray = Convert.ToBoolean(ConfigurationHelper.GetValue(ConfigurationKeys.MinimizeToTray, bool.FalseString)); - SetMinimizeToTaskbar(minimizeToTray); + SetMinimizeToTaskBar(minimizeToTray); } /// - public virtual void Show() + public void Show() { MainWindow.Show(); MainWindow.WindowState = MainWindow.WindowState = WindowState.Normal; @@ -51,19 +51,19 @@ namespace MaaWpfGui.Services.Managers } /// - public virtual void ForceShow() + public void ForceShow() { ((WindowManager)Instances.WindowManager).ForceShow(MainWindow); } /// - public virtual void Collapse() + public void Collapse() { MainWindow.WindowState = MainWindow.WindowState = WindowState.Minimized; } /// - public virtual void SwitchWindowState() + public void SwitchWindowState() { if (MainWindow.WindowState == WindowState.Minimized) { @@ -76,12 +76,12 @@ namespace MaaWpfGui.Services.Managers } /// - public virtual WindowState GetWindowState() => MainWindow.WindowState; + public WindowState GetWindowState() => MainWindow.WindowState; /// - public virtual void SetMinimizeToTaskbar(bool shouldMinimizeToTaskbar) + public void SetMinimizeToTaskBar(bool shouldMinimizeToTaskBar) { - ShouldMinimizeToTaskbar = shouldMinimizeToTaskbar; + ShouldMinimizeToTaskBar = shouldMinimizeToTaskBar; } /// @@ -89,9 +89,9 @@ namespace MaaWpfGui.Services.Managers /// /// The object that triggered the event. /// The event arguments. - protected virtual void MainWindow_StateChanged(object sender, EventArgs e) + private void MainWindowStateChanged(object sender, EventArgs e) { - if (ShouldMinimizeToTaskbar) + if (ShouldMinimizeToTaskBar) { ChangeVisibility(MainWindow.WindowState != WindowState.Minimized); } @@ -101,7 +101,7 @@ namespace MaaWpfGui.Services.Managers /// Change visibility of the main window /// /// A boolean indicating whether the main window should be visible or hidden. - protected virtual void ChangeVisibility(bool visible) + private static void ChangeVisibility(bool visible) { if (visible) { @@ -115,19 +115,11 @@ namespace MaaWpfGui.Services.Managers } } - public virtual Window GetWindowIfVisible() + public Window GetWindowIfVisible() { - if (MainWindow == null) - { - return null; - } - - if (MainWindow.WindowState == WindowState.Minimized) - { - return null; - } - - if (MainWindow.Visibility != Visibility.Visible) + if (MainWindow == null || + MainWindow.WindowState == WindowState.Minimized || + MainWindow.Visibility != Visibility.Visible) { return null; } diff --git a/src/MaaWpfGui/Services/StageManager.cs b/src/MaaWpfGui/Services/StageManager.cs index 9028f11e04..e75bd501cf 100644 --- a/src/MaaWpfGui/Services/StageManager.cs +++ b/src/MaaWpfGui/Services/StageManager.cs @@ -44,7 +44,7 @@ namespace MaaWpfGui.Services private static readonly ILogger _logger = Log.ForContext(); - // datas + // data private Dictionary _stages; /// @@ -59,7 +59,7 @@ namespace MaaWpfGui.Services await UpdateStageWeb(); if (Instances.TaskQueueViewModel != null) { - Execute.OnUIThread(() => + _ = Execute.OnUIThreadAsync(() => { Instances.TaskQueueViewModel.UpdateDatePrompt(); Instances.TaskQueueViewModel.UpdateStageList(true); @@ -122,26 +122,24 @@ namespace MaaWpfGui.Services return activity; } - private async Task CheckWebUpdate() + private static async Task CheckWebUpdate() { // Check if we need to update from the web - string lastUpdateTimeFile = "lastUpdateTime.json"; - string allFileDownloadCompleteFile = "allFileDownloadComplete.json"; - JObject localLastUpdatedJson = Instances.MaaApiService.LoadApiCache(lastUpdateTimeFile); - JObject allFileDownloadCompleteJson = Instances.MaaApiService.LoadApiCache(allFileDownloadCompleteFile); - JObject webLastUpdatedJson = await Instances.MaaApiService.RequestMaaApiWithCache(lastUpdateTimeFile).ConfigureAwait(false); - if (localLastUpdatedJson != null && webLastUpdatedJson != null) + const string LastUpdateTimeFile = "lastUpdateTime.json"; + const string AllFileDownloadCompleteFile = "allFileDownloadComplete.json"; + JObject localLastUpdatedJson = Instances.MaaApiService.LoadApiCache(LastUpdateTimeFile); + JObject allFileDownloadCompleteJson = Instances.MaaApiService.LoadApiCache(AllFileDownloadCompleteFile); + JObject webLastUpdatedJson = await Instances.MaaApiService.RequestMaaApiWithCache(LastUpdateTimeFile).ConfigureAwait(false); + + if (localLastUpdatedJson?["timestamp"] == null || webLastUpdatedJson?["timestamp"] == null) { - long localTimestamp = localLastUpdatedJson["timestamp"].ToObject(); - long webTimestamp = webLastUpdatedJson["timestamp"].ToObject(); - bool allFileDownloadComplete = allFileDownloadCompleteJson?["allFileDownloadComplete"]?.ToObject() ?? false; - if (webTimestamp <= localTimestamp && allFileDownloadComplete) - { - return false; - } + return true; } - return true; + long localTimestamp = localLastUpdatedJson["timestamp"].ToObject(); + long webTimestamp = webLastUpdatedJson["timestamp"].ToObject(); + bool allFileDownloadComplete = allFileDownloadCompleteJson?["allFileDownloadComplete"]?.ToObject() ?? false; + return webTimestamp > localTimestamp || !allFileDownloadComplete; } private async Task LoadWebStages() @@ -181,7 +179,7 @@ namespace MaaWpfGui.Services var clientType = GetClientType(); - bool isDebugVersion = Marshal.PtrToStringAnsi(AsstGetVersion()).Contains("DEBUG"); + bool isDebugVersion = Marshal.PtrToStringAnsi(AsstGetVersion())!.Contains("DEBUG"); bool curVerParsed = SemVersion.TryParse(Marshal.PtrToStringAnsi(AsstGetVersion()), SemVersionStyles.AllowLowerV, out var curVersionObj); // bool curResourceVerParsed = SemVersion.TryParse( @@ -192,11 +190,6 @@ namespace MaaWpfGui.Services IsResourceCollection = true, }; - static DateTime GetDateTime(JToken keyValuePairs, string key) - => DateTime.ParseExact(keyValuePairs[key].ToString(), - "yyyy/MM/dd HH:mm:ss", - CultureInfo.InvariantCulture).AddHours(-Convert.ToInt32(keyValuePairs?["TimeZone"].ToString() ?? "0")); - if (activity?[clientType] != null) { try @@ -218,7 +211,7 @@ namespace MaaWpfGui.Services // bool minResourceRequiredParsed = SemVersion.TryParse(stageObj?["MinimumResourceRequired"]?.ToString() ?? string.Empty, SemVersionStyles.AllowLowerV, out var minResourceRequiredObj); bool minRequiredParsed = SemVersion.TryParse(stageObj?["MinimumRequired"]?.ToString() ?? string.Empty, SemVersionStyles.AllowLowerV, out var minRequiredObj); - var stageInfo = new StageInfo(); + StageInfo stageInfo; // && (!minResourceRequiredParsed || curResourceVerParsed)) if (isDebugVersion || (curVerParsed && minRequiredParsed)) @@ -227,7 +220,7 @@ namespace MaaWpfGui.Services if (!isDebugVersion) { // &&(!minResourceRequiredParsed || curResourceVersionObj.CompareSortOrderTo(minResourceRequiredObj) < 0) - if (isDebugVersion || curVersionObj.CompareSortOrderTo(minRequiredObj) < 0) + if (curVersionObj.CompareSortOrderTo(minRequiredObj) < 0) { if (!tempStage.ContainsKey(LocalizationHelper.GetString("UnsupportedStages"))) { @@ -236,13 +229,13 @@ namespace MaaWpfGui.Services Display = LocalizationHelper.GetString("UnsupportedStages"), Value = LocalizationHelper.GetString("UnsupportedStages"), Drop = LocalizationHelper.GetString("LowVersion") + '\n' + - LocalizationHelper.GetString("MinimumRequirements") + minRequiredObj.ToString(), + LocalizationHelper.GetString("MinimumRequirements") + minRequiredObj, Activity = new StageActivityInfo() { - Tip = stageObj["Activity"]?["Tip"]?.ToString(), - StageName = stageObj["Activity"]?["StageName"]?.ToString(), - UtcStartTime = GetDateTime(stageObj["Activity"], "UtcStartTime"), - UtcExpireTime = GetDateTime(stageObj["Activity"], "UtcExpireTime"), + Tip = stageObj?["Activity"]?["Tip"]?.ToString(), + StageName = stageObj?["Activity"]?["StageName"]?.ToString(), + UtcStartTime = GetDateTime(stageObj?["Activity"], "UtcStartTime"), + UtcExpireTime = GetDateTime(stageObj?["Activity"], "UtcExpireTime"), }, }; @@ -261,14 +254,14 @@ namespace MaaWpfGui.Services stageInfo = new StageInfo { Display = stageObj?["Display"]?.ToString() ?? string.Empty, - Value = stageObj["Value"].ToString(), + Value = stageObj?["Value"]?.ToString(), Drop = stageObj?["Drop"]?.ToString(), Activity = new StageActivityInfo() { - Tip = stageObj["Activity"]?["Tip"]?.ToString(), - StageName = stageObj["Activity"]?["StageName"]?.ToString(), - UtcStartTime = GetDateTime(stageObj["Activity"], "UtcStartTime"), - UtcExpireTime = GetDateTime(stageObj["Activity"], "UtcExpireTime"), + Tip = stageObj?["Activity"]?["Tip"]?.ToString(), + StageName = stageObj?["Activity"]?["StageName"]?.ToString(), + UtcStartTime = GetDateTime(stageObj?["Activity"], "UtcStartTime"), + UtcExpireTime = GetDateTime(stageObj?["Activity"], "UtcExpireTime"), }, }; @@ -317,6 +310,12 @@ namespace MaaWpfGui.Services } _stages = tempStage; + return; + + static DateTime GetDateTime(JToken keyValuePairs, string key) + => DateTime.ParseExact(keyValuePairs[key].ToString(), + "yyyy/MM/dd HH:mm:ss", + CultureInfo.InvariantCulture).AddHours(-Convert.ToInt32(keyValuePairs["TimeZone"].ToString())); } /// diff --git a/src/MaaWpfGui/Services/TrayIcon.cs b/src/MaaWpfGui/Services/TrayIcon.cs index 9eb88ea5a8..c9fa99832c 100644 --- a/src/MaaWpfGui/Services/TrayIcon.cs +++ b/src/MaaWpfGui/Services/TrayIcon.cs @@ -70,12 +70,12 @@ namespace MaaWpfGui.Services forceShowMenu.Click += ForceShow; MenuItem exitMenu = new MenuItem(LocalizationHelper.GetString("Exit")); - exitMenu.Click += App_exit; - MenuItem[] menuItems = new MenuItem[] { startMenu, stopMenu, switchLangMenu, forceShowMenu, exitMenu }; + exitMenu.Click += AppExit; + MenuItem[] menuItems = { startMenu, stopMenu, switchLangMenu, forceShowMenu, exitMenu }; this._notifyIcon.ContextMenu = new ContextMenu(menuItems); } - private void NotifyIcon_MouseClick(object sender, MouseEventArgs e) + private static void NotifyIcon_MouseClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { @@ -85,7 +85,7 @@ namespace MaaWpfGui.Services Instances.MainWindowManager.SwitchWindowState(); } - private void StartTask(object sender, EventArgs e) + private static void StartTask(object sender, EventArgs e) { // taskQueueViewModel意外为null了是不是也可以考虑Log一下 // 先放个log点方便跟踪 @@ -93,29 +93,29 @@ namespace MaaWpfGui.Services _logger.Information("Tray service task started."); } - private void StopTask(object sender, EventArgs e) + private static void StopTask(object sender, EventArgs e) { Instances.TaskQueueViewModel?.Stop(); _logger.Information("Tray service task stop."); } - private void ForceShow(object sender, EventArgs e) + private static void ForceShow(object sender, EventArgs e) { Instances.MainWindowManager.ForceShow(); - _logger.Information("WindowManager Forceshow."); + _logger.Information("WindowManager ForceShow."); } - private void App_exit(object sender, EventArgs e) + private static void AppExit(object sender, EventArgs e) { - System.Windows.Application.Current.MainWindow.Close(); + System.Windows.Application.Current.MainWindow?.Close(); } - private void App_show(object sender, EventArgs e) + private void AppShow(object sender, EventArgs e) { Instances.MainWindowManager.Show(); } - private void OnNotifyIconDoubleClick(object sender, EventArgs e) + private static void OnNotifyIconDoubleClick(object sender, EventArgs e) { Instances.MainWindowManager.Show(); } diff --git a/src/MaaWpfGui/Styles/Controls/TextBlock.cs b/src/MaaWpfGui/Styles/Controls/TextBlock.cs index 7aab6fb35a..8950f171f2 100644 --- a/src/MaaWpfGui/Styles/Controls/TextBlock.cs +++ b/src/MaaWpfGui/Styles/Controls/TextBlock.cs @@ -24,7 +24,7 @@ namespace MaaWpfGui.Styles.Controls DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBlock), new FrameworkPropertyMetadata(typeof(TextBlock))); } - public static readonly DependencyProperty CustomForegroundProperty = DependencyProperty.Register("CustomForeground", typeof(Brush), typeof(TextBlock), new PropertyMetadata(ThemeHelper.DefaultBrush)); + public static readonly DependencyProperty CustomForegroundProperty = DependencyProperty.Register(nameof(CustomForeground), typeof(Brush), typeof(TextBlock), new PropertyMetadata(ThemeHelper.DefaultBrush)); public Brush CustomForeground { @@ -32,7 +32,7 @@ namespace MaaWpfGui.Styles.Controls set { SetValue(CustomForegroundProperty, value); } } - public static readonly DependencyProperty ForegroundKeyProperty = DependencyProperty.Register("ForegroundKey", typeof(string), typeof(TextBlock), new PropertyMetadata(ThemeHelper.DefaultKey, OnForegroundKeyChanged)); + public static readonly DependencyProperty ForegroundKeyProperty = DependencyProperty.Register(nameof(ForegroundKey), typeof(string), typeof(TextBlock), new PropertyMetadata(ThemeHelper.DefaultKey, OnForegroundKeyChanged)); private static void OnForegroundKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { diff --git a/src/MaaWpfGui/Styles/Properties/AutoScroll.cs b/src/MaaWpfGui/Styles/Properties/AutoScroll.cs index ae5d4782b1..2480e7e56b 100644 --- a/src/MaaWpfGui/Styles/Properties/AutoScroll.cs +++ b/src/MaaWpfGui/Styles/Properties/AutoScroll.cs @@ -29,6 +29,7 @@ namespace MaaWpfGui.Styles.Properties /// /// The instance. /// The property value. + // ReSharper disable once UnusedMember.Global public static bool GetAutoScroll(DependencyObject obj) { return (bool)obj.GetValue(AutoScrollProperty); diff --git a/src/MaaWpfGui/Styles/Properties/ScrollViewerBinding.cs b/src/MaaWpfGui/Styles/Properties/ScrollViewerBinding.cs index e898685a11..7da83ab03b 100644 --- a/src/MaaWpfGui/Styles/Properties/ScrollViewerBinding.cs +++ b/src/MaaWpfGui/Styles/Properties/ScrollViewerBinding.cs @@ -44,6 +44,7 @@ namespace MaaWpfGui.Styles.Properties /// /// The instance. /// The property value. + // ReSharper disable once UnusedMember.Global public static double GetVerticalOffset(DependencyObject depObj) { if (!(depObj is ScrollViewer)) @@ -120,6 +121,7 @@ namespace MaaWpfGui.Styles.Properties /// /// The instance. /// The property value. + // ReSharper disable once UnusedMember.Global public static double GetViewportHeight(DependencyObject depObj) { if (!(depObj is ScrollViewer scrollViewer)) @@ -196,6 +198,7 @@ namespace MaaWpfGui.Styles.Properties /// /// The instance. /// The property value. + // ReSharper disable once UnusedMember.Global public static double GetExtentHeight(DependencyObject depObj) { if (!(depObj is ScrollViewer scrollViewer)) @@ -273,6 +276,7 @@ namespace MaaWpfGui.Styles.Properties /// /// The instance. /// The property value. + // ReSharper disable once UnusedMember.Global public static List GetDividerVerticalOffsetList(DependencyObject depObj) { return (List)depObj.GetValue(DividerVerticalOffsetListProperty); diff --git a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs index d52e4055aa..db93ce1921 100644 --- a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs @@ -535,7 +535,7 @@ namespace MaaWpfGui.ViewModels.UI } } - private string _userAdditional = ConfigurationHelper.GetValue(ConfigurationKeys.CopilotUserAdditional, "W,2;Friston-3,1"); + private string _userAdditional = ConfigurationHelper.GetValue(ConfigurationKeys.CopilotUserAdditional, string.Empty); /// /// Gets or sets a value indicating whether to use auto-formation. @@ -553,7 +553,7 @@ namespace MaaWpfGui.ViewModels.UI /// /// Gets or sets a value indicating whether to use auto-formation. /// - private bool _useCopilotList = false; + private bool _useCopilotList; public bool UseCopilotList { diff --git a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs index 9325c38980..be9cff9f88 100644 --- a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs @@ -761,7 +761,6 @@ namespace MaaWpfGui.ViewModels.UI { string fileName = string.Empty; string arguments = string.Empty; - ProcessStartInfo startInfo; if (Path.GetExtension(EmulatorPath).ToLower() == ".lnk") { @@ -796,14 +795,7 @@ namespace MaaWpfGui.ViewModels.UI arguments = EmulatorAddCommand; } - if (arguments.Length != 0) - { - startInfo = new ProcessStartInfo(fileName, arguments); - } - else - { - startInfo = new ProcessStartInfo(fileName); - } + var startInfo = arguments.Length != 0 ? new ProcessStartInfo(fileName, arguments) : new ProcessStartInfo(fileName); startInfo.UseShellExecute = false; Process process = new Process @@ -2479,14 +2471,14 @@ namespace MaaWpfGui.ViewModels.UI toastMessage = LocalizationHelper.GetString("NewVersionIsBeingBuilt"); break; - case VersionUpdateViewModel.CheckUpdateRetT.OnlyGameReourceUpdated: + case VersionUpdateViewModel.CheckUpdateRetT.OnlyGameResourceUpdated: toastMessage = LocalizationHelper.GetString("GameResourceUpdated"); break; } if (toastMessage != null) { - Execute.OnUIThread(() => + _ = Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification(toastMessage); toast.Show(); @@ -3108,7 +3100,7 @@ namespace MaaWpfGui.ViewModels.UI { SetAndNotify(ref _minimizeToTray, value); ConfigurationHelper.SetValue(ConfigurationKeys.MinimizeToTray, value.ToString()); - Instances.MainWindowManager.SetMinimizeToTaskbar(value); + Instances.MainWindowManager.SetMinimizeToTaskBar(value); } } @@ -3141,7 +3133,7 @@ namespace MaaWpfGui.ViewModels.UI NotifyOfPropertyChange(); if (value) { - Execute.OnUIThread(() => + Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification("Test test"); toast.Show(); @@ -3510,7 +3502,7 @@ namespace MaaWpfGui.ViewModels.UI set => SetHotKey(MaaHotKeyAction.LinkStart, value); } - private void SetHotKey(MaaHotKeyAction action, MaaHotKey value) + private static void SetHotKey(MaaHotKeyAction action, MaaHotKey value) { if (value != null) { @@ -3518,7 +3510,7 @@ namespace MaaWpfGui.ViewModels.UI } else { - Instances.MaaHotKeyManager.Unregister(action); + Instances.MaaHotKeyManager.UnRegister(action); } } diff --git a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs index 57875f6139..a74c0fdb05 100644 --- a/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs +++ b/src/MaaWpfGui/ViewModels/UI/VersionUpdateViewModel.cs @@ -195,7 +195,7 @@ namespace MaaWpfGui.ViewModels.UI return false; } - Execute.OnUIThread(() => + Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification(LocalizationHelper.GetString("NewVersionZipFileFoundTitle")); toast.AppendContentText(LocalizationHelper.GetString("NewVersionZipFileFoundDescDecompressing")) @@ -220,7 +220,7 @@ namespace MaaWpfGui.ViewModels.UI catch (InvalidDataException) { File.Delete(UpdatePackageName); - Execute.OnUIThread(() => + Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification(LocalizationHelper.GetString("NewVersionZipFileBrokenTitle")); toast.AppendContentText(LocalizationHelper.GetString("NewVersionZipFileBrokenDescFilename") + UpdatePackageName) @@ -372,8 +372,10 @@ namespace MaaWpfGui.ViewModels.UI /// NewVersionIsBeingBuilt, - // 只更新了游戏资源 - OnlyGameReourceUpdated, + /// + /// 只更新了游戏资源 + /// + OnlyGameResourceUpdated, } // ReSharper disable once IdentifierTypo @@ -476,7 +478,7 @@ namespace MaaWpfGui.ViewModels.UI } } ); - await Execute.OnUIThreadAsync(() => + _ = Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification((otaFound ? LocalizationHelper.GetString("NewVersionFoundTitle") : LocalizationHelper.GetString("NewVersionFoundButNoPackageTitle")) + " : " + UpdateTag); if (goDownload) @@ -593,7 +595,7 @@ namespace MaaWpfGui.ViewModels.UI else { OutputDownloadProgress(downloading: false, output: LocalizationHelper.GetString("NewVersionDownloadFailedTitle")); - await Execute.OnUIThreadAsync(() => + _ = Execute.OnUIThreadAsync(() => { using var toast = new ToastNotification(LocalizationHelper.GetString("NewVersionDownloadFailedTitle")); toast.ButtonSystemUrl = UpdateUrl;