diff --git a/src/MaaWpfGui/Configuration/ConfigFactory.cs b/src/MaaWpfGui/Configuration/ConfigFactory.cs
index deb298dee4..e0b5af8893 100644
--- a/src/MaaWpfGui/Configuration/ConfigFactory.cs
+++ b/src/MaaWpfGui/Configuration/ConfigFactory.cs
@@ -131,7 +131,8 @@ namespace MaaWpfGui.Configuration
};
}
- private static Root Root => _rootConfig.Value;
+ // ReSharper disable once MemberCanBePrivate.Global
+ public static Root Root => _rootConfig.Value;
public static readonly SpecificConfig CurrentConfig = Root.CurrentConfig;
diff --git a/src/MaaWpfGui/Helper/MessageBoxHelper.cs b/src/MaaWpfGui/Helper/MessageBoxHelper.cs
index 221506952a..0f0144b8c3 100644
--- a/src/MaaWpfGui/Helper/MessageBoxHelper.cs
+++ b/src/MaaWpfGui/Helper/MessageBoxHelper.cs
@@ -206,6 +206,10 @@ namespace MaaWpfGui.Helper
config.mainIcon = iconInfo.hIcon.DangerousGetHandle();
config.dwFlags |= ComCtl32.TASKDIALOG_FLAGS.TDF_USE_HICON_MAIN;
break;
+ case MessageBoxImage.None:
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(icon), icon, null);
}
bool hasOk = false, hasCancel = false, hasYes = false, hasNo = false;
diff --git a/src/MaaWpfGui/Helper/ThemeHelper.cs b/src/MaaWpfGui/Helper/ThemeHelper.cs
index 5e9a47ba23..526089ab03 100644
--- a/src/MaaWpfGui/Helper/ThemeHelper.cs
+++ b/src/MaaWpfGui/Helper/ThemeHelper.cs
@@ -98,12 +98,9 @@ namespace MaaWpfGui.Helper
public static string Color2HexString(Color color, bool keepAlpha = false)
{
- if (keepAlpha)
- {
- return $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}";
- }
-
- return $"#FF{color.R:X2}{color.G:X2}{color.B:X2}";
+ return keepAlpha
+ ? $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}"
+ : $"#FF{color.R:X2}{color.G:X2}{color.B:X2}";
}
// ReSharper disable once UnusedMember.Global
diff --git a/src/MaaWpfGui/Helper/ToastNotification.cs b/src/MaaWpfGui/Helper/ToastNotification.cs
index 5c2b730b68..c615c87f3a 100644
--- a/src/MaaWpfGui/Helper/ToastNotification.cs
+++ b/src/MaaWpfGui/Helper/ToastNotification.cs
@@ -64,27 +64,29 @@ namespace MaaWpfGui.Helper
/// The toast system is initialized.
public bool CheckToastSystem()
{
- if (!_systemToastCheckInited)
+ if (_systemToastCheckInited)
{
- _systemToastCheckInited = true;
-
- // like "Microsoft Windows 10.0.10240 "
- var osDesc = RuntimeInformation.OSDescription;
- Regex versionRegex = new Regex(@"\d+\.\d+\.\d+");
- var matched = versionRegex.Match(osDesc);
- if (!matched.Success)
- {
- _systemToastChecked = false;
- return _systemToastChecked;
- }
-
- var osVersion = matched.Groups[0].Value;
- bool verParsed = SemVersion.TryParse(osVersion, SemVersionStyles.Strict, out var curVersionObj);
-
- var minimumVersionObj = new SemVersion(10, 0, 10240);
- _systemToastChecked = verParsed && curVersionObj.CompareSortOrderTo(minimumVersionObj) >= 0;
+ return _systemToastChecked;
}
+ _systemToastCheckInited = true;
+
+ // like "Microsoft Windows 10.0.10240 "
+ var osDesc = RuntimeInformation.OSDescription;
+ Regex versionRegex = new Regex(@"\d+\.\d+\.\d+");
+ var matched = versionRegex.Match(osDesc);
+ if (!matched.Success)
+ {
+ _systemToastChecked = false;
+ return _systemToastChecked;
+ }
+
+ var osVersion = matched.Groups[0].Value;
+ bool verParsed = SemVersion.TryParse(osVersion, SemVersionStyles.Strict, out var curVersionObj);
+
+ var minimumVersionObj = new SemVersion(10, 0, 10240);
+ _systemToastChecked = verParsed && curVersionObj.CompareSortOrderTo(minimumVersionObj) >= 0;
+
return _systemToastChecked;
}
@@ -543,7 +545,6 @@ namespace MaaWpfGui.Helper
///
/// 闪烁信息
///
- // ReSharper disable once InconsistentNaming
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "NotAccessedField.Local")]
private struct FLASHWINFO
diff --git a/src/MaaWpfGui/Helper/WinAdapter.cs b/src/MaaWpfGui/Helper/WinAdapter.cs
index 993d9686c7..cf6ef36cbb 100644
--- a/src/MaaWpfGui/Helper/WinAdapter.cs
+++ b/src/MaaWpfGui/Helper/WinAdapter.cs
@@ -11,6 +11,7 @@
// but WITHOUT ANY WARRANTY
//
+using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@@ -41,29 +42,29 @@ namespace MaaWpfGui.Helper
{
"BlueStacks", new List
{
- ".\\HD-Adb.exe",
- ".\\Engine\\ProgramFiles\\HD-Adb.exe",
+ @".\HD-Adb.exe",
+ @".\Engine\ProgramFiles\HD-Adb.exe",
}
},
- { "LDPlayer", new List { ".\\adb.exe" } },
- { "Nox", new List { ".\\nox_adb.exe" } },
+ { "LDPlayer", new List {@".\adb.exe"} },
+ { "Nox", new List {@".\nox_adb.exe"} },
{
"MuMuEmulator", new List
{
- "..\\vmonitor\\bin\\adb_server.exe",
- "..\\..\\MuMu\\emulator\\nemu\\vmonitor\\bin\\adb_server.exe",
- ".\\adb.exe",
+ @"..\vmonitor\bin\adb_server.exe",
+ @"..\..\MuMu\emulator\nemu\vmonitor\bin\adb_server.exe",
+ @".\adb.exe",
}
},
{
"MuMuEmulator12", new List
{
- "..\\vmonitor\\bin\\adb_server.exe",
- "..\\..\\MuMu\\emulator\\nemu\\vmonitor\\bin\\adb_server.exe",
- ".\\adb.exe",
+ @"..\vmonitor\bin\adb_server.exe",
+ @"..\..\MuMu\emulator\nemu\vmonitor\bin\adb_server.exe",
+ @".\adb.exe",
}
},
- { "XYAZ", new List { ".\\adb.exe" } },
+ { "XYAZ", new List { @".\adb.exe" } },
};
private readonly Dictionary _adbAbsolutePathDict = new Dictionary();
@@ -104,12 +105,9 @@ namespace MaaWpfGui.Helper
/// The ADB path of the emulator.
public string GetAdbPathByEmulatorName(string emulatorName)
{
- if (_adbAbsolutePathDict.Keys.Contains(emulatorName))
- {
- return _adbAbsolutePathDict[emulatorName];
- }
-
- return null;
+ return _adbAbsolutePathDict.Keys.Contains(emulatorName)
+ ? _adbAbsolutePathDict[emulatorName]
+ : null;
}
///
@@ -119,26 +117,27 @@ namespace MaaWpfGui.Helper
/// The list of ADB addresses.
public List GetAdbAddresses(string adbPath)
{
- using Process process = new Process();
- process.StartInfo.FileName = adbPath;
- process.StartInfo.Arguments = "devices";
+ try {
+ 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('\r', '\n');
+ // 禁用操作系统外壳程序
+ 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');
- return
- (from line in outLines
- where !line.StartsWith("List of devices attached")
- && line.Length != 0
- && line.Contains("device")
- select line.Split('\t')[0])
- .ToList();
+ return (from line in outLines where !line.StartsWith("List of devices attached") && line.Length != 0 && line.Contains("device") select line.Split('\t')[0]).ToList();
+ }
+ catch(Exception e)
+ {
+ _logger.Error(e.Message);
+ return new List();
+ }
}
}
}
diff --git a/src/MaaWpfGui/Helper/WindowHandle.cs b/src/MaaWpfGui/Helper/WindowHandle.cs
index f89e3c090d..37bb5ae2dd 100644
--- a/src/MaaWpfGui/Helper/WindowHandle.cs
+++ b/src/MaaWpfGui/Helper/WindowHandle.cs
@@ -19,13 +19,11 @@ namespace MaaWpfGui.Helper
{
public struct WindowHandle
{
- private IntPtr _handle;
+ public IntPtr Handle { get; private set; }
- public IntPtr Handle => _handle;
+ public static WindowHandle None => new WindowHandle() { Handle = IntPtr.Zero };
- public static WindowHandle None => new WindowHandle() { _handle = IntPtr.Zero };
-
- public static implicit operator WindowHandle(IntPtr h) => new WindowHandle() { _handle = h };
+ public static implicit operator WindowHandle(IntPtr h) => new WindowHandle() { Handle = h };
public static implicit operator WindowHandle(Window w)
{
@@ -35,7 +33,7 @@ namespace MaaWpfGui.Helper
}
var interop = new WindowInteropHelper(w);
- return new WindowHandle { _handle = interop.Handle };
+ return new WindowHandle { Handle = interop.Handle };
}
}
}
diff --git a/src/MaaWpfGui/Main/AsstProxy.cs b/src/MaaWpfGui/Main/AsstProxy.cs
index 43bf6d8125..c98c0f0232 100644
--- a/src/MaaWpfGui/Main/AsstProxy.cs
+++ b/src/MaaWpfGui/Main/AsstProxy.cs
@@ -38,17 +38,10 @@ using static MaaWpfGui.Helper.Instances.Data;
namespace MaaWpfGui.Main
{
-#pragma warning disable SA1135 // Using directives should be qualified
-
using AsstHandle = IntPtr;
using AsstInstanceOptionKey = Int32;
-
using AsstTaskId = Int32;
-#pragma warning restore SA1135 // Using directives should be qualified
-
-#pragma warning disable SA1121 // Use built-in type alias
-
///
/// MaaCore 代理类。
///
@@ -232,7 +225,7 @@ namespace MaaWpfGui.Main
///
~AsstProxy()
{
- if (_handle != IntPtr.Zero)
+ if (_handle != AsstHandle.Zero)
{
AsstDestroy();
}
@@ -273,7 +266,7 @@ namespace MaaWpfGui.Main
static bool LoadResIfExists(string path)
{
- const string Resource = "\\resource";
+ const string Resource = @"\resource";
if (!Directory.Exists(path + Resource))
{
_logger.Warning($"Resource not found: {path + Resource}");
@@ -292,9 +285,9 @@ namespace MaaWpfGui.Main
{
bool loaded = LoadResource();
- _handle = AsstCreateEx(_callback, IntPtr.Zero);
+ _handle = AsstCreateEx(_callback, AsstHandle.Zero);
- if (loaded == false || _handle == IntPtr.Zero)
+ if (loaded == false || _handle == AsstHandle.Zero)
{
Execute.OnUIThreadAsync(() =>
{
@@ -305,9 +298,9 @@ namespace MaaWpfGui.Main
Instances.TaskQueueViewModel.SetInited();
_runningState.SetIdle(true);
- 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");
+ AsstSetInstanceOption(InstanceOptionKey.TouchMode, Instances.SettingsViewModel.TouchMode);
+ AsstSetInstanceOption(InstanceOptionKey.DeploymentWithPause, Instances.SettingsViewModel.DeploymentWithPause ? "1" : "0");
+ AsstSetInstanceOption(InstanceOptionKey.AdbLiteEnabled, Instances.SettingsViewModel.AdbLiteEnabled ? "1" : "0");
// TODO: 之后把这个 OnUIThread 拆出来
// ReSharper disable once AsyncVoidLambda
Execute.OnUIThread(async () =>
@@ -343,14 +336,14 @@ namespace MaaWpfGui.Main
/// The null-terminated string to be checked.
///
/// The function returns the length of the string, in characters.
- /// If is , the function returns 0.
+ /// If is , the function returns 0.
///
[DllImport("ucrtbase.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
- internal static extern int strlen(IntPtr ptr);
+ internal static extern int strlen(AsstHandle ptr);
- private static string PtrToStringCustom(IntPtr ptr, Encoding enc)
+ private static string PtrToStringCustom(AsstHandle ptr, Encoding enc)
{
- if (ptr == IntPtr.Zero)
+ if (ptr == AsstHandle.Zero)
{
return null;
}
@@ -367,7 +360,7 @@ namespace MaaWpfGui.Main
return enc.GetString(bytes);
}
- private void CallbackFunction(int msg, IntPtr jsonBuffer, IntPtr customArg)
+ private void CallbackFunction(int msg, AsstHandle jsonBuffer, AsstHandle customArg)
{
string jsonStr = PtrToStringCustom(jsonBuffer, Encoding.UTF8);
@@ -417,6 +410,10 @@ namespace MaaWpfGui.Main
case AsstMsg.SubTaskExtraInfo:
ProcSubTaskMsg(msg, details);
break;
+ case AsstMsg.SubTaskStopped:
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(msg), msg, null);
}
}
@@ -501,18 +498,20 @@ namespace MaaWpfGui.Main
{
string taskChain = details["taskchain"].ToString();
- if (taskChain == "CloseDown")
+ switch (taskChain)
{
- return;
- }
-
- if (taskChain == "Recruit")
- {
- if (msg == AsstMsg.TaskChainError)
+ case "CloseDown":
+ return;
+ case "Recruit":
{
- Instances.RecognizerViewModel.RecruitInfo = LocalizationHelper.GetString("IdentifyTheMistakes");
- using var toast = new ToastNotification(LocalizationHelper.GetString("IdentifyTheMistakes"));
- toast.Show();
+ if (msg == AsstMsg.TaskChainError)
+ {
+ Instances.RecognizerViewModel.RecruitInfo = LocalizationHelper.GetString("IdentifyTheMistakes");
+ using var toast = new ToastNotification(LocalizationHelper.GetString("IdentifyTheMistakes"));
+ toast.Show();
+ }
+
+ break;
}
}
@@ -558,29 +557,34 @@ namespace MaaWpfGui.Main
}
case AsstMsg.TaskChainStart:
- if (taskChain == "Fight")
+ switch (taskChain)
{
- Instances.TaskQueueViewModel.FightTaskRunning = true;
- }
- else if (taskChain == "Infrast")
- {
- Instances.TaskQueueViewModel.InfrastTaskRunning = true;
+ case "Fight":
+ Instances.TaskQueueViewModel.FightTaskRunning = true;
+ break;
+ case "Infrast":
+ Instances.TaskQueueViewModel.InfrastTaskRunning = true;
+ break;
}
Instances.TaskQueueViewModel.AddLog(LocalizationHelper.GetString("StartTask") + taskChain);
break;
case AsstMsg.TaskChainCompleted:
- if (taskChain == "Infrast")
+ switch (taskChain)
{
- Instances.TaskQueueViewModel.IncreaseCustomInfrastPlanIndex();
- }
- else if (taskChain == "Mall")
- {
- if (Instances.TaskQueueViewModel.Stage != string.Empty && Instances.SettingsViewModel.CreditFightTaskEnabled)
+ case "Infrast":
+ Instances.TaskQueueViewModel.IncreaseCustomInfrastPlanIndex();
+ break;
+ case "Mall":
{
- Instances.SettingsViewModel.LastCreditFightTaskTime = DateTime.UtcNow.ToYjDate().ToFormattedString();
- Instances.TaskQueueViewModel.AddLog(LocalizationHelper.GetString("CompleteTask") + LocalizationHelper.GetString("CreditFight"));
+ if (Instances.TaskQueueViewModel.Stage != string.Empty && Instances.SettingsViewModel.CreditFightTaskEnabled)
+ {
+ Instances.SettingsViewModel.LastCreditFightTaskTime = DateTime.UtcNow.ToYjDate().ToFormattedString();
+ Instances.TaskQueueViewModel.AddLog(LocalizationHelper.GetString("CompleteTask") + LocalizationHelper.GetString("CreditFight"));
+ }
+
+ break;
}
}
@@ -734,10 +738,32 @@ namespace MaaWpfGui.Main
case AsstMsg.SubTaskExtraInfo:
ProcSubTaskExtraInfo(details);
break;
+ case AsstMsg.InternalError:
+ break;
+ case AsstMsg.InitFailed:
+ break;
+ case AsstMsg.ConnectionInfo:
+ break;
+ case AsstMsg.AllTasksCompleted:
+ break;
+ case AsstMsg.TaskChainError:
+ break;
+ case AsstMsg.TaskChainStart:
+ break;
+ case AsstMsg.TaskChainCompleted:
+ break;
+ case AsstMsg.TaskChainExtraInfo:
+ break;
+ case AsstMsg.TaskChainStopped:
+ break;
+ case AsstMsg.SubTaskStopped:
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(msg), msg, null);
}
}
- private void ProcSubTaskError(JObject details)
+ private static void ProcSubTaskError(JObject details)
{
string subTask = details["subtask"].ToString();
@@ -1272,7 +1298,7 @@ namespace MaaWpfGui.Main
}
}
- private void ProcRecruitCalcMsg(JObject details)
+ private static void ProcRecruitCalcMsg(JObject details)
{
Instances.RecognizerViewModel.ProcRecruitMsg(details);
}
@@ -1429,19 +1455,17 @@ namespace MaaWpfGui.Main
// 尝试默认的备选端口
if (!ret && Instances.SettingsViewModel.AutoDetectConnection)
{
- foreach (var address in Instances.SettingsViewModel.DefaultAddress[Instances.SettingsViewModel.ConnectConfig])
+ foreach (var address in Instances.SettingsViewModel.DefaultAddress[Instances.SettingsViewModel.ConnectConfig]
+ .TakeWhile(address => !_runningState.GetIdle()))
{
- if (_runningState.GetIdle())
+ ret = AsstConnect(_handle, Instances.SettingsViewModel.AdbPath, address, Instances.SettingsViewModel.ConnectConfig);
+ if (!ret)
{
- break;
+ continue;
}
- ret = AsstConnect(_handle, Instances.SettingsViewModel.AdbPath, address, Instances.SettingsViewModel.ConnectConfig);
- if (ret)
- {
- Instances.SettingsViewModel.ConnectAddress = address;
- break;
- }
+ Instances.SettingsViewModel.ConnectAddress = address;
+ break;
}
}
@@ -1499,7 +1523,8 @@ namespace MaaWpfGui.Main
private readonly Dictionary _latestTaskId = new Dictionary();
- private JObject SerializeFightTaskParams(string stage, int maxMedicine, int maxStone, int maxTimes, string dropsItemId, int dropsItemQuantity)
+ private static JObject SerializeFightTaskParams(string stage, int maxMedicine, int maxStone, int maxTimes,
+ string dropsItemId, int dropsItemQuantity, bool reportToPenguin = true)
{
var taskParams = new JObject
{
@@ -1507,7 +1532,7 @@ namespace MaaWpfGui.Main
["medicine"] = maxMedicine,
["stone"] = maxStone,
["times"] = maxTimes,
- ["report_to_penguin"] = true,
+ ["report_to_penguin"] = reportToPenguin,
};
if (dropsItemQuantity != 0 && !string.IsNullOrWhiteSpace(dropsItemId))
{
diff --git a/src/MaaWpfGui/Main/Bootstrapper.cs b/src/MaaWpfGui/Main/Bootstrapper.cs
index 51d3e8e22a..b58f18b87c 100644
--- a/src/MaaWpfGui/Main/Bootstrapper.cs
+++ b/src/MaaWpfGui/Main/Bootstrapper.cs
@@ -76,16 +76,16 @@ namespace MaaWpfGui.Main
Directory.CreateDirectory("debug");
}
- string logFilename = "debug/gui.log";
- string logBakFilename = "debug/gui.bak.log";
- if (File.Exists(logFilename) && new FileInfo(logFilename).Length > 4 * 1024 * 1024)
+ const string LogFilename = "debug/gui.log";
+ const string LogBakFilename = "debug/gui.bak.log";
+ if (File.Exists(LogFilename) && new FileInfo(LogFilename).Length > 4 * 1024 * 1024)
{
- if (File.Exists(logBakFilename))
+ if (File.Exists(LogBakFilename))
{
- File.Delete(logBakFilename);
+ File.Delete(LogBakFilename);
}
- File.Move(logFilename, logBakFilename);
+ File.Move(LogFilename, LogBakFilename);
}
// Bootstrap serilog
@@ -93,7 +93,7 @@ namespace MaaWpfGui.Main
.WriteTo.Debug(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] <{ThreadId}><{ThreadName}> {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
- logFilename,
+ LogFilename,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] <{ThreadId}><{ThreadName}> {Message:lj}{NewLine}{Exception}")
.Enrich.FromLogContext()
.Enrich.WithThreadId()
diff --git a/src/MaaWpfGui/Models/StageInfo.cs b/src/MaaWpfGui/Models/StageInfo.cs
index 2ab29f7329..4254a91e63 100644
--- a/src/MaaWpfGui/Models/StageInfo.cs
+++ b/src/MaaWpfGui/Models/StageInfo.cs
@@ -124,30 +124,14 @@ namespace MaaWpfGui.Models
/// Whether stage is open
public bool IsStageOpenOrWillOpen()
{
- if (Activity != null)
- {
- if (!Activity.IsExpired)
- {
- return true;
- }
-
- // expired activity
- if (!Activity.IsResourceCollection)
- {
- return false;
- }
-
- // expired resource activity, check open days
- }
-
- // resource stage
- if (OpenDays != null && OpenDays.Any())
+ // 只有活动会过期且不开放
+ if (Activity == null)
{
return true;
}
- // regular stage, always open
- return true;
+ return !Activity.IsExpired ||
+ Activity.IsResourceCollection;
}
}
}
diff --git a/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs b/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs
index 063ef2b477..bf275c67f3 100644
--- a/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs
+++ b/src/MaaWpfGui/Services/HotKeys/MaaHotKeyManager.cs
@@ -106,7 +106,7 @@ namespace MaaWpfGui.Services.HotKeys
Instances.MaaHotKeyActionHandler.HandleKeyPressed(action);
}
- private Dictionary GetPersistentHotKeys()
+ private static Dictionary GetPersistentHotKeys()
{
var hotKeysString = ConfigurationHelper.GetValue(HotKeyConfigName, null);
@@ -115,7 +115,7 @@ namespace MaaWpfGui.Services.HotKeys
: JsonConvert.DeserializeObject>(hotKeysString);
}
- private Dictionary CreateInitialHotKeys()
+ private static Dictionary CreateInitialHotKeys()
{
var hotKeys = new Dictionary
{
diff --git a/src/MaaWpfGui/Services/StageManager.cs b/src/MaaWpfGui/Services/StageManager.cs
index e75bd501cf..2b04750c7b 100644
--- a/src/MaaWpfGui/Services/StageManager.cs
+++ b/src/MaaWpfGui/Services/StageManager.cs
@@ -103,7 +103,7 @@ namespace MaaWpfGui.Services
}
}
- private string GetClientType()
+ private static string GetClientType()
{
var clientType = ConfigurationHelper.GetValue(ConfigurationKeys.ClientType, string.Empty);
@@ -116,7 +116,7 @@ namespace MaaWpfGui.Services
return clientType;
}
- private JObject LoadLocalStages()
+ private static JObject LoadLocalStages()
{
JObject activity = Instances.MaaApiService.LoadApiCache(StageApi);
return activity;
@@ -142,7 +142,7 @@ namespace MaaWpfGui.Services
return webTimestamp > localTimestamp || !allFileDownloadComplete;
}
- private async Task LoadWebStages()
+ private static async Task LoadWebStages()
{
var clientType = GetClientType();
@@ -355,31 +355,28 @@ namespace MaaWpfGui.Services
{
var builder = new StringBuilder();
var sideStoryFlags = new Dictionary();
- foreach (var item in _stages)
+ foreach (var item in _stages.Where(item => item.Value.IsStageOpen(dayOfWeek)))
{
- if (item.Value.IsStageOpen(dayOfWeek))
+ if (!string.IsNullOrEmpty(item.Value.Activity?.StageName)
+ && !sideStoryFlags.ContainsKey(item.Value.Activity.StageName))
{
- if (!string.IsNullOrEmpty(item.Value.Activity?.StageName)
- && !sideStoryFlags.ContainsKey(item.Value.Activity.StageName))
- {
- DateTime dateTime = DateTime.UtcNow;
- var daysLeftOpen = (item.Value.Activity.UtcExpireTime - dateTime).Days;
- builder.AppendLine(item.Value.Activity.StageName
- + " "
- + LocalizationHelper.GetString("DaysLeftOpen")
- + (daysLeftOpen > 0 ? daysLeftOpen.ToString() : LocalizationHelper.GetString("LessThanOneDay")));
- sideStoryFlags[item.Value.Activity.StageName] = true;
- }
+ DateTime dateTime = DateTime.UtcNow;
+ var daysLeftOpen = (item.Value.Activity.UtcExpireTime - dateTime).Days;
+ builder.AppendLine(item.Value.Activity.StageName
+ + " "
+ + LocalizationHelper.GetString("DaysLeftOpen")
+ + (daysLeftOpen > 0 ? daysLeftOpen.ToString() : LocalizationHelper.GetString("LessThanOneDay")));
+ sideStoryFlags[item.Value.Activity.StageName] = true;
+ }
- if (!string.IsNullOrEmpty(item.Value.Tip))
- {
- builder.AppendLine(item.Value.Tip);
- }
+ if (!string.IsNullOrEmpty(item.Value.Tip))
+ {
+ builder.AppendLine(item.Value.Tip);
+ }
- if (!string.IsNullOrEmpty(item.Value.Drop))
- {
- builder.AppendLine(item.Value.Display + ": " + ItemListHelper.GetItemName(item.Value.Drop));
- }
+ if (!string.IsNullOrEmpty(item.Value.Drop))
+ {
+ builder.AppendLine(item.Value.Display + ": " + ItemListHelper.GetItemName(item.Value.Drop));
}
}
diff --git a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs
index e5d04ae8b7..42242eb35c 100644
--- a/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs
+++ b/src/MaaWpfGui/ViewModels/UI/CopilotViewModel.cs
@@ -385,11 +385,13 @@ namespace MaaWpfGui.ViewModels.UI
_taskType = "Copilot";
}
- if (IsDataFromWeb)
+ if (!IsDataFromWeb)
{
- File.Delete(TempCopilotFile);
- File.WriteAllText(TempCopilotFile, json.ToString());
+ return;
}
+
+ File.Delete(TempCopilotFile);
+ File.WriteAllText(TempCopilotFile, json.ToString());
}
catch (Exception)
{
@@ -797,11 +799,13 @@ namespace MaaWpfGui.ViewModels.UI
bool startAny = false;
foreach (var model in CopilotItemViewModels)
{
- if (model.IsChecked)
+ if (!model.IsChecked)
{
- ret &= Instances.AsstProxy.AsstStartCopilot(model.FilePath, Form, AddTrust, AddUserAdditional, mUserAdditional, UseCopilotList, model.Name.Replace("-Adverse", string.Empty), model.Name.Contains("-Adverse"), _taskType, Loop ? LoopTimes : 1, false);
- startAny = true;
+ continue;
}
+
+ ret &= Instances.AsstProxy.AsstStartCopilot(model.FilePath, Form, AddTrust, AddUserAdditional, mUserAdditional, UseCopilotList, model.Name.Replace("-Adverse", string.Empty), model.Name.Contains("-Adverse"), _taskType, Loop ? LoopTimes : 1, false);
+ startAny = true;
}
ret &= Instances.AsstProxy.AsstStart();
diff --git a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs
index 79f32322b3..19f7cd23ad 100644
--- a/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs
+++ b/src/MaaWpfGui/ViewModels/UI/SettingsViewModel.cs
@@ -412,7 +412,7 @@ namespace MaaWpfGui.ViewModels.UI
DefaultInfrastList = new List
{
- new CombinedData { Display = LocalizationHelper.GetString("UserDefined"), Value = _userDefined },
+ new CombinedData { Display = LocalizationHelper.GetString("UserDefined"), Value = UserDefined },
new CombinedData { Display = LocalizationHelper.GetString("153Time3"), Value = "153_layout_3_times_a_day.json" },
new CombinedData { Display = LocalizationHelper.GetString("243Time3"), Value = "243_layout_3_times_a_day.json" },
new CombinedData { Display = LocalizationHelper.GetString("243Time4"), Value = "243_layout_4_times_a_day.json" },
@@ -525,16 +525,10 @@ namespace MaaWpfGui.ViewModels.UI
new GenericCombinedData { Display = LocalizationHelper.GetString("UpdateCheckStable"), Value = UpdateVersionType.Stable },
};
- var languageList = new List();
- foreach (var pair in LocalizationHelper.SupportedLanguages)
- {
- if (pair.Key == PallasLangKey && !Cheers)
- {
- continue;
- }
-
- languageList.Add(new CombinedData { Display = pair.Value, Value = pair.Key });
- }
+ var languageList = (from pair in LocalizationHelper.SupportedLanguages
+ where pair.Key != PallasLangKey || Cheers
+ select new CombinedData { Display = pair.Value, Value = pair.Key })
+ .ToList();
LanguageList = languageList;
}
@@ -727,28 +721,30 @@ namespace MaaWpfGui.ViewModels.UI
_ => false,
};
- if (enable)
+ if (!enable)
{
- Func func = str switch
- {
- "StartsWithScript" => RunStartCommand,
- "EndsWithScript" => RunEndCommand,
- _ => () => false,
- };
+ return;
+ }
+ Func func = str switch
+ {
+ "StartsWithScript" => RunStartCommand,
+ "EndsWithScript" => RunEndCommand,
+ _ => () => false,
+ };
+
+ Execute.OnUIThread(() => Instances.TaskQueueViewModel.AddLog(
+ LocalizationHelper.GetString("StartTask") + LocalizationHelper.GetString(str)));
+ if (func())
+ {
Execute.OnUIThread(() => Instances.TaskQueueViewModel.AddLog(
- LocalizationHelper.GetString("StartTask") + LocalizationHelper.GetString(str)));
- if (func())
- {
- Execute.OnUIThread(() => Instances.TaskQueueViewModel.AddLog(
- LocalizationHelper.GetString("CompleteTask") + LocalizationHelper.GetString(str)));
- }
- else
- {
- Execute.OnUIThread(() => Instances.TaskQueueViewModel.AddLog(
- LocalizationHelper.GetString("TaskError") + LocalizationHelper.GetString(str),
- UiLogColor.Warning));
- }
+ LocalizationHelper.GetString("CompleteTask") + LocalizationHelper.GetString(str)));
+ }
+ else
+ {
+ Execute.OnUIThread(() => Instances.TaskQueueViewModel.AddLog(
+ LocalizationHelper.GetString("TaskError") + LocalizationHelper.GetString(str),
+ UiLogColor.Warning));
}
}
@@ -1109,12 +1105,9 @@ namespace MaaWpfGui.ViewModels.UI
{
get
{
- foreach (var item in ClientTypeList)
+ foreach (var item in ClientTypeList.Where(item => item.Value == ClientType))
{
- if (item.Value == ClientType)
- {
- return item.Display;
- }
+ return item.Display;
}
return "Unknown Client";
@@ -1375,9 +1368,9 @@ namespace MaaWpfGui.ViewModels.UI
}
}
- private string _defaultInfrast = ConfigurationHelper.GetValue(ConfigurationKeys.DefaultInfrast, _userDefined);
+ private string _defaultInfrast = ConfigurationHelper.GetValue(ConfigurationKeys.DefaultInfrast, UserDefined);
- private static readonly string _userDefined = "user_defined";
+ private const string UserDefined = "user_defined";
///
/// Gets or sets the uses of drones.
@@ -1388,9 +1381,9 @@ namespace MaaWpfGui.ViewModels.UI
set
{
SetAndNotify(ref _defaultInfrast, value);
- if (_defaultInfrast != _userDefined)
+ if (_defaultInfrast != UserDefined)
{
- CustomInfrastFile = "resource\\custom_infrast\\" + value;
+ CustomInfrastFile = @"resource\custom_infrast\" + value;
IsCustomInfrastFileReadOnly = true;
}
else
@@ -1492,7 +1485,7 @@ namespace MaaWpfGui.ViewModels.UI
CustomInfrastFile = dialog.FileName;
}
- DefaultInfrast = _userDefined;
+ DefaultInfrast = UserDefined;
}
private string _customInfrastFile = ConfigurationHelper.GetValue(ConfigurationKeys.CustomInfrastFile, string.Empty);
@@ -2564,6 +2557,8 @@ namespace MaaWpfGui.ViewModels.UI
case VersionUpdateViewModel.CheckUpdateRetT.OnlyGameResourceUpdated:
toastMessage = LocalizationHelper.GetString("GameResourceUpdated");
break;
+ default:
+ throw new ArgumentOutOfRangeException();
}
if (toastMessage != null)
@@ -2854,13 +2849,8 @@ namespace MaaWpfGui.ViewModels.UI
}
else if (addresses.Count > 1)
{
- foreach (var address in addresses)
+ foreach (var address in addresses.Where(address => address != "emulator-5554"))
{
- if (address == "emulator-5554")
- {
- continue;
- }
-
ConnectAddress = address;
break;
}
@@ -2890,7 +2880,7 @@ namespace MaaWpfGui.ViewModels.UI
object value = key?.GetValue(BluestacksNxtValueName);
if (value != null)
{
- return (string)value + "\\bluestacks.conf";
+ return (string)value + @"\bluestacks.conf";
}
return null;
@@ -2921,12 +2911,9 @@ namespace MaaWpfGui.ViewModels.UI
{
var rvm = (RootViewModel)this.Parent;
var connectConfigName = string.Empty;
- foreach (var data in ConnectConfigList)
+ foreach (var data in ConnectConfigList.Where(data => data.Value == ConnectConfig))
{
- if (data.Value == ConnectConfig)
- {
- connectConfigName = data.Display;
- }
+ connectConfigName = data.Display;
}
string prefix = ConfigurationHelper.GetValue(ConfigurationKeys.WindowTitlePrefix, string.Empty);
@@ -2935,10 +2922,10 @@ namespace MaaWpfGui.ViewModels.UI
prefix += " - ";
}
- string officialClientType = "Official";
- string bilibiliClientType = "Bilibili";
+ const string OfficialClientType = "Official";
+ const string BilibiliClientType = "Bilibili";
string jsonPath = "resource/version.json";
- if (!(ClientType == string.Empty || ClientType == officialClientType || ClientType == bilibiliClientType))
+ if (!(ClientType == string.Empty || ClientType == OfficialClientType || ClientType == BilibiliClientType))
{
jsonPath = $"resource/global/{ClientType}/resource/version.json";
}
@@ -2999,29 +2986,27 @@ namespace MaaWpfGui.ViewModels.UI
var allLines = File.ReadAllLines(_bluestacksConfig);
+ // ReSharper disable once InvertIf
if (string.IsNullOrEmpty(_bluestacksKeyWord))
{
foreach (var line in allLines)
{
- if (line.StartsWith("bst.installed_images"))
+ if (!line.StartsWith("bst.installed_images"))
{
- var images = line.Split('"')[1].Split(',');
- _bluestacksKeyWord = "bst.instance." + images[0] + ".status.adb_port";
- break;
+ continue;
}
+
+ var images = line.Split('"')[1].Split(',');
+ _bluestacksKeyWord = "bst.instance." + images[0] + ".status.adb_port";
+ break;
}
}
- foreach (var line in allLines)
- {
- if (line.StartsWith(_bluestacksKeyWord))
- {
- var sp = line.Split('"');
- return "127.0.0.1:" + sp[1];
- }
- }
-
- return null;
+ return (from line in allLines
+ where line.StartsWith(_bluestacksKeyWord)
+ select line.Split('"') into sp
+ select "127.0.0.1:" + sp[1])
+ .FirstOrDefault();
}
public bool IsAdbTouchMode()
@@ -3439,17 +3424,17 @@ namespace MaaWpfGui.ViewModels.UI
Instances.TaskQueueViewModel.ShowInverse = false;
Instances.TaskQueueViewModel.SelectedAllWidth = 90;
break;
-
case InverseClearType.Inverse:
Instances.TaskQueueViewModel.InverseMode = true;
Instances.TaskQueueViewModel.ShowInverse = false;
Instances.TaskQueueViewModel.SelectedAllWidth = 90;
break;
-
case InverseClearType.ClearInverse:
Instances.TaskQueueViewModel.ShowInverse = true;
Instances.TaskQueueViewModel.SelectedAllWidth = TaskQueueViewModel.SelectedAllWidthWhenBoth;
break;
+ default:
+ throw new ArgumentOutOfRangeException();
}
}
}
diff --git a/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs b/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs
index a4828e62a8..323a04f496 100644
--- a/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs
+++ b/src/MaaWpfGui/ViewModels/UI/TaskQueueViewModel.cs
@@ -791,15 +791,16 @@ namespace MaaWpfGui.ViewModels.UI
connected = await Task.Run(() => Instances.AsstProxy.AsstConnect(ref errMsg));
}
- if (!connected)
+ if (connected)
{
- AddLog(errMsg, UiLogColor.Error);
- _runningState.SetIdle(true);
- SetStopped();
- return false;
+ return true;
}
- return true;
+ AddLog(errMsg, UiLogColor.Error);
+ _runningState.SetIdle(true);
+ SetStopped();
+ return false;
+
}
///