90 Commits
Author SHA1 Message Date
龙腾猫跃 e5c8e65e2b fix: 当打开中的 Tooltip 改变时,其显示不会动态地改变(Meloong-Git/PCL#8891,@iPodtouch6557) 2026-07-03 14:41:23 +08:00
龙腾猫跃 4309899c79 ICollection.RemoveAll 2026-07-03 14:38:29 +08:00
龙腾猫跃 cf42cf19e3 fix: 无法删除部分文件夹(Meloong-Git/PCL#8878,@Peacock-Que) 2026-07-03 14:15:10 +08:00
龙腾猫跃 c16ef849e6 fix: 特定情况下崩溃:“ToolTip”不能有逻辑或视觉父级(Meloong-Git/PCL#8876,@lactobionicAcid) 2026-07-03 14:05:42 +08:00
龙腾猫跃 1ee19b4023 fix: 鼠标从特定被禁用的控件上移开不会使 Tooltip 消失(Meloong-Git/PCL#8882,@MovTery) 2026-07-03 14:03:18 +08:00
龙腾猫跃 da5069856e impr: 证书验证失败也会被视作网络异常,以给出更有效的错误提示 2026-07-03 13:26:24 +08:00
龙腾猫跃 d3b9ccde9c fix: 首次启动无法创建日志文件夹;Config 使用了错误的锁 2026-07-02 09:33:35 +08:00
龙腾猫跃 473ac94d63 进度传递与测试框架修复 2026-07-01 22:29:54 +08:00
龙腾猫跃 1f91e757c2 * 2026-07-01 07:17:49 +08:00
龙腾猫跃 c18fef7074 Logger.StackTrace 2026-07-01 06:58:01 +08:00
龙腾猫跃 d3daf1988f * 2026-06-29 08:18:44 +08:00
龙腾猫跃 a1fcb5241a PathUtils.IsParentOf 2026-06-29 07:42:59 +08:00
龙腾猫跃 0a3b21505a 健壮性优化 2026-06-28 23:57:37 +08:00
龙腾猫跃 fe9fc04c20 Worker 额外日志、迁移 IsGenericInstanceOf 2026-06-28 23:34:24 +08:00
龙腾猫跃 dbdbfcebd2 worker 和进度相关 2026-06-28 10:49:57 +08:00
龙腾猫跃 93e2f5cde8 RedoableWorker 添加更多 API 2026-06-28 08:54:07 +08:00
龙腾猫跃 8b26dccd22 RedoableWorker 的一些扩展 2026-06-28 08:33:49 +08:00
龙腾猫跃 be802ede2e TaskUtils 的进度支持 2026-06-28 08:00:39 +08:00
龙腾猫跃 251061c8eb Progress 的子项自动兼容 2026-06-28 04:40:49 +08:00
龙腾猫跃 0bdeb20c0e 从 ResilientUtils 迁移到 Retrier 2026-06-26 10:26:29 +08:00
龙腾猫跃 94ef3f8f8e 重新整理 Workers 2026-06-26 09:55:02 +08:00
龙腾猫跃 00b49bc3e3 * 2026-06-26 09:26:10 +08:00
龙腾猫跃 204fc52ba2 改进 Config 的延迟写入 2026-06-26 09:22:32 +08:00
龙腾猫跃 2d811e8f58 ProgressObserver 2026-06-26 08:58:33 +08:00
龙腾猫跃 fc92759a39 为 Config 添加延迟写入 2026-06-26 08:56:56 +08:00
龙腾猫跃 3e579aff79 ProgressProvider.ProgressChanged 2026-06-26 07:54:20 +08:00
龙腾猫跃 e2bb70f70d ProgressProvider 完成 2026-06-26 07:40:36 +08:00
龙腾猫跃 de2014e427 Worker、Progress 优化 2026-06-26 06:42:06 +08:00
龙腾猫跃 093827b853 ProgressProvider 初步 2026-06-26 05:45:32 +08:00
龙腾猫跃 a6d1716044 RedoableWorker 2026-06-26 05:41:58 +08:00
龙腾猫跃 3a34eda3e8 * 2026-06-25 23:47:21 +08:00
龙腾猫跃 6a6b43fe9a 迁移部分方法到 TaskExtensions 2026-06-25 07:30:00 +08:00
龙腾猫跃 1a639fa88f 统一编码 2026-06-23 22:33:22 +08:00
龙腾猫跃 8e87d13d76 重构ConfigEntry<T>的Edit方法以支持引用修改 2026-06-23 19:13:42 +08:00
龙腾猫跃 a1749c7e1e ValueRange 相同判断 2026-06-23 08:55:37 +08:00
龙腾猫跃 d66af3d6cd 取消异常相关 2026-06-23 08:33:17 +08:00
龙腾猫跃 20ed81ed9e * 2026-06-23 06:48:50 +08:00
龙腾猫跃 d4c9adc7ca ref: 让 Rider 编辑器更高兴 2026-06-23 03:44:07 +08:00
龙腾猫跃 907021bdb2 RunProgramAsync 支持取消、TaskUtils.ForEachAsync 2026-06-23 00:40:27 +08:00
龙腾猫跃 b6873fd850 ConfigEntry.Edit 2026-06-22 20:32:02 +08:00
龙腾猫跃 7ce6a6abc0 * 2026-06-22 20:22:22 +08:00
龙腾猫跃 1508b58a9b tooltip 鼠标移出相关修复 2026-06-22 19:18:26 +08:00
龙腾猫跃 ba81428f34 StringUtils.ParseVersionWithDefaults 2026-06-22 18:08:24 +08:00
龙腾猫跃 619aeac2f5 ValueRange.FromString/IsEmpty、StringUtils.ToVersion 2026-06-20 04:46:23 +08:00
龙腾猫跃 ada0032079 添加 ConfigTest 2026-06-19 20:41:40 +08:00
龙腾猫跃 5c44002d5d 新的 Config 存储框架 2026-06-19 20:22:50 +08:00
龙腾猫跃 2515eb5781 Config 序列化调整 2026-06-19 19:49:03 +08:00
龙腾猫跃 9ff4fe1114 Config 的初步实现 2026-06-19 06:27:09 +08:00
龙腾猫跃 f64685b177 AES 加密添加校验位;继续写 Config 2026-06-19 05:56:52 +08:00
龙腾猫跃 7bf59d7f74 AES 对称加解密 2026-06-19 03:15:32 +08:00
龙腾猫跃 fbc7565d7b ECDSA 的完整实现 2026-06-19 01:36:34 +08:00
龙腾猫跃 a42f33a8c1 初步的 Config 实现 2026-06-19 01:23:31 +08:00
龙腾猫跃 d1389396dc 分离 Logger 初始化 2026-06-18 22:11:31 +08:00
龙腾猫跃 966b2db312 迁移部分常用路径 2026-06-18 21:43:27 +08:00
龙腾猫跃 e9cd356f2b * 2026-06-18 20:38:39 +08:00
龙腾猫跃 c3fd315d89 fix: ModernTooltipService 的 ShowOnDisabled 兼容 2026-06-18 19:00:04 +08:00
龙腾猫跃 5979cbd87d 继续优化 ModernTooltipService 2026-06-18 05:11:45 +08:00
龙腾猫跃 212552503e fix: tooltip 触发优先级 2026-06-18 04:22:20 +08:00
龙腾猫跃 4f44549354 fix: Tooltip 在文本区域长按左键时自动收回 2026-06-18 04:09:44 +08:00
龙腾猫跃 3982f92ebf 回滚长按部分 2026-06-18 04:05:12 +08:00
龙腾猫跃 282a779997 ModernTooltipService 优化 2026-06-18 03:52:43 +08:00
龙腾猫跃 7d2d656f23 整理 ModernTooltipService 2026-06-18 03:34:46 +08:00
龙腾猫跃 0208b6c78f 初步添加 ModernToolTipService 2026-06-18 01:48:33 +08:00
龙腾猫跃 3af26fbd3e * 2026-06-17 21:56:08 +08:00
龙腾猫跃 db1b6a5670 Dialogs.SelectFile 支持输入原始过滤器 2026-06-17 05:10:42 +08:00
龙腾猫跃 40d7e83d41 * 2026-06-17 04:15:16 +08:00
龙腾猫跃 934bf1e729 RunProgramAsync 2026-06-15 23:42:36 +08:00
龙腾猫跃 a407618ee1 DeserializeJson<T> 2026-06-15 01:00:23 +08:00
龙腾猫跃 ace30bfa50 ValueRange.Intersect 2026-06-14 23:59:37 +08:00
龙腾猫跃 59337411c0 添加 ValueRange 2026-06-14 21:29:03 +08:00
龙腾猫跃 8bab27236e 迁移部分函数 2026-06-14 20:14:43 +08:00
龙腾猫跃 174b645b4a * 2026-06-14 16:55:10 +08:00
龙腾猫跃 45ada2850c IList.Any 2026-06-14 15:43:29 +08:00
龙腾猫跃 c9e1b15740 支持处理只读文件/文件夹 2026-06-14 01:52:13 +08:00
龙腾猫跃 0b075c97c0 ref: 日志中附带线程 ID 2026-06-14 01:11:15 +08:00
龙腾猫跃 d3b657d725 HttpRequest Clone 相关 2026-06-14 01:01:40 +08:00
龙腾猫跃 d05df2df9b ReadAsJson 2026-06-11 02:13:08 +08:00
龙腾猫跃 9470a6160a FileChecker、DeserializeJson 2026-06-11 00:36:04 +08:00
龙腾猫跃 ec1ad309d8 删除 DES 加密 2026-06-10 19:31:00 +08:00
龙腾猫跃 8ef47830b6 支持读取内嵌的资源 2026-06-10 18:10:06 +08:00
龙腾猫跃 4d389f4375 fix: 文件 IO 不支持相对路径(Meloong-Git/PCL#8691,@DSHADB) 2026-05-24 16:12:10 +08:00
龙腾猫跃 f30c861f6e 若删除到回收站失败,会回退到永久删除 2026-05-21 00:50:52 +08:00
龙腾猫跃 7f70c2e7f7 * 2026-05-21 00:38:29 +08:00
龙腾猫跃 35e6e1e904 对于特定异常会尝试显示更多信息 2026-05-21 00:24:15 +08:00
龙腾猫跃 0f70132452 Merge pull request #13 from Meloong-Git/copilot/modify-resilientutils-exception-types
扩展 ResilientUtils:支持最多 2 种异常类型的重试
2026-05-21 00:05:20 +08:00
copilot-swe-agent[bot]andLTCatt abc020ca0f Add two-exception-type overloads to ResilientUtils
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/e3c21784-1e8f-4a30-920e-5dad98923d73

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-20 15:59:48 +00:00
龙腾猫跃 04e7c56ba7 fix: 当缺少某个文件夹时,GetFolderPath 会返回空字符串,导致安全检查异常(close Meloong-Git/PCL#8636,@qwer154899) 2026-05-20 22:40:24 +08:00
龙腾猫跃 19541cecce GetStableHashCode、DES 加解密 2026-05-20 19:17:40 +08:00
龙腾猫跃 3d91c024e2 * 2026-05-20 17:09:23 +08:00
龙腾猫跃 0b62180d50 ECDSA P-256 签名验证 2026-05-20 16:39:37 +08:00
46 changed files with 2861 additions and 466 deletions

No files matched your search

+13 -2
View File
@@ -1,5 +1,3 @@
using System.Collections.Concurrent;
namespace MeloongCore.Extensions; namespace MeloongCore.Extensions;
public static class EnumerableExtensions { public static class EnumerableExtensions {
@@ -320,6 +318,13 @@ public static class EnumerableExtensions {
foreach (var item in itemsToRemove) source.Remove(item); foreach (var item in itemsToRemove) source.Remove(item);
} }
/// <summary>
/// 从集合中移除另一个集合中的所有元素。
/// </summary>
public static void RemoveAll<T>(this ICollection<T> source, IEnumerable<T> itemsToRemove) {
foreach (var item in itemsToRemove) source.Remove(item);
}
/// <summary> /// <summary>
/// 仅保留满足条件的元素,移除不满足条件的元素。 /// 仅保留满足条件的元素,移除不满足条件的元素。
/// </summary> /// </summary>
@@ -328,6 +333,12 @@ public static class EnumerableExtensions {
foreach (var item in itemsToRemove) source.Remove(item); foreach (var item in itemsToRemove) source.Remove(item);
} }
/// <summary>
/// 从集合中移除指定元素。
/// </summary>
public static IEnumerable<T> Except<T>(this IEnumerable<T> source, T element)
=> source.Except([element]);
/// <summary> /// <summary>
/// 判断集合是否有且仅有一个元素。 /// 判断集合是否有且仅有一个元素。
/// 在输入 null 时返回 false。 /// 在输入 null 时返回 false。
+31 -8
View File
@@ -1,4 +1,4 @@
using System.Net.Sockets; using System.Net.Sockets;
namespace MeloongCore.Extensions; namespace MeloongCore.Extensions;
public static class ExceptionExtensions { public static class ExceptionExtensions {
@@ -11,6 +11,24 @@ public static class ExceptionExtensions {
return ex; return ex;
} }
/// <summary>
/// 该异常或其子异常是否为 <see cref="OperationCanceledException"/>、<see cref="TaskCanceledException"/> 或 <see cref="ThreadInterruptedException"/>。
/// </summary>
public static bool IsCanceled(this Exception ex) {
foreach (var inner in ex.Flatten()) {
if (inner is OperationCanceledException or TaskCanceledException or ThreadInterruptedException) return true;
}
return false;
}
/// <summary>
/// 当该异常或其子异常是 <see cref="OperationCanceledException"/>、<see cref="TaskCanceledException"/> 或 <see cref="ThreadInterruptedException"/> 时,抛出对应异常。
/// </summary>
public static void ThrowIfCanceled(this Exception ex) {
foreach (var inner in ex.Flatten()) {
if (inner is OperationCanceledException or TaskCanceledException or ThreadInterruptedException) throw inner;
}
}
/// <summary> /// <summary>
/// 将异常所有的 <see cref="Exception.InnerException"/> 展开。 /// 将异常所有的 <see cref="Exception.InnerException"/> 展开。
/// 若为 <see cref="AggregateException"/>,也会展开其中所有的子异常。 /// 若为 <see cref="AggregateException"/>,也会展开其中所有的子异常。
@@ -31,24 +49,29 @@ public static class ExceptionExtensions {
/// <summary> /// <summary>
/// 获取 <paramref name="ex"/> 的用户友好描述。 /// 获取 <paramref name="ex"/> 的用户友好描述。
/// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。 /// 若 <paramref name="multiline"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
/// </summary> /// </summary>
public static string GetDisplay(this Exception? ex, bool showMultilineStacks) { public static string GetDisplay(this Exception? ex, bool multiline) {
if (ex is null) return "无可用错误信息!"; if (ex is null) return "无可用错误信息!";
// 提取堆栈信息 // 提取堆栈信息
var lines = new List<string>(); var lines = new List<string>();
bool isInnerException = false; bool isInnerException = false;
static string getExceptionMessage(Exception e) => e.Message + (e switch {
WebException webEx => $" (Status={webEx.Status})",
SocketException socketEx => $" (SocketErrorCode={socketEx.SocketErrorCode})",
_ => ""
});
foreach (var currentEx in ex.Flatten()) { foreach (var currentEx in ex.Flatten()) {
if (showMultilineStacks) { if (multiline) {
lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true)); lines.Add((isInnerException ? "→ " : "") + getExceptionMessage(currentEx).ReplaceLineEndings("\r\n", true));
var stackLines = (currentEx.StackTrace?.SplitLines(true) ?? []) var stackLines = (currentEx.StackTrace?.SplitLines(true) ?? [])
.Select(l => l.BeforeLast("(") + l.AfterLast(")")) .Select(l => l.BeforeLast("(") + l.AfterLast(")"))
.Distinct(); .Distinct();
lines.AddRange(stackLines); lines.AddRange(stackLines);
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName); if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
} else { } else {
lines.Add(currentEx.Message.ReplaceLineEndings(" ", true)); lines.Add(getExceptionMessage(currentEx).ReplaceLineEndings(" ", true));
} }
isInnerException = true; isInnerException = true;
} }
@@ -68,7 +91,7 @@ public static class ExceptionExtensions {
commonReason = "你的网络环境不佳,请稍后再试,或使用 VPN 改善网络环境。"; commonReason = "你的网络环境不佳,请稍后再试,或使用 VPN 改善网络环境。";
// 输出 // 输出
if (showMultilineStacks) { if (multiline) {
if (commonReason is null) { if (commonReason is null) {
return lines.Join("\r\n"); return lines.Join("\r\n");
} else { } else {
@@ -104,7 +127,7 @@ public static class ExceptionExtensions {
} }
if (webEx.Status is WebExceptionStatus.NameResolutionFailure or WebExceptionStatus.ConnectFailure or WebExceptionStatus.ReceiveFailure or if (webEx.Status is WebExceptionStatus.NameResolutionFailure or WebExceptionStatus.ConnectFailure or WebExceptionStatus.ReceiveFailure or
WebExceptionStatus.SendFailure or WebExceptionStatus.ConnectionClosed or WebExceptionStatus.KeepAliveFailure or WebExceptionStatus.Timeout or WebExceptionStatus.SendFailure or WebExceptionStatus.ConnectionClosed or WebExceptionStatus.KeepAliveFailure or WebExceptionStatus.Timeout or
WebExceptionStatus.ProxyNameResolutionFailure) return true; WebExceptionStatus.ProxyNameResolutionFailure or WebExceptionStatus.SecureChannelFailure or WebExceptionStatus.TrustFailure) return true;
} else if (currentEx is SocketException socketEx) { } else if (currentEx is SocketException socketEx) {
if (socketEx.SocketErrorCode is SocketError.NetworkDown or SocketError.NetworkUnreachable or SocketError.NetworkReset or SocketError.ConnectionAborted or if (socketEx.SocketErrorCode is SocketError.NetworkDown or SocketError.NetworkUnreachable or SocketError.NetworkReset or SocketError.ConnectionAborted or
SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostUnreachable or SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostUnreachable or
+43 -18
View File
@@ -1,5 +1,4 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;
namespace MeloongCore.Extensions; namespace MeloongCore.Extensions;
public static class StringExtensions { public static class StringExtensions {
@@ -129,7 +128,7 @@ public static class StringExtensions {
public static string BeforeFirst(this string str, string text, bool ignoreCase = false) { public static string BeforeFirst(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(0, pos); return str[..pos];
} }
/// <summary> /// <summary>
/// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。 /// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
@@ -144,7 +143,7 @@ public static class StringExtensions {
if (p >= 0 && (pos < 0 || pos > p)) pos = p; if (p >= 0 && (pos < 0 || pos > p)) pos = p;
} }
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(0, pos); return str[..pos];
} }
/// <summary> /// <summary>
@@ -154,7 +153,7 @@ public static class StringExtensions {
public static string BeforeLast(this string str, string text, bool ignoreCase = false) { public static string BeforeLast(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(0, pos); return str[..pos];
} }
/// <summary> /// <summary>
/// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。 /// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
@@ -169,7 +168,7 @@ public static class StringExtensions {
if (p >= 0 && (pos < 0 || pos < p)) pos = p; if (p >= 0 && (pos < 0 || pos < p)) pos = p;
} }
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(0, pos); return str[..pos];
} }
/// <summary> /// <summary>
@@ -179,7 +178,7 @@ public static class StringExtensions {
public static string AfterFirst(this string str, string text, bool ignoreCase = false) { public static string AfterFirst(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(pos + text!.Length); return str[(pos + text!.Length)..];
} }
/// <summary> /// <summary>
/// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。 /// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
@@ -198,7 +197,7 @@ public static class StringExtensions {
} }
} }
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(pos + len); return str[(pos + len)..];
} }
/// <summary> /// <summary>
@@ -208,7 +207,7 @@ public static class StringExtensions {
public static string AfterLast(this string str, string text, bool ignoreCase = false) { public static string AfterLast(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(pos + text!.Length); return str[(pos + text!.Length)..];
} }
/// <summary> /// <summary>
/// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。 /// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
@@ -227,7 +226,7 @@ public static class StringExtensions {
} }
} }
if (pos < 0) return str; if (pos < 0) return str;
return str.Substring(pos + len); return str[(pos + len)..];
} }
/// <summary> /// <summary>
@@ -245,9 +244,9 @@ public static class StringExtensions {
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase); int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
if (endPos >= 0) { if (endPos >= 0) {
return str.Substring(startPos, endPos - startPos); return str[startPos..endPos];
} else if (startPos > 0) { } else if (startPos > 0) {
return str.Substring(startPos); return str[startPos..];
} else { } else {
return str; return str;
} }
@@ -332,8 +331,6 @@ public static class StringExtensions {
#endregion #endregion
#region 读取为字符串
/// <summary> /// <summary>
/// 读取 <see cref="Stream"/> 中的内容,并解码为字符串。 /// 读取 <see cref="Stream"/> 中的内容,并解码为字符串。
/// 会将流的位置主动重置到开头。 /// 会将流的位置主动重置到开头。
@@ -367,14 +364,12 @@ public static class StringExtensions {
} }
} }
#endregion
/// <summary> /// <summary>
/// 将第一个字符转换为大写,其余字符转换为小写。 /// 将第一个字符转换为大写,其余字符转换为小写。
/// </summary> /// </summary>
public static string Capitalize(this string word) { public static string Capitalize(this string word) {
if (string.IsNullOrEmpty(word)) return word; if (string.IsNullOrEmpty(word)) return word;
return $"{word.Substring(0, 1).Upper()}{word.Substring(1).Lower()}"; return $"{word[..1].Upper()}{word[1..].Lower()}";
} }
/// <summary> /// <summary>
@@ -383,7 +378,7 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string EnsureLength(this string? str, char code, int length) { public static string EnsureLength(this string? str, char code, int length) {
str ??= ""; str ??= "";
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code); return str.Length > length ? str[..length] : str.PadLeft(length, code);
} }
/// <summary> /// <summary>
@@ -392,4 +387,34 @@ public static class StringExtensions {
public static bool IsAsciiOnly(this string input) public static bool IsAsciiOnly(this string input)
=> input.All(c => c < 128); => input.All(c => c < 128);
/// <summary>
/// 计算字符串的哈希,其结果在不同环境中均能保持一致。
/// </summary>
public static ulong GetStableHashCode(this string str) {
ulong result = 5381;
foreach (char v in str) result = (result << 5) ^ result ^ v;
return result ^ 0xA98F501BC684032FUL;
}
/// <summary>
/// 将字符串转化为 JSON 对象,若失败则抛出异常。
/// </summary>
public static JToken? DeserializeJson(this string data) {
try {
return JsonConvert.DeserializeObject<JToken>(data, new JsonSerializerSettings {DateTimeZoneHandling = DateTimeZoneHandling.Local});
} catch (Exception ex) {
int length = (data ?? "").Length;
throw new FormatException("JSON deserialize failed: " +
(length > 2000
? $"{data![..500]}...(total {length} characters)...{data[^500..]}"
: (data ?? "")),
ex);
}
}
/// <summary>
/// 将字符串转化为 JSON 对象,若失败则抛出异常。
/// </summary>
public static T? DeserializeJson<T>(this string data) where T : JToken
=> (T?) DeserializeJson(data);
} }
+10
View File
@@ -0,0 +1,10 @@
namespace MeloongCore.Extensions;
public static class TaskExtensions {
public static void Run(this Task task) => task.GetAwaiter().GetResult();
public static T Run<T>(this Task<T> task) => task.GetAwaiter().GetResult();
public static ConfiguredTaskAwaitable NoCapture(this Task task) => task.ConfigureAwait(false);
public static ConfiguredTaskAwaitable<T> NoCapture<T>(this Task<T> task) => task.ConfigureAwait(false);
}
+42
View File
@@ -0,0 +1,42 @@
namespace MeloongCore.Extensions;
public static class WebExtensions {
// Source - https://stackoverflow.com/a/46026230, Posted by desautelsj, Retrieved 2026-06-14, License - CC BY-SA 4.0
public static HttpRequestMessage Clone(this HttpRequestMessage request) {
var clone = new HttpRequestMessage(request.Method, request.RequestUri) {
Content = request.Content.Clone(),
Version = request.Version
};
foreach (KeyValuePair<string, object> prop in request.Properties) clone.Properties.Add(prop);
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers) clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
return clone;
}
public static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessage request) {
var clone = new HttpRequestMessage(request.Method, request.RequestUri) {
Content = await request.Content.CloneAsync().NoCapture(),
Version = request.Version
};
foreach (KeyValuePair<string, object> prop in request.Properties) clone.Properties.Add(prop);
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers) clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
return clone;
}
public static HttpContent? Clone(this HttpContent? content) {
if (content == null) return null;
var ms = new MemoryStream();
content.CopyToAsync(ms).Wait();
ms.Position = 0;
var clone = new StreamContent(ms);
foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers) clone.Headers.Add(header.Key, header.Value);
return clone;
}
public static async Task<HttpContent?> CloneAsync(this HttpContent? content) {
if (content == null) return null;
var ms = new MemoryStream();
await content.CopyToAsync(ms).NoCapture();
ms.Position = 0;
var clone = new StreamContent(ms);
foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers) clone.Headers.Add(header.Key, header.Value);
return clone;
}
}
+25 -24
View File
@@ -1,7 +1,8 @@
namespace MeloongCore; namespace MeloongCore;
/// <summary> /// <summary>
/// 使用粗粒度锁的线程安全 <see cref="List{T}"/> 实现。 /// 使用粗粒度锁的线程安全 <see cref="List{T}"/> 实现。
/// 通常建议使用 <see cref="ConcurrentBag{T}"/> 或其他线程安全集合,它们具有更好的性能。
/// </summary> /// </summary>
public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> { public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> {
@@ -11,54 +12,54 @@ public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> {
public ConcurrentList() { } public ConcurrentList() { }
public ConcurrentList(IEnumerable<T> data) => _items = new(data); public ConcurrentList(IEnumerable<T> data) => _items = new(data);
public static implicit operator ConcurrentList<T>(List<T> data) => new(data); public static implicit operator ConcurrentList<T>(List<T> data) => new(data);
public static implicit operator List<T>(ConcurrentList<T> data) { lock (data._syncLock) { return new(data._items); } } public static implicit operator List<T>(ConcurrentList<T> data) { lock (data.SyncRoot) { return new(data._items); } }
// 枚举器 // 枚举器
/// <summary> /// <summary>
/// 返回此列表的副本。 /// 返回此列表的副本。
/// </summary> /// </summary>
public IEnumerator<T> GetEnumerator() { lock (_syncLock) return _items.ToList().GetEnumerator(); } public IEnumerator<T> GetEnumerator() { lock (SyncRoot) return _items.ToList().GetEnumerator(); }
/// <summary> /// <summary>
/// 返回此列表的副本。 /// 返回此列表的副本。
/// </summary> /// </summary>
IEnumerator IEnumerable.GetEnumerator() { lock (_syncLock) return _items.ToList().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { lock (SyncRoot) return _items.ToList().GetEnumerator(); }
// 成员 // 成员
public int Count { get { lock (_syncLock) { return _items.Count; } } } public int Count { get { lock (SyncRoot) { return _items.Count; } } }
public bool IsReadOnly => false; public bool IsReadOnly => false;
bool IList.IsFixedSize => false; bool IList.IsFixedSize => false;
bool ICollection.IsSynchronized => true; bool ICollection.IsSynchronized => true;
private readonly object _syncLock = new(); public readonly object SyncRoot = new();
object ICollection.SyncRoot => _syncLock; object ICollection.SyncRoot => SyncRoot;
public T this[int index] { public T this[int index] {
get { lock (_syncLock) { return _items[index]; } } get { lock (SyncRoot) { return _items[index]; } }
set { lock (_syncLock) { _items[index] = value; } } set { lock (SyncRoot) { _items[index] = value; } }
} }
object? IList.this[int index] { object? IList.this[int index] {
get => this[index]; get => this[index];
set { lock (_syncLock) { _items[index] = (T) value!; } } set { lock (SyncRoot) { _items[index] = (T) value!; } }
} }
public void Add(T item) { lock (_syncLock) { _items.Add(item); } } public void Add(T item) { lock (SyncRoot) { _items.Add(item); } }
int IList.Add(object? value) { lock (_syncLock) { _items.Add((T) value!); return _items.Count - 1; } } int IList.Add(object? value) { lock (SyncRoot) { _items.Add((T) value!); return _items.Count - 1; } }
public void Insert(int index, T item) { lock (_syncLock) { _items.Insert(index, item); } } public void Insert(int index, T item) { lock (SyncRoot) { _items.Insert(index, item); } }
void IList.Insert(int index, object? value) { lock (_syncLock) { _items.Insert(index, (T) value!); } } void IList.Insert(int index, object? value) { lock (SyncRoot) { _items.Insert(index, (T) value!); } }
public bool Remove(T item) { lock (_syncLock) { return _items.Remove(item); } } public bool Remove(T item) { lock (SyncRoot) { return _items.Remove(item); } }
void IList.Remove(object? value) { lock (_syncLock) { if (value is T t) _items.Remove(t); } } void IList.Remove(object? value) { lock (SyncRoot) { if (value is T t) _items.Remove(t); } }
public void RemoveAt(int index) { lock (_syncLock) { _items.RemoveAt(index); } } public void RemoveAt(int index) { lock (SyncRoot) { _items.RemoveAt(index); } }
public void Clear() { lock (_syncLock) { _items.Clear(); } } public void Clear() { lock (SyncRoot) { _items.Clear(); } }
public bool Contains(T item) { lock (_syncLock) { return _items.Contains(item); } } public bool Contains(T item) { lock (SyncRoot) { return _items.Contains(item); } }
bool IList.Contains(object? value) { lock (_syncLock) { return value is T t && _items.Contains(t); } } bool IList.Contains(object? value) { lock (SyncRoot) { return value is T t && _items.Contains(t); } }
public int IndexOf(T item) { lock (_syncLock) { return _items.IndexOf(item); } } public int IndexOf(T item) { lock (SyncRoot) { return _items.IndexOf(item); } }
int IList.IndexOf(object? value) { lock (_syncLock) { return value is T t ? _items.IndexOf(t) : -1; } } int IList.IndexOf(object? value) { lock (SyncRoot) { return value is T t ? _items.IndexOf(t) : -1; } }
public void CopyTo(T[] array, int arrayIndex) { lock (_syncLock) { _items.CopyTo(array, arrayIndex); } } public void CopyTo(T[] array, int arrayIndex) { lock (SyncRoot) { _items.CopyTo(array, arrayIndex); } }
void ICollection.CopyTo(Array array, int index) { lock (_syncLock) { ((ICollection) _items).CopyTo(array, index); } } void ICollection.CopyTo(Array array, int index) { lock (SyncRoot) { ((ICollection) _items).CopyTo(array, index); } }
} }
+172
View File
@@ -0,0 +1,172 @@
using System.Security.Cryptography;
namespace MeloongCore;
public interface IConfigProvider {
void Set<T>(string key, T? value, bool encrypted);
void Remove(string key);
T? Read<T>(string key, T? defaultValue, bool encrypted);
bool HasValue(string key);
void DiscardCache();
}
public class JsonConfigProvider : IConfigProvider {
public static readonly ConcurrentBag<WeakReference<JsonConfigProvider>> allProviders = [];
private readonly string filePath;
public JsonConfigProvider(string filePath) {
this.filePath = filePath;
allProviders.Add(new(this));
saveAction = Throttler.Throttle(Save, TimeSpan.FromMilliseconds(500), leading: false, trailing: true);
InitJson();
}
// 原始文件缓存
private Lazy<JObject> json;
// 反序列化后的结果缓存
private readonly ConcurrentDictionary<string, object?> cache = new();
private void InitJson() {
json = new(() => {
try {
return FileUtils.Exists(filePath) ? ((JObject?) FileUtils.ReadAsJson(filePath) ?? []) : [];
} catch (Exception ex) {
Logger.Error(ex, $"读取配置文件失败({filePath})", LogBehavior.Alert);
return [];
}
});
}
// ================================= 设置、读取、缓存 =================================
public void Set<T>(string key, T? value, bool encrypted) {
cache[key] = value;
lock (this) {
if (value is null) {
// 直接在 JSON 中表示为 null
json.Value[key] = JValue.CreateNull();
Logger.Trace($"配置已修改:{key} = null({filePath})");
} else if (encrypted) {
// 需要加密,在 JSON 中保存密文字符串
throw new NotImplementedException("加密需要改为使用识别码,现在尚未实现。");
Logger.Trace($"配置已修改:{key} = 已加密({filePath})");
json.Value[key] = CryptographyUtils.AesEncrypt(value is string str ? str : JsonConvert.SerializeObject(value));
} else {
// 用 JToken 保留原始结构
JToken token = JToken.FromObject(value);
json.Value[key] = token;
Logger.Trace($"配置已修改:{key} = {token.ToString(Formatting.None)}({filePath})");
}
}
MakeDirty();
}
public T? Read<T>(string key, T? defaultValue, bool encrypted) {
if (cache.TryGetValue(key, out var cachedValue)) return (T?) cachedValue; // 读取缓存
JToken entry;
lock (this) {
if (!json.Value.TryGetValue(key, out entry!)) return defaultValue; // 未找到该键
entry = entry.DeepClone();
}
try {
T? result;
if (entry.Type is JTokenType.Null or JTokenType.Undefined) {
result = default;
} else if (encrypted) {
string plainText = CryptographyUtils.AesDecrypt(entry.Value<string>())!;
result = typeof(T) == typeof(string) ? (T) (object) plainText : JsonConvert.DeserializeObject<T>(plainText);
} else {
result = entry.ToObject<T>();
}
cache[key] = result;
return result;
} catch (CryptographicException ex) {
Logger.Error(ex, $"解密配置失败,该配置将被重置({key})", LogBehavior.Alert);
Remove(key);
return defaultValue;
}
}
public bool HasValue(string key) {
lock (this) return json.Value.ContainsKey(key);
}
public void Remove(string key) {
lock (this) json.Value.Remove(key);
cache.TryRemove(key, out _);
MakeDirty();
}
public void DiscardCache() {
lock (this) InitJson();
cache.Clear();
}
// ===================================== 保存 =====================================
private readonly RateLimitedAction saveAction;
private bool isDirty = false;
public void MakeDirty() {
isDirty = true;
saveAction.Invoke();
}
public void Save() {
if (!isDirty) return;
isDirty = false;
lock (this) FileUtils.Write(filePath, json.Value.ToString(Formatting.Indented));
}
}
public static class ConfigUtils {
public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
/// <summary>
/// 立即保存所有配置。
/// </summary>
public static void SaveAll() {
foreach (var weakRef in JsonConfigProvider.allProviders) {
if (weakRef.TryGetTarget(out var provider)) provider.Save();
}
}
/// <summary>
/// 从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。
/// </summary>
public static string GetSecret(string key)
=> secret.Read<string>(key, null, false) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
}
public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
public IConfigProvider DefaultProvider => defaultProvider ?? ConfigUtils.AppData;
/// <summary>
/// 当设置项的值被改变时触发,参数为新值。新值可能和旧值相同。
/// </summary>
public event Action<T?, IConfigProvider>? Changed;
public void Edit(Func<T?, T?> editFunc, IConfigProvider? providerOverride = null) {
var provider = providerOverride ?? DefaultProvider;
Set(editFunc(Get(provider)), provider);
}
public void Edit(RefAction editAction, IConfigProvider? providerOverride = null) {
var provider = providerOverride ?? DefaultProvider;
var current = Get(provider);
editAction(ref current);
Set(current, provider);
}
public delegate void RefAction(ref T? value);
public void Set(T? value, IConfigProvider? providerOverride = null) {
var provider = providerOverride ?? DefaultProvider;
provider.Set(key, value, encrypted);
Changed?.Invoke(value, provider);
}
public void Reset(IConfigProvider? providerOverride = null) {
var provider = providerOverride ?? DefaultProvider;
if (!provider.HasValue(key)) return; // 值未设置,无需重置
provider.Remove(key);
Changed?.Invoke(defaultValue, provider);
}
public T? Get(IConfigProvider? providerOverride = null)
=> (providerOverride ?? DefaultProvider).Read(key, defaultValue, encrypted);
public bool HasValue(IConfigProvider? providerOverride = null)
=> (providerOverride ?? DefaultProvider).HasValue(key);
public static implicit operator T?(ConfigEntry<T> entry) => entry.Get();
}
+18 -7
View File
@@ -1,4 +1,3 @@
using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
namespace MeloongCore; namespace MeloongCore;
@@ -78,6 +77,12 @@ public static class Logger {
public static void SendToDebug(Exception ex, string? message = null, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "") public static void SendToDebug(Exception ex, string? message = null, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "")
=> Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{(message is null ? "" : $"{message}:")}{ex.GetDisplay(true)}"); => Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{(message is null ? "" : $"{message}:")}{ex.GetDisplay(true)}");
/// <summary>
/// 记录当前堆栈信息。
/// </summary>
public static void StackTrace(LogLevel level = LogLevel.Trace, [CallerFilePath] string filePath = "")
=> Instance.Log(null, new StackTrace(skipFrames: 1, fNeedFileInfo: true).ToString(), level, LogBehavior.None, filePath);
#region 内插优化 #region 内插优化
// VB.NET:由于不兼容 InterpolatedStringHandler,只能手动使用 Lambda // VB.NET:由于不兼容 InterpolatedStringHandler,只能手动使用 Lambda
@@ -185,8 +190,8 @@ public class BaseLogger {
// 核心方法 // 核心方法
public virtual void Log(Exception? ex, string? message, LogLevel level, LogBehavior behavior, string filePath) { public virtual void Log(Exception? ex, string? message, LogLevel level, LogBehavior behavior, string filePath) {
if (ex is ThreadInterruptedException) { if (ex?.IsCanceled() == true) {
Thread.CurrentThread.Interrupt(); Log(null, $"操作已取消({message})", LogLevel.Info, LogBehavior.None, filePath);
return; return;
} }
if (MinLevel > level) return; if (MinLevel > level) return;
@@ -220,7 +225,10 @@ public class BaseLogger {
.Join("\r\n"); .Join("\r\n");
} }
public static string GetLogPrefix(LogLevel level, string filePath) public static string GetLogPrefix(LogLevel level, string filePath)
=> $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{PathUtils.GetLastPart(filePath).BeforeFirst(".")}] "; => $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {
(Thread.CurrentThread.Name is not null ? $"<{Thread.CurrentThread.ManagedThreadId} · {Thread.CurrentThread.Name}> " :
(Thread.CurrentThread.IsThreadPoolThread ? "<Async> " : ""))}[{
PathUtils.GetLastPart(filePath).BeforeFirst(".")}] ";
/// <summary> /// <summary>
/// 执行 <see cref="LogBehavior"/>。 /// 执行 <see cref="LogBehavior"/>。
@@ -273,8 +281,9 @@ public class BaseLogger {
public void Flush() { public void Flush() {
try { try {
if (!avaliable) return; if (!avaliable) return;
lock (flushLock) lock (flushLock) {
while (queue.TryDequeue(out LogEntry entry)) Output(entry); // writer 指定了 AutoFlush while (queue.TryDequeue(out LogEntry entry)) Output(entry); // writer 指定了 AutoFlush
}
} catch (Exception logEx) { } catch (Exception logEx) {
Logger.SendToDebug(logEx, "输出日志失败"); Logger.SendToDebug(logEx, "输出日志失败");
} }
@@ -291,7 +300,7 @@ public class BaseLogger {
/// </summary> /// </summary>
public class FileLogger : BaseLogger, IDisposable { public class FileLogger : BaseLogger, IDisposable {
public string logFolder = Path.Combine(PathUtils.CurrentFolder, "logs"); public string logFolder = Path.Combine(Paths.Base, "logs");
public string fileNamePrefix = "Log"; public string fileNamePrefix = "Log";
public string fileNameSuffix = ".txt"; public string fileNameSuffix = ".txt";
private StreamWriter? writer; private StreamWriter? writer;
@@ -314,7 +323,9 @@ public class FileLogger : BaseLogger, IDisposable {
Logger.Warn(ex, "整理日志文件失败"); Logger.Warn(ex, "整理日志文件失败");
} }
// 新建 writer // 新建 writer
writer = new StreamWriter(PathUtils.ForApi(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true }; string logFilePath = PathUtils.ForApi(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}"));
DirectoryUtils.Create(logFolder);
writer = new StreamWriter(logFilePath, append: true) { AutoFlush = true };
} }
/// <inheritdoc/> /// <inheritdoc/>
+79 -69
View File
@@ -1,67 +1,14 @@
namespace MeloongCore; namespace MeloongCore;
public readonly struct OneOf<T0, T1> { public readonly struct OneOf<T1, T2> {
private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0) private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
private readonly T0? _value0;
private readonly T1? _value1;
public static implicit operator OneOf<T0, T1>(T0 value) => new(0, value, default);
public static implicit operator OneOf<T0, T1>(T1 value) => new(1, default, value);
public static implicit operator T0(OneOf<T0, T1> value) => value.As<T0>();
public static implicit operator T1(OneOf<T0, T1> value) => value.As<T1>();
private OneOf(int index, T0? value0, T1? value1) {
_index = index;
_value0 = value0;
_value1 = value1;
}
/// <summary>
/// 对不同类型执行不同的操作,并返回同一个值。
/// </summary>
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1) => _index switch {
0 => f0(_value0!),
1 => f1(_value1!),
_ => throw new InvalidOperationException()
};
/// <summary>
/// 对不同类型执行不同的操作。
/// </summary>
public void Switch(Action<T0> f0, Action<T1> f1) {
if (_index == 0) f0(_value0!);
else if (_index == 1) f1(_value1!);
else throw new InvalidOperationException();
}
/// <summary>
/// 判断当前的类型是否为 T。
/// </summary>
public bool Is<T>() => _index switch {
0 when typeof(T) == typeof(T0) => true,
1 when typeof(T) == typeof(T1) => true,
_ => false
};
/// <summary>
/// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
/// </summary>
public T As<T>() => _index switch {
0 when typeof(T) == typeof(T0) => (T)(object)_value0!,
1 when typeof(T) == typeof(T1) => (T)(object)_value1!,
_ => throw new InvalidOperationException()
};
}
public readonly struct OneOf<T0, T1, T2> {
private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
private readonly T0? _value0;
private readonly T1? _value1; private readonly T1? _value1;
private readonly T2? _value2; private readonly T2? _value2;
public static implicit operator OneOf<T0, T1, T2>(T0 value) => new(0, value, default, default); public static implicit operator OneOf<T1, T2>(T1 value) => new(1, value, default);
public static implicit operator OneOf<T0, T1, T2>(T1 value) => new(1, default, value, default); public static implicit operator OneOf<T1, T2>(T2 value) => new(2, default, value);
public static implicit operator OneOf<T0, T1, T2>(T2 value) => new(2, default, default, value); public static implicit operator T1(OneOf<T1, T2> value) => value.As<T1>();
public static implicit operator T0(OneOf<T0, T1, T2> value) => value.As<T0>(); public static implicit operator T2(OneOf<T1, T2> value) => value.As<T2>();
public static implicit operator T1(OneOf<T0, T1, T2> value) => value.As<T1>(); private OneOf(int index, T1? value1, T2? value2) {
public static implicit operator T2(OneOf<T0, T1, T2> value) => value.As<T2>();
private OneOf(int index, T0? value0, T1? value1, T2? value2) {
_index = index; _index = index;
_value0 = value0;
_value1 = value1; _value1 = value1;
_value2 = value2; _value2 = value2;
} }
@@ -69,8 +16,7 @@ public readonly struct OneOf<T0, T1, T2> {
/// <summary> /// <summary>
/// 对不同类型执行不同的操作,并返回同一个值。 /// 对不同类型执行不同的操作,并返回同一个值。
/// </summary> /// </summary>
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch { public TResult Switch<TResult>(Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch {
0 => f0(_value0!),
1 => f1(_value1!), 1 => f1(_value1!),
2 => f2(_value2!), 2 => f2(_value2!),
_ => throw new InvalidOperationException() _ => throw new InvalidOperationException()
@@ -78,9 +24,8 @@ public readonly struct OneOf<T0, T1, T2> {
/// <summary> /// <summary>
/// 对不同类型执行不同的操作。 /// 对不同类型执行不同的操作。
/// </summary> /// </summary>
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2) { public void Switch(Action<T1> f1, Action<T2> f2) {
if (_index == 0) f0(_value0!); if (_index == 1) f1(_value1!);
else if (_index == 1) f1(_value1!);
else if (_index == 2) f2(_value2!); else if (_index == 2) f2(_value2!);
else throw new InvalidOperationException(); else throw new InvalidOperationException();
} }
@@ -88,19 +33,84 @@ public readonly struct OneOf<T0, T1, T2> {
/// 判断当前的类型是否为 T。 /// 判断当前的类型是否为 T。
/// </summary> /// </summary>
public bool Is<T>() => _index switch { public bool Is<T>() => _index switch {
0 when typeof(T) == typeof(T0) => true,
1 when typeof(T) == typeof(T1) => true, 1 when typeof(T) == typeof(T1) => true,
2 when typeof(T) == typeof(T2) => true, 2 when typeof(T) == typeof(T2) => true,
_ => false _ => false
}; };
public bool IsT1() => _index == 1;
public bool IsT2() => _index == 2;
/// <summary> /// <summary>
/// 假定当前的类型为 T,并返回该值。 /// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。 /// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
/// </summary> /// </summary>
public T As<T>() => _index switch { public T As<T>() => _index switch {
0 when typeof(T) == typeof(T0) => (T) (object) _value0!, 1 when typeof(T) == typeof(T1) => (T)(object)_value1!,
1 when typeof(T) == typeof(T1) => (T) (object) _value1!, 2 when typeof(T) == typeof(T2) => (T)(object)_value2!,
2 when typeof(T) == typeof(T2) => (T) (object) _value2!,
_ => throw new InvalidOperationException() _ => throw new InvalidOperationException()
}; };
public T1 AsT1() => _index switch { 1 => _value1!, _ => throw new InvalidOperationException() };
public T2 AsT2() => _index switch { 2 => _value2!, _ => throw new InvalidOperationException() };
}
public readonly struct OneOf<T1, T2, T3> {
private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
private readonly T1? _value1;
private readonly T2? _value2;
private readonly T3? _value3;
public static implicit operator OneOf<T1, T2, T3>(T1 value) => new(1, value, default, default);
public static implicit operator OneOf<T1, T2, T3>(T2 value) => new(2, default, value, default);
public static implicit operator OneOf<T1, T2, T3>(T3 value) => new(3, default, default, value);
public static implicit operator T1(OneOf<T1, T2, T3> value) => value.As<T1>();
public static implicit operator T2(OneOf<T1, T2, T3> value) => value.As<T2>();
public static implicit operator T3(OneOf<T1, T2, T3> value) => value.As<T3>();
private OneOf(int index, T1? value1, T2? value2, T3? value3) {
_index = index;
_value1 = value1;
_value2 = value2;
_value3 = value3;
}
/// <summary>
/// 对不同类型执行不同的操作,并返回同一个值。
/// </summary>
public TResult Switch<TResult>(Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3) => _index switch {
1 => f1(_value1!),
2 => f2(_value2!),
3 => f3(_value3!),
_ => throw new InvalidOperationException()
};
/// <summary>
/// 对不同类型执行不同的操作。
/// </summary>
public void Switch(Action<T1> f1, Action<T2> f2, Action<T3> f3) {
if (_index == 1) f1(_value1!);
else if (_index == 2) f2(_value2!);
else if (_index == 3) f3(_value3!);
else throw new InvalidOperationException();
}
/// <summary>
/// 判断当前的类型是否为 T。
/// </summary>
public bool Is<T>() => _index switch {
1 when typeof(T) == typeof(T1) => true,
2 when typeof(T) == typeof(T2) => true,
3 when typeof(T) == typeof(T3) => true,
_ => false
};
public bool IsT1() => _index == 1;
public bool IsT2() => _index == 2;
public bool IsT3() => _index == 3;
/// <summary>
/// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
/// </summary>
public T As<T>() => _index switch {
1 when typeof(T) == typeof(T1) => (T) (object) _value1!,
2 when typeof(T) == typeof(T2) => (T) (object) _value2!,
3 when typeof(T) == typeof(T3) => (T) (object) _value3!,
_ => throw new InvalidOperationException()
};
public T1 AsT1() => _index switch { 1 => _value1!, _ => throw new InvalidOperationException() };
public T2 AsT2() => _index switch { 2 => _value2!, _ => throw new InvalidOperationException() };
public T3 AsT3() => _index switch { 3 => _value3!, _ => throw new InvalidOperationException() };
} }
+205
View File
@@ -0,0 +1,205 @@
namespace MeloongCore;
/// <summary>
/// 提供一个追踪任务进度的对象,它所提供的供用户查看的进度必定单调递增。
/// 支持重试、拆分子项进度、记录部分进度被跳过。
/// </summary>
public class ProgressProvider {
/// <summary>
/// 当原始进度可能被改变时触发。
/// </summary>
public event Action<(double actual, double skiped)>? ProgressChanged;
private event Action? ChildProgressChanged;
private void InvokeProgressChanged() {
ProgressChanged?.Invoke(GetRaw());
ChildProgressChanged?.Invoke();
}
// ===================================== 主项进度 =====================================
private (double actual, double skiped, double splited) progressParts = (0, 0, 0);
private double progressSum => progressParts.actual + progressParts.skiped + progressParts.splited;
private bool _Set(double value, bool skiped) {
value = value.Clamp(0, 1);
double delta = value - progressSum;
if (delta < 0) { // 等比减少
progressParts = (progressParts.actual * value / progressSum,
progressParts.skiped * value / progressSum,
progressParts.splited * value / progressSum);
} else if (skiped) {
progressParts.skiped += delta;
} else {
progressParts.actual += delta;
}
return delta != 0;
}
/// <summary>
/// 将当前进度设置为指定值。
/// 若指定了 <paramref name="skiped"/>,这段进度的增量值将被计为跳过:当前观测进度不会增加,后续观测进度将增加地更快。
/// </summary>
public void Set(double value, bool skiped = false, ChildrenAction action = ChildrenAction.Finished) {
bool changed;
lock (this) {
changed = _Set(value, skiped);
changed |= AssumeChildrenAs(action);
}
if (changed) InvokeProgressChanged();
}
/// <summary>
/// 将当前进度增加指定值。
/// 若指定了 <paramref name="skiped"/>,这段进度的增量值将被计为跳过:当前观测进度不会增加,后续观测进度将增加地更快。
/// 若指定了 <paramref name="markChildrenAsFinished"/>,当前所有未完成的子项将被视为已完成。
/// </summary>
public void Add(double value, bool skiped = false, ChildrenAction action = ChildrenAction.Finished) {
bool changed;
lock (this) {
changed = _Set(value + progressSum, skiped);
changed |= AssumeChildrenAs(action);
}
if (changed) InvokeProgressChanged();
}
/// <summary>完成当前项的剩余进度。</summary>
public void Finish(ChildrenAction action = ChildrenAction.Finished) => Set(1, skiped: false, action: action);
/// <summary>跳过当前项的剩余进度。</summary>
public void Skip(ChildrenAction action = ChildrenAction.Skiped) => Set(1, skiped: true, action: action);
/// <summary>
/// 重置当前进度,并清除所有子项。
/// </summary>
public void Reset() {
bool changed;
lock (this) {
changed = progressSum > 0;
progressParts = (0, 0, 0);
childrens.ForEach(c => c.child.ChildProgressChanged -= InvokeProgressChanged);
childrens.Clear();
}
if (changed) InvokeProgressChanged();
}
// ===================================== 子项进度 =====================================
private readonly List<(double percentage, ProgressProvider child)> childrens = [];
/// <summary>
/// 拆分一个子项:当该子项完成时,进度将从当前值增加至 <paramref name="value"/>。
/// </summary>
public ProgressProvider SplitTo(double value) {
lock (this) return SplitBy(value - progressSum).First();
}
/// <summary>
/// 拆分多个子项,每个子项都占据对应指定的进度量。
/// <para/>例如,调用 <c>SplitBy(0.2, 0.3)</c> 将返回两个子项,分别占据总进度的 20%、30%。
/// <para/>若总进度量 > 1,子项的进度量将相对缩小。
/// </summary>
public List<ProgressProvider> SplitBy(params double[] percentages) {
lock (this) {
if (percentages.Any(p => p <= 0)) throw new ArgumentException("子项进度必须为正数且");
progressParts.splited += (percentages.Sum() + progressSum).Clamp(0, 1) - progressSum;
return percentages.Select(percentage => {
var sub = new ProgressProvider();
sub.ChildProgressChanged += InvokeProgressChanged;
childrens.Add((percentage, sub));
return sub;
}).ToList();
}
}
public enum ChildrenAction {
/// <summary>不做任何处理。</summary>
None,
/// <summary>将未完成的子项的剩余进度视为已完成。</summary>
Finished,
/// <summary>将未完成的子项的剩余进度视为已跳过。</summary>
Skiped
}
/// <summary>
/// 修改所有未完成的子项。
/// </summary>
/// <returns>是否修改了任意进度不到 1 的子项。</returns>
private bool AssumeChildrenAs(ChildrenAction action) {
if (action == ChildrenAction.None) return false;
lock (this) {
bool changed = false;
if (childrens.Any(c => c.percentage > 0)) { // 将子项的进度加入主项
var mult = progressParts.splited / childrens.Sum(c => c.percentage);
childrens.ForEach(c => {
var (subActual, subSkiped) = c.child.GetRaw();
progressParts.actual += mult * c.percentage * (action == ChildrenAction.Finished ? (1 - subSkiped) : subActual);
progressParts.skiped += mult * c.percentage * (action == ChildrenAction.Skiped ? (1 - subActual) : subSkiped);
c.child.ChildProgressChanged -= InvokeProgressChanged;
if (subActual + subSkiped < 0.9999999) changed = true;
});
}
progressParts.splited = 0;
childrens.Clear();
return changed;
}
}
// ===================================== 观测 =====================================
/// <summary>
/// 获取包含子项进度的实际总进度值。
/// </summary>
public (double actual, double skiped) GetRaw() {
lock (this) {
(double actual, double skiped) current = (progressParts.actual, progressParts.skiped);
if (childrens.Any(c => c.percentage > 0)) { // 将子项的进度加入主项
var mult = progressParts.splited / childrens.Sum(c => c.percentage);
childrens.ForEach(c => {
var (subActual, subSkiped) = c.child.GetRaw();
current.actual += mult * c.percentage * subActual;
current.skiped += mult * c.percentage * subSkiped;
});
}
return current;
}
}
private (double actual, double skiped) observedProgress = (0, 0);
private double incrementProgress = 0;
/// <summary>
/// 获取一个在多次观测之间必定单调递增的进度值,范围为 [0, 1]。
/// </summary>
public double GetIncrement() {
lock (this) {
(double actual, double skiped) current = GetRaw();
if (current == observedProgress) return incrementProgress; // 未改变
if (current.actual + current.skiped > 0.9999999) { // 已完成
incrementProgress = 1;
} else if (current.actual >= observedProgress.actual) { // 进度增加
incrementProgress += (1 - incrementProgress) *
(current.actual - observedProgress.actual) / (1 - observedProgress.actual - current.skiped);
}
observedProgress = current;
return incrementProgress;
}
}
}
/// <summary>
/// 监听进度变化,并将观测到的进度节流后传给更新方法。
/// </summary>
public class ProgressObserver : RateLimitedWorker {
private readonly ProgressProvider provider;
public ProgressObserver(ProgressProvider provider, Action<double> updateAction, double minimalIntervalMs = 70)
: base(() => Observe(provider, updateAction), minimalIntervalMs, RateLimitMode.ImmediateThenMerge) {
this.provider = provider;
provider.ProgressChanged += StartObserver;
}
public override void Dispose() {
provider.ProgressChanged -= StartObserver;
base.Dispose();
}
private void StartObserver((double actual, double skiped) raw) => Start();
private static void Observe(ProgressProvider provider, Action<double> updateAction) {
double progress = provider.GetIncrement();
// TODO: 添加平缓过渡
updateAction(progress);
}
}
+218
View File
@@ -0,0 +1,218 @@
namespace MeloongCore;
/// <summary>
/// 表示一个由可选下界和可选上界组成的范围。
/// </summary>
public sealed class ValueRange<T>(
T? lower, T? upper,
bool isLowerInclusive, bool isUpperInclusive,
bool hasLower, bool hasUpper
) : IEquatable<ValueRange<T>?> where T : notnull, IComparable<T> {
#region 基础字段
public T? Lower { get; private set; } = hasLower && lower is null ? throw new ArgumentNullException(nameof(lower)) : lower;
public T? Upper { get; private set; } = hasUpper && upper is null ? throw new ArgumentNullException(nameof(upper)) : upper;
public bool HasLower { get; private set; } = hasLower;
public bool HasUpper { get; private set; } = hasUpper;
public void ClearLower() { Lower = default; HasLower = false; }
public void ClearUpper() { Upper = default; HasUpper = false; }
public void SetLower(T lower, bool isInclusive) {
Lower = lower;
HasLower = true;
IsLowerInclusive = isInclusive;
}
public void SetUpper(T upper, bool isInclusive) {
Upper = upper;
HasUpper = true;
IsUpperInclusive = isInclusive;
}
/// <summary> 下界值是否为闭区间。 </summary>
public bool IsLowerInclusive = isLowerInclusive;
/// <summary> 上界值是否为闭区间。 </summary>
public bool IsUpperInclusive = isUpperInclusive;
#endregion
#region ClosedOpen、AtLeast 等工厂方法
/// <summary> 创建等同于 <c>[lower, upper]</c> 的闭区间。 </summary>
public static ValueRange<T> Closed(T lower, T upper) => new(lower, upper, true, true, true, true);
/// <summary> 创建形如 <c>[lower, upper)</c> 的左闭右开区间。 </summary>
public static ValueRange<T> ClosedOpen(T lower, T upper) => new(lower, upper, true, false, true, true);
/// <summary> 创建形如 <c>(lower, upper]</c> 的左开右闭区间。 </summary>
public static ValueRange<T> OpenClosed(T lower, T upper) => new(lower, upper, false, true, true, true);
/// <summary> 创建形如 <c>(lower, upper)</c> 的开区间。 </summary>
public static ValueRange<T> Open(T lower, T upper) => new(lower, upper, false, false, true, true);
/// <summary> 创建形如 <c>[value, value]</c> 的单值闭区间。 </summary>
public static ValueRange<T> Exactly(T value) => new(value, value, true, true, true, true);
/// <summary> 创建形如 <c>[lower, +∞)</c> 的范围。 </summary>
public static ValueRange<T> AtLeast(T lower) => new(lower, default, true, true, true, false);
/// <summary> 创建形如 <c>(lower, +∞)</c> 的范围。 </summary>
public static ValueRange<T> GreaterThan(T lower) => new(lower, default, false, true, true, false);
/// <summary> 创建形如 <c>(-∞, upper]</c> 的范围。 </summary>
public static ValueRange<T> AtMost(T upper) => new(default, upper, true, true, false, true);
/// <summary> 创建形如 <c>(-∞, upper)</c> 的范围。 </summary>
public static ValueRange<T> LessThan(T upper) => new(default, upper, true, false, false, true);
/// <summary> 创建形如 <c>(-∞, +∞)</c> 的无限范围。 </summary>
public static ValueRange<T> All() => new(default, default, true, true, false, false);
#endregion
#region 字符串双向转换
/// <summary>
/// 从字符串解析 <see cref="ValueRange{T}"/> 实例。
/// </summary>
public static ValueRange<T> FromString(string str, Func<string, T>? parseFunc = null) {
if (string.IsNullOrEmpty(str)) throw new ArgumentException("不能为空");
var isLowerInclusive = str[0] == '[';
var isUpperInclusive = str[^1] == ']';
if (!isLowerInclusive && str[0] != '(') throw new ArgumentException("开头必须是 [ 或 (");
if (!isUpperInclusive && str[^1] != ')') throw new ArgumentException("结尾必须是 ] 或 )");
var commaIndex = str.IndexOfAny([',', ',']);
if (commaIndex == -1) throw new ArgumentException("需要用逗号分隔两个值");
var lowerStr = str[1..commaIndex].Trim();
var upperStr = str[(commaIndex + 1)..^1].Trim();
T? lower = default;
T? upper = default;
bool hasLower = false;
bool hasUpper = false;
if (lowerStr is not ("" or "-∞")) {
lower = parseFunc != null ? parseFunc(lowerStr) : (T) Convert.ChangeType(lowerStr, typeof(T));
hasLower = true;
}
if (upperStr is not ("" or "+∞" or "∞")) {
upper = parseFunc != null ? parseFunc(upperStr) : (T) Convert.ChangeType(upperStr, typeof(T));
hasUpper = true;
}
return new(lower, upper, isLowerInclusive, isUpperInclusive, hasLower, hasUpper);
}
public override string ToString()
=> $"{(HasLower && IsLowerInclusive ? "[" : "(")}{(HasLower ? Lower!.ToString() : "-∞")}, {(HasUpper ? Upper!.ToString() : "+∞")}{(HasUpper && IsUpperInclusive ? "]" : ")")}";
#endregion
/// <summary>
/// 判断指定值是否位于当前范围内。
/// </summary>
public bool Contains(T value) {
if (HasLower) {
var compareLower = value.CompareTo(Lower!);
if (compareLower < 0) return false;
if (compareLower == 0 && !IsLowerInclusive) return false;
}
if (HasUpper) {
var compareUpper = value.CompareTo(Upper!);
if (compareUpper > 0) return false;
if (compareUpper == 0 && !IsUpperInclusive) return false;
}
return true;
}
/// <summary>
/// 该范围是否不包含任何值。
/// </summary>
public bool IsEmpty() {
if (!HasLower || !HasUpper) return false;
int compared = Lower!.CompareTo(Upper!);
return compared > 0 || (compared == 0 && (!IsLowerInclusive || !IsUpperInclusive));
}
/// <summary>
/// 取当前范围与另一个范围的交集。
/// </summary>
/// <returns> 若两个范围存在交集,则返回交集范围;否则返回 <see langword="null" />。 </returns>
public ValueRange<T>? Intersect(ValueRange<T> other) {
T? lower = default;
T? upper = default;
var isLowerInclusive = true;
var isUpperInclusive = true;
if (HasLower && other.HasLower) {
switch (Lower!.CompareTo(other.Lower!)) {
case > 0:
lower = Lower;
isLowerInclusive = IsLowerInclusive;
break;
case < 0:
lower = other.Lower;
isLowerInclusive = other.IsLowerInclusive;
break;
default:
lower = Lower;
isLowerInclusive = IsLowerInclusive && other.IsLowerInclusive;
break;
}
} else if (HasLower) {
lower = Lower;
isLowerInclusive = IsLowerInclusive;
} else if (other.HasLower) {
lower = other.Lower;
isLowerInclusive = other.IsLowerInclusive;
}
if (HasUpper && other.HasUpper) {
switch (Upper!.CompareTo(other.Upper!)) {
case < 0:
upper = Upper;
isUpperInclusive = IsUpperInclusive;
break;
case > 0:
upper = other.Upper;
isUpperInclusive = other.IsUpperInclusive;
break;
default:
upper = Upper;
isUpperInclusive = IsUpperInclusive && other.IsUpperInclusive;
break;
}
} else if (HasUpper) {
upper = Upper;
isUpperInclusive = IsUpperInclusive;
} else if (other.HasUpper) {
upper = other.Upper;
isUpperInclusive = other.IsUpperInclusive;
}
var anyHasLower = HasLower || other.HasLower;
var anyHasUpper = HasUpper || other.HasUpper;
return new(lower, upper, isLowerInclusive, isUpperInclusive, anyHasLower, anyHasUpper);
}
#region 相等判断(自动生成)
public override bool Equals(object? obj) => Equals(obj as ValueRange<T>);
public bool Equals(ValueRange<T>? other) {
return other is not null&&
EqualityComparer<T?>.Default.Equals(Lower, other.Lower)&&
EqualityComparer<T?>.Default.Equals(Upper, other.Upper)&&
HasLower==other.HasLower&&
HasUpper==other.HasUpper&&
IsLowerInclusive==other.IsLowerInclusive&&
IsUpperInclusive==other.IsUpperInclusive;
}
public override int GetHashCode() {
int hashCode = 169504101;
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(Lower);
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(Upper);
hashCode=hashCode*-1521134295+HasLower.GetHashCode();
hashCode=hashCode*-1521134295+HasUpper.GetHashCode();
hashCode=hashCode*-1521134295+IsLowerInclusive.GetHashCode();
hashCode=hashCode*-1521134295+IsUpperInclusive.GetHashCode();
return hashCode;
}
#pragma warning disable CS8604 // 引用类型参数可能为 null。
public static bool operator ==(ValueRange<T>? left, ValueRange<T>? right) => EqualityComparer<ValueRange<T>>.Default.Equals(left, right);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
public static bool operator !=(ValueRange<T>? left, ValueRange<T>? right) => !(left==right);
#endregion
}
@@ -0,0 +1,35 @@
namespace MeloongCore;
public enum RateLimitMode {
/// <summary>Throttle:立即执行一次,然后一段时间内合并为一次尾随执行。</summary>
ImmediateThenMerge,
/// <summary>Debounce (leading):立即执行一次,然后忽略一段时间内的后续调用。</summary>
ImmediateThenIgnore,
/// <summary>Debounce (trailing):不立即执行,直到一段时间内不再有任何新调用后再执行一次。</summary>
WaitUnillNoNewInvoke,
}
/// <summary>
/// 对高频调用进行限制。
/// 详见:<see href="https://aldaviva.com/portfolio.html#ratelimiting" />
/// </summary>
public class RateLimitedWorker(Action workload, double minimalIntervalMs, RateLimitMode mode) : IDisposable {
private readonly RateLimitedAction action = mode switch {
RateLimitMode.ImmediateThenMerge => Throttler.Throttle(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: true),
RateLimitMode.WaitUnillNoNewInvoke => Debouncer.Debounce(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: false, trailing: true),
RateLimitMode.ImmediateThenIgnore => Debouncer.Debounce(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: false)
};
public void Start() {
if (!disposed) action.Invoke();
}
private bool disposed = false;
public virtual void Dispose() {
if (disposed) return;
disposed = true;
action.Dispose();
}
}
+211
View File
@@ -0,0 +1,211 @@
namespace MeloongCore;
public interface IWorker {
/// <summary>在工作线程运行工作负载。</summary>
void Start(CancellationToken cancellationToken = default, ProgressProvider? progressOverride = null);
/// <summary>取消当前运行。</summary>
void Cancel();
/// <summary>若当前正在运行中,等待其完成。若未在运行中,则立即返回。</summary>
/// <returns>若未超时则返回 true。</returns>
bool WaitIfRunning(int millisecondsTimeout = -1, CancellationToken cancellationToken = default);
/// <summary>若当前正在运行中,异步等待其完成。若未在运行中,则立即返回。</summary>
/// <returns>若未超时则返回 true。</returns>
Task<bool> WaitIfRunningAsync(int millisecondsTimeout = -1, CancellationToken cancellationToken = default);
/// <summary>从空闲状态进入运行状态时触发。</summary>
event Action? Started;
/// <summary>运行结束并进入空闲状态时触发。</summary>
event Action? Stopped;
/// <summary>工作负载成功完成时触发。</summary>
public event Action? Succeeded;
/// <summary>工作负载执行失败时触发,参数为发生的异常。</summary>
public event Action<Exception>? Failed;
/// <summary>运行被取消时触发。</summary>
event Action? Canceled;
/// <summary>当前是否正在运行。</summary>
bool Running { get; }
/// <summary>是否曾经有过未被取消且未失败的运行。</summary>
bool HasSucceeded { get; }
/// <summary>标识上次进入空闲时,并非因为取消或失败,而是正常运行到结束。</summary>
bool LastSucceeded { get; }
/// <summary>当前工作负载的执行进度。</summary>
ProgressProvider Progress { get; }
}
/// <summary>
/// 可合并和重启的工作器。
/// <para/> 在工作负载运行期间多次调用 <see cref="Start(CancellationToken)"/> 会取消当前负载并使用最新令牌重新执行;多次调用也只重新执行一次。
/// </summary>
public abstract class RedoableWorkerBase<TOut>(Func<CancellationToken?, ProgressProvider?, TOut> workload,
ProgressProvider? progress = null, [CallerMemberName] string creatorMemberName = "") : IWorker {
// ============================================ 状态与事件 ============================================
/// <inheritdoc/>
public bool Running { get { lock (this) return running; } }
private bool running;
/// <inheritdoc/>
public event Action? Started;
/// <inheritdoc/>
public event Action? Stopped;
/// <inheritdoc/>
public bool HasSucceeded { get { lock (this) return hasSucceeded; } }
private bool hasSucceeded;
/// <inheritdoc/>
public event Action? Succeeded;
/// <inheritdoc/>
public event Action<Exception>? Failed;
/// <inheritdoc/>
public event Action? Canceled;
/// <inheritdoc/>
public bool LastSucceeded { get { lock (this) return lastSucceeded; } }
private bool lastSucceeded;
/// <summary>上次未被取消且未失败的运行中,工作负载的返回值。</summary>
public TOut LastResult {
get {
lock (this) {
if (typeof(TOut) == typeof(NoType)) throw new InvalidOperationException("该 Worker 没有返回值。");
if (!hasSucceeded) throw new InvalidOperationException("从未成功完成过。");
return lastResult == null ? default! : (TOut) lastResult;
}
}
}
private object? lastResult;
/// <inheritdoc/>
public ProgressProvider Progress { get; private set; } = progress ?? new ProgressProvider();
private bool pendingRedo;
// =========================================== 运行与取消 ===========================================
private CancellationTokenSource? realCts;
private CancellationToken lastToken;
private readonly ManualResetEventSlim idleEvent = new(initialState: true);
/// <summary>在工作线程运行工作负载。若当前已在运行,则取消当前负载并使用最新令牌重启。</summary>
public void Start(CancellationToken cancellationToken = default, ProgressProvider? progressOverride = null) {
// 接取运行状态
lock (this) {
lastToken = cancellationToken;
if (progressOverride != null) Progress = progressOverride;
if (running) {
Logger.Info($"{creatorMemberName}:接到重启请求");
pendingRedo = true;
realCts?.Cancel();
return;
}
running = true; idleEvent.Reset();
realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
}
var th = new Thread(_Start) { IsBackground = true, Name = $"W/{creatorMemberName}" };
th.Start();
}
private void _Start() {
Logger.Info($"{creatorMemberName}:运行开始");
Started?.Invoke();
while (true) {
try {
realCts!.Token.ThrowIfCancellationRequested();
Progress?.Reset();
TOut result = workload(realCts.Token, Progress); // 实际的执行
realCts.Token.ThrowIfCancellationRequested();
lock (this) {
realCts?.Dispose();
if (pendingRedo) { // 接取重启请求
pendingRedo = false;
realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
continue;
}
realCts = null;
lastSucceeded = true;
lastResult = result;
hasSucceeded = true;
running = false; idleEvent.Set();
Progress?.Finish();
}
Logger.Info($"{creatorMemberName}:运行成功");
Succeeded?.Invoke();
} catch (Exception ex) {
if (!ex.IsCanceled())
Logger.Log(ex, $"{creatorMemberName}:运行失败{(pendingRedo ? ",但即将重启,或可忽略" : "")}",
pendingRedo ? LogLevel.Warn : LogLevel.Error, LogBehavior.ToastIfDebug);
lock (this) {
realCts?.Dispose();
if (pendingRedo) { // 接取重启请求
Logger.Info($"{creatorMemberName}:重启开始");
pendingRedo = false;
realCts = CancellationTokenSource.CreateLinkedTokenSource(lastToken);
continue;
}
realCts = null;
lastSucceeded = false;
running = false; idleEvent.Set();
Progress?.Skip();
}
if (ex.IsCanceled()) {
Logger.Info($"{creatorMemberName}:运行已取消");
Canceled?.Invoke();
} else {
Failed?.Invoke(ex);
}
}
break;
}
Stopped?.Invoke();
}
/// <inheritdoc/>
public void Cancel() {
lock (this) {
pendingRedo = false;
Logger.Info($"{creatorMemberName}:接到取消请求");
realCts?.Cancel();
}
}
/// <inheritdoc/>
public bool WaitIfRunning(int millisecondsTimeout = -1, CancellationToken cancellationToken = default)
=> idleEvent.Wait(millisecondsTimeout, cancellationToken);
/// <inheritdoc/>
public async Task<bool> WaitIfRunningAsync(int millisecondsTimeout = -1, CancellationToken cancellationToken = default) {
cancellationToken.ThrowIfCancellationRequested();
var completionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var waitHandle = ThreadPool.RegisterWaitForSingleObject(idleEvent.WaitHandle,
(_, timedOut) => completionSource.TrySetResult(!timedOut), null, millisecondsTimeout, executeOnlyOnce: true);
using var cancellationRegistration = cancellationToken.Register(() => completionSource.TrySetCanceled(cancellationToken));
try {
return await completionSource.Task.NoCapture();
} finally {
waitHandle.Unregister(null);
}
}
}
/// <inheritdoc />
public class RedoableWorker<TOut> : RedoableWorkerBase<TOut> {
public RedoableWorker(Func<CancellationToken?, ProgressProvider?, TOut> workload, [CallerMemberName] string creatorMemberName = "")
: base(workload, creatorMemberName: creatorMemberName) { }
public RedoableWorker(Func<CancellationToken?, TOut> workload, [CallerMemberName] string creatorMemberName = "")
: base((c, _) => workload(c), creatorMemberName: creatorMemberName) { }
public RedoableWorker(Func<TOut> workload, [CallerMemberName] string creatorMemberName = "")
: base((_, _) => workload(), creatorMemberName: creatorMemberName) { }
}
/// <inheritdoc />
public class RedoableWorker : RedoableWorkerBase<NoType?> {
public RedoableWorker(Action<CancellationToken?, ProgressProvider?> workload, [CallerMemberName] string creatorMemberName = "")
: base((c, p) => { workload(c, p); return null; }, creatorMemberName: creatorMemberName) { }
public RedoableWorker(Action<CancellationToken?> workload, [CallerMemberName] string creatorMemberName = "")
: base((c, _) => { workload(c); return null; }, creatorMemberName: creatorMemberName) { }
public RedoableWorker(Action workload, [CallerMemberName] string creatorMemberName = "")
: base((_, _) => { workload(); return null; }, creatorMemberName: creatorMemberName) { }
}
/// <summary>指示没有该类型,用于泛型参数。</summary>
public class NoType { }
+5 -4
View File
@@ -1,9 +1,10 @@
namespace MeloongCore; namespace MeloongCore;
public static class Main { public static class Main {
public static void Init(BaseLogger? logger = null) { public static string AppName = "Meloong";
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(2)); public static void Init(string appName) {
if (logger != null) Logger.Instance = logger; AppName = appName;
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(5));
} }
} }
+14 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
@@ -22,16 +22,29 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Using Include="ThrottleDebounce" />
<Using Include="System.Diagnostics.CodeAnalysis" /> <Using Include="System.Diagnostics.CodeAnalysis" />
<Using Include="System.Collections" /> <Using Include="System.Collections" />
<Using Include="System.Collections.Generic" /> <Using Include="System.Collections.Generic" />
<Using Include="System.Collections.Concurrent" />
<Using Include="System.Text" /> <Using Include="System.Text" />
<Using Include="System.Net" /> <Using Include="System.Net" />
<Using Include="System.Runtime.CompilerServices" /> <Using Include="System.Runtime.CompilerServices" />
<Using Include="System.Runtime.InteropServices" /> <Using Include="System.Runtime.InteropServices" />
<Using Include="Newtonsoft.Json" />
<Using Include="Newtonsoft.Json.Linq" />
<Using Include="MeloongCore.Extensions" /> <Using Include="MeloongCore.Extensions" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Reference Include="ThrottleDebounce">
<HintPath>..\..\Plain Craft Launcher 2\Resources\ThrottleDebounce.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\Plain Craft Launcher 2\Resources\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants);SNAPSHOT</DefineConstants> <DefineConstants>$(DefineConstants);SNAPSHOT</DefineConstants>
</PropertyGroup> </PropertyGroup>
+200
View File
@@ -0,0 +1,200 @@
using System.Security;
using System.Security.Cryptography;
namespace MeloongCore;
public static class CryptographyUtils {
#region Hash
public enum HashMethod {
/// <summary>
/// 使用 <see cref="MD5"/> 算法。在 16 进制下哈希为 32 长度字符串。
/// </summary>
Md5,
/// <summary>
/// 使用 <see cref="SHA1"/> 算法。在 16 进制下哈希为 40 长度字符串。
/// </summary>
Sha1,
/// <summary>
/// 使用 <see cref="SHA256"/> 算法。在 16 进制下哈希为 64 长度字符串。
/// </summary>
Sha256,
/// <summary>
/// 使用 <see cref="SHA512"/> 算法。在 16 进制下哈希为 128 长度字符串。
/// </summary>
Sha512
}
private static HashAlgorithm GetHashAlgorithm(HashMethod method) => method switch {
HashMethod.Md5 => MD5.Create(),
HashMethod.Sha1 => SHA1.Create(),
HashMethod.Sha256 => SHA256.Create(),
HashMethod.Sha512 => SHA512.Create(),
_ => throw new ArgumentOutOfRangeException(nameof(method))
};
/// <summary>
/// 计算文件的 Hash。返回 16 进制小写字符串。
/// </summary>
public static string ComputeFileHash(string filePath, HashMethod method = HashMethod.Md5) {
using HashAlgorithm hashImpl = GetHashAlgorithm(method);
Logger.Trace($"计算文件 {method}:{filePath}");
using var file = FileUtils.ReadAsStream(filePath);
return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").Lower();
}
/// <summary>
/// 计算字节数组的 Hash。返回 16 进制小写字符串。
/// </summary>
public static string ComputeHash(byte[] input, HashMethod method = HashMethod.Md5) {
using HashAlgorithm hashImpl = GetHashAlgorithm(method);
return BitConverter.ToString(hashImpl.ComputeHash(input)).Replace("-", "").Lower();
}
/// <summary>
/// 计算字符串的 Hash。返回 16 进制小写字符串。
/// <para/> 使用 UTF-8 将字符串转换为字节数组。
/// </summary>
public static string ComputeHash(string input, HashMethod method = HashMethod.Md5)
=> ComputeHash(Encoding.UTF8.GetBytes(input), method);
#endregion
#region AES 对称加解密
private const byte AesDataVersion = 1;
/// <summary>
/// 使用 AES-256-CBC 对称加密字符串。
/// </summary>
/// <returns>加密后的 Base64 字符串。若输入为空字符串或 null,则原样返回空字符串或 null。</returns>
public static string? AesEncrypt(string? sourceString, string key = "EncryptKey") {
if (string.IsNullOrEmpty(sourceString)) return sourceString; // 原样返回空字符串或 null
byte[] iv = new byte[AesIvSize];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(iv);
byte[] cipherBytes;
using var sha256 = SHA256.Create();
byte[] aesKey = sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
byte[] hmacKey = sha256.ComputeHash(Encoding.UTF8.GetBytes("AES-HMAC|" + key));
using Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform encryptor = aes.CreateEncryptor(aesKey, iv);
byte[] sourceBytes = Encoding.UTF8.GetBytes(sourceString);
cipherBytes = encryptor.TransformFinalBlock(sourceBytes, 0, sourceBytes.Length);
// 格式:版本 [1 字节] | IV [16 字节] | 密文 [N 字节] | 校验 [4 字节]
byte[] encryptedBytes = new byte[1 + iv.Length + cipherBytes.Length + AesCheckSize];
encryptedBytes[0] = AesDataVersion;
Array.Copy(iv, 0, encryptedBytes, 1, iv.Length);
Array.Copy(cipherBytes, 0, encryptedBytes, 1 + iv.Length, cipherBytes.Length);
using var hmac = new HMACSHA256(hmacKey);
byte[] checkBytes = hmac.ComputeHash(encryptedBytes, 0, 1 + iv.Length + cipherBytes.Length);
Array.Copy(checkBytes, 0, encryptedBytes, 1 + iv.Length + cipherBytes.Length, AesCheckSize);
return Convert.ToBase64String(encryptedBytes);
}
/// <summary>
/// 使用 AES-256-CBC 对称解密字符串。
/// 如果输入数据有误,则确保会抛出 <see cref="CryptographicException"/>。
/// </summary>
/// <returns>解密后的字符串。若输入为空字符串或 null,则原样返回空字符串或 null。</returns>
public static string? AesDecrypt(string? encryptedString, string key = "EncryptKey") {
if (string.IsNullOrEmpty(encryptedString)) return encryptedString; // 原样返回空字符串或 null
byte[] encryptedBytes;
try {
encryptedBytes = Convert.FromBase64String(encryptedString);
} catch (FormatException ex) {
throw new CryptographicException($"数据不是一个有效的 Base64 字符串({encryptedString})", ex);
}
if (encryptedBytes.Length == 0) throw new CryptographicException($"对称加密数据长度有误({encryptedString})");
int cipherSize = encryptedBytes.Length - 1 - AesIvSize - AesCheckSize;
if (encryptedBytes[0] != AesDataVersion || cipherSize < 16 || cipherSize % 16 != 0)
throw new CryptographicException($"对称加密数据长度有误({encryptedString})");
using var sha256 = SHA256.Create();
byte[] hmacKey = sha256.ComputeHash(Encoding.UTF8.GetBytes("AES-HMAC|" + key));
using var hmac = new HMACSHA256(hmacKey);
byte[] checkBytes = hmac.ComputeHash(encryptedBytes, 0, 1 + AesIvSize + cipherSize);
int checkOffset = 1 + AesIvSize + cipherSize;
int checkDiff = 0;
for (int i = 0; i < AesCheckSize; i++)
checkDiff |= encryptedBytes[checkOffset + i] ^ checkBytes[i];
if (checkDiff != 0) throw new CryptographicException($"对称加密数据校验失败({encryptedString})");
byte[] aesKey = sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
byte[] iv = new byte[AesIvSize];
Array.Copy(encryptedBytes, 1, iv, 0, iv.Length);
using Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform decryptor = aes.CreateDecryptor(aesKey, iv);
byte[] output = decryptor.TransformFinalBlock(encryptedBytes, 1 + iv.Length, cipherSize);
return Encoding.UTF8.GetString(output);
}
private const int AesIvSize = 16;
private const int AesCheckSize = 4;
#endregion
#region ECDSA 非对称加密签名
/// <summary>
/// 使用 ECDSA 算法,验证一个字符串的签名是否使用私钥生成。
/// 如果验证失败则抛出 <see cref="CryptographicException"/>。
/// </summary>
public static void EcdsaVerify(string sourceString, string sign, string publicKey) {
using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
IntPtr algorithmHandle = IntPtr.Zero;
IntPtr keyHandle = IntPtr.Zero;
// 直接调用 DLL,以避免 .NET API 依赖的系统服务存在问题
try {
int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey), 72, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
} finally {
if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
}
}
/// <summary>
/// 使用 ECDSA 算法,为一个双方均知晓的字符串生成签名。
/// </summary>
public static string EcdsaSign(string sourceString, string privateKey) {
using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
IntPtr algorithmHandle = IntPtr.Zero;
IntPtr keyHandle = IntPtr.Zero;
// 直接调用 DLL,避免 .NET API 依赖的系统服务存在问题
try {
int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPRIVATEBLOB", out keyHandle, privateKeyBytes, privateKeyBytes.Length, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, null, 0, out int signSize, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
byte[] sign = new byte[signSize];
status = BCryptSignHash(keyHandle, IntPtr.Zero, hash, hash.Length, sign, sign.Length, out int actualSignSize, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptSignHash)} 失败,错误码 {status}");
if (actualSignSize != sign.Length) Array.Resize(ref sign, actualSignSize);
return Convert.ToBase64String(sign);
} finally {
if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
}
}
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptImportKeyPair(IntPtr algorithmHandle, IntPtr importKey, string blobType, out IntPtr keyHandle, byte[] input, int inputSize, int flags);
[DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
[DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
[DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
[DllImport("bcrypt.dll")] private static extern int BCryptSignHash(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[]? signature, int signatureSize, out int resultSize, int flags);
#endregion
}
+61 -43
View File
@@ -1,14 +1,14 @@
namespace MeloongCore; namespace MeloongCore;
public static class DirectoryUtils { public static class DirectoryUtils {
/// <summary> /// <summary>
/// 创建文件夹,或文件所在的文件夹。 /// 创建文件夹,或文件所在的文件夹。
/// 文件夹已存在时不会抛出异常。 /// 文件夹已存在时不会抛出异常。
/// </summary> /// </summary>
public static void Create(string path) { public static void Create(string folder) {
if (DirectoryUtils.Exists(path)) return; if (DirectoryUtils.Exists(folder)) return;
Logger.Trace($"新建文件夹:{path}"); Logger.Trace($"新建文件夹:{folder}");
Directory.CreateDirectory(PathUtils.ForApi(path)); Directory.CreateDirectory(PathUtils.ForApi(folder));
} }
/// <summary> /// <summary>
@@ -23,22 +23,22 @@ public static class DirectoryUtils {
/// <summary> /// <summary>
/// 判断文件夹是否存在。 /// 判断文件夹是否存在。
/// </summary> /// </summary>
public static bool Exists(string path) public static bool Exists(string folder)
=> Directory.Exists(PathUtils.ForApi(path)); => Directory.Exists(PathUtils.ForApi(folder));
/// <summary> /// <summary>
/// 获取 <see cref="DirectoryInfo"/> 对象。 /// 获取 <see cref="DirectoryInfo"/> 对象。
/// </summary> /// </summary>
public static DirectoryInfo GetInfo(string path) public static DirectoryInfo GetInfo(string folder)
=> new(PathUtils.ForApi(path)); => new(PathUtils.ForApi(folder));
/// <summary> /// <summary>
/// 返回指定路径下的所有文件,不以 \\?\ 开头。 /// 返回指定路径下的所有文件,不以 \\?\ 开头。
/// 如果文件夹不存在,返回空列表。 /// 如果文件夹不存在,返回空列表。
/// </summary> /// </summary>
public static IEnumerable<string> GetFiles(string path, bool topDirectoryOnly = false, string searchPattern = "*") { public static IEnumerable<string> EnumerateFiles(string folder, bool includeSubDirectories = false, string searchPattern = "*") {
if (!DirectoryUtils.Exists(path)) return []; if (!DirectoryUtils.Exists(folder)) return [];
return Directory.EnumerateFiles(PathUtils.ForApi(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories). return Directory.EnumerateFiles(PathUtils.ForApi(folder), searchPattern, includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).
Select(PathUtils.RemoveExtendedPrefix); Select(PathUtils.RemoveExtendedPrefix);
} }
@@ -46,9 +46,9 @@ public static class DirectoryUtils {
/// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。 /// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。
/// 如果文件夹不存在,返回空列表。 /// 如果文件夹不存在,返回空列表。
/// </summary> /// </summary>
public static IEnumerable<string> GetDirectories(string path, bool topDirectoryOnly = false, string searchPattern = "*") { public static IEnumerable<string> EnumerateDirectories(string folder, bool includeSubDirectories = false, string searchPattern = "*") {
if (!DirectoryUtils.Exists(path)) return []; if (!DirectoryUtils.Exists(folder)) return [];
return Directory.EnumerateDirectories(PathUtils.ForApi(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories). return Directory.EnumerateDirectories(PathUtils.ForApi(folder), searchPattern, includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).
Select(PathUtils.RemoveExtendedPrefix); Select(PathUtils.RemoveExtendedPrefix);
} }
@@ -56,9 +56,9 @@ public static class DirectoryUtils {
/// 该文件夹是否为空。 /// 该文件夹是否为空。
/// 如果文件夹不存在,返回 true。 /// 如果文件夹不存在,返回 true。
/// </summary> /// </summary>
public static bool IsEmpty(string path) { public static bool IsEmpty(string folder) {
if (!DirectoryUtils.Exists(path)) return true; if (!DirectoryUtils.Exists(folder)) return true;
return !Directory.EnumerateFileSystemEntries(PathUtils.ForApi(path)).Any(); return !Directory.EnumerateFileSystemEntries(PathUtils.ForApi(folder)).Any();
} }
/// <summary> /// <summary>
@@ -78,7 +78,7 @@ public static class DirectoryUtils {
} else { } else {
// 实际的复制 // 实际的复制
Logger.Trace($"复制文件夹:{sourceFolder} → {destFolder}"); Logger.Trace($"复制文件夹:{sourceFolder} → {destFolder}");
foreach (var file in DirectoryUtils.GetFiles(sourceFolder)) FileUtils.Copy(file, file.Replace(sourceFolder, destFolder)); foreach (var file in DirectoryUtils.EnumerateFiles(sourceFolder, includeSubDirectories: true).ToList()) FileUtils.Copy(file, file.Replace(sourceFolder, destFolder));
} }
} }
@@ -103,8 +103,10 @@ public static class DirectoryUtils {
// 同一磁盘剪切,直接调用 Move(这只修改文件夹名,效率更高) // 同一磁盘剪切,直接调用 Move(这只修改文件夹名,效率更高)
Logger.Trace($"剪切文件夹到同一磁盘:{sourceFolder} → {destFolder}"); Logger.Trace($"剪切文件夹到同一磁盘:{sourceFolder} → {destFolder}");
DirectoryUtils.Delete(destFolder); // Move 要求此前不存在对应文件夹 DirectoryUtils.Delete(destFolder); // Move 要求此前不存在对应文件夹
ResilientUtils.RetryOn<IOException>(() Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
=> Directory.Move(PathUtils.ForApi(sourceFolder), PathUtils.ForApi(destFolder))); FileUtils.SetReadOnly(sourceFolder, false);
Directory.Move(PathUtils.ForApi(sourceFolder), PathUtils.ForApi(destFolder));
});
} else { } else {
// 不同磁盘,必须先复制再删除,这就是我们傻逼微软 // 不同磁盘,必须先复制再删除,这就是我们傻逼微软
Logger.Trace($"剪切文件夹到不同磁盘:{sourceFolder} → {destFolder}"); Logger.Trace($"剪切文件夹到不同磁盘:{sourceFolder} → {destFolder}");
@@ -115,32 +117,48 @@ public static class DirectoryUtils {
/// <summary> /// <summary>
/// 删除文件夹。 /// 删除文件夹。
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
/// </summary> /// </summary>
public static void Delete(string folder, bool toRecycleBin = false) { /// <returns>
if (!DirectoryUtils.Exists(folder)) return; /// 如果文件夹不存在,返回 <see langword="null"/>。
/// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
/// <para/>如果永久删除,返回 <see langword="false"/>。
/// </returns>
public static bool? Delete(string folder, bool toRecycleBin = false) {
if (!DirectoryUtils.Exists(folder)) return null;
Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{folder}"); Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{folder}");
SafetyCheck(folder); SafetyCheck(folder);
// 删除 // 删除到回收站
if (toRecycleBin) { if (toRecycleBin) {
FileUtils.DeleteToRecycleBin(folder); // 删除到回收站 try {
} else { FileUtils.DeleteToRecycleBin(folder);
DeleteInternal(folder); // 永久删除 return true;
static void DeleteInternal(string folder) { } catch (Exception ex) {
try { Logger.Warn(ex, $"无法将文件夹删除到回收站,回退到永久删除:{folder}");
folder = PathUtils.ForApi(folder); }
foreach (string filePath in DirectoryUtils.GetFiles(folder, true)) FileUtils.Delete(filePath); // 删除文件 }
foreach (string str in DirectoryUtils.GetDirectories(folder, true)) DeleteInternal(str); // 递归删除子文件夹 // 永久删除
ResilientUtils.RetryOn<IOException>(() => Directory.Delete(folder, true)); // 最终删除文件夹 DeleteInternal(folder);
} catch (DirectoryNotFoundException ex) { // #4549,也可能已被其他线程删除 static void DeleteInternal(string folder) {
if (DirectoryUtils.Exists(folder)) { try {
Logger.Warn(ex, $"该文件夹可能为孤立的符号链接,尝试直接删除({folder})"); folder = PathUtils.ForApi(folder);
Directory.Delete(folder); foreach (string filePath in DirectoryUtils.EnumerateFiles(folder)) FileUtils.Delete(filePath); // 删除文件
} else { foreach (string str in DirectoryUtils.EnumerateDirectories(folder)) DeleteInternal(str); // 递归删除子文件夹
throw; Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
} FileUtils.SetReadOnly(folder, false);
Directory.Delete(folder, true);
}); // 最终删除文件夹
} catch (DirectoryNotFoundException ex) { // #4549,也可能已被其他线程删除
if (DirectoryUtils.Exists(folder)) {
Logger.Warn(ex, $"该文件夹可能为孤立的符号链接,尝试直接删除({folder})");
FileUtils.SetReadOnly(folder, false);
Directory.Delete(folder);
} else {
throw;
} }
} }
} }
return false;
} }
/// <summary> /// <summary>
@@ -151,16 +169,16 @@ public static class DirectoryUtils {
folder = PathUtils.ForCompare(folder); folder = PathUtils.ForCompare(folder);
if (folder == PathUtils.ForCompare(Path.GetPathRoot(folder))) if (folder == PathUtils.ForCompare(Path.GetPathRoot(folder)))
throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}"); throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}");
if (criticalFolders.Value.Any(f => f.StartsWithF(folder, ignoreCase: true))) if (criticalFolders.Value.Any(f => PathUtils.IsParentOf(folder, f)))
throw new UnauthorizedAccessException($"不应操作文件夹:{folder}"); throw new UnauthorizedAccessException($"不应操作文件夹:{folder}");
} }
private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] { private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] {
PathUtils.CurrentFolder, Paths.Base,
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Environment.GetFolderPath(Environment.SpecialFolder.Windows), Environment.GetFolderPath(Environment.SpecialFolder.Windows),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads") // 下载文件夹没有 SpecialFolder 枚举 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads") // 下载文件夹没有 SpecialFolder 枚举
}.Select(f => PathUtils.ForCompare(f)))); }.Where(f => f.Contains(Path.VolumeSeparatorChar)))); // 当缺少某个文件夹时,GetFolderPath 会返回空字符串(#8636)
} }
+15 -1
View File
@@ -1,4 +1,3 @@
using System.Collections.Concurrent;
using System.Globalization; using System.Globalization;
namespace MeloongCore; namespace MeloongCore;
@@ -10,6 +9,21 @@ public static class EnumUtils {
private static IEnumerable<T> GetAllValues<T>() where T : struct, Enum private static IEnumerable<T> GetAllValues<T>() where T : struct, Enum
=> Enum.GetValues(typeof(T)).Cast<T>(); => Enum.GetValues(typeof(T)).Cast<T>();
/// <summary>
/// 将字符串转换为枚举。
/// 支持枚举名或枚举序数;若为空字符串或 <see langword="null"/> 则返回 0。
/// 转换失败会抛出异常。
/// </summary>
public static T FromString<T>(string? value) where T : struct, Enum {
if (string.IsNullOrEmpty(value)) {
return (T) Enum.ToObject(typeof(T), 0);
} else if (double.TryParse(value, NumberStyles.Float, CultureInfo.CurrentCulture, out var number)) {
return (T) Enum.ToObject(typeof(T), Convert.ToInt64(number));
} else {
return (T) Enum.Parse(typeof(T), value, true);
}
}
/// <summary> /// <summary>
/// 对于具有 <see cref="FlagsAttribute"/> 的枚举,返回其所有 Flag 值。 /// 对于具有 <see cref="FlagsAttribute"/> 的枚举,返回其所有 Flag 值。
/// 建议仅对没有极端值的正数枚举使用。 /// 建议仅对没有极端值的正数枚举使用。
-95
View File
@@ -1,95 +0,0 @@
using System.Text.RegularExpressions;
namespace MeloongCore;
public static class EscapeUtils {
/// <summary>
/// WPF XML 转义。
/// </summary>
public static string XmlEscape(string str) {
if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str
.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
.Replace("\"", "&quot;").ReplaceLineEndings("&#xa;");
}
/// <summary>
/// VB.NET 的 Like 关键字转义。
/// </summary>
public static string LikePatternEscape(string input) {
var builder = new StringBuilder();
foreach (char c in input) {
if (c is '[' or ']' or '*' or '?' or '#') {
builder.Append('[').Append(c).Append(']');
} else {
builder.Append(c);
}
}
return builder.ToString();
}
/// <summary>
/// 正则表达式转义。
/// 等同于 <see cref="Regex.Escape"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string RegexEscape(string value)
=> Regex.Escape(value);
/// <summary>
/// 正则表达式去转义。
/// 等同于 <see cref="Regex.Unescape"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string RegexUnescape(string value)
=> Regex.Unescape(value);
/// <summary>
/// URL 转义。
/// 等同于 <see cref="Uri.EscapeDataString"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string UrlEscape(string value)
=> Uri.EscapeDataString(value);
/// <summary>
/// URL 去转义。
/// 等同于 <see cref="Uri.UnescapeDataString"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string UrlUnescape(string value)
=> Uri.UnescapeDataString(value);
/// <summary>
/// 表单转义。
/// 等同于 <see cref="WebUtility.UrlEncode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormUrlEscape(string value)
=> WebUtility.UrlEncode(value);
/// <summary>
/// 表单去转义。
/// 等同于 <see cref="WebUtility.UrlDecode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormUrlUnescape(string value)
=> WebUtility.UrlDecode(value);
/// <summary>
/// HTML 转义。
/// 等同于 <see cref="WebUtility.HtmlEncode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string HtmlEscape(string value)
=> WebUtility.HtmlEncode(value);
/// <summary>
/// HTML 去转义。
/// 等同于 <see cref="WebUtility.HtmlDecode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string HtmlUnescape(string value)
=> WebUtility.HtmlDecode(value);
}
+181 -40
View File
@@ -1,4 +1,4 @@
using System.IO.Compression; using System.IO.Compression;
namespace MeloongCore; namespace MeloongCore;
public static class FileUtils { public static class FileUtils {
@@ -6,17 +6,24 @@ public static class FileUtils {
#region 读取 #region 读取
/// <summary> /// <summary>
/// 打开指定文件的只读 <see cref="FileStream"/>。 /// 打开指定文件的只读 <see cref="Stream"/>。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary> /// </summary>
public static FileStream ReadAsStream(string filePath) public static Stream ReadAsStream(string filePath, Type? type = null) {
=> ResilientUtils.RetryOn<IOException, FileStream>(() if (type is null) {
=> new(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); return Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
=> new FileStream(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
} else {
return type.Assembly.GetManifestResourceStream(filePath) ?? throw new FileNotFoundException($"Embedded resource \"{filePath}\" was not found.");
}
}
/// <summary> /// <summary>
/// 读取文件中的所有内容。 /// 读取文件中的所有内容。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary> /// </summary>
public static byte[] ReadAsBytes(string filePath) { public static byte[] ReadAsBytes(string filePath, Type? type = null) {
using Stream fs = FileUtils.ReadAsStream(filePath); // 不能使用 File.ReadAllBytes,它不指定 FileShare.ReadWrite,会在文件被占用时抛出异常 using Stream fs = FileUtils.ReadAsStream(filePath, type); // 不能使用 File.ReadAllBytes,它不指定 FileShare.ReadWrite,会在文件被占用时抛出异常
using MemoryStream ms = new(); using MemoryStream ms = new();
fs.CopyTo(ms); fs.CopyTo(ms);
return ms.ToArray(); return ms.ToArray();
@@ -24,17 +31,19 @@ public static class FileUtils {
/// <summary> /// <summary>
/// 读取文件中的所有内容。 /// 读取文件中的所有内容。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary> /// </summary>
public static string ReadAsString(string filePath, Encoding? encoding = null) public static string ReadAsString(string filePath, Encoding? encoding = null, Type? type = null)
=> FileUtils.ReadAsBytes(filePath).GetString(encoding); => FileUtils.ReadAsBytes(filePath, type).GetString(encoding);
/// <summary> /// <summary>
/// 读取文件中的所有内容。 /// 读取文件中的所有内容。
/// 若文件不存在或读取失败,返回 <see langword="null"/>,而不是抛出异常。 /// <para/>若文件不存在或读取失败,返回 <see langword="null"/>,而不是抛出异常。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary> /// </summary>
public static string? TryReadAsString(string filePath, Encoding? encoding = null) { public static string? TryReadAsString(string filePath, Encoding? encoding = null, Type? type = null) {
try { try {
if (!FileUtils.Exists(filePath)) return null; if (type == null && !FileUtils.Exists(filePath)) return null;
return FileUtils.ReadAsBytes(filePath).GetString(encoding); return FileUtils.ReadAsBytes(filePath, type).GetString(encoding);
} catch { } catch {
return null; return null;
} }
@@ -42,15 +51,24 @@ public static class FileUtils {
/// <summary> /// <summary>
/// 读取文件中的所有内容,并按行分割。 /// 读取文件中的所有内容,并按行分割。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary> /// </summary>
public static string[] ReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null) public static string[] ReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null, Type? type = null)
=> FileUtils.ReadAsString(filePath, encoding).SplitLines(skipEmptyLines); => FileUtils.ReadAsString(filePath, encoding, type).SplitLines(skipEmptyLines);
/// <summary> /// <summary>
/// 读取文件中的所有内容,并按行分割。 /// 读取文件中的所有内容,并按行分割。
/// 若文件不存在或读取失败,返回空数组,而不是抛出异常。 /// <para/>若文件不存在或读取失败,返回空数组,而不是抛出异常。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary> /// </summary>
public static string[] TryReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null) public static string[] TryReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null, Type? type = null)
=> FileUtils.TryReadAsString(filePath, encoding)?.SplitLines(skipEmptyLines) ?? []; => FileUtils.TryReadAsString(filePath, encoding, type)?.SplitLines(skipEmptyLines) ?? [];
/// <summary>
/// 读取 JSON 文件中的所有内容。
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
/// </summary>
public static JToken? ReadAsJson(string filePath, Encoding? encoding = null, Type? type = null)
=> FileUtils.ReadAsString(filePath, encoding, type).DeserializeJson();
#endregion #endregion
@@ -75,7 +93,7 @@ public static class FileUtils {
public static void Write(string filePath, byte[] content) { public static void Write(string filePath, byte[] content) {
DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath)); DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
Logger.Trace($"写入文件:{filePath}({content.Length} 字节)"); Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
ResilientUtils.RetryOn<IOException>(() => { Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
FileUtils.Delete(filePath); FileUtils.Delete(filePath);
File.WriteAllBytes(PathUtils.ForApi(filePath), content); File.WriteAllBytes(PathUtils.ForApi(filePath), content);
}); });
@@ -87,7 +105,7 @@ public static class FileUtils {
/// 若文件已存在,则会覆盖原文件。 /// 若文件已存在,则会覆盖原文件。
/// </summary> /// </summary>
public static void Write(string filePath, Stream stream) { public static void Write(string filePath, Stream stream) {
ResilientUtils.RetryOn<IOException>(() => { Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
FileUtils.Delete(filePath); FileUtils.Delete(filePath);
using FileStream fileStream = FileUtils.CreateAsStream(filePath); using FileStream fileStream = FileUtils.CreateAsStream(filePath);
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin); if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
@@ -102,7 +120,7 @@ public static class FileUtils {
public static FileStream CreateAsStream(string filePath) { public static FileStream CreateAsStream(string filePath) {
DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath)); DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
Logger.Trace($"创建文件流:{filePath}"); Logger.Trace($"创建文件流:{filePath}");
return ResilientUtils.RetryOn<IOException, FileStream>(() => { return Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _ => {
FileUtils.Delete(filePath); FileUtils.Delete(filePath);
return new FileStream(PathUtils.ForApi(filePath), FileMode.Create); return new FileStream(PathUtils.ForApi(filePath), FileMode.Create);
}); });
@@ -112,7 +130,8 @@ public static class FileUtils {
/// 在临时文件夹下创建一个随机名称的文件,并返回其路径。 /// 在临时文件夹下创建一个随机名称的文件,并返回其路径。
/// </summary> /// </summary>
public static string CreateRandom() public static string CreateRandom()
=> ResilientUtils.RetryOn<IOException, string>(Path.GetTempFileName); => Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
=> Path.GetTempFileName());
#endregion #endregion
@@ -137,7 +156,8 @@ public static class FileUtils {
// 实际的复制 // 实际的复制
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath)); DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}"); Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn<IOException>(() if (FileUtils.Exists(destFilePath)) FileUtils.SetReadOnly(destFilePath, false);
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _
=> File.Copy(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath), true)); => File.Copy(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath), true));
} }
} }
@@ -155,8 +175,10 @@ public static class FileUtils {
} else if (string.Compare(sourceFilePath, destFilePath, ignoreCase: true) == 0) { } else if (string.Compare(sourceFilePath, destFilePath, ignoreCase: true) == 0) {
// 路径仅大小写不同 // 路径仅大小写不同
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}"); Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn<IOException>(() => { Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFilePath), Path.GetRandomFileName()); var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFilePath), Path.GetRandomFileName());
FileUtils.SetReadOnly(sourceFilePath, false);
if (FileUtils.Exists(destFilePath)) FileUtils.SetReadOnly(destFilePath, false);
File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(temp)); File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(temp));
File.Move(PathUtils.ForApi(temp), PathUtils.ForApi(destFilePath)); File.Move(PathUtils.ForApi(temp), PathUtils.ForApi(destFilePath));
}); });
@@ -165,8 +187,11 @@ public static class FileUtils {
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath)); DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
FileUtils.Delete(destFilePath); FileUtils.Delete(destFilePath);
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}"); Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn<IOException>(() Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
=> File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath))); FileUtils.SetReadOnly(sourceFilePath, false);
if (FileUtils.Exists(destFilePath)) FileUtils.SetReadOnly(destFilePath, false);
File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath));
});
} }
} }
@@ -176,16 +201,31 @@ public static class FileUtils {
/// <summary> /// <summary>
/// 删除文件。 /// 删除文件。
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
/// </summary> /// </summary>
public static void Delete(string filePath, bool toRecycleBin = false) { /// <returns>
if (!FileUtils.Exists(filePath)) return; /// 如果文件不存在,返回 <see langword="null"/>。
/// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
/// <para/>如果永久删除,返回 <see langword="false"/>。
/// </returns>
public static bool? Delete(string filePath, bool toRecycleBin = false) {
if (!FileUtils.Exists(filePath)) return null;
Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}"); Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}");
// 删除到回收站
if (toRecycleBin) { if (toRecycleBin) {
DeleteToRecycleBin(filePath); try {
} else { DeleteToRecycleBin(filePath);
ResilientUtils.RetryOn<IOException>(() return true;
=> File.Delete(PathUtils.ForApi(filePath))); } catch (Exception ex) {
Logger.Warn(ex, $"无法将文件删除到回收站,回退到永久删除:{filePath}");
}
} }
// 永久删除
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
FileUtils.SetReadOnly(filePath, false);
File.Delete(PathUtils.ForApi(filePath));
});
return false;
} }
/// <summary> /// <summary>
@@ -212,12 +252,12 @@ public static class FileUtils {
} }
// 在 STA 线程中执行删除方法 // 在 STA 线程中执行删除方法
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
ResilientUtils.RetryOn<IOException>(Run); Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => Run());
} else { } else {
System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常 System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
var thread = new Thread(() => { var thread = new Thread(() => {
try { try {
ResilientUtils.RetryOn<IOException>(Run); Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException or COMException, action: _ => Run());
} catch (Exception ex) { } catch (Exception ex) {
internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex);
} }
@@ -318,15 +358,14 @@ public static class FileUtils {
if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount); if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount);
if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空) if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
// ZipSlip 修复 // ZipSlip 修复
string outputFilePath = PathUtils.ForCompare(Path.Combine(outputDirectory, entry.FullName)); string outputFilePath = Path.Combine(outputDirectory, entry.FullName);
if (!outputFilePath.StartsWithF(PathUtils.AddSlashSuffix(PathUtils.ForCompare(outputDirectory)), ignoreCase:true)) if (!PathUtils.IsParentOf(outputDirectory, outputFilePath))
throw new ZipSlipException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题"); throw new InvalidDataException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
// 实际的解压 // 实际的解压
using var entryStream = entry.Open(); using var entryStream = entry.Open();
FileUtils.Write(outputFilePath, entryStream); FileUtils.Write(outputFilePath, entryStream);
} }
} }
public class ZipSlipException(string message) : Exception(message) {}
/// <summary> /// <summary>
/// 将指定文件夹的内容打包为 zip 文件。 /// 将指定文件夹的内容打包为 zip 文件。
@@ -336,7 +375,7 @@ public static class FileUtils {
DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath)); DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
FileUtils.Delete(outputFullPath); FileUtils.Delete(outputFullPath);
Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}"); Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}");
ResilientUtils.RetryOn<IOException>(() Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _
=> ZipFile.CreateFromDirectory(PathUtils.ForApi(sourceDirectory), PathUtils.ForApi(outputFullPath))); => ZipFile.CreateFromDirectory(PathUtils.ForApi(sourceDirectory), PathUtils.ForApi(outputFullPath)));
} }
@@ -362,7 +401,7 @@ public static class FileUtils {
public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) { public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) {
DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath)); DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
FileUtils.Delete(outputFullPath); FileUtils.Delete(outputFullPath);
using var archive = ResilientUtils.RetryOn<IOException, ZipArchive>(() using var archive = Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
=> ZipFile.Open(PathUtils.ForApi(outputFullPath), ZipArchiveMode.Create)); => ZipFile.Open(PathUtils.ForApi(outputFullPath), ZipArchiveMode.Create));
Logger.Trace($"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}"); Logger.Trace($"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}");
foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.ForApi(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal); foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.ForApi(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal);
@@ -382,4 +421,106 @@ public static class FileUtils {
public static FileInfo GetInfo(string path) public static FileInfo GetInfo(string path)
=> new(PathUtils.ForApi(path)); => new(PathUtils.ForApi(path));
/// <summary>
/// 设置文件或文件夹的只读属性。
/// 对文件夹使用时,只会设置文件夹本身的属性,不会递归设置其中的文件或子文件夹。
/// </summary>
public static void SetReadOnly(string path, bool readOnly) {
path = PathUtils.ForApi(path);
var attributes = File.GetAttributes(path);
var newAttributes = readOnly
? attributes | FileAttributes.ReadOnly
: attributes & ~FileAttributes.ReadOnly;
if (attributes == newAttributes) return;
Logger.Trace($"{(readOnly ? "添加" : "移除")}只读属性:{path}(原属性:{attributes},新属性:{newAttributes})");
File.SetAttributes(path, newAttributes);
}
}
/// <summary>
/// 检查文件是否符合校验规则,包括大小、Hash 值、是否为 JSON 文件。
/// </summary>
public class FileChecker {
/// <summary>
/// 文件的准确大小。
/// <para/>不检查则为 -1。
/// </summary>
public long ActualSize = -1;
/// <summary>
/// 文件的最小大小。
/// <para/>不检查则为 -1。
/// </summary>
public long MinSize = -1;
/// <summary>
/// 文件的 MD5、SHA1、SHA256 或 SHA512。会根据输入字符串的长度自动判断种类。
/// <para/>不检查则为 <c>null</c>。
/// </summary>
public string? Hash = null;
/// <summary>
/// 是否要求为 JSON 文件。
/// </summary>
public bool IsJson = false;
/// <summary>
/// 检查文件。
/// <para/>若成功则返回 <c>null</c>,失败则返回错误的描述文本(文本不以句号结尾)。
/// <para/>不会抛出异常。
/// </summary>
public string? Check(string localPath) {
try {
var info = FileUtils.GetInfo(localPath);
if (!info.Exists) return "文件不存在:" + localPath;
long fileSize = info.Length;
if (ActualSize >= 0 && ActualSize != fileSize) {
return $"文件大小应为 {ActualSize} B,实际为 {fileSize} B" +
(fileSize < 2000 ? ",内容为:" + FileUtils.ReadAsString(localPath) : "");
}
if (MinSize >= 0 && MinSize > fileSize) {
return $"文件大小应至少为 {MinSize} B,实际为 {fileSize} B" +
(fileSize < 2000 ? ",内容为:" + FileUtils.ReadAsString(localPath) : "");
}
string? hash = Hash;
if (!string.IsNullOrEmpty(hash)) {
hash = hash!.Lower();
switch (hash.Length) {
case 32:
string md5 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Md5);
if (hash != md5) return "文件 MD5 应为 " + hash + ",实际为 " + md5;
break;
case 40:
string sha1 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Sha1);
if (hash != sha1) return "文件 SHA1 应为 " + hash + ",实际为 " + sha1;
break;
case 64:
string sha256 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Sha256);
if (hash != sha256) return "文件 SHA256 应为 " + hash + ",实际为 " + sha256;
break;
case 128:
string sha512 = CryptographyUtils.ComputeFileHash(localPath, CryptographyUtils.HashMethod.Sha512);
if (hash != sha512) return "文件 SHA512 应为 " + hash + ",实际为 " + sha512;
break;
default:
return $"无法识别的 Hash 类型(长度为 {hash.Length}):{hash}";
}
}
if (IsJson) {
string content = FileUtils.ReadAsString(localPath);
if (content == "") return "读取到的文件为空";
content.DeserializeJson();
}
return null;
} catch (Exception ex) {
Logger.Warn(ex, "检查文件出错");
return ex.GetDisplay(false);
}
}
} }
+15
View File
@@ -0,0 +1,15 @@
namespace MeloongCore;
public static class GeneralUtils {
/// <summary>
/// 判断对象是否为指定泛型类型的实例。
/// </summary>
public static bool IsGenericInstanceOf(object? instance, Type genericTypeDefinition) {
if (instance is null) return false;
for (var type = instance.GetType(); type is not null; type = type.BaseType) {
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition) return true;
}
return false;
}
}
-23
View File
@@ -1,23 +0,0 @@
using System.Security.Cryptography;
namespace MeloongCore;
public static class HashUtils {
public enum HashMethod { Md5, Sha1, Sha256, Sha512 }
/// <summary>
/// 计算文件的哈希值(十六进制小写)。
/// </summary>
public static string ComputeFromFile(string filePath, HashMethod method) {
using var file = FileUtils.ReadAsStream(filePath);
using HashAlgorithm hashImpl = method switch {
HashMethod.Md5 => MD5.Create(),
HashMethod.Sha1 => SHA1.Create(),
HashMethod.Sha256 => SHA256.Create(),
HashMethod.Sha512 => SHA512.Create(),
_ => throw new ArgumentOutOfRangeException(nameof(method))
};
Logger.Trace($"计算文件 {method}:{filePath}");
return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").ToLower();
}
}
+13 -4
View File
@@ -1,4 +1,4 @@
using System.Numerics; using System.Numerics;
namespace MeloongCore; namespace MeloongCore;
public static class MathUtils { public static class MathUtils {
@@ -24,7 +24,7 @@ public static class MathUtils {
if (digit == -1 || digit >= fromRadix) throw new ArgumentException($"Character '{c}' in input '{input}' is not a valid digit for radix {fromRadix}."); if (digit == -1 || digit >= fromRadix) throw new ArgumentException($"Character '{c}' in input '{input}' is not a valid digit for radix {fromRadix}.");
realNum = realNum * fromRadix + digit; realNum = realNum * fromRadix + digit;
} }
return ConvertRadix(realNum * (isNegative ? -1 : 1), toRadix); return (realNum * (isNegative ? -1 : 1)).ConvertRadix(toRadix);
} }
/// <summary> /// <summary>
/// 转换为 2 到 86 进制的字符串。 /// 转换为 2 到 86 进制的字符串。
@@ -36,6 +36,12 @@ public static class MathUtils {
/// 转换为 2 到 86 进制的字符串。 /// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。 /// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary> /// </summary>
public static string ConvertRadix(this ulong input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this int input, int toRadix) public static string ConvertRadix(this int input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix); => ConvertRadix((BigInteger) input, toRadix);
/// <summary> /// <summary>
@@ -44,8 +50,11 @@ public static class MathUtils {
/// </summary> /// </summary>
public static string ConvertRadix(this byte input, int toRadix) public static string ConvertRadix(this byte input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix); => ConvertRadix((BigInteger) input, toRadix);
/// <summary>
private static string ConvertRadix(this BigInteger input, int toRadix) { /// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this BigInteger input, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',"; const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86."); if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86.");
// 零与负数的预处理 // 零与负数的预处理
+85 -56
View File
@@ -1,4 +1,4 @@
namespace MeloongCore; namespace MeloongCore;
public static class PathUtils { public static class PathUtils {
#region 分隔符 #region 分隔符
@@ -23,31 +23,31 @@ public static class PathUtils {
/// 若路径较长,则尽量将其转换为短路径。 /// 若路径较长,则尽量将其转换为短路径。
/// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。 /// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
/// </summary> /// </summary>
public static string ToShortPath(string fullName, bool keepFileName = false) { public static string ToShortPath(string pathName, bool keepFileName = false) {
if (string.IsNullOrEmpty(fullName)) return fullName; if (string.IsNullOrEmpty(pathName)) return pathName;
if (!fullName.Contains(@":\")) return fullName; if (!pathName.Contains(":")) return pathName;
if (fullName.Length <= 200) return fullName; if (pathName.Length <= 200) return pathName;
fullName = PathUtils.ForCompare(fullName); pathName = PathUtils.ForCompare(pathName);
// 保留文件名 // 保留文件名
string pathToKeep = ""; string pathToKeep = "";
string pathToShorten = fullName; string pathToShorten = pathName;
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名 if (pathName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && FileUtils.Exists(fullName)) { if (keepFileName && FileUtils.Exists(pathName)) {
pathToKeep = PathUtils.GetLastPart(fullName); pathToKeep = PathUtils.GetLastPart(pathName);
pathToShorten = PathUtils.RemoveLastPart(fullName); pathToShorten = PathUtils.RemoveLastPart(pathName);
} }
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短 // 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在 while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
string parentPath = Path.GetDirectoryName(pathToShorten); string parentPath = Path.GetDirectoryName(pathToShorten);
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回 if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return pathName; // 已经到达根目录,全都不存在,直接返回
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep); pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
pathToShorten = parentPath; pathToShorten = parentPath;
} }
if (pathToShorten.Length <= 10) return fullName; if (pathToShorten.Length <= 10) return pathName;
// 实际缩短路径 // 实际缩短路径
char[] buffer = new char[260]; char[] buffer = new char[260];
int result = GetShortPathNameW(PathUtils.ForApi(pathToShorten), buffer, buffer.Length); int result = GetShortPathNameW(PathUtils.ForApi(pathToShorten), buffer, buffer.Length);
if (result == 0) return fullName; if (result == 0) return pathName;
string shortPath = new(buffer, 0, result); string shortPath = new(buffer, 0, result);
return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.Combine(shortPath, pathToKeep))); return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.Combine(shortPath, pathToKeep)));
} }
@@ -58,24 +58,25 @@ public static class PathUtils {
/// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。 /// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。
/// 这会去除路径末尾的分隔符,将 / 替换为 \。 /// 这会去除路径末尾的分隔符,将 / 替换为 \。
/// </summary> /// </summary>
public static string ToExtendedFormat(string path) { public static string ToExtendedFormat(string pathName) {
if (string.IsNullOrWhiteSpace(path)) return path; if (string.IsNullOrWhiteSpace(pathName)) return pathName;
if (path.StartsWithF(@"\\?\")) return path; // 已经是长路径 if (!pathName.Contains(@":")) return pathName; // 可能是相对路径,保持不变
path = RemoveSlashSuffix(path).Replace('/', '\\'); // API 要求这个格式…… if (pathName.StartsWithF(@"\\?\")) return pathName; // 已经是长路径
if (path.StartsWithF(@"\\")) { pathName = RemoveSlashSuffix(pathName).Replace('/', '\\'); // API 要求这个格式……
return $@"\\?\UNC\{path.Substring(2)}"; if (pathName.StartsWithF(@"\\")) {
return $@"\\?\UNC\{pathName[2..]}";
} else { } else {
return $@"\\?\{path}"; return $@"\\?\{pathName}";
} }
} }
/// <summary> /// <summary>
/// 去除路径开头的 <c>\\?\</c>。 /// 去除路径开头的 <c>\\?\</c>。
/// </summary> /// </summary>
public static string RemoveExtendedPrefix(string path) { public static string RemoveExtendedPrefix(string pathName) {
if (path.StartsWithF(@"\\?\UNC\")) return @"\\" + path.AfterLast(@"\\?\UNC\"); if (pathName.StartsWithF(@"\\?\UNC\")) return @"\\" + pathName.AfterLast(@"\\?\UNC\");
if (path.StartsWithF(@"\\?\")) return path.AfterLast(@"\\?\"); if (pathName.StartsWithF(@"\\?\")) return pathName.AfterLast(@"\\?\");
return path; return pathName;
} }
#endregion #endregion
@@ -91,11 +92,11 @@ public static class PathUtils {
/// "C:\foo\" → "C:" /// "C:\foo\" → "C:"
/// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file" /// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
/// </code></summary> /// </code></summary>
public static string RemoveLastPart(string path) { public static string RemoveLastPart(string pathName) {
if (path!.Contains("://")) { // 网络路径 if (pathName!.Contains("://")) { // 网络路径
path = PathUtils.RemoveSlashSuffix(path.BeforeFirst("#").BeforeFirst("?")); // 去除参数 pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
} }
return PathUtils.RemoveSlashSuffix(path!).BeforeLastOfAny([@"\", "/"]); return PathUtils.RemoveSlashSuffix(pathName!).BeforeLastOfAny([@"\", "/"]);
} }
/// <summary> /// <summary>
@@ -106,13 +107,13 @@ public static class PathUtils {
/// "C:\foo\bar" → "bar" /// "C:\foo\bar" → "bar"
/// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip" /// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip"
/// </code></summary> /// </code></summary>
public static string GetLastPart(string path) { public static string GetLastPart(string pathName) {
if (path!.Contains("://")) { // 网络路径 if (pathName!.Contains("://")) { // 网络路径
path = PathUtils.RemoveSlashSuffix(path.BeforeFirst("#").BeforeFirst("?")); // 去除参数 pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
} else { // 文件路径 } else { // 文件路径
path = PathUtils.RemoveSlashSuffix(path); pathName = PathUtils.RemoveSlashSuffix(pathName);
} }
return path.AfterLastOfAny([@"\", "/"]); return pathName.AfterLastOfAny([@"\", "/"]);
} }
/// <summary> /// <summary>
@@ -123,8 +124,8 @@ public static class PathUtils {
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "page.xaml" /// "https://foo.bar/file/page.xaml.vb?arg=1" → "page.xaml"
/// </code> /// </code>
/// </summary> /// </summary>
public static string GetFileNameWithoutExtension(string path) public static string GetFileNameWithoutExtension(string pathName)
=> GetLastPart(path).BeforeLast("."); => GetLastPart(pathName).BeforeLast(".");
/// <summary> /// <summary>
/// 获取路径或文件名中的最后一级文件扩展名,不包含 <c>.</c>,固定小写。 /// 获取路径或文件名中的最后一级文件扩展名,不包含 <c>.</c>,固定小写。
@@ -136,8 +137,8 @@ public static class PathUtils {
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "vb" /// "https://foo.bar/file/page.xaml.vb?arg=1" → "vb"
/// </code> /// </code>
/// </summary> /// </summary>
public static string GetExtension(string path) { public static string GetExtension(string pathName) {
var name = GetLastPart(path); var name = GetLastPart(pathName);
return name.Contains(".") ? name.AfterLast(".").Lower() : ""; return name.Contains(".") ? name.AfterLast(".").Lower() : "";
} }
@@ -145,40 +146,68 @@ public static class PathUtils {
/// 获取路径的盘符,返回一个大写字母。 /// 获取路径的盘符,返回一个大写字母。
/// 若路径不包含盘符,则返回 <c>null</c>。 /// 若路径不包含盘符,则返回 <c>null</c>。
/// </summary> /// </summary>
public static char? GetDiskName(string? path) { public static char? GetDiskName(string? pathName) {
if (string.IsNullOrEmpty(path)) return null; if (string.IsNullOrEmpty(pathName)) return null;
path = PathUtils.RemoveExtendedPrefix(path!); pathName = PathUtils.RemoveExtendedPrefix(pathName!);
if (path.StartsWithF(@"\\") || path.StartsWithF("/")) return null; if (pathName.StartsWithF(@"\\") || pathName.StartsWithF("/")) return null;
return char.ToUpper(path[0]); return char.ToUpper(pathName[0]);
} }
/// <summary> /// <summary>
/// 统一路径格式,以便比较。 /// 统一路径格式,以便比较。
/// <para/>具体而言:将短路径展开,去除前导的 <c>\\?\</c>,将分隔符改为 \,去除末尾的分隔符。 /// <para/>具体而言:将短路径展开,去除前导的 <c>\\?\</c>,将分隔符改为 \,去除末尾的分隔符。
/// </summary> /// </summary>
public static string ForCompare(string path) public static string ForCompare(string pathName) {
=> PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.GetFullPath(path)).Replace("/", @"\")); try {
return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.GetFullPath(pathName)).Replace("/", @"\"));
} catch (ArgumentException ex) {
throw new ArgumentException($"路径不正确:{pathName}", ex);
}
}
/// <summary> /// <summary>
/// 将路径转换为兼容各种 Windows API 的格式。 /// 将路径转换为兼容各种 Windows API 的格式。
/// <para/>具体而言:将分隔符改为 \。添加前导的 <c>\\?\</c>。若为驱动器则添加末尾分隔符,否则去除分隔符。 /// <para/>具体而言:将分隔符改为 \。添加前导的 <c>\\?\</c>。若为驱动器则添加末尾分隔符,否则去除分隔符。
/// </summary> /// </summary>
public static string ForApi(string path) { public static string ForApi(string pathName) {
path = PathUtils.ToExtendedFormat(path); pathName = PathUtils.ToExtendedFormat(pathName);
if (path.EndsWithF(":")) path += @"\"; // 驱动器路径必须保留末尾的分隔符 if (pathName.EndsWithF(":")) pathName += @"\"; // 驱动器路径必须保留末尾的分隔符
if (path.EndsWithF(@":\")) return path; if (pathName.EndsWithF(@":\")) return pathName;
return PathUtils.RemoveSlashSuffix(path); return PathUtils.RemoveSlashSuffix(pathName);
} }
#endregion #endregion
#region 常用路径
/// <summary> /// <summary>
/// 程序可执行文件的所在文件夹,以 \ 结尾。 /// 判断 <param name="parentPath"/> 是否为 <paramref name="childPath"/> 的父路径,或两者是否相同。
/// </summary> /// </summary>
public static string CurrentFolder => PathUtils.AddSlashSuffix(AppDomain.CurrentDomain.BaseDirectory); public static bool IsParentOf(string parentPath, string childPath) {
parentPath = PathUtils.ForCompare(parentPath);
#endregion childPath = PathUtils.ForCompare(childPath);
return childPath.StartsWithF(parentPath + @"\") || childPath == parentPath;
}
} }
/// <summary>
/// 常用路径合集。
/// 所有路径均以分隔符结尾。
/// </summary>
public static class Paths {
/// <summary>
/// 可执行文件所在的文件夹。
/// </summary>
public static string Base => PathUtils.AddSlashSuffix(AppContext.BaseDirectory);
/// <summary>
/// 可执行文件所在的文件夹中,名为 <see cref="Main.AppName"/> 的子文件夹。
/// </summary>
public static string BaseThenName => PathUtils.AddSlashSuffix(Base + Main.AppName);
/// <summary>
/// %AppData% 文件夹。
/// </summary>
public static string AppData => PathUtils.AddSlashSuffix(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
/// <summary>
/// %AppData% 文件夹中,名为 <see cref="Main.AppName"/> 的子文件夹。
/// </summary>
public static string AppDataThenName => PathUtils.AddSlashSuffix(AppData + Main.AppName);
}
-41
View File
@@ -1,41 +0,0 @@
namespace MeloongCore;
public static class ResilientUtils {
/// <summary>
/// 在抛出任意异常时,延迟并自动重试。
/// </summary>
public static void Retry(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "")
=> RetryOn<Exception>(action, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出特定异常时,延迟并自动重试。
/// </summary>
public static void RetryOn<TException>(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException : Exception
=> RetryOn<TException, object?>(() => { action(); return null; }, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出任意异常时,延迟并自动重试。
/// </summary>
public static void Retry<TOut>(Func<TOut> func, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "")
=> RetryOn<Exception, TOut>(func, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出特定异常时,延迟并自动重试。
/// </summary>
public static TOut RetryOn<TException, TOut>(Func<TOut> func, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException : Exception {
int attempt = 0;
while (true) {
try {
return func(); // 成功则退出
} catch (TException ex) {
attempt++;
if (attempt < maxAttempts) {
Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,将在 {delayMs}ms 后重试");
Thread.Sleep(delayMs);
} else { // 超过最大尝试次数
Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,已到达最大尝试次数");
throw;
}
}
}
}
}
+204
View File
@@ -0,0 +1,204 @@
using System.Text.RegularExpressions;
namespace MeloongCore;
public static class StringUtils {
#region 转义
/// <summary>
/// WPF XML 转义。
/// </summary>
public static string XmlEscape(string str) {
if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str
.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
.Replace("\"", "&quot;").ReplaceLineEndings("&#xa;");
}
/// <summary>
/// VB.NET 的 Like 关键字转义。
/// </summary>
public static string LikePatternEscape(string input) {
var builder = new StringBuilder();
foreach (char c in input) {
if (c is '[' or ']' or '*' or '?' or '#') {
builder.Append('[').Append(c).Append(']');
} else {
builder.Append(c);
}
}
return builder.ToString();
}
/// <summary>
/// 正则表达式转义。
/// 等同于 <see cref="Regex.Escape"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string RegexEscape(string value)
=> Regex.Escape(value);
/// <summary>
/// 正则表达式去转义。
/// 等同于 <see cref="Regex.Unescape"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string RegexUnescape(string value)
=> Regex.Unescape(value);
/// <summary>
/// URL 转义。
/// 等同于 <see cref="Uri.EscapeDataString"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string UrlEscape(string value)
=> Uri.EscapeDataString(value);
/// <summary>
/// URL 去转义。
/// 等同于 <see cref="Uri.UnescapeDataString"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string UrlUnescape(string value)
=> Uri.UnescapeDataString(value);
/// <summary>
/// 表单转义。
/// 等同于 <see cref="WebUtility.UrlEncode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormUrlEscape(string value)
=> WebUtility.UrlEncode(value);
/// <summary>
/// 表单去转义。
/// 等同于 <see cref="WebUtility.UrlDecode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormUrlUnescape(string value)
=> WebUtility.UrlDecode(value);
/// <summary>
/// HTML 转义。
/// 等同于 <see cref="WebUtility.HtmlEncode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string HtmlEscape(string value)
=> WebUtility.HtmlEncode(value);
/// <summary>
/// HTML 去转义。
/// 等同于 <see cref="WebUtility.HtmlDecode"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string HtmlUnescape(string value)
=> WebUtility.HtmlDecode(value);
#endregion
#region 格式化
/// <summary>
/// 将文件大小的字节数格式化为适合阅读的文本,如 <c>"1.28 M"</c>、<c>"128 G"</c>。
/// </summary>
public static string FormatByteSize(long byteSize) {
var sign = byteSize < 0 ? "-" : "";
if (byteSize < 0) byteSize *= -1;
if (byteSize < 1000) { // B 级
return $"{sign}{byteSize} B";
} else if (byteSize < 1024 * 1000) { // K 级
var roundResult = Math.Round(byteSize / 1024D).ToString();
return $"{sign}{Math.Round(byteSize / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} K";
} else if (byteSize < 1024 * 1024 * 1000) { // M 级
var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString();
return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} M";
} else { // G 级
var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString();
return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} G";
}
}
/// <summary>
/// 将时间间隔格式化为适合阅读的文本。
/// <para/>若指定了 <paramref name="isShort"/>,则只使用一个单位,如 <c>"5 分钟前"</c>,否则有可能会使用两个单位,如 <c>"5 分 10 秒前"</c>。
/// </summary>
public static string FormatTimeSpan(TimeSpan span, bool isShort) {
var suffix = span.TotalMilliseconds > 0 ? "后" : "前";
if (span.TotalMilliseconds < 0) span = -span;
var totalMonths = (int) Math.Floor(span.Days / 30D);
if (isShort) {
if (totalMonths >= 12) {
// 1+ 年,“3 年”
return $"{Math.Floor(totalMonths / 12D)} 年{suffix}";
} else if (totalMonths >= 2) {
// 2~11 月,“5 个月”
return $"{totalMonths} 个月{suffix}";
} else if (span.TotalDays >= 2) {
// 2 天 ~ 2 月,“23 天”
return $"{span.Days} 天{suffix}";
} else if (span.TotalHours >= 1) {
// 1 小时 ~ 2 天,“15 小时”
return $"{span.Hours} 小时{suffix}";
} else if (span.TotalMinutes >= 1) {
// 1 分钟 ~ 1 小时,“49 分钟”
return $"{span.Minutes} 分钟{suffix}";
} else if (span.TotalSeconds >= 1) {
// 1 秒 ~ 1 分钟,“23 秒”
return $"{span.Seconds} 秒{suffix}";
} else {
// 不到 1 秒
return $"1 秒{suffix}";
}
} else {
if (totalMonths >= 61) {
// 5+ 年,“5 年”
return $"{Math.Floor(totalMonths / 12D)} 年{suffix}";
} else if (totalMonths >= 12) {
// 12~60 月,“1 年 2 个月”
return $"{Math.Floor(totalMonths / 12D)} 年{(totalMonths % 12 > 0 ? $" {totalMonths % 12} 个月" : "")}{suffix}";
} else if (totalMonths >= 4) {
// 4~11 月,“5 个月”
return $"{totalMonths} 个月{suffix}";
} else if (totalMonths >= 1) {
// 1~4 月,“2 个月 13 天”
return $"{totalMonths} 月{(span.Days % 30 > 0 ? $" {span.Days % 30} 天" : "")}{suffix}";
} else if (span.TotalDays >= 4) {
// 4~30 天,“23 天”
return $"{span.Days} 天{suffix}";
} else if (span.TotalDays >= 1) {
// 1~3 天,“2 天 20 小时”
return $"{span.Days} 天{(span.Hours > 0 ? $" {span.Hours} 小时" : "")}{suffix}";
} else if (span.TotalHours >= 10) {
// 10 小时 ~ 1 天,“15 小时”
return $"{span.Hours} 小时{suffix}";
} else if (span.TotalHours >= 1) {
// 1~10 小时,“1 小时 20 分钟”
return $"{span.Hours} 小时{(span.Minutes > 0 ? $" {span.Minutes} 分钟" : "")}{suffix}";
} else if (span.TotalMinutes >= 10) {
// 10 分钟 ~ 1 小时,“49 分钟”
return $"{span.Minutes} 分钟{suffix}";
} else if (span.TotalMinutes >= 1) {
// 1~10 分钟,“9 分 23 秒”
return $"{span.Minutes} 分{(span.Seconds > 0 ? $" {span.Seconds} 秒" : "")}{suffix}";
} else if (span.TotalSeconds >= 1) {
// 1 秒 ~ 1 分钟,“23 秒”
return $"{span.Seconds} 秒{suffix}";
} else {
// 不到 1 秒
return $"1 秒{suffix}";
}
}
}
#endregion
/// <summary>
/// 将字符串解析为版本号。
/// 允许缺少任意多个段,且会将缺失的段不为 0,而不是 -1。例如,"2" 会被解析为 2.0.0.0。
/// </summary>
public static Version ParseVersionWithDefaults(string value) {
while (value.Count(c => c == '.') < 3) value += ".0";
return Version.Parse(value);
}
}
+125
View File
@@ -0,0 +1,125 @@
using System.Diagnostics;
namespace MeloongCore;
public static class TaskUtils {
/// <summary>
/// 并行执行所有任务。
/// </summary>
public static Task WhenAll(IEnumerable<Func<ProgressProvider?, Task>> tasks, ProgressProvider? progress = null) {
var taskList = tasks.ToList();
if (!taskList.Any()) {
progress?.Skip();
return Task.CompletedTask;
}
// 实际分割
var progressEach = 1d / taskList.Count;
return Task.WhenAll(taskList.Select(async (task, index) => {
var cp = progress?.SplitBy(progressEach)[0];
await task(cp).NoCapture();
cp?.Finish();
}));
}
/// <summary>
/// 并行执行所有任务并返回结果。
/// </summary>
public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Func<ProgressProvider?, Task<TResult>>> tasks, ProgressProvider? progress = null) {
var taskList = tasks.ToList();
if (!taskList.Any()) {
progress?.Skip();
return Task.FromResult(Array.Empty<TResult>());
}
// 实际分割
var progressEach = 1d / taskList.Count;
return Task.WhenAll(taskList.Select(async (task, index) => {
var cp = progress?.SplitBy(progressEach)[0];
var result = await task(cp).NoCapture();
cp?.Finish();
return result;
}));
}
/// <summary>
/// 并行执行所有任务。
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks, ProgressProvider? progress = null)
=> WhenAll(tasks.Select(task => new Func<ProgressProvider?, Task>(_ => task)), progress);
/// <summary>
/// 并行执行所有任务并返回结果。
/// </summary>
public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks, ProgressProvider? progress = null)
=> WhenAll(tasks.Select(task => new Func<ProgressProvider?, Task<TResult>>(_ => task)), progress);
public static void ForEach<T>(IEnumerable<T> source, Action<T> body)
=> Parallel.ForEach(source, body);
public static async Task ForEachAsync<T>(IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, ProgressProvider?, Task> body,
CancellationToken cancellationToken = default, ProgressProvider? progress = null) {
using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var token = linkedCancellationTokenSource.Token;
var enumeratorLock = new object();
using var enumerator = source.GetEnumerator();
async Task WorkerAsync(ProgressProvider? cp) {
try {
while (true) {
T item;
lock (enumeratorLock) {
token.ThrowIfCancellationRequested();
if (!enumerator.MoveNext()) return;
item = enumerator.Current;
}
await body(item, cp).NoCapture();
}
} catch {
try {
linkedCancellationTokenSource.Cancel(); // 让尚未开始的 worker 尽快停止
} catch {
}
throw;
}
}
await TaskUtils.WhenAll(Enumerable.Repeat(WorkerAsync, maxDegreeOfParallelism), progress).NoCapture();
}
/// <summary>
/// 静默运行程序并等待其结束,返回其输出和退出码。
/// 支持 notepad、git 等命令。
/// 超时或启动失败会抛出异常。
/// </summary>
public static async Task<(string Output, int ExitCode)> RunProgramAsync(string file, string arguments = "", int? timeoutMs = null, Encoding? encoding = null, CancellationToken cancellationToken = default) {
cancellationToken.ThrowIfCancellationRequested();
var info = new ProcessStartInfo {
Arguments = arguments,
FileName = PathUtils.ToShortPath(file),
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true, StandardOutputEncoding = encoding,
RedirectStandardError = true, StandardErrorEncoding = encoding
};
using var program = new Process { StartInfo = info, EnableRaisingEvents = true };
if (!program.Start()) throw new InvalidOperationException($"运行程序时出现意外错误:{file} {arguments}");
bool hasTimeout = timeoutMs is > 0;
Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}");
// 输出和错误流
var outputTask = program.StandardOutput.ReadToEndAsync();
var errorTask = program.StandardError.ReadToEndAsync();
var completionSource = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
program.Exited += (_, _) => completionSource.TrySetResult(null);
if (program.HasExited) completionSource.TrySetResult(null);
var task = completionSource.Task;
var timeoutTask = Task.Delay(hasTimeout ? timeoutMs!.Value : Timeout.Infinite);
var cancelTask = Task.Delay(Timeout.Infinite, cancellationToken);
Logger.Trace($"等待程序 {program.Id} 完成");
var completedTask = await Task.WhenAny(task, timeoutTask, cancelTask).NoCapture();
if (completedTask != task) {
try {
if (!program.HasExited) program.Kill();
} catch (InvalidOperationException) { // 进程已退出,无需处理
}
if (completedTask == cancelTask) throw new OperationCanceledException(cancellationToken);
throw new TimeoutException($"运行程序超时:{file} {arguments}");
}
return (await outputTask.NoCapture() + await errorTask.NoCapture(), program.ExitCode);
}
}
@@ -1,4 +1,4 @@
namespace MeloongCore; namespace MeloongCore;
/// <summary> /// <summary>
/// 当 HTTP 请求的状态码不指示成功时引发的异常。 /// 当 HTTP 请求的状态码不指示成功时引发的异常。
+100
View File
@@ -0,0 +1,100 @@
namespace MeloongCore.Tests;
public class ConfigTest : TestWithFolder {
#region JsonConfigProvider
[Test]
public async Task JsonConfigProvider_字符串列表() {
string configFile = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(configFile);
var entry = new ConfigEntry<List<string>>("list", [], provider);
entry.Set(["Alpha", "中文", "123"]);
provider.Save();
var reloadedEntry = new ConfigEntry<List<string>>("list", [], new JsonConfigProvider(configFile));
var reloadedValue = reloadedEntry.Get();
await Assert.That(reloadedValue is not null).IsTrue();
await Assert.That(string.Join("|", reloadedValue!)).IsEqualTo("Alpha|中文|123");
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"list\": [");
}
[Test]
public async Task JsonConfigProvider_自定义类列表() {
string configFile = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(configFile);
var entry = new ConfigEntry<List<TestConfigItem>>("items", [], provider);
entry.Set([
new() { Name = "Fabric", Count = 2, Enabled = true },
new() { Name = "Forge 中文", Count = 5, Enabled = false }
]);
provider.Save();
var reloadedEntry = new ConfigEntry<List<TestConfigItem>>("items", [], new JsonConfigProvider(configFile));
var reloadedValue = reloadedEntry.Get();
await Assert.That(reloadedValue is not null).IsTrue();
await Assert.That(string.Join("|", reloadedValue!.Select(i => $"{i.Name}:{i.Count}:{i.Enabled}"))).IsEqualTo("Fabric:2:True|Forge 中文:5:False");
string json = FileUtils.ReadAsString(configFile);
await Assert.That(json).Contains("\"items\": [");
await Assert.That(json).Contains("\"Name\": \"Fabric\"");
await Assert.That(json).Contains("\"Count\": 2");
await Assert.That(json).Contains("\"Enabled\": true");
await Assert.That(json).Contains("\"Name\": \"Forge 中文\"");
await Assert.That(json).Contains("\"Enabled\": false");
}
[Test]
public async Task ConfigEntry_SetNull_RoundTripsThroughJson() {
string configFile = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(configFile);
var entry = new ConfigEntry<string>("nullable", "fallback", provider);
entry.Set(null);
provider.Save();
var reloadedEntry = new ConfigEntry<string>("nullable", "fallback", new JsonConfigProvider(configFile));
await Assert.That(reloadedEntry.HasValue()).IsTrue();
await Assert.That(reloadedEntry.Get() is null).IsTrue();
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"nullable\": null");
}
[Test]
public async Task ConfigEntry_SetString_RoundTripsThroughJson() {
string configFile = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(configFile);
var entry = new ConfigEntry<string>("text", "fallback", provider);
entry.Set("plain text 中文");
provider.Save();
var reloadedEntry = new ConfigEntry<string>("text", "fallback", new JsonConfigProvider(configFile));
await Assert.That(reloadedEntry.Get()).IsEqualTo("plain text 中文");
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"text\": \"plain text 中文\"");
}
[Test]
public async Task ConfigUtils_SaveAll_WritesPendingChangesImmediately() {
string configFile = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(configFile);
var entry = new ConfigEntry<string>("text", "fallback", provider);
entry.Set("pending 中文");
ConfigUtils.SaveAll();
ConfigUtils.SaveAll();
var reloadedEntry = new ConfigEntry<string>("text", "fallback", new JsonConfigProvider(configFile));
await Assert.That(reloadedEntry.Get()).IsEqualTo("pending 中文");
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"text\": \"pending 中文\"");
}
public class TestConfigItem {
public string Name { get; set; } = "";
public int Count { get; set; }
public bool Enabled { get; set; }
}
#endregion
}
+74
View File
@@ -0,0 +1,74 @@
namespace MeloongCore.Tests;
public class ProgressTest : TestBase {
[Test]
public async Task ProgressChanged_主进度实际改变时触发() {
var progress = new ProgressProvider();
int changedCount = 0;
progress.ProgressChanged += _ => changedCount++;
progress.Set(0.2);
progress.Set(0.2);
progress.Add(0.1);
progress.Add(0);
progress.Set(0.5, skiped: true);
await Assert.That(changedCount).IsEqualTo(3);
}
[Test]
public async Task ProgressChanged_子进度改变时向父级传播() {
var progress = new ProgressProvider();
int changedCount = 0;
(double actual, double skiped) changedProgress = default;
progress.ProgressChanged += value => {
changedCount++;
changedProgress = value;
};
var sub = progress.SplitBy(0.5).Single();
sub.Set(0.5);
sub.Set(0.5);
await Assert.That(changedCount).IsEqualTo(1);
await Assert.That(changedProgress.actual).IsEqualTo(0.25);
await Assert.That(changedProgress.skiped).IsEqualTo(0);
}
[Test]
public async Task ProgressChanged_不会触发Observe() {
var progress = new ProgressProvider();
int changedCount = 0;
progress.ProgressChanged += _ => changedCount++;
progress.Set(0.5);
progress.Set(0.75, skiped: true);
await Assert.That(changedCount).IsEqualTo(2);
await Assert.That(Math.Abs(progress.GetIncrement() - 2.0 / 3) < 0.000001).IsTrue();
}
[Test]
public async Task ProgressObserver_监听进度变化并更新UI() {
var progress = new ProgressProvider();
int updateCount = 0;
double updatedProgress = 0;
using (var observer = new ProgressObserver(progress, value => {
updateCount++;
updatedProgress = value;
}, TimeSpan.FromHours(1).TotalMilliseconds)) {
progress.Set(0.25);
await Assert.That(updateCount).IsEqualTo(1);
await Assert.That(updatedProgress).IsEqualTo(0.25);
}
progress.Set(0.5);
await Task.Delay(50);
await Assert.That(updateCount).IsEqualTo(1);
}
}
+52
View File
@@ -0,0 +1,52 @@
namespace MeloongCore.Tests;
public class WorkerTest : TestBase {
[Test]
public async Task Run_在工作线程执行工作负载() {
int callerThreadId = Thread.CurrentThread.ManagedThreadId;
int workloadThreadId = callerThreadId;
using var started = new ManualResetEventSlim(false);
var worker = new RedoableWorker(() => {
workloadThreadId = Thread.CurrentThread.ManagedThreadId;
started.Set();
});
worker.Start();
await Assert.That(started.Wait(3000)).IsTrue();
await Assert.That(worker.WaitIfRunning(3000)).IsTrue();
await Assert.That(workloadThreadId != callerThreadId).IsTrue();
await Assert.That(worker.LastSucceeded).IsTrue();
}
[Test]
public async Task Run_运行中再次调用只重跑一次() {
int callerThreadId = Thread.CurrentThread.ManagedThreadId;
int runCount = 0;
var workloadThreadIds = new ConcurrentQueue<int>();
using var firstStarted = new ManualResetEventSlim(false);
var worker = new RedoableWorker(ct => {
int currentRun = Interlocked.Increment(ref runCount);
workloadThreadIds.Enqueue(Thread.CurrentThread.ManagedThreadId);
if (currentRun == 1) {
firstStarted.Set();
while (true) {
ct?.ThrowIfCancellationRequested();
Thread.Sleep(10);
}
}
});
worker.Start();
await Assert.That(firstStarted.Wait(3000)).IsTrue();
worker.Start();
worker.Start();
await Assert.That(worker.WaitIfRunning(3000)).IsTrue();
await Assert.That(runCount).IsEqualTo(2);
await Assert.That(workloadThreadIds.All(id => id != callerThreadId)).IsTrue();
await Assert.That(worker.LastSucceeded).IsTrue();
}
}
+2 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net48</TargetFramework> <TargetFramework>net48</TargetFramework>
@@ -59,6 +59,7 @@
<Using Include="System.Diagnostics.CodeAnalysis" /> <Using Include="System.Diagnostics.CodeAnalysis" />
<Using Include="System.Collections" /> <Using Include="System.Collections" />
<Using Include="System.Collections.Generic" /> <Using Include="System.Collections.Generic" />
<Using Include="System.Collections.Concurrent" />
<Using Include="System.Text" /> <Using Include="System.Text" />
<Using Include="System.Net" /> <Using Include="System.Net" />
<Using Include="System.Runtime.CompilerServices" /> <Using Include="System.Runtime.CompilerServices" />
+4 -3
View File
@@ -1,4 +1,4 @@
namespace MeloongCore.Tests; namespace MeloongCore.Tests;
/// <summary> /// <summary>
/// 所有测试的基类。 /// 所有测试的基类。
@@ -7,7 +7,8 @@
public abstract class TestBase { public abstract class TestBase {
public TestBase() { public TestBase() {
MeloongCore.Main.Init(new TestLogger()); MeloongCore.Main.Init("MeloongCoreTest");
Logger.Instance = new TestLogger();
} }
private class TestLogger : BaseLogger { private class TestLogger : BaseLogger {
public override void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex) public override void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex)
@@ -40,7 +41,7 @@ public abstract class TestWithFolder : TestBase {
/// 输出指定的测试用文件,返回文件路径。 /// 输出指定的测试用文件,返回文件路径。
/// </summary> /// </summary>
public string GetTestFile(string fileName) { public string GetTestFile(string fileName) {
var sourceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", GetType().Name.Replace("Test", ""), fileName); var sourceFilePath = Path.Combine(Paths.Base, "TestFiles", GetType().Name.Replace("Test", ""), fileName);
var distPath = Path.Combine(tempFolder, PathUtils.GetLastPart(sourceFilePath)); var distPath = Path.Combine(tempFolder, PathUtils.GetLastPart(sourceFilePath));
FileUtils.Copy(sourceFilePath, distPath); FileUtils.Copy(sourceFilePath, distPath);
return distPath; return distPath;
+48
View File
@@ -0,0 +1,48 @@
using System.Security.Cryptography;
namespace MeloongCore.Tests;
public class CryptographyUtilsTest : TestBase {
#region 对称加密
[Test]
[Arguments("")]
[Arguments("PCL")]
[Arguments("中文内容 Test 123 !@#$%^&*()")]
public async Task 对称加密_往返(string sourceString) {
string encryptedString = CryptographyUtils.AesEncrypt(sourceString, "PCL-Key-中文");
if (!string.IsNullOrEmpty(sourceString))
await Assert.That(encryptedString != sourceString).IsTrue();
await Assert.That(CryptographyUtils.AesDecrypt(encryptedString, "PCL-Key-中文")).IsEqualTo(sourceString);
}
[Test]
public async Task 对称加密_随机化()
=> await Assert.That(CryptographyUtils.AesEncrypt("same source", "same key") != CryptographyUtils.AesEncrypt("same source", "same key")).IsTrue();
[Test]
public void 对称加密_篡改失败() {
byte[] encryptedBytes = Convert.FromBase64String(CryptographyUtils.AesEncrypt("source", "key"));
encryptedBytes[encryptedBytes.Length - 1] ^= 1;
Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt(Convert.ToBase64String(encryptedBytes), "key"));
}
[Test]
public void AesDecrypt_TamperedIvFails() {
byte[] encryptedBytes = Convert.FromBase64String(CryptographyUtils.AesEncrypt("source", "key"));
encryptedBytes[1] ^= 1;
Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt(Convert.ToBase64String(encryptedBytes), "key"));
}
[Test]
public void 对称加密_错误密钥失败() {
Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt(CryptographyUtils.AesEncrypt("source", "key"), "bad key"));
}
[Test]
public void 对称加密_格式错误失败()
=> Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt("not base64", "key"));
#endregion
}
+16 -4
View File
@@ -20,7 +20,7 @@ public class DirectoryUtilsTest : TestWithFolder {
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa"); await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa");
await Assert.That(FileUtils.ReadAsString(Path.Combine(src, "sub", "b file.txt"))).IsEqualTo("bbb"); await Assert.That(FileUtils.ReadAsString(Path.Combine(src, "sub", "b file.txt"))).IsEqualTo("bbb");
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb"); await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb");
await Assert.That(DirectoryUtils.GetDirectories(Path.Combine(tempFolder))).Contains(dest); // 目标文件夹名 await Assert.That(DirectoryUtils.EnumerateDirectories(tempFolder, true)).Contains(dest); // 目标文件夹名
} }
[Test] [Test]
@@ -38,8 +38,8 @@ public class DirectoryUtilsTest : TestWithFolder {
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa"); await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa");
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb"); await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb");
if (src != dest) await Assert.That(DirectoryUtils.GetDirectories(Path.Combine(tempFolder))).DoesNotContain(src); if (src != dest) await Assert.That(DirectoryUtils.EnumerateDirectories(tempFolder, true)).DoesNotContain(src);
await Assert.That(DirectoryUtils.GetDirectories(Path.Combine(tempFolder))).Contains(dest); // 目标文件夹名 await Assert.That(DirectoryUtils.EnumerateDirectories(tempFolder, true)).Contains(dest); // 目标文件夹名
} }
[Test] [Test]
@@ -73,7 +73,19 @@ public class DirectoryUtilsTest : TestWithFolder {
[Test] [Test]
public void 剪切_安全检查() public void 剪切_安全检查()
=> Assert.Throws<UnauthorizedAccessException>(() => DirectoryUtils.Move(PathUtils.CurrentFolder, Path.Combine(tempFolder, "SafetyCheckDest"))); => Assert.Throws<UnauthorizedAccessException>(() => DirectoryUtils.Move(Paths.Base, Path.Combine(tempFolder, "SafetyCheckDest")));
[Test]
public async Task 删除_安全检查_允许程序目录下的子文件夹() {
var folder = Path.Combine(Paths.Base, $"MeloongTest_{Guid.NewGuid():N}");
try {
DirectoryUtils.Create(folder);
DirectoryUtils.Delete(folder);
await Assert.That(DirectoryUtils.Exists(folder)).IsFalse();
} finally {
if (Directory.Exists(PathUtils.ForApi(folder))) Directory.Delete(PathUtils.ForApi(folder), true);
}
}
#endregion #endregion
+2 -6
View File
@@ -30,14 +30,10 @@ public class FileUtilsTest : TestWithFolder {
[Test] [Test]
[Arguments("Corrupted.zip")] [Arguments("Corrupted.zip")]
[Arguments("Not zip.zip")] [Arguments("Not zip.zip")]
public void 解压_ReadBad(string testFile)
=> Assert.Throws<InvalidDataException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
[Test]
[Arguments("DotDot ZipSlip.zip")] [Arguments("DotDot ZipSlip.zip")]
[Arguments("AbsPath ZipSlip.zip")] [Arguments("AbsPath ZipSlip.zip")]
public void 解压_ZipSlip(string testFile) public void 解压_ReadBad(string testFile)
=> Assert.Throws<FileUtils.ZipSlipException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder)); => Assert.Throws<InvalidDataException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
#endregion #endregion
+1 -1
View File
@@ -1,4 +1,4 @@
namespace MeloongCore.Tests; namespace MeloongCore.Tests;
public class PathUtilsTests : TestBase { public class PathUtilsTests : TestBase {
#region 路径处理 #region 路径处理
+31
View File
@@ -0,0 +1,31 @@
namespace MeloongCore.Tests;
public class TaskUtilsTest : TestBase {
[Test]
public async Task WhenAll_汇总等权子进度并保持结果顺序() {
var progress = new ProgressProvider();
var continueSecond = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
ProgressProvider? firstProgress = null, secondProgress = null;
var whenAll = TaskUtils.WhenAll<int>([
child => {
firstProgress = child;
return Task.FromResult(1);
},
async child => {
secondProgress = child;
await continueSecond.Task;
return 2;
}
], progress);
await Assert.That(ReferenceEquals(firstProgress, secondProgress)).IsFalse();
await Assert.That(progress.GetIncrement()).IsEqualTo(0.5);
continueSecond.SetResult(null);
var results = await whenAll;
await Assert.That(string.Join(",", results)).IsEqualTo("1,2");
await Assert.That(progress.GetIncrement()).IsEqualTo(1);
}
}
+470
View File
@@ -0,0 +1,470 @@
// 此文件主体由 AI 生成,应作为独立模块,尽量减少与其他内容的耦合。
// 使用 ModernTooltipService 接管后,TooltipService 仅有 IsEnabled、ShowOnDisabled、InitialShowDelay 仍然有效,其他属性不再生效。
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
namespace MeloongCore.Wpf;
public static class ModernTooltipService {
// 控制是否使用现代化 Tooltip 渲染;默认为 true。是否允许显示 Tooltip 仍由 ToolTipService.IsEnabled 控制。
public static void SetUseModernTooltip(DependencyObject element, bool value) => element.SetValue(UseModernTooltipProperty, value);
public static bool GetUseModernTooltip(DependencyObject element) => (bool) element.GetValue(UseModernTooltipProperty);
// 控制 Tooltip 是否跟随鼠标移动;默认为 true。
public static void SetFollowMouse(DependencyObject element, bool value) => element.SetValue(FollowMouseProperty, value);
public static bool GetFollowMouse(DependencyObject element) => (bool) element.GetValue(FollowMouseProperty);
/// <summary>
/// 全局启用现代 Tooltip。启用后会接管所有 <see cref="FrameworkElement.ToolTip"/>。
/// </summary>
internal static void Init() {
if (initialized) return;
initialized = true;
EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseEnterEvent, new MouseEventHandler(OnMouseEnter), true);
EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseMoveEvent, new MouseEventHandler(OnMouseMove), true);
EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseLeaveEvent, new MouseEventHandler(OnMouseLeave), true);
EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.PreviewMouseUpEvent, new MouseButtonEventHandler(OnPreviewMouseUp), true);
EventManager.RegisterClassHandler(typeof(FrameworkElement), ToolTipService.ToolTipOpeningEvent, new ToolTipEventHandler(OnToolTipOpening), true);
EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.UnloadedEvent, new RoutedEventHandler(static (sender, _) => {
if (sender is FrameworkElement owner && ReferenceEquals(owner, currentOwner)) Close(false);
}), true);
// Loaded 负责常规路径;PreviewMouseDown 兜底处理 Init 晚于控件 Loaded 的情况。
EventManager.RegisterClassHandler(typeof(ComboBox), FrameworkElement.LoadedEvent, new RoutedEventHandler(static (sender, _) => HookComboBoxDropDown(sender as ComboBox)), true);
EventManager.RegisterClassHandler(typeof(ComboBox), UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(static (sender, _) => HookComboBoxDropDown(sender as ComboBox)), true);
}
#region 字段与属性
// 附加属性
public static readonly DependencyProperty UseModernTooltipProperty = DependencyProperty.RegisterAttached(
"UseModernTooltip", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(true));
public static readonly DependencyProperty FollowMouseProperty = DependencyProperty.RegisterAttached(
"FollowMouse", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(true));
private static readonly DependencyProperty IsComboBoxDropDownHookedProperty = DependencyProperty.RegisterAttached(
"IsComboBoxDropDownHooked", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(false));
// 常量
private const double closedScale = 0.97;
private const int shadowRadius = 18, contentMaxWidth = 676;
private static readonly Thickness contentMargin = new(12, 11, 12, 8);
private static readonly Brush backgroundBrush = new SolidColorBrush(Colors.White);
private static readonly Brush borderBrush = new SolidColorBrush(Color.FromRgb(0xD6, 0xD6, 0xD6));
private static readonly Brush foregroundBrush = new SolidColorBrush(Color.FromRgb(0x52, 0x52, 0x52));
private static readonly DependencyPropertyDescriptor toolTipPropertyDescriptor =
DependencyPropertyDescriptor.FromProperty(FrameworkElement.ToolTipProperty, typeof(FrameworkElement));
// 状态字段
private static readonly DispatcherTimer openTimer = new();
private static bool initialized;
private static int animationToken;
private static Point lastMousePoint;
private static Popup? popup;
private static Border? popupCard;
private static ScaleTransform? popupScale;
private static FrameworkElement? currentOwner;
private static FrameworkElement? observedToolTipOwner;
private static ToolTip? borrowedToolTip;
private static object? borrowedContent;
static ModernTooltipService() {
backgroundBrush.Freeze();
borderBrush.Freeze();
foregroundBrush.Freeze();
openTimer.Tick += (_, _) => {
openTimer.Stop();
if (currentOwner is not null) Show(currentOwner, lastMousePoint);
};
}
#endregion
#region 事件入口
private static void OnMouseEnter(object sender, MouseEventArgs e) {
if (sender is not FrameworkElement reference) return;
reference.Dispatcher.BeginInvoke(new Action(() => RefreshCurrentOwner(reference)), DispatcherPriority.Input);
}
private static void OnMouseMove(object sender, MouseEventArgs e) {
if (sender is not FrameworkElement reference) return;
if (Mouse.LeftButton == MouseButtonState.Pressed) {
if (currentOwner is FrameworkElement pressedOwner) {
lastMousePoint = Mouse.GetPosition(pressedOwner);
if (GetFollowMouse(pressedOwner) && popup is { IsOpen: true }) {
UpdatePosition(pressedOwner, lastMousePoint);
}
} else if (popup is { IsOpen: true, PlacementTarget: FrameworkElement popupOwner } && GetFollowMouse(popupOwner)) {
lastMousePoint = Mouse.GetPosition(popupOwner);
UpdatePosition(popupOwner, lastMousePoint);
}
return;
}
RefreshCurrentOwner(reference);
if (currentOwner is FrameworkElement owner) {
lastMousePoint = Mouse.GetPosition(owner);
if (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, lastMousePoint);
return;
}
if (popup is { IsOpen: true, PlacementTarget: FrameworkElement closingOwner } && GetFollowMouse(closingOwner)) {
lastMousePoint = Mouse.GetPosition(closingOwner);
UpdatePosition(closingOwner, lastMousePoint);
}
}
private static void OnMouseLeave(object sender, MouseEventArgs e) {
if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
if (!(owner.IsEnabled || !ToolTipService.GetShowOnDisabled(owner) || !IsPointInside(owner, Mouse.GetPosition(owner)))) return;
var nextOwner = FindCurrentTooltipOwner(owner);
if (nextOwner is not null && !ReferenceEquals(nextOwner, owner)) {
BeginShow(nextOwner, Mouse.GetPosition(nextOwner));
return;
}
Close(true);
}
private static void OnPreviewMouseUp(object sender, MouseButtonEventArgs e) {
if (sender is not FrameworkElement reference) return;
reference.Dispatcher.BeginInvoke(new Action(() => {
if (currentOwner is null) return;
var owner = FindCurrentTooltipOwner(reference);
if (owner is null) {
Close(true);
} else {
BeginShow(owner, Mouse.GetPosition(owner));
}
}), DispatcherPriority.Input);
}
private static void OnToolTipOpening(object sender, ToolTipEventArgs e) {
if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
e.Handled = true;
if (ShouldSuppressTooltip(owner)) {
Close(false);
return;
}
// 启用状态控件走 MouseEnter 延迟逻辑;禁用控件只能从原生 Opening 事件接管。
if (owner.IsEnabled) return;
if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
currentOwner = owner;
openTimer.Stop();
lastMousePoint = Mouse.GetPosition(owner);
Show(owner, lastMousePoint);
}
#endregion
#region Tooltip 目标解析
private static void RefreshCurrentOwner(FrameworkElement reference) {
var owner = FindCurrentTooltipOwner(reference);
if (currentOwner is { IsEnabled: false } disabledOwner &&
ToolTipService.GetShowOnDisabled(disabledOwner) &&
IsPointInside(disabledOwner, Mouse.GetPosition(disabledOwner))) {
return;
}
if (ShouldSuppressTooltip(owner)) {
// 鼠标捕获仍在当前拥有者分支内时,保留现有气泡,避免拖选或按压时闪烁。
if (currentOwner is not null &&
Mouse.Captured is DependencyObject captured &&
IsSameTreeBranch(captured, currentOwner) &&
IsPointInside(currentOwner, Mouse.GetPosition(currentOwner))) {
return;
}
Close(false);
return;
}
if (owner is not null) {
BeginShow(owner, Mouse.GetPosition(owner));
} else if (currentOwner is { IsEnabled: false }) {
Close(true); // 禁用的控件不会触发 MouseLeave,需要由其他元素收到的 MouseMove 主动关闭
}
}
private static FrameworkElement? FindCurrentTooltipOwner(FrameworkElement reference) {
static FrameworkElement? FindOwnerInAncestors(DependencyObject? start) {
for (var current = start; current is not null; current = GetParent(current)) {
if (current is FrameworkElement owner && CanShowModernTooltip(owner) && TryGetToolTip(owner, out _, out _)) {
return owner;
}
}
return null;
}
var owner = FindOwnerInAncestors(Mouse.DirectlyOver as DependencyObject);
if (owner is not null) return owner;
return reference.InputHitTest(Mouse.GetPosition(reference)) is DependencyObject hit
? FindOwnerInAncestors(hit)
: null;
}
private static bool CanShowModernTooltip(FrameworkElement owner) =>
GetUseModernTooltip(owner) && ToolTipService.GetIsEnabled(owner) && (owner.IsEnabled || ToolTipService.GetShowOnDisabled(owner));
private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
var raw = owner.ToolTip;
sourceToolTip = raw as ToolTip;
content = sourceToolTip is null
? raw
: sourceToolTip.Content ?? (ReferenceEquals(sourceToolTip, borrowedToolTip) ? borrowedContent : null);
return content is not null && (content is not string text || text.Length > 0);
}
private static bool ShouldSuppressTooltip(FrameworkElement? owner) {
if (Mouse.LeftButton == MouseButtonState.Pressed || Mouse.Captured is null) return false;
if (Mouse.Captured is not DependencyObject captured) return true;
if (owner is null) return true;
return !IsSameTreeBranch(captured, owner);
}
private static bool IsPointInside(FrameworkElement owner, Point point) =>
point.X >= 0 && point.Y >= 0 && point.X <= owner.ActualWidth && point.Y <= owner.ActualHeight;
private static bool IsSameTreeBranch(DependencyObject first, DependencyObject second) {
if (ReferenceEquals(first, second)) return true;
for (var current = GetParent(second); current is not null; current = GetParent(current)) {
if (ReferenceEquals(current, first)) return true;
}
for (var current = GetParent(first); current is not null; current = GetParent(current)) {
if (ReferenceEquals(current, second)) return true;
}
return false;
}
private static DependencyObject? GetParent(DependencyObject current) {
if (current is Visual or Visual3D && VisualTreeHelper.GetParent(current) is { } visualParent) return visualParent;
return LogicalTreeHelper.GetParent(current);
}
#endregion
#region 显示生命周期
private static void BeginShow(FrameworkElement owner, Point point) {
if (!CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
if (ShouldSuppressTooltip(owner)) {
Close(false);
return;
}
if (owner is ComboBox comboBox) HookComboBoxDropDown(comboBox);
if (ReferenceEquals(currentOwner, owner)) {
lastMousePoint = point;
if (popup is not { IsOpen: true } && !openTimer.IsEnabled) StartOpenTimer(owner);
return;
}
HideImmediately();
currentOwner = owner;
lastMousePoint = point;
StartOpenTimer(owner);
}
private static void StartOpenTimer(FrameworkElement owner) {
openTimer.Stop();
var delay = Math.Max(0, ToolTipService.GetInitialShowDelay(owner));
if (delay == 0) {
Show(owner, lastMousePoint);
return;
}
openTimer.Interval = TimeSpan.FromMilliseconds(delay);
openTimer.Start();
}
private static void Show(FrameworkElement owner, Point point) {
if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
if (popup is null) {
popupScale = new ScaleTransform(closedScale, closedScale);
popupCard = new Border {
Background = backgroundBrush, BorderBrush = borderBrush, BorderThickness = new(1),
CornerRadius = new(8), MaxWidth = 700, SnapsToDevicePixels = true, UseLayoutRounding = true,
RenderTransform = popupScale, RenderTransformOrigin = new(0, 0),
Effect = new DropShadowEffect { Opacity = 0.15, BlurRadius = shadowRadius, ShadowDepth = 0, Color = Colors.Black }
};
var root = new Grid { Margin = new(shadowRadius + 1), SnapsToDevicePixels = true, UseLayoutRounding = true };
root.Children.Add(popupCard);
popup = new Popup {
AllowsTransparency = true, IsHitTestVisible = false, StaysOpen = true, PopupAnimation = PopupAnimation.None,
Placement = PlacementMode.Relative, Child = root
};
}
popup!.PlacementTarget = owner;
UpdatePosition(owner, point);
ObserveToolTip(owner);
UpdateContent(owner, content!, sourceToolTip);
animationToken++;
popupCard!.Opacity = 0;
popupScale!.ScaleX = closedScale;
popupScale.ScaleY = closedScale;
popup.IsOpen = true;
Animate(1, 1, null);
}
private static void UpdateContent(FrameworkElement owner, object content, ToolTip? sourceToolTip) {
popupCard!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
popupCard.FlowDirection = owner.FlowDirection;
// 先还原上一次借出的 Visual,再挂载新的内容,避免同一元素拥有两个逻辑父级。
popupCard.Child = null;
RestoreBorrowedContent();
if (sourceToolTip is not null && content is DependencyObject contentObject && ReferenceEquals(LogicalTreeHelper.GetParent(contentObject), sourceToolTip)) {
borrowedToolTip = sourceToolTip;
borrowedContent = content;
sourceToolTip.Content = null;
}
var hasTemplate = sourceToolTip?.ContentTemplate is not null || sourceToolTip?.ContentTemplateSelector is not null;
popupCard.Child = content is string stringContent && !hasTemplate
? new TextBlock {
Text = stringContent, TextWrapping = TextWrapping.Wrap, Foreground = foregroundBrush,
Margin = contentMargin, FontSize = 12.5, LineHeight = 17, MaxWidth = contentMaxWidth
}
: new ContentPresenter {
Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = contentMaxWidth
};
}
private static void ObserveToolTip(FrameworkElement owner) {
if (ReferenceEquals(observedToolTipOwner, owner)) return;
StopObservingToolTip();
observedToolTipOwner = owner;
toolTipPropertyDescriptor.AddValueChanged(owner, OnToolTipChanged);
}
private static void StopObservingToolTip() {
if (observedToolTipOwner is null) return;
toolTipPropertyDescriptor.RemoveValueChanged(observedToolTipOwner, OnToolTipChanged);
observedToolTipOwner = null;
}
private static void OnToolTipChanged(object? sender, EventArgs e) {
if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner) || popup is not { IsOpen: true }) return;
if (!CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) {
Close(true);
return;
}
UpdateContent(owner, content!, sourceToolTip);
}
private static void Close(bool animated) {
openTimer.Stop();
currentOwner = null;
StopObservingToolTip();
if (popup is not { IsOpen: true } || popupCard is null || !animated) {
HideImmediately();
return;
}
var token = ++animationToken;
Animate(0, closedScale, (_, _) => {
if (token != animationToken) return;
HideImmediately();
});
}
private static void HideImmediately() {
openTimer.Stop();
animationToken++;
StopObservingToolTip();
if (popup is not null) popup.IsOpen = false;
if (popupCard is not null) {
popupCard.BeginAnimation(UIElement.OpacityProperty, null);
popupCard.Child = null;
}
if (popupScale is not null) {
popupScale.BeginAnimation(ScaleTransform.ScaleXProperty, null);
popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, null);
}
RestoreBorrowedContent();
}
private static void RestoreBorrowedContent() {
if (borrowedToolTip is null) return;
borrowedToolTip.Content = borrowedContent;
borrowedToolTip = null;
borrowedContent = null;
}
#endregion
#region Popup 渲染与动画
private static void UpdatePosition(FrameworkElement owner, Point point) {
popup!.PlacementTarget = owner;
popup.HorizontalOffset = Math.Round(point.X + 15);
popup.VerticalOffset = Math.Round(point.Y + 25);
}
private static void Animate(double opacity, double scale, EventHandler? completed) {
var duration = new Duration(TimeSpan.FromMilliseconds(70));
var opacityAnimation = new DoubleAnimation(opacity, duration) {
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
};
if (completed is not null) opacityAnimation.Completed += completed;
var scaleAnimation = new DoubleAnimation(scale, duration) {
EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
};
popupCard!.BeginAnimation(UIElement.OpacityProperty, opacityAnimation, HandoffBehavior.SnapshotAndReplace);
popupScale!.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
}
#endregion
// WPF 原生 Tooltip 会在 ComboBox 下拉弹出时关闭;这里保持同样行为。
private static void HookComboBoxDropDown(ComboBox? comboBox) {
if (comboBox is null || (bool) comboBox.GetValue(IsComboBoxDropDownHookedProperty)) return;
comboBox.SetValue(IsComboBoxDropDownHookedProperty, true);
comboBox.DropDownOpened += static (_, _) => { if (currentOwner is not null) Close(true); };
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
using System.Windows.Controls; using System.Windows.Controls;
namespace MeloongCore.Wpf.Extensions; namespace MeloongCore.Wpf.Extensions;
public static class WpfExtensions { public static class WpfExtensions {
+12 -9
View File
@@ -16,7 +16,7 @@ public static class Dialogs {
FileName = defaultFileName FileName = defaultFileName
}; };
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!); if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!);
if (filters != null) { if (filters is not null) {
dialog.Filter = filters.Select(f => $"{f.Display}(*.{f.Extension})|*.{f.Extension}").Join("|"); dialog.Filter = filters.Select(f => $"{f.Display}(*.{f.Extension})|*.{f.Extension}").Join("|");
} }
@@ -36,10 +36,9 @@ public static class Dialogs {
/// <summary> /// <summary>
/// 弹出 “选择文件” 弹窗,返回用户选择的文件路径,若取消则返回空数组。 /// 弹出 “选择文件” 弹窗,返回用户选择的文件路径,若取消则返回空数组。
/// <para/> <paramref name="filter"/> 中的扩展名不加 <c>.</c>。 /// <para/> 若使用扩展名 <paramref name="filter"/>,则扩展名不加 <c>.</c>。
/// </summary> /// </summary>
public static List<string> SelectFile(string title, bool multiselect, string? defaultDirectory = null, IEnumerable<(string[] Extensions, string Display)>? filter = null) { public static List<string> SelectFile(string title, bool multiselect, string? defaultDirectory = null, OneOf<IEnumerable<(string[] Extensions, string Display)>, string>? filter = null) {
var filters = filter?.ToList();
var dialog = new OpenFileDialog { var dialog = new OpenFileDialog {
AddExtension = true, AddExtension = true,
CheckFileExists = true, CheckFileExists = true,
@@ -48,11 +47,15 @@ public static class Dialogs {
ValidateNames = true ValidateNames = true
}; };
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!); if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!);
if (filters != null) { if (filter is not null) {
dialog.Filter = filters.Select(f => { if (filter.Value.Is<string>()) {
var exts = string.Join(";", f.Extensions.Select(e => $"*.{e}")); dialog.Filter = filter.Value.As<string>();
return $"{f.Display}({exts})|{exts}"; } else {
}).Join("|"); dialog.Filter = filter.Value.As<IEnumerable<(string[] Extensions, string Display)>>().Select(f => {
var exts = string.Join(";", f.Extensions.Select(e => $"*.{e}"));
return $"{f.Display}({exts})|{exts}";
}).Join("|");
}
} }
Logger.Info($"选择文件弹窗:{dialog.Title}(Multiselect={dialog.Multiselect}, InitialDirectory={dialog.InitialDirectory}, Filter={dialog.Filter})"); Logger.Info($"选择文件弹窗:{dialog.Title}(Multiselect={dialog.Multiselect}, InitialDirectory={dialog.InitialDirectory}, Filter={dialog.Filter})");
+1 -1
View File
@@ -1,4 +1,4 @@
using System.Globalization; using System.Globalization;
using System.Windows; using System.Windows;
using System.Windows.Data; using System.Windows.Data;
+8
View File
@@ -0,0 +1,8 @@
namespace MeloongCore.Wpf;
public static class Main {
public static void Init() {
ModernTooltipService.Init();
}
}
+11 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net48</TargetFramework> <TargetFramework>net48</TargetFramework>
@@ -26,10 +26,13 @@
<Using Include="System.Diagnostics.CodeAnalysis" /> <Using Include="System.Diagnostics.CodeAnalysis" />
<Using Include="System.Collections" /> <Using Include="System.Collections" />
<Using Include="System.Collections.Generic" /> <Using Include="System.Collections.Generic" />
<Using Include="System.Collections.Concurrent" />
<Using Include="System.Text" /> <Using Include="System.Text" />
<Using Include="System.Net" /> <Using Include="System.Net" />
<Using Include="System.Runtime.CompilerServices" /> <Using Include="System.Runtime.CompilerServices" />
<Using Include="System.Runtime.InteropServices" /> <Using Include="System.Runtime.InteropServices" />
<Using Include="Newtonsoft.Json" />
<Using Include="Newtonsoft.Json.Linq" />
<Using Include="MeloongCore" /> <Using Include="MeloongCore" />
<Using Include="MeloongCore.Extensions" /> <Using Include="MeloongCore.Extensions" />
</ItemGroup> </ItemGroup>
@@ -38,10 +41,17 @@
<ProjectReference Include="..\Shared\MeloongCore.csproj" /> <ProjectReference Include="..\Shared\MeloongCore.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\Plain Craft Launcher 2\Resources\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="PresentationCore" /> <Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" /> <Reference Include="PresentationFramework" />
<Reference Include="System.Xaml" />
</ItemGroup> </ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@@ -1,7 +1,7 @@
using System.Security.Principal; using System.Security.Principal;
namespace MeloongCore; namespace MeloongCore;
public static class SystemUtils { public static class WindowsUtils {
/// <summary> /// <summary>
/// 当前程序是否拥有管理员权限。 /// 当前程序是否拥有管理员权限。
+5
View File
@@ -0,0 +1,5 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}