Compare commits
194
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98157d65c7 | ||
|
|
c774ae4c85 | ||
|
|
2336fd237c | ||
|
|
ae6676cd90 | ||
|
|
201948eac8 | ||
|
|
d4a98babd3 | ||
|
|
2a954ba52f | ||
|
|
52290ece97 | ||
|
|
794d1c1c79 | ||
|
|
97d5dc9d17 | ||
|
|
36ecaf29b6 | ||
|
|
8a7e33c66a | ||
|
|
53935f225d | ||
|
|
c20feff8ab | ||
|
|
3ed3a98bc3 | ||
|
|
9d877cc32c | ||
|
|
6b292a45f7 | ||
|
|
3f4bc4df2e | ||
|
|
bd319ff0d3 | ||
|
|
6c56050be8 | ||
|
|
811438aa3c | ||
|
|
d6186caa8b | ||
|
|
cea547982f | ||
|
|
5a6dce8b96 | ||
|
|
995d0e5859 | ||
|
|
8bfb4f709f | ||
|
|
ddad46e30d | ||
|
|
41f44afd9f | ||
|
|
08eaf4af85 | ||
|
|
26cd2f8ddf | ||
|
|
735c3485e1 | ||
|
|
fcb946e827 | ||
|
|
e985c72b33 | ||
|
|
d49baa7bad | ||
|
|
da10a2b132 | ||
|
|
d8697c7ddb | ||
|
|
7d7dac3762 | ||
|
|
162a22158c | ||
|
|
298eaddbe9 | ||
|
|
48a7450f2f | ||
|
|
32bbf7430e | ||
|
|
be671d560d | ||
|
|
bbe7910ed1 | ||
|
|
2744437977 | ||
|
|
0e2d24c0cd | ||
|
|
4f7f154b25 | ||
|
|
86263b0b75 | ||
|
|
7bc61645d5 | ||
|
|
e5c8e65e2b | ||
|
|
4309899c79 | ||
|
|
cf42cf19e3 | ||
|
|
c16ef849e6 | ||
|
|
1ee19b4023 | ||
|
|
da5069856e | ||
|
|
d3b9ccde9c | ||
|
|
473ac94d63 | ||
|
|
1f91e757c2 | ||
|
|
c18fef7074 | ||
|
|
d3daf1988f | ||
|
|
a1fcb5241a | ||
|
|
0a3b21505a | ||
|
|
fe9fc04c20 | ||
|
|
dbdbfcebd2 | ||
|
|
93e2f5cde8 | ||
|
|
8b26dccd22 | ||
|
|
be802ede2e | ||
|
|
251061c8eb | ||
|
|
0bdeb20c0e | ||
|
|
94ef3f8f8e | ||
|
|
00b49bc3e3 | ||
|
|
204fc52ba2 | ||
|
|
2d811e8f58 | ||
|
|
fc92759a39 | ||
|
|
3e579aff79 | ||
|
|
e2bb70f70d | ||
|
|
de2014e427 | ||
|
|
093827b853 | ||
|
|
a6d1716044 | ||
|
|
3a34eda3e8 | ||
|
|
6a6b43fe9a | ||
|
|
1a639fa88f | ||
|
|
8e87d13d76 | ||
|
|
a1749c7e1e | ||
|
|
d66af3d6cd | ||
|
|
20ed81ed9e | ||
|
|
d4c9adc7ca | ||
|
|
907021bdb2 | ||
|
|
b6873fd850 | ||
|
|
7ce6a6abc0 | ||
|
|
1508b58a9b | ||
|
|
ba81428f34 | ||
|
|
619aeac2f5 | ||
|
|
ada0032079 | ||
|
|
5c44002d5d | ||
|
|
2515eb5781 | ||
|
|
9ff4fe1114 | ||
|
|
f64685b177 | ||
|
|
7bf59d7f74 | ||
|
|
fbc7565d7b | ||
|
|
a42f33a8c1 | ||
|
|
d1389396dc | ||
|
|
966b2db312 | ||
|
|
e9cd356f2b | ||
|
|
c3fd315d89 | ||
|
|
5979cbd87d | ||
|
|
212552503e | ||
|
|
4f44549354 | ||
|
|
3982f92ebf | ||
|
|
282a779997 | ||
|
|
7d2d656f23 | ||
|
|
0208b6c78f | ||
|
|
3af26fbd3e | ||
|
|
db1b6a5670 | ||
|
|
40d7e83d41 | ||
|
|
934bf1e729 | ||
|
|
a407618ee1 | ||
|
|
ace30bfa50 | ||
|
|
59337411c0 | ||
|
|
8bab27236e | ||
|
|
174b645b4a | ||
|
|
45ada2850c | ||
|
|
c9e1b15740 | ||
|
|
0b075c97c0 | ||
|
|
d3b657d725 | ||
|
|
d05df2df9b | ||
|
|
9470a6160a | ||
|
|
ec1ad309d8 | ||
|
|
8ef47830b6 | ||
|
|
4d389f4375 | ||
|
|
f30c861f6e | ||
|
|
7f70c2e7f7 | ||
|
|
35e6e1e904 | ||
|
|
0f70132452 | ||
|
|
abc020ca0f | ||
|
|
04e7c56ba7 | ||
|
|
19541cecce | ||
|
|
3d91c024e2 | ||
|
|
0b62180d50 | ||
|
|
5ee6f88cde | ||
|
|
883b912104 | ||
|
|
8ef8796922 | ||
|
|
b1b18d4bb3 | ||
|
|
159f16fd57 | ||
|
|
14812561f9 | ||
|
|
454d167869 | ||
|
|
6ec4fcee5f | ||
|
|
d3dbc23003 | ||
|
|
2b5fc810bd | ||
|
|
f2d4070b6a | ||
|
|
f57f496d25 | ||
|
|
03483d5f7a | ||
|
|
5edff6c73f | ||
|
|
b821973e2a | ||
|
|
77d400a21f | ||
|
|
f9ca4727ef | ||
|
|
cc1bc99ab3 | ||
|
|
8c961fd64d | ||
|
|
518077c21e | ||
|
|
27e650d698 | ||
|
|
0ff787c5d9 | ||
|
|
d4af33f5be | ||
|
|
347a51f9d4 | ||
|
|
a10ec00951 | ||
|
|
7402647008 | ||
|
|
a1a367a749 | ||
|
|
b4c10ce79d | ||
|
|
5c79bb8954 | ||
|
|
b54a8f1683 | ||
|
|
b44fee289b | ||
|
|
8c2b3b37aa | ||
|
|
f760befa26 | ||
|
|
4f1664459d | ||
|
|
256db1e973 | ||
|
|
86544de606 | ||
|
|
e4a70e2447 | ||
|
|
fbc25509bc | ||
|
|
29f2ee58ac | ||
|
|
db15780671 | ||
|
|
c2d052e1ca | ||
|
|
0e8671a7af | ||
|
|
ffb79cf1eb | ||
|
|
487f54e4a9 | ||
|
|
4e07bcf17a | ||
|
|
e391dd22b6 | ||
|
|
9a77157dcf | ||
|
|
2d682afd2c | ||
|
|
b26e2c77e6 | ||
|
|
6bce8a6515 | ||
|
|
368280fcb5 | ||
|
|
9158a69b62 | ||
|
|
be6336f548 | ||
|
|
983ae1af11 | ||
|
|
49c2a9c8ff | ||
|
|
c017654b6a |
No files matched your search
@@ -0,0 +1,58 @@
|
||||
# Shared 复用指南
|
||||
|
||||
[代码约定](../仓库指示.md) · [Wpf](../Wpf/架构分析.md) · [Tests](../Tests/架构分析.md)
|
||||
|
||||
## 按功能定位
|
||||
|
||||
| 场景 | 源码入口 |
|
||||
| --- | --- |
|
||||
| 初始化、应用目录 | [Main.cs](../../Shared/Main.cs)、[PathUtils.cs](../../Shared/Utils/PathUtils.cs) |
|
||||
| 强类型键、JSON 配置 | [Config.cs](../../Shared/General/Config.cs) |
|
||||
| 日志接入 | [Logger.cs](../../Shared/General/Logger.cs) |
|
||||
| 分阶段进度 | [Progress.cs](../../Shared/General/Progress.cs) |
|
||||
| 节流、防抖、取消后重跑 | [Worker](../../Shared/General/Worker) |
|
||||
| 异步并发、进程执行 | [TaskUtils.cs](../../Shared/Utils/TaskUtils.cs) |
|
||||
| 并发列表、联合值、范围 | [ConcurrentList.cs](../../Shared/General/ConcurrentList.cs)、[OneOf.cs](../../Shared/General/OneOf.cs)、[ValueRange.cs](../../Shared/General/ValueRange.cs) |
|
||||
| 集合、字符串、异常、Task、HTTP 克隆扩展 | [Extensions](../../Shared/Extensions) |
|
||||
| 文件、目录、路径、压缩、校验 | [FileUtils.cs](../../Shared/Utils/FileUtils.cs)、[DirectoryUtils.cs](../../Shared/Utils/DirectoryUtils.cs)、[PathUtils.cs](../../Shared/Utils/PathUtils.cs) |
|
||||
| 格式化、数学、枚举、类型、加密 | [Utils](../../Shared/Utils) |
|
||||
| 注册表、Windows 增量补丁 | [RegistryUtils.cs](../../Shared/Utils/RegistryUtils.cs)、[MsDelta.cs](../../Shared/General/MsDelta.cs) |
|
||||
|
||||
扩展方法主要位于 `MeloongCore.Extensions`,MathUtils、EnumUtils 的扩展位于 `MeloongCore`;项目全局 using 不传播到引用方。新框架同名方法可能改变重载绑定,替换前核对语义。注册表和 MsDelta 是 Windows 专属,Shared 的目标框架不代表所有入口均可跨平台使用。
|
||||
|
||||
以下保留不易从名称判断的行为;具体重载和实现以链接源码为准。
|
||||
|
||||
## 初始化、配置与日志
|
||||
|
||||
- 首次访问默认配置前调用 `Main.Init(appName)`;它设置应用名和默认正则超时,不初始化 WPF 或文件日志。默认 provider 静态初始化后,修改应用名不会迁移其路径。
|
||||
- `ConfigEntry<T>` 绑定固定 provider,`DynamicConfigEntry<T>` 每次操作传 provider。替换 `ConfigProviders.Default` 不改变已有 entry 的绑定。
|
||||
- `ConfigUtils.GetSecret` 独立读取 `Paths.AppData/Meloong/Dev/secret.json`,使用 `CryptographyUtils.AesDecrypt` ,首次读取后缓存 JSON 对象;不使用配置 provider、不参与 SaveAll。文件不存在或键为 null/缺失时抛出缺键异常;解密或解析失败抛出脱敏异常,不覆盖文件。默认密钥仅用于避免明文存储,不提供可靠保密保护。
|
||||
- 同一 provider 的同一键固定使用同一类型;显式 JSON null 算已存值。Get 返回对象缓存,修改对象后需 Edit/Set 才安排保存;Edit 不是原子更新。
|
||||
- Set 即使值相同也触发 Changed;动态 entry 的 Changed 不携带 provider。PreviewGet 仅修正本次读取,不自动写回。
|
||||
- JSON 写入防抖 500 ms;明确落盘点可用 `ConfigUtils.SaveAll()`。DiscardCache 不保存变更;Save 写盘失败不保证恢复 dirty。整文件加载失败回退空对象,不代表所有键读取错误都会回退默认值。
|
||||
- `Logger.Instance` 可替换;基类不实现 LogBehavior 所表达的 UI 动作。BaseLogger 构造时启动后台线程并调用虚方法 Init;Output 通常在日志线程,HandleBehavior 在调用线程。
|
||||
- FileLogger 创建后修改路径字段可能晚于初始化;退出时先 Flush 再 Dispose,但尚未就绪时 Flush 会返回,Dispose 不保证排空或等待线程。
|
||||
|
||||
## 进度与后台任务
|
||||
|
||||
- ProgressProvider 用 SplitBy/SplitTo 分阶段;Reset 不清除单调观测历史,全新任务需要新 provider。Finish/Skip 可结算子项,IsFinished 不代表业务成功。
|
||||
- ProgressObserver 订阅并节流 GetIncreasing,构造时不立即刷新,结束时 Dispose;回调不保证 UI 线程。
|
||||
- RateLimitedWorker 的 ImmediateThenMerge 为节流,ImmediateThenIgnore 忽略密集后续请求,WaitUnillNoNewInvoke 为尾随防抖。复用同一实例;Dispose 不补执行最后一次。
|
||||
- RedoableWorker 在运行中 Start 会请求取消旧负载并合并重跑,负载必须协作取消。WaitIfRunning* 只等待空闲,不重抛负载错误,也不保证事件回调已结束。
|
||||
- RedoableWorker 的 HasSucceeded/LastResult 可保留历史成功,判断最近运行用 LastSucceeded;事件在工作线程。Worker 接受同步委托,不等待 async lambda 内的异步工作。
|
||||
- TaskUtils.WhenAll 聚合进度但不限并发;ForEach 是同步并行,异步限并发用 ForEachAsync。后者失败会停止领取新项,但内部取消令牌不传入 body,在途动作需自行响应外部令牌。
|
||||
- RunProgramAsync 返回 Output/ExitCode,非零退出码不自动抛错;输出按 stdout + stderr 拼接。取消/超时不保证终止子进程树;参数会写日志,不应包含密钥。
|
||||
|
||||
## 数据结构与扩展语义
|
||||
|
||||
- ConcurrentList 单次操作加锁,复合操作需共用 SyncRoot;枚举及与 List 的转换都复制列表,元素仍共享引用。
|
||||
- OneOf 的 default 没有有效分支;Is<T> 按声明类型精确匹配,取错分支会抛错。
|
||||
- ValueRange.Intersect 无交集仍返回范围,应检查 IsEmpty;IsEmpty 不识别离散域空区间。范围可变,不应修改已作为字典键的实例。
|
||||
- EnumerableExtensions 的并行 DistinctBy 不保证首项,重复枚举沿用已见键;MaxBy/MinBy 空输入返回 default;二维数组 ToDictionary 重复键以后者覆盖。
|
||||
- RemoveIf/KeepIf 原地修改;RemoveAll 对每项仅移除一次;Except(单值) 还会去重;ForAll 立即顺序枚举且不等待 async lambda。
|
||||
- 字符串 Before/After 系列未找到分隔符时保留原文;Between 从最后一个起始分隔符之后截取,不做括号配对。Split 去空模式对空串返回空数组,SplitLines 不修剪行内空白。
|
||||
- RegexSearch 的惰性枚举仍可能抛超时;RegexSeek/RegexCheck 捕获失败,而 RegexReplace 直接抛错。
|
||||
- ReadString 不关闭输入流;默认 GetString 尝试 BOM、严格 UTF-8,再回退 GB18030。DeserializeJson<T> 用于 JToken 子类,解析错误可能包含原文。
|
||||
- ExceptionExtensions.IsCanceled 对混有其他错误的聚合也可返回 true;RootException 只沿单条 InnerException,Flatten 扩展与 AggregateException 同名实例方法含义不同。ThrowIfCanceled 不保证保留原堆栈;IsBadNetwork 可能把主动取消判为网络不佳。
|
||||
- TaskExtensions.Run 同步阻塞;NoCapture 仅为 ConfigureAwait(false),不保证切到后台线程。
|
||||
- HTTP CloneAsync 缓冲复制全部内容,Properties 中的对象仍共享;无取消令牌重载。WebUtils.cs 定义 HttpRequestCodeException,未提供自动发送或失败状态检查。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Tests 定位与环境
|
||||
|
||||
[代码约定](../仓库指示.md) · [WPF 构建要求](../Wpf/架构分析.md)
|
||||
|
||||
Tests 是 TUnit 可执行测试项目,引用 Shared 与 Wpf,运行目标为 .NET Framework 4.8;其运行结果不能证明 macOS 兼容性。运行机制和资源复制配置见 [项目文件](../../Tests/MeloongCore.Tests.csproj)。
|
||||
|
||||
| 修改能力 | 对应测试目录或文件(相对于 Tests/) |
|
||||
| --- | --- |
|
||||
| 配置、进度、Worker | `General/` |
|
||||
| 加密、目录、文件、路径、任务和进程 | `Utils/` |
|
||||
| 初始化、日志接入、临时目录 | `TestUtils.cs` |
|
||||
| 压缩格式、编码、损坏文件与 Zip Slip | `TestFiles/FileUtils/` |
|
||||
|
||||
[TestUtils.cs](../../Tests/TestUtils.cs) 中 TestBase 初始化 MeloongCore 并接入测试日志;TestWithFolder 在系统临时目录下创建含 GUID、特殊字符和长路径的测试目录,样本从输出目录复制。
|
||||
|
||||
测试目前主要覆盖 Shared,引用 Wpf 不意味着已覆盖其平台行为。按本次修改选择相关行为验证,上层应用业务测试留在引用方仓库。
|
||||
@@ -0,0 +1,18 @@
|
||||
# Wpf 入口与构建
|
||||
|
||||
[代码约定](../仓库指示.md) · [Shared](../Shared/架构分析.md)
|
||||
|
||||
构建 WPF 工程使用 Visual Studio 2022 的 `MSBuild.exe`。本项目为通用 Windows/WPF 适配层,依赖 Shared;纯 .NET 逻辑留在 Shared,应用专用外观和页面逻辑留在引用方。
|
||||
|
||||
路径相对于 `Wpf/`:
|
||||
|
||||
| 场景 | 入口 |
|
||||
| --- | --- |
|
||||
| WPF 初始化 | `Main.cs` |
|
||||
| ToolTip 附加行为 | `Controls/ModernTooltipService.cs` |
|
||||
| 控件与对象扩展 | `Extensions/WpfExtensions.cs` |
|
||||
| 文件、文件夹与消息对话框 | `General/Dialogs.cs` |
|
||||
| Binding 转换器 | `General/ValueConverters.cs` |
|
||||
| Windows 权限、窗口与系统操作 | `Utils/WindowsUtils.cs` |
|
||||
|
||||
System.Windows.Forms 与 WPF 互操作涉及 DPI、窗口句柄和线程模型;调整相关行为时检查调用线程与窗口归属。
|
||||
@@ -0,0 +1,21 @@
|
||||
# MeloongCore 代码约定
|
||||
|
||||
## 风格与复用
|
||||
|
||||
- 使用 C# 13、Nullable、Implicit Usings 和 PolySharp;保持目标框架兼容。
|
||||
- 保持改动精简、结构紧凑并保留必要注释;避免无实际收益的抽象、优化和防御性检查。
|
||||
- 不为一两行逻辑添加辅助方法;仅有一个引用的方法或变量优先考虑内联。
|
||||
- 新增工具前检查现有 Extensions、General 和 Utils,避免重复实现。
|
||||
|
||||
## C# 风格
|
||||
|
||||
- 大括号不换行;变量名小驼峰,类型、属性和方法名大驼峰。
|
||||
- 无 `else`、简短且仅一条语句的 `if` 写成 `if (flag) break;`;换行则加大括号。单行大括号内部不留首尾空格,如 `{element}`。
|
||||
- 行尾注释格式为 `break; // 注释`;XML 文档参数引用用 `<paramref name="..."/>`。
|
||||
- 使用 `""` 表示空字符串;优先采用 C# 13 下简洁清晰的写法。
|
||||
|
||||
## 公共 API 与平台边界
|
||||
|
||||
- Shared 承载跨产品通用能力;Windows/WPF 特有功能优先放入 Wpf,已有平台专属入口需保持明确的调用边界。
|
||||
- 上层应用的业务、页面和全局状态留在引用方;Tests 只保护本库公共行为,不反向依赖应用项目。
|
||||
- 修改公共 API 签名或语义时检查已有引用方的兼容性。
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
# 如果要从更高级别的目录继承 .editorconfig 设置,请删除以下行
|
||||
root = true
|
||||
|
||||
# c# 文件
|
||||
[*.cs]
|
||||
|
||||
#### Core EditorConfig 选项 ####
|
||||
|
||||
# 缩进和间距
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
tab_width = 4
|
||||
|
||||
# 新行首选项
|
||||
end_of_line = crlf
|
||||
insert_final_newline = false
|
||||
|
||||
#### .NET 代码操作 ####
|
||||
|
||||
# 类型成员
|
||||
dotnet_hide_advanced_members = false
|
||||
dotnet_member_insertion_location = with_other_members_of_the_same_kind
|
||||
dotnet_property_generation_behavior = prefer_throwing_properties
|
||||
|
||||
# 符号搜索
|
||||
dotnet_search_reference_assemblies = true
|
||||
|
||||
#### .NET 编码约定 ####
|
||||
|
||||
# 组织 Using
|
||||
dotnet_separate_import_directive_groups = false
|
||||
dotnet_sort_system_directives_first = false
|
||||
file_header_template = unset
|
||||
|
||||
# this. 和 Me. 首选项
|
||||
dotnet_style_qualification_for_event = false
|
||||
dotnet_style_qualification_for_field = false
|
||||
dotnet_style_qualification_for_method = false
|
||||
dotnet_style_qualification_for_property = false
|
||||
|
||||
# 语言关键字与 bcl 类型首选项
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true
|
||||
dotnet_style_predefined_type_for_member_access = true
|
||||
|
||||
# 括号首选项
|
||||
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
|
||||
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
|
||||
dotnet_style_parentheses_in_other_operators = never_if_unnecessary
|
||||
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
|
||||
|
||||
# 修饰符首选项
|
||||
dotnet_style_require_accessibility_modifiers = for_non_interface_members
|
||||
|
||||
# 表达式级首选项
|
||||
dotnet_prefer_system_hash_code = true
|
||||
dotnet_style_coalesce_expression = true
|
||||
dotnet_style_collection_initializer = true
|
||||
dotnet_style_explicit_tuple_names = true
|
||||
dotnet_style_namespace_match_folder = true
|
||||
dotnet_style_null_propagation = true
|
||||
dotnet_style_object_initializer = true
|
||||
dotnet_style_operator_placement_when_wrapping = beginning_of_line
|
||||
dotnet_style_prefer_auto_properties = true:suggestion
|
||||
dotnet_style_prefer_collection_expression = when_types_loosely_match
|
||||
dotnet_style_prefer_compound_assignment = true
|
||||
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
|
||||
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
|
||||
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
|
||||
dotnet_style_prefer_inferred_anonymous_type_member_names = true
|
||||
dotnet_style_prefer_inferred_tuple_names = true
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true
|
||||
dotnet_style_prefer_simplified_interpolation = true
|
||||
|
||||
# 字段首选项
|
||||
dotnet_style_readonly_field = true
|
||||
|
||||
# 参数首选项
|
||||
dotnet_code_quality_unused_parameters = all
|
||||
|
||||
# 禁止显示首选项
|
||||
dotnet_remove_unnecessary_suppression_exclusions = none
|
||||
|
||||
# 新行首选项
|
||||
dotnet_style_allow_multiple_blank_lines_experimental = true
|
||||
dotnet_style_allow_statement_immediately_after_block_experimental = true
|
||||
|
||||
#### c# 编码约定 ####
|
||||
|
||||
# var 首选项
|
||||
csharp_style_var_elsewhere = false
|
||||
csharp_style_var_for_built_in_types = false
|
||||
csharp_style_var_when_type_is_apparent = false
|
||||
|
||||
# Expression-bodied 成员
|
||||
csharp_style_expression_bodied_accessors = true
|
||||
csharp_style_expression_bodied_constructors = false
|
||||
csharp_style_expression_bodied_indexers = true
|
||||
csharp_style_expression_bodied_lambdas = true
|
||||
csharp_style_expression_bodied_local_functions = false
|
||||
csharp_style_expression_bodied_methods = false
|
||||
csharp_style_expression_bodied_operators = false
|
||||
csharp_style_expression_bodied_properties = true
|
||||
|
||||
# 模式匹配首选项
|
||||
csharp_style_pattern_matching_over_as_with_null_check = true
|
||||
csharp_style_pattern_matching_over_is_with_cast_check = true
|
||||
csharp_style_prefer_extended_property_pattern = true
|
||||
csharp_style_prefer_not_pattern = true
|
||||
csharp_style_prefer_pattern_matching = true:suggestion
|
||||
csharp_style_prefer_switch_expression = true
|
||||
|
||||
# Null 检查首选项
|
||||
csharp_style_conditional_delegate_call = true
|
||||
|
||||
# 修饰符首选项
|
||||
csharp_prefer_static_anonymous_function = true
|
||||
csharp_prefer_static_local_function = true
|
||||
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async
|
||||
csharp_style_prefer_readonly_struct = true
|
||||
csharp_style_prefer_readonly_struct_member = true
|
||||
|
||||
# 代码块首选项
|
||||
csharp_prefer_braces = true
|
||||
csharp_prefer_simple_using_statement = true
|
||||
csharp_prefer_system_threading_lock = true
|
||||
csharp_style_namespace_declarations = file_scoped:suggestion
|
||||
csharp_style_prefer_method_group_conversion = true
|
||||
csharp_style_prefer_primary_constructors = true
|
||||
csharp_style_prefer_top_level_statements = true
|
||||
|
||||
# 表达式级首选项
|
||||
csharp_prefer_simple_default_expression = true
|
||||
csharp_style_deconstructed_variable_declaration = true
|
||||
csharp_style_implicit_object_creation_when_type_is_apparent = true
|
||||
csharp_style_inlined_variable_declaration = true
|
||||
csharp_style_prefer_implicitly_typed_lambda_expression = true
|
||||
csharp_style_prefer_index_operator = true
|
||||
csharp_style_prefer_local_over_anonymous_function = true
|
||||
csharp_style_prefer_null_check_over_type_check = true
|
||||
csharp_style_prefer_range_operator = true
|
||||
csharp_style_prefer_tuple_swap = true
|
||||
csharp_style_prefer_unbound_generic_type_in_nameof = true
|
||||
csharp_style_prefer_utf8_string_literals = true
|
||||
csharp_style_throw_expression = true
|
||||
csharp_style_unused_value_assignment_preference = discard_variable
|
||||
csharp_style_unused_value_expression_statement_preference = discard_variable
|
||||
|
||||
# "using" 指令首选项
|
||||
csharp_using_directive_placement = outside_namespace
|
||||
|
||||
# 新行首选项
|
||||
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
|
||||
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true
|
||||
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true
|
||||
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true
|
||||
csharp_style_allow_embedded_statements_on_same_line_experimental = true
|
||||
|
||||
#### C# 格式规则 ####
|
||||
|
||||
# 新行首选项
|
||||
csharp_new_line_before_catch = false
|
||||
csharp_new_line_before_else = false
|
||||
csharp_new_line_before_finally = false
|
||||
csharp_new_line_before_members_in_anonymous_types = false
|
||||
csharp_new_line_before_members_in_object_initializers = false
|
||||
csharp_new_line_before_open_brace = none
|
||||
csharp_new_line_between_query_expression_clauses = false
|
||||
|
||||
# 缩进首选项
|
||||
csharp_indent_block_contents = true
|
||||
csharp_indent_braces = false
|
||||
csharp_indent_case_contents = true
|
||||
csharp_indent_case_contents_when_block = false
|
||||
csharp_indent_labels = flush_left
|
||||
csharp_indent_switch_labels = false
|
||||
|
||||
# 空格键首选项
|
||||
csharp_space_after_cast = true
|
||||
csharp_space_after_colon_in_inheritance_clause = true
|
||||
csharp_space_after_comma = true
|
||||
csharp_space_after_dot = false
|
||||
csharp_space_after_keywords_in_control_flow_statements = true
|
||||
csharp_space_after_semicolon_in_for_statement = true
|
||||
csharp_space_around_binary_operators = ignore
|
||||
csharp_space_around_declaration_statements = false
|
||||
csharp_space_before_colon_in_inheritance_clause = true
|
||||
csharp_space_before_comma = false
|
||||
csharp_space_before_dot = false
|
||||
csharp_space_before_open_square_brackets = false
|
||||
csharp_space_before_semicolon_in_for_statement = false
|
||||
csharp_space_between_empty_square_brackets = false
|
||||
csharp_space_between_method_call_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_call_name_and_opening_parenthesis = false
|
||||
csharp_space_between_method_call_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_name_and_open_parenthesis = false
|
||||
csharp_space_between_method_declaration_parameter_list_parentheses = false
|
||||
csharp_space_between_parentheses = false
|
||||
csharp_space_between_square_brackets = false
|
||||
|
||||
# 包装首选项
|
||||
csharp_preserve_single_line_blocks = true
|
||||
csharp_preserve_single_line_statements = true
|
||||
|
||||
#### 命名样式 ####
|
||||
|
||||
# 命名规则
|
||||
|
||||
dotnet_naming_rule.interface_should_be_以_i_开始.severity = suggestion
|
||||
dotnet_naming_rule.interface_should_be_以_i_开始.symbols = interface
|
||||
dotnet_naming_rule.interface_should_be_以_i_开始.style = 以_i_开始
|
||||
|
||||
dotnet_naming_rule.类型_should_be_帕斯卡拼写法.severity = suggestion
|
||||
dotnet_naming_rule.类型_should_be_帕斯卡拼写法.symbols = 类型
|
||||
dotnet_naming_rule.类型_should_be_帕斯卡拼写法.style = 帕斯卡拼写法
|
||||
|
||||
dotnet_naming_rule.非字段成员_should_be_帕斯卡拼写法.severity = suggestion
|
||||
dotnet_naming_rule.非字段成员_should_be_帕斯卡拼写法.symbols = 非字段成员
|
||||
dotnet_naming_rule.非字段成员_should_be_帕斯卡拼写法.style = 帕斯卡拼写法
|
||||
|
||||
# 符号规范
|
||||
|
||||
dotnet_naming_symbols.interface.applicable_kinds = interface
|
||||
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.interface.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.类型.applicable_kinds = class, struct, interface, enum
|
||||
dotnet_naming_symbols.类型.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.类型.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.非字段成员.applicable_kinds = property, event, method
|
||||
dotnet_naming_symbols.非字段成员.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.非字段成员.required_modifiers =
|
||||
|
||||
# 命名样式
|
||||
|
||||
dotnet_naming_style.帕斯卡拼写法.required_prefix =
|
||||
dotnet_naming_style.帕斯卡拼写法.required_suffix =
|
||||
dotnet_naming_style.帕斯卡拼写法.word_separator =
|
||||
dotnet_naming_style.帕斯卡拼写法.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.以_i_开始.required_prefix = I
|
||||
dotnet_naming_style.以_i_开始.required_suffix =
|
||||
dotnet_naming_style.以_i_开始.word_separator =
|
||||
dotnet_naming_style.以_i_开始.capitalization = pascal_case
|
||||
@@ -0,0 +1,16 @@
|
||||
# MeloongCore Agents 指南
|
||||
|
||||
- 使用中文沟通;文本使用 UTF-8 无 BOM(65001),PowerShell 文本读写显式指定 UTF-8 编码。
|
||||
- 通用代码兼顾 Windows 与 macOS;Shared 面向 .NET Standard 2.0,不依赖 WPF。Wpf 与 Tests 面向 .NET Framework 4.8。
|
||||
- 本库是独立仓库,不依赖引用方的业务、私有目录或开发流程。
|
||||
|
||||
## 按任务查阅
|
||||
|
||||
| 任务 | 文档 |
|
||||
| --- | --- |
|
||||
| 修改代码或公共 API | [代码约定](.agents/仓库指示.md) |
|
||||
| 查找通用能力、扩展方法及其语义差异 | [Shared 复用指南](.agents/Shared/架构分析.md) |
|
||||
| 修改 Windows/WPF 能力或构建 WPF 工程 | [Wpf 说明](.agents/Wpf/架构分析.md) |
|
||||
| 定位测试与测试环境 | [Tests 说明](.agents/Tests/架构分析.md) |
|
||||
|
||||
只读当前任务相关资料;入口、约定或关键行为变化时更新对应文档。
|
||||
@@ -1,24 +1,42 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
|
||||
namespace MeloongCore.Extensions;
|
||||
public static class EnumerableExtensions {
|
||||
|
||||
#region Distinct
|
||||
#region 查找
|
||||
|
||||
/// <summary>
|
||||
/// 按优先级依次查找,返回首个有匹配结果的条件所匹配的第一个元素。
|
||||
/// 所有条件均无匹配时返回 default。每尝试一个条件都会重新枚举序列。
|
||||
/// </summary>
|
||||
public static TSource? FirstOrDefault<TSource>(this IEnumerable<TSource> source, params Func<TSource, bool>[] predicates) {
|
||||
foreach (var predicate in predicates) {
|
||||
foreach (var item in source) {
|
||||
if (predicate(item)) return item;
|
||||
}
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 去重
|
||||
|
||||
/// <summary>
|
||||
/// 通过比较器进行去重。
|
||||
/// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) {
|
||||
for (int i = 0; i < list.Count; i++) {
|
||||
if (!list.Skip(i + 1).Any(item => comparer(list[i], item))) yield return list[i];
|
||||
var seen = new List<T>();
|
||||
foreach (var item in list) {
|
||||
if (!seen.Any(s => comparer(s, item))) {
|
||||
seen.Add(item);
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 按对象的指定值去重。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) {
|
||||
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) {
|
||||
var seen = new HashSet<TKey>();
|
||||
foreach (var element in source) {
|
||||
if (seen.Add(selector(element))) yield return element;
|
||||
@@ -27,29 +45,29 @@ public static class EnumerableExtensions {
|
||||
/// <summary>
|
||||
/// 按对象的指定值去重。
|
||||
/// </summary>
|
||||
public static ParallelQuery<T> DistinctBy<T, TKey>(this ParallelQuery<T> source, Func<T, TKey> selector) {
|
||||
public static ParallelQuery<TSource> DistinctBy<TSource, TKey>(this ParallelQuery<TSource> source, Func<TSource, TKey> selector) {
|
||||
var seen = new ConcurrentDictionary<TKey, bool>();
|
||||
return source.Where(element => seen.TryAdd(selector(element), true));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region MinBy / MaxBy
|
||||
#region 最大 / 最小
|
||||
|
||||
/// <summary>
|
||||
/// 选择所有最大值对应的对象。
|
||||
/// 若没有元素则返回空列表。
|
||||
/// </summary>
|
||||
public static List<TKey> MaxByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
|
||||
var results = new List<TKey>();
|
||||
public static List<TSource> MaxByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
|
||||
var results = new List<TSource>();
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return results;
|
||||
TKey maxItem = enumerator.Current;
|
||||
TValue maxValue = selector(maxItem);
|
||||
TSource maxItem = enumerator.Current;
|
||||
TKey maxValue = selector(maxItem);
|
||||
results.Add(maxItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TKey currentItem = enumerator.Current;
|
||||
TValue currentValue = selector(currentItem);
|
||||
TSource currentItem = enumerator.Current;
|
||||
TKey currentValue = selector(currentItem);
|
||||
int comparisonResult = currentValue.CompareTo(maxValue);
|
||||
if (comparisonResult > 0) {
|
||||
maxValue = currentValue;
|
||||
@@ -62,19 +80,44 @@ public static class EnumerableExtensions {
|
||||
return results;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择所有最大值对应的对象。
|
||||
/// 若没有元素则返回空列表。
|
||||
/// </summary>
|
||||
public static List<TSource> MaxByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
|
||||
var results = new List<TSource>();
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return results;
|
||||
TSource maxItem = enumerator.Current;
|
||||
TKey maxValue = selector(maxItem);
|
||||
results.Add(maxItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TSource currentItem = enumerator.Current;
|
||||
TKey currentValue = selector(currentItem);
|
||||
int comparisonResult = comparer.Compare(currentValue, maxValue);
|
||||
if (comparisonResult > 0) {
|
||||
maxValue = currentValue;
|
||||
results.Clear();
|
||||
results.Add(currentItem);
|
||||
} else if (comparisonResult == 0) {
|
||||
results.Add(currentItem);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择所有最小值对应的对象。
|
||||
/// 若没有元素则返回空列表。
|
||||
/// </summary>
|
||||
public static List<TKey> MinByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
|
||||
var results = new List<TKey>();
|
||||
public static List<TSource> MinByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
|
||||
var results = new List<TSource>();
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return results;
|
||||
TKey minItem = enumerator.Current;
|
||||
TValue minValue = selector(minItem);
|
||||
TSource minItem = enumerator.Current;
|
||||
TKey minValue = selector(minItem);
|
||||
results.Add(minItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TKey currentItem = enumerator.Current;
|
||||
TValue currentValue = selector(currentItem);
|
||||
TSource currentItem = enumerator.Current;
|
||||
TKey currentValue = selector(currentItem);
|
||||
int comparisonResult = currentValue.CompareTo(minValue);
|
||||
if (comparisonResult < 0) {
|
||||
minValue = currentValue;
|
||||
@@ -86,18 +129,43 @@ public static class EnumerableExtensions {
|
||||
}
|
||||
return results;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择所有最小值对应的对象。
|
||||
/// 若没有元素则返回空列表。
|
||||
/// </summary>
|
||||
public static List<TSource> MinByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
|
||||
var results = new List<TSource>();
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return results;
|
||||
TSource minItem = enumerator.Current;
|
||||
TKey minValue = selector(minItem);
|
||||
results.Add(minItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TSource currentItem = enumerator.Current;
|
||||
TKey currentValue = selector(currentItem);
|
||||
int comparisonResult = comparer.Compare(currentValue, minValue);
|
||||
if (comparisonResult < 0) {
|
||||
minValue = currentValue;
|
||||
results.Clear();
|
||||
results.Add(currentItem);
|
||||
} else if (comparisonResult == 0) {
|
||||
results.Add(currentItem);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 选择最大值对应的对象。
|
||||
/// 若没有元素则返回 null。
|
||||
/// </summary>
|
||||
public static TKey? MaxBy<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> {
|
||||
public static TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return default;
|
||||
TKey maxItem = enumerator.Current;
|
||||
TValue maxValue = selector(maxItem);
|
||||
TSource maxItem = enumerator.Current;
|
||||
TKey maxValue = selector(maxItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TValue value = selector(enumerator.Current);
|
||||
TKey value = selector(enumerator.Current);
|
||||
if (value.CompareTo(maxValue) <= 0) continue;
|
||||
maxItem = enumerator.Current;
|
||||
maxValue = value;
|
||||
@@ -105,22 +173,72 @@ public static class EnumerableExtensions {
|
||||
return maxItem;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择最大值对应的对象。
|
||||
/// 若没有元素则返回 null。
|
||||
/// </summary>
|
||||
public static TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) return default;
|
||||
TSource maxItem = enumerator.Current;
|
||||
TKey maxValue = selector(maxItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TKey value = selector(enumerator.Current);
|
||||
if (comparer.Compare(value, maxValue) <= 0) continue;
|
||||
maxItem = enumerator.Current;
|
||||
maxValue = value;
|
||||
}
|
||||
return maxItem;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择最小值对应的对象。
|
||||
/// 若没有元素则返回 null。
|
||||
/// </summary>
|
||||
public static TKey? MinBy<TKey, TValue>(this IEnumerable<TKey> List, Func<TKey, TValue> Selector) where TValue : IComparable<TValue> {
|
||||
using var enumerator = List.GetEnumerator();
|
||||
public static TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) { return default; }
|
||||
TKey minItem = enumerator.Current;
|
||||
TValue minValue = Selector(minItem);
|
||||
TSource minItem = enumerator.Current;
|
||||
TKey minValue = selector(minItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TValue value = Selector(enumerator.Current);
|
||||
TKey value = selector(enumerator.Current);
|
||||
if (value.CompareTo(minValue) >= 0) { continue; }
|
||||
minItem = enumerator.Current;
|
||||
minValue = value;
|
||||
}
|
||||
return minItem;
|
||||
}
|
||||
/// <summary>
|
||||
/// 选择最小值对应的对象。
|
||||
/// 若没有元素则返回 null。
|
||||
/// </summary>
|
||||
public static TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
|
||||
using var enumerator = source.GetEnumerator();
|
||||
if (!enumerator.MoveNext()) { return default; }
|
||||
TSource minItem = enumerator.Current;
|
||||
TKey minValue = selector(minItem);
|
||||
while (enumerator.MoveNext()) {
|
||||
TKey value = selector(enumerator.Current);
|
||||
if (comparer.Compare(value, minValue) >= 0) { continue; }
|
||||
minItem = enumerator.Current;
|
||||
minValue = value;
|
||||
}
|
||||
return minItem;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 排序
|
||||
|
||||
/// <summary>
|
||||
/// 使用默认比较器对集合进行排序。顺序为从小到大。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> Ordered<T>(this IEnumerable<T> source) where T : IComparable<T>
|
||||
=> source.OrderBy(x => x);
|
||||
|
||||
/// <summary>
|
||||
/// 使用默认比较器对集合进行排序。顺序为从大到小。
|
||||
/// </summary>
|
||||
public static IEnumerable<T> OrderedDescending<T>(this IEnumerable<T> source) where T : IComparable<T>
|
||||
=> source.OrderByDescending(x => x);
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -153,7 +271,7 @@ public static class EnumerableExtensions {
|
||||
isFirst = false;
|
||||
else
|
||||
builder.Append(split);
|
||||
if (element is not null) builder.Append(element.ToString());
|
||||
if (element is not null) builder.Append(element);
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
@@ -166,7 +284,8 @@ public static class EnumerableExtensions {
|
||||
/// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。
|
||||
/// 返回是否确实移除了元素。
|
||||
/// </summary>
|
||||
public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key) => dict.TryRemove(key, out _);
|
||||
public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key)
|
||||
=> dict.TryRemove(key, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 将二维数组转换为字典。
|
||||
@@ -182,8 +301,8 @@ public static class EnumerableExtensions {
|
||||
/// <summary>
|
||||
/// 尝试从字典中获取某项,如果该项不存在,则返回默认值。
|
||||
/// </summary>
|
||||
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default!) =>
|
||||
dict.TryGetValue(key, out var result) ? result : defaultValue;
|
||||
public static TValue? GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue? defaultValue = default)
|
||||
=> dict.TryGetValue(key, out var result) ? result : defaultValue;
|
||||
|
||||
/// <summary>
|
||||
/// 将值添加到字典的对应项的列表中。
|
||||
@@ -205,19 +324,43 @@ public static class EnumerableExtensions {
|
||||
/// <remarks>
|
||||
/// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
|
||||
/// </remarks>
|
||||
public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum {
|
||||
foreach (var element in Enum.GetValues(typeof(T)).Cast<T>().Distinct()) {
|
||||
var number = Convert.ToInt64(element, CultureInfo.InvariantCulture);
|
||||
if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值
|
||||
if (value.HasFlag(element)) yield return element;
|
||||
}
|
||||
public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum
|
||||
=> EnumUtils.GetAllFlags<T>().Where(element => value.HasFlag(element));
|
||||
|
||||
/// <summary>
|
||||
/// 从集合中移除满足条件的元素。
|
||||
/// </summary>
|
||||
public static void RemoveIf<T>(this ICollection<T> source, Func<T, bool> predicate) {
|
||||
var itemsToRemove = source.Where(predicate).ToList();
|
||||
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>
|
||||
public static void KeepIf<T>(this ICollection<T> source, Func<T, bool> predicate) {
|
||||
var itemsToRemove = source.Where(item => !predicate(item)).ToList();
|
||||
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>
|
||||
/// 判断集合是否有且仅有一个元素。
|
||||
/// 在输入 null 时返回 false。
|
||||
/// </summary>
|
||||
public static bool IsSingle<T>([AllowNull] this IEnumerable<T> source) {
|
||||
public static bool IsSingle<T>(this IEnumerable<T>? source) {
|
||||
if (source is null) return false;
|
||||
if (source is IList<T> list) return list.Count == 1;
|
||||
using var enumerator = source.GetEnumerator();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace MeloongCore.Extensions;
|
||||
public static class ExceptionExtensions {
|
||||
@@ -12,25 +12,66 @@ public static class ExceptionExtensions {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 <paramref name="ex"/> 的用户友好描述。
|
||||
/// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
|
||||
/// 该异常或其子异常是否为 <see cref="OperationCanceledException"/>、<see cref="TaskCanceledException"/> 或 <see cref="ThreadInterruptedException"/>。
|
||||
/// </summary>
|
||||
public static string GetDisplay(this Exception? ex, bool showMultilineStacks) {
|
||||
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>
|
||||
/// 将异常所有的 <see cref="Exception.InnerException"/> 展开。
|
||||
/// 若为 <see cref="AggregateException"/>,也会展开其中所有的子异常。
|
||||
/// </summary>
|
||||
public static IEnumerable<Exception> Flatten(this Exception ex) {
|
||||
var toFlatten = new Stack<Exception>();
|
||||
toFlatten.Push(ex);
|
||||
while (toFlatten.Any()) {
|
||||
var current = toFlatten.Pop();
|
||||
yield return current;
|
||||
if (current is AggregateException ag) {
|
||||
foreach (var inner in ag.InnerExceptions) toFlatten.Push(inner);
|
||||
} else if (current.InnerException is not null) {
|
||||
toFlatten.Push(current.InnerException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 <paramref name="ex"/> 的用户友好描述。
|
||||
/// 若 <paramref name="multiline"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
|
||||
/// </summary>
|
||||
public static string GetDisplay(this Exception? ex, bool multiline) {
|
||||
if (ex is null) return "无可用错误信息!";
|
||||
|
||||
// 提取堆栈信息
|
||||
var lines = new List<string>();
|
||||
bool isInnerException = false;
|
||||
for (Exception? currentEx = ex; currentEx is not null; currentEx = currentEx.InnerException) {
|
||||
if (showMultilineStacks) {
|
||||
lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true));
|
||||
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
|
||||
var stackLines = (currentEx.StackTrace?.ReplaceLineEndings("\r", true).Split('\r') ?? [])
|
||||
.Select(l => l.BeforeFirst("(") + l.AfterFirst(")"))
|
||||
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()) {
|
||||
if (multiline) {
|
||||
lines.Add((isInnerException ? "→ " : "") + getExceptionMessage(currentEx).ReplaceLineEndings("\r\n", true));
|
||||
var stackLines = (currentEx.StackTrace?.SplitLines(true) ?? [])
|
||||
.Select(l => l.BeforeLast("(") + l.AfterLast(")"))
|
||||
.Distinct();
|
||||
lines.AddRange(stackLines);
|
||||
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
|
||||
} else {
|
||||
lines.Add(currentEx.Message.ReplaceLineEndings(" ", true));
|
||||
lines.Add(getExceptionMessage(currentEx).ReplaceLineEndings(" ", true));
|
||||
}
|
||||
isInnerException = true;
|
||||
}
|
||||
@@ -50,7 +91,7 @@ public static class ExceptionExtensions {
|
||||
commonReason = "你的网络环境不佳,请稍后再试,或使用 VPN 改善网络环境。";
|
||||
|
||||
// 输出
|
||||
if (showMultilineStacks) {
|
||||
if (multiline) {
|
||||
if (commonReason is null) {
|
||||
return lines.Join("\r\n");
|
||||
} else {
|
||||
@@ -62,7 +103,7 @@ public static class ExceptionExtensions {
|
||||
lines.Reverse();
|
||||
return lines.Join(" ← ");
|
||||
} else {
|
||||
return commonReason + "详细错误:" + lines.First();
|
||||
return $"{commonReason}({lines.First()})";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,9 +112,11 @@ public static class ExceptionExtensions {
|
||||
/// 判断该异常是否是由于网络连接不良导致。
|
||||
/// </summary>
|
||||
public static bool IsBadNetwork(this Exception ex) {
|
||||
for (Exception? currentEx = ex; currentEx is not null; currentEx = currentEx.InnerException) {
|
||||
foreach (var currentEx in ex.Flatten()) {
|
||||
if (currentEx is TimeoutException) {
|
||||
return true;
|
||||
} else if (currentEx is TaskCanceledException) {
|
||||
return true;
|
||||
} else if (currentEx is HttpRequestCodeException reqEx) {
|
||||
if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false;
|
||||
if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true;
|
||||
@@ -84,10 +127,10 @@ public static class ExceptionExtensions {
|
||||
}
|
||||
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.ProxyNameResolutionFailure) return true;
|
||||
WebExceptionStatus.ProxyNameResolutionFailure or WebExceptionStatus.SecureChannelFailure) return true;
|
||||
} else if (currentEx is SocketException socketEx) {
|
||||
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.HostDown or SocketError.HostUnreachable or
|
||||
SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostUnreachable or
|
||||
SocketError.HostNotFound or SocketError.TryAgain or SocketError.NoData) return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MeloongCore.Extensions;
|
||||
public static class StringExtensions {
|
||||
@@ -6,146 +6,226 @@ public static class StringExtensions {
|
||||
#region 区域性 / 大小写 简化
|
||||
|
||||
/// <summary>
|
||||
/// 高速的 StartsWith。
|
||||
/// 非区域性的 <see cref="string.StartsWith(string)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false) {
|
||||
if (value is null) return false;
|
||||
return value.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false)
|
||||
=> value?.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
|
||||
/// <summary>
|
||||
/// 高速的 StartsWith。
|
||||
/// 判断字符串是否以 <paramref name="prefix"/> 开头。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool StartsWithF(this string? value, char prefix, bool ignoreCase = false) {
|
||||
if (value is null) return false;
|
||||
return value.StartsWith(prefix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static bool StartsWithF(this string? value, char prefix, bool ignoreCase = false)
|
||||
=> value?.StartsWith(prefix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
|
||||
/// <summary>
|
||||
/// 高速的 EndsWith。
|
||||
/// 非区域性的 <see cref="string.EndsWith(string)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false) {
|
||||
if (value is null) return false;
|
||||
return value.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false)
|
||||
=> value?.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
|
||||
/// <summary>
|
||||
/// 高速的 EndsWith。
|
||||
/// 判断字符串是否以 <paramref name="suffix"/> 结尾。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool EndsWithF(this string? value, char suffix, bool ignoreCase = false) {
|
||||
if (value is null) return false;
|
||||
return value.EndsWith(suffix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static bool EndsWithF(this string? value, char suffix, bool ignoreCase = false)
|
||||
=> value?.EndsWith(suffix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
|
||||
|
||||
/// <summary>
|
||||
/// 忽略大小写的 Contains。
|
||||
/// 忽略大小写的 <see cref="string.Contains(string)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool ContainsIgnoreCase(this string value, string subString) {
|
||||
return value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
}
|
||||
public static bool ContainsIgnoreCase(this string value, string subString)
|
||||
=> value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
/// <summary>
|
||||
/// 高速的 IndexOf。
|
||||
/// 非区域性的 <see cref="string.IndexOf(string)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int IndexOfF(this string value, string subString, bool ignoreCase = false) {
|
||||
return value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static int IndexOfF(this string value, string subString, bool ignoreCase = false)
|
||||
=> value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
/// <summary>
|
||||
/// 高速的 IndexOf。
|
||||
/// 非区域性的 <see cref="string.IndexOf(string, int)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) {
|
||||
return value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false)
|
||||
=> value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// 高速的 LastIndexOf。
|
||||
/// 非区域性的 <see cref="string.LastIndexOf(string)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false) {
|
||||
return value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false)
|
||||
=> value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
/// <summary>
|
||||
/// 高速的 LastIndexOf。
|
||||
/// 非区域性的 <see cref="string.LastIndexOf(string, int)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) {
|
||||
return value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false)
|
||||
=> value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// ToLowerInvariant 的简略写法。
|
||||
/// <see cref="string.ToLowerInvariant"/> 的简略写法。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string Lower(this string str) => str.ToLowerInvariant();
|
||||
public static string Lower(this string str)
|
||||
=> str.ToLowerInvariant();
|
||||
/// <summary>
|
||||
/// ToUpperInvariant 的简略写法。
|
||||
/// <see cref="string.ToUpperInvariant"/> 的简略写法。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string Upper(this string str) => str.ToUpperInvariant();
|
||||
public static string Upper(this string str)
|
||||
=> str.ToUpperInvariant();
|
||||
|
||||
#endregion
|
||||
|
||||
#region 分割与裁切
|
||||
#region Split
|
||||
|
||||
/// <summary>
|
||||
/// 分割字符串。
|
||||
/// 若原始字符串为空,则返回 {""}。
|
||||
/// </summary>
|
||||
public static string[] Split(this string fullStr, string splitStr) {
|
||||
if (splitStr.IsSingle())
|
||||
return fullStr.Split(splitStr[0]);
|
||||
else
|
||||
return fullStr.Split([splitStr], StringSplitOptions.None);
|
||||
public static string[] Split(this string fullStr, string splitStr, bool removeEmptyEntries = false) {
|
||||
if (splitStr.IsSingle()) {
|
||||
return fullStr.Split(splitStr[0], removeEmptyEntries);
|
||||
} else {
|
||||
return fullStr.Split([splitStr], removeEmptyEntries);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 分割字符串。
|
||||
/// 若原始字符串为空,则返回 {""}。
|
||||
/// </summary>
|
||||
public static string[] Split(this string fullStr, char splitChar, bool removeEmptyEntries = false)
|
||||
=> fullStr.Split([splitChar], removeEmptyEntries);
|
||||
/// <summary>
|
||||
/// 分割字符串。
|
||||
/// 若原始字符串为空,则返回 {""}。
|
||||
/// </summary>
|
||||
public static string[] Split(this string fullStr, string[] splitStrings, bool removeEmptyEntries = false)
|
||||
=> fullStr.Split(splitStrings, removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
|
||||
/// <summary>
|
||||
/// 分割字符串。
|
||||
/// 若原始字符串为空,则返回 {""}。
|
||||
/// </summary>
|
||||
public static string[] Split(this string fullStr, char[] splitChars, bool removeEmptyEntries = false)
|
||||
=> fullStr.Split(splitChars, removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
|
||||
|
||||
/// <summary>
|
||||
/// 将字符串分割为多行。
|
||||
/// </summary>
|
||||
public static string[] SplitLines(this string input, bool skipEmptyLines = false)
|
||||
=> input.ReplaceLineEndings("\n").Split('\n', skipEmptyLines);
|
||||
|
||||
#endregion
|
||||
|
||||
#region 裁切
|
||||
|
||||
/// <summary>
|
||||
/// 获取在子字符串第一次出现之前的部分,如果未找到子字符串则不裁切。
|
||||
/// <code>"2024/11/08".BeforeFirst("/") => "2024"</code>
|
||||
/// </summary>
|
||||
public static string BeforeFirst(this string str, string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
|
||||
if (pos < 0) return str;
|
||||
return str[..pos];
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
|
||||
/// <code>"2024/11-08".BeforeFirstOfAny(["/", "-"]) => "2024"</code>
|
||||
/// </summary>
|
||||
public static string BeforeFirstOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||
if (texts == null) return str;
|
||||
int pos = -1;
|
||||
foreach (string text in texts) {
|
||||
if (string.IsNullOrEmpty(text)) continue;
|
||||
int p = str.IndexOfF(text, ignoreCase);
|
||||
if (p >= 0 && (pos < 0 || pos > p)) pos = p;
|
||||
}
|
||||
if (pos < 0) return str;
|
||||
return str[..pos];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// 获取在子字符串最后一次出现之前的部分,如果未找到子字符串则不裁切。
|
||||
/// <code>"2024/11/08".BeforeLast("/") => "2024/11"</code>
|
||||
/// </summary>
|
||||
public static string BeforeFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(0, pos);
|
||||
else
|
||||
return str;
|
||||
public static string BeforeLast(this string str, string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
|
||||
if (pos < 0) return str;
|
||||
return str[..pos];
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
|
||||
/// <code>"2024/11-08".BeforeLastOfAny(["/", "-"]) => "2024/11"</code>
|
||||
/// </summary>
|
||||
public static string BeforeLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(0, pos);
|
||||
else
|
||||
return str;
|
||||
public static string BeforeLastOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||
if (texts == null) return str;
|
||||
int pos = -1;
|
||||
foreach (string text in texts) {
|
||||
if (string.IsNullOrEmpty(text)) continue;
|
||||
int p = str.LastIndexOfF(text, ignoreCase);
|
||||
if (p >= 0 && (pos < 0 || pos < p)) pos = p;
|
||||
}
|
||||
if (pos < 0) return str;
|
||||
return str[..pos];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取在子字符串第一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 11/08。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// 获取在子字符串第一次出现之后的部分,如果未找到子字符串则不裁切。
|
||||
/// <code>"2024/11/08".AfterFirst("/") => "11/08"</code>
|
||||
/// </summary>
|
||||
public static string AfterFirst(this string str, [AllowNull] 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);
|
||||
if (pos >= 0)
|
||||
return str.Substring(pos + text!.Length);
|
||||
else
|
||||
return str;
|
||||
if (pos < 0) return str;
|
||||
return str[(pos + text!.Length)..];
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。
|
||||
/// 如果未找到子字符串则不裁切。
|
||||
/// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
|
||||
/// <code>"2024/11-08".AfterFirstOfAny(["/", "-"]) => "11-08"</code>
|
||||
/// </summary>
|
||||
public static string AfterLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
|
||||
public static string AfterFirstOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||
if (texts == null) return str;
|
||||
int pos = -1;
|
||||
int len = 0;
|
||||
foreach (string text in texts) {
|
||||
if (string.IsNullOrEmpty(text)) continue;
|
||||
int p = str.IndexOfF(text, ignoreCase);
|
||||
if (p >= 0 && (pos < 0 || pos > p)) {
|
||||
pos = p;
|
||||
len = text.Length;
|
||||
}
|
||||
}
|
||||
if (pos < 0) return str;
|
||||
return str[(pos + len)..];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取在子字符串最后一次出现之后的部分,如果未找到子字符串则不裁切。
|
||||
/// <code>"2024/11/08".AfterLast("/") => "08"</code>
|
||||
/// </summary>
|
||||
public static string AfterLast(this string str, string? text, bool ignoreCase = false) {
|
||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
|
||||
if (pos >= 0)
|
||||
return str.Substring(pos + text!.Length);
|
||||
else
|
||||
return str;
|
||||
if (pos < 0) return str;
|
||||
return str[(pos + text!.Length)..];
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
|
||||
/// <code>"2024/11-08".AfterLastOfAny(["/", "-"]) => "08"</code>
|
||||
/// </summary>
|
||||
public static string AfterLastOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||
if (texts == null) return str;
|
||||
int pos = -1;
|
||||
int len = 0;
|
||||
foreach (string text in texts) {
|
||||
if (string.IsNullOrEmpty(text)) continue;
|
||||
int p = str.LastIndexOfF(text, ignoreCase);
|
||||
if (p >= 0 && (pos < 0 || pos < p)) {
|
||||
pos = p;
|
||||
len = text.Length;
|
||||
}
|
||||
}
|
||||
if (pos < 0) return str;
|
||||
return str[(pos + len)..];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -155,18 +235,20 @@ public static class StringExtensions {
|
||||
/// </summary>
|
||||
public static string Between(this string str, string after, string before, bool ignoreCase = false) {
|
||||
int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
|
||||
if (startPos >= 0)
|
||||
if (startPos >= 0) {
|
||||
startPos += after.Length;
|
||||
else
|
||||
} else {
|
||||
startPos = 0;
|
||||
}
|
||||
|
||||
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
|
||||
if (endPos >= 0)
|
||||
return str.Substring(startPos, endPos - startPos);
|
||||
else if (startPos > 0)
|
||||
return str.Substring(startPos);
|
||||
else
|
||||
if (endPos >= 0) {
|
||||
return str[startPos..endPos];
|
||||
} else if (startPos > 0) {
|
||||
return str[startPos..];
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -175,29 +257,118 @@ public static class StringExtensions {
|
||||
|
||||
/// <summary>
|
||||
/// 替换字符串中的内容。
|
||||
/// 仅当需要替换时,才调用 <paramref name="newValue"/> 获取结果字符串。
|
||||
/// 仅当需要替换时,才调用 <paramref name="newValueGetter"/> 获取结果字符串。
|
||||
/// </summary>
|
||||
public static string ReplaceOnDemand(this string str, string oldValue, Func<string> newValue) =>
|
||||
str.Contains(oldValue) ? str.Replace(oldValue, newValue()) : str;
|
||||
public static string Replace(this string str, string oldValue, Func<string> newValueGetter)
|
||||
=> str.Contains(oldValue) ? str.Replace(oldValue, newValueGetter()) : str;
|
||||
|
||||
/// <summary>
|
||||
/// 将字符串中的换行符统一替换为指定字符。
|
||||
/// 将字符串中的换行符统一替换为指定字符串。
|
||||
/// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
|
||||
/// </summary>
|
||||
public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false) =>
|
||||
Regex.Replace(input,
|
||||
mergeMultiple ? @"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+" : @"\r\n|[\n\r\f\u0085\u2028\u2029]",
|
||||
newValue.Replace("$", "$$"), // 避免识别成捕获组
|
||||
RegexOptions.Compiled);
|
||||
public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false)
|
||||
=> (mergeMultiple ? regexLineEndingAndMerge : regexLineEnding).Replace(input, newValue.Replace("$", "$$")); // 避免识别成捕获组
|
||||
private static readonly Regex regexLineEndingAndMerge = new(@"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+", RegexOptions.Compiled);
|
||||
private static readonly Regex regexLineEnding = new(@"\r\n|[\n\r\f\u0085\u2028\u2029]", RegexOptions.Compiled);
|
||||
|
||||
#endregion
|
||||
|
||||
#region 正则
|
||||
|
||||
/// <summary>
|
||||
/// 搜索字符串中所有的正则匹配项。
|
||||
/// </summary>
|
||||
public static IEnumerable<string> RegexSearch(this string str, string pattern, RegexOptions options = RegexOptions.None) {
|
||||
try {
|
||||
return Regex.Matches(str, pattern, options).Cast<Match>().Select(m => m.Value);
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"{nameof(RegexSearch)} 失败({pattern})");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取字符串中的第一个正则匹配项,若无匹配或失败则返回 <see langword="null"/>。
|
||||
/// </summary>
|
||||
public static string? RegexSeek(this string str, string pattern, RegexOptions options = RegexOptions.None) {
|
||||
try {
|
||||
var match = Regex.Match(str, pattern, options);
|
||||
return match.Success ? match.Value : null;
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"{nameof(RegexSeek)} 失败({pattern})");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查字符串是否匹配某正则模式。
|
||||
/// </summary>
|
||||
public static bool RegexCheck(this string str, string pattern, RegexOptions options = RegexOptions.None) {
|
||||
try {
|
||||
return Regex.IsMatch(str, pattern, options);
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"{nameof(RegexCheck)} 失败({pattern})");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 进行正则替换。
|
||||
/// 失败时会抛出异常。
|
||||
/// </summary>
|
||||
public static string RegexReplace(this string allContents, string searchRegex, string replaceTo, RegexOptions options = RegexOptions.None) {
|
||||
return Regex.Replace(allContents, searchRegex, replaceTo, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对每个正则匹配分别进行替换。
|
||||
/// 失败时会抛出异常。
|
||||
/// </summary>
|
||||
public static string RegexReplace(this string allContents, string searchRegex, MatchEvaluator replaceTo, RegexOptions options = RegexOptions.None) {
|
||||
return Regex.Replace(allContents, searchRegex, replaceTo, options);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 读取 <see cref="Stream"/> 中的内容,并解码为字符串。
|
||||
/// 会将流的位置主动重置到开头。
|
||||
/// </summary>
|
||||
public static string ReadString(this Stream stream, Encoding? encoding = null) {
|
||||
using var memoryStream = new MemoryStream();
|
||||
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
|
||||
stream.CopyTo(memoryStream);
|
||||
return memoryStream.ToArray().GetString(encoding);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 <paramref name="bytes"/> 解码为字符串。
|
||||
/// </summary>
|
||||
public static string GetString(this byte[] bytes, Encoding? encoding = null) {
|
||||
if (encoding is not null) return encoding.GetString(bytes);
|
||||
int length = bytes.Length;
|
||||
// 根据 BOM 判断编码
|
||||
if (length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) {
|
||||
return Encoding.UTF8.GetString(bytes, 3, length - 3); // 带 BOM 的 UTF8
|
||||
} else if (length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) {
|
||||
return Encoding.BigEndianUnicode.GetString(bytes, 2, length - 2);
|
||||
} else if (length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) {
|
||||
return Encoding.Unicode.GetString(bytes, 2, length - 2);
|
||||
}
|
||||
// 无 BOM 文件:GB18030(ANSI)或 UTF8
|
||||
try {
|
||||
return new UTF8Encoding(false, true).GetString(bytes); // 不带 BOM 的 UTF8
|
||||
} catch (DecoderFallbackException) {
|
||||
return Encoding.GetEncoding("GB18030").GetString(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将第一个字符转换为大写,其余字符转换为小写。
|
||||
/// </summary>
|
||||
public static string Capitalize(this string 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>
|
||||
@@ -205,13 +376,43 @@ public static class StringExtensions {
|
||||
/// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
|
||||
/// </summary>
|
||||
public static string EnsureLength(this string? str, char code, int length) {
|
||||
if (str == null) str = "";
|
||||
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
|
||||
str ??= "";
|
||||
return str.Length > length ? str[..length] : str.PadLeft(length, code);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 该字符串中的字符是否均为 ASCII 字符。
|
||||
/// </summary>
|
||||
public static bool IsAsciiOnly(this string input) => input.All(c => c < 128);
|
||||
public static bool IsAsciiOnly(this string input)
|
||||
=> 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);
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,67 +1,65 @@
|
||||
namespace MeloongCore;
|
||||
namespace MeloongCore;
|
||||
|
||||
/// <summary>
|
||||
/// 线程安全的 <see cref="List{T}"/> 实现。
|
||||
/// 当调用枚举器时返回一个临时副本,以避免列表在枚举过程中被修改导致异常。
|
||||
/// 使用粗粒度锁的线程安全 <see cref="List{T}"/> 实现。
|
||||
/// 通常建议使用 <see cref="ConcurrentBag{T}"/> 或其他线程安全集合,它们具有更好的性能。
|
||||
/// </summary>
|
||||
public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> {
|
||||
public class ConcurrentList<T> : IList<T>, IList {
|
||||
|
||||
private readonly List<T> _items = [];
|
||||
public readonly object syncLock = new();
|
||||
|
||||
// 构造函数
|
||||
public ConcurrentList() { }
|
||||
public ConcurrentList(IEnumerable<T> data) => _items = new List<T>(data);
|
||||
public ConcurrentList(IEnumerable<T> data) => _items = 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 List<T>(data._items); } }
|
||||
public static implicit operator List<T>(ConcurrentList<T> data) { lock (data.SyncRoot) { return new(data._items); } }
|
||||
|
||||
// 枚举器
|
||||
public IEnumerator<T> GetEnumerator() {
|
||||
lock (syncLock) {
|
||||
return _items.ToList().GetEnumerator();
|
||||
}
|
||||
}
|
||||
IEnumerator IEnumerable.GetEnumerator() {
|
||||
lock (syncLock) {
|
||||
return _items.ToList().GetEnumerator();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 返回此列表的副本。
|
||||
/// </summary>
|
||||
public IEnumerator<T> GetEnumerator() { lock (SyncRoot) return _items.ToList().GetEnumerator(); }
|
||||
/// <summary>
|
||||
/// 返回此列表的副本。
|
||||
/// </summary>
|
||||
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;
|
||||
bool IList.IsFixedSize => false;
|
||||
bool ICollection.IsSynchronized => true;
|
||||
object ICollection.SyncRoot => syncLock;
|
||||
public readonly object SyncRoot = new();
|
||||
object ICollection.SyncRoot => SyncRoot;
|
||||
|
||||
public T this[int index] {
|
||||
get { lock (syncLock) { return _items[index]; } }
|
||||
set { lock (syncLock) { _items[index] = value; } }
|
||||
get { lock (SyncRoot) { return _items[index]; } }
|
||||
set { lock (SyncRoot) { _items[index] = value; } }
|
||||
}
|
||||
object? IList.this[int 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); } }
|
||||
int IList.Add(object? value) { lock (syncLock) { _items.Add((T) value!); return _items.Count - 1; } }
|
||||
public void Add(T item) { lock (SyncRoot) { _items.Add(item); } }
|
||||
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); } }
|
||||
void IList.Insert(int index, object? value) { lock (syncLock) { _items.Insert(index, (T) value!); } }
|
||||
public void Insert(int index, T item) { lock (SyncRoot) { _items.Insert(index, item); } }
|
||||
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); } }
|
||||
void IList.Remove(object? value) { lock (syncLock) { if (value is T t) _items.Remove(t); } }
|
||||
public bool Remove(T item) { lock (SyncRoot) { return _items.Remove(item); } }
|
||||
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 Clear() { lock (syncLock) { _items.Clear(); } }
|
||||
public void RemoveAt(int index) { lock (SyncRoot) { _items.RemoveAt(index); } }
|
||||
public void Clear() { lock (SyncRoot) { _items.Clear(); } }
|
||||
|
||||
public bool Contains(T item) { lock (syncLock) { return _items.Contains(item); } }
|
||||
bool IList.Contains(object? value) { lock (syncLock) { return value is T t && _items.Contains(t); } }
|
||||
public bool Contains(T item) { lock (SyncRoot) { return _items.Contains(item); } }
|
||||
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); } }
|
||||
int IList.IndexOf(object? value) { lock (syncLock) { return value is T t ? _items.IndexOf(t) : -1; } }
|
||||
public int IndexOf(T item) { lock (SyncRoot) { return _items.IndexOf(item); } }
|
||||
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); } }
|
||||
void ICollection.CopyTo(Array array, int index) { lock (syncLock) { ((ICollection) _items).CopyTo(array, index); } }
|
||||
public void CopyTo(T[] array, int arrayIndex) { lock (SyncRoot) { _items.CopyTo(array, arrayIndex); } }
|
||||
void ICollection.CopyTo(Array array, int index) { lock (SyncRoot) { ((ICollection) _items).CopyTo(array, index); } }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
using System.Security.Cryptography;
|
||||
namespace MeloongCore;
|
||||
|
||||
#region ConfigProvider | 配置提供器
|
||||
|
||||
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;
|
||||
|
||||
#pragma warning disable CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 'required' 修饰符或声明为可以为 null。
|
||||
public JsonConfigProvider(string filePath) {
|
||||
#pragma warning restore CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 'required' 修饰符或声明为可以为 null。
|
||||
this.filePath = filePath;
|
||||
allProviders.Add(new(this));
|
||||
saveWorker = new(Save, 500, RateLimitMode.WaitUnillNoNewInvoke);
|
||||
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 RateLimitedWorker saveWorker;
|
||||
private bool isDirty = false;
|
||||
public void MakeDirty() {
|
||||
lock (this) isDirty = true;
|
||||
saveWorker.Start();
|
||||
}
|
||||
/// <summary>同步保存配置,并等待同一实例正在进行的保存完成;保存失败时保留待保存状态。</summary>
|
||||
public void Save() {
|
||||
lock (this) {
|
||||
if (!isDirty) return;
|
||||
FileUtils.WriteAtomic(filePath, json.Value.ToString(Formatting.Indented));
|
||||
isDirty = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ConfigProviders {
|
||||
public static JsonConfigProvider Default = new(Path.Combine(Paths.AppDataThenName, "config.json"));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ConfigEntry | 单个配置项
|
||||
|
||||
/// <summary>
|
||||
/// 当前获取到的配置值。
|
||||
/// </summary>
|
||||
public class PreviewGetEventArgs<T>(T? value) : EventArgs {
|
||||
public T? Value { get; set; } = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用固定的 <see cref="IConfigProvider"/> 的配置项。
|
||||
/// <para/>若不指定 <paramref name="provider"/>,则使用 <see cref="ConfigProviders.Default"/>。
|
||||
/// </summary>
|
||||
public class ConfigEntry<T>(string key, T? defaultValue, bool encrypted = false, IConfigProvider? provider = null) {
|
||||
public IConfigProvider Provider { get; } = provider ?? ConfigProviders.Default;
|
||||
|
||||
/// <summary>
|
||||
/// 当调整配置项的值时触发,参数为新值。<para/>新值可能和旧值相同。
|
||||
/// </summary>
|
||||
public event Action<T?>? Changed;
|
||||
/// <summary>
|
||||
/// 当获取配置项的值时触发。
|
||||
/// </summary>
|
||||
public event Action<PreviewGetEventArgs<T>, IConfigProvider>? PreviewGet;
|
||||
|
||||
public void Edit(Func<T?, T?> editFunc) => Set(editFunc(Get()));
|
||||
public void Edit(RefAction editAction) {
|
||||
var current = Get();
|
||||
editAction(ref current);
|
||||
Set(current);
|
||||
}
|
||||
public delegate void RefAction(ref T? value);
|
||||
|
||||
public void Set(T? value) {
|
||||
Provider.Set(key, value, encrypted);
|
||||
Changed?.Invoke(value);
|
||||
}
|
||||
public void Reset() {
|
||||
if (!Provider.HasValue(key)) return; // 值未设置,无需重置
|
||||
Provider.Remove(key);
|
||||
Changed?.Invoke(defaultValue);
|
||||
}
|
||||
public T? Get() {
|
||||
PreviewGetEventArgs<T> args = new(Provider.Read(key, defaultValue, encrypted));
|
||||
PreviewGet?.Invoke(args, Provider);
|
||||
return args.Value;
|
||||
}
|
||||
public bool HasValue() => Provider.HasValue(key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在每次操作时动态指定 <see cref="IConfigProvider"/> 的配置项。
|
||||
/// </summary>
|
||||
public class DynamicConfigEntry<T>(string key, T? defaultValue, bool encrypted = false) {
|
||||
/// <summary>
|
||||
/// 当调整配置项的值时触发,参数为新值。<para/>新值可能和旧值相同。
|
||||
/// </summary>
|
||||
public event Action<T?>? Changed;
|
||||
/// <summary>
|
||||
/// 当获取配置项的值时触发。
|
||||
/// </summary>
|
||||
public event Action<PreviewGetEventArgs<T>, IConfigProvider>? PreviewGet;
|
||||
|
||||
|
||||
public void Edit(Func<T?, T?> editFunc, IConfigProvider provider) => Set(editFunc(Get(provider)), provider);
|
||||
public void Edit(RefAction editAction, IConfigProvider provider) {
|
||||
var current = Get(provider);
|
||||
editAction(ref current);
|
||||
Set(current, provider);
|
||||
}
|
||||
public delegate void RefAction(ref T? value);
|
||||
|
||||
public void Set(T? value, IConfigProvider provider) {
|
||||
provider.Set(key, value, encrypted);
|
||||
Changed?.Invoke(value);
|
||||
}
|
||||
public void Reset(IConfigProvider provider) {
|
||||
if (!provider.HasValue(key)) return; // 值未设置,无需重置
|
||||
provider.Remove(key);
|
||||
Changed?.Invoke(defaultValue);
|
||||
}
|
||||
public T? Get(IConfigProvider provider) {
|
||||
PreviewGetEventArgs<T> args = new(provider.Read(key, defaultValue, encrypted));
|
||||
PreviewGet?.Invoke(args, provider);
|
||||
return args.Value;
|
||||
}
|
||||
|
||||
public bool HasValue(IConfigProvider provider) => provider.HasValue(key);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static class ConfigUtils {
|
||||
|
||||
/// <summary>立即保存所有配置。</summary>
|
||||
public static void SaveAll() {
|
||||
foreach (var weakRef in JsonConfigProvider.allProviders) {
|
||||
if (weakRef.TryGetTarget(out var provider)) provider.Save();
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly Lazy<JObject> secret = new(() => {
|
||||
string filePath = Path.Combine(Paths.AppData, "Meloong", "Dev", "secret.json");
|
||||
try {
|
||||
return FileUtils.Exists(filePath) ? JObject.Parse(FileUtils.ReadAsString(filePath)) : [];
|
||||
} catch {
|
||||
throw new InvalidDataException($"读取密钥文件失败({filePath}),请检查文件内容与加密格式。");
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>从 secret.json 中读取加密的密钥;如果未找到对应密钥则抛出异常。</summary>
|
||||
public static string GetSecret(string key) {
|
||||
string value = secret.Value.Value<string>(key) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
|
||||
try {
|
||||
return CryptographyUtils.AesDecrypt(value)!;
|
||||
} catch {
|
||||
throw new InvalidDataException($"读取密钥失败({key}),请检查文件内容与加密格式。");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+248
-113
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace MeloongCore;
|
||||
@@ -6,30 +5,12 @@ namespace MeloongCore;
|
||||
/// <summary>
|
||||
/// 日志等级。
|
||||
/// </summary>
|
||||
public enum LogLevels {
|
||||
/// <summary>
|
||||
/// 追踪。
|
||||
/// 只在调试状态下输出日志信息。
|
||||
/// </summary>
|
||||
Trace,
|
||||
/// <summary>
|
||||
/// 信息。
|
||||
/// </summary>
|
||||
Info,
|
||||
/// <summary>
|
||||
/// 警告。
|
||||
/// </summary>
|
||||
Warning,
|
||||
/// <summary>
|
||||
/// 错误。
|
||||
/// </summary>
|
||||
Error
|
||||
}
|
||||
public enum LogLevel { Trace, Info, Warn, Error }
|
||||
|
||||
/// <summary>
|
||||
/// 输出日志时执行的错误汇报行为。
|
||||
/// </summary>
|
||||
public enum LogBehaviors {
|
||||
public enum LogBehavior {
|
||||
/// <summary>
|
||||
/// 无提示。
|
||||
/// </summary>
|
||||
@@ -59,150 +40,304 @@ public enum LogBehaviors {
|
||||
public static class Logger {
|
||||
public static BaseLogger Instance { get; set; } = new();
|
||||
|
||||
// 转发给实例的方法调用
|
||||
// 转发给 BaseLogger 实例的对外方法
|
||||
|
||||
public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "")
|
||||
=> Instance.Log(message, level, behavior, filePath);
|
||||
public static void Log(Exception ex, string? message = null, LogLevels level = LogLevels.Warning, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "")
|
||||
public static void Trace(string message, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(null, message, LogLevel.Trace, behavior, filePath);
|
||||
public static void Info(string message, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(null, message, LogLevel.Info, behavior, filePath);
|
||||
public static void Warn(string message, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
|
||||
=> Log(null, message, LogLevel.Warn, behavior, filePath);
|
||||
public static void Error(string message, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
|
||||
=> Log(null, message, LogLevel.Error, behavior, filePath);
|
||||
public static void Log(string message, LogLevel level = LogLevel.Info, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(null, message, level, behavior, filePath);
|
||||
|
||||
public static void Trace(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(ex, message, LogLevel.Trace, behavior, filePath);
|
||||
public static void Info(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(ex, message, LogLevel.Info, behavior, filePath);
|
||||
public static void Warn(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
|
||||
=> Log(ex, message, LogLevel.Warn, behavior, filePath);
|
||||
public static void Error(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
|
||||
=> Log(ex, message, LogLevel.Error, behavior, filePath);
|
||||
public static void Log(Exception? ex, string? message = null, LogLevel level = LogLevel.Warn, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
|
||||
=> Instance.Log(ex, message, level, behavior, filePath);
|
||||
|
||||
public static void Trace(Func<string> message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") { if (Instance.MinLevel <= LogLevels.Trace) Log(message(), LogLevels.Trace, behavior, filePath); }
|
||||
public static void Trace(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Trace, behavior, filePath);
|
||||
public static void Info(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Info, behavior, filePath);
|
||||
public static void Warning(string message, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Warning, behavior, filePath);
|
||||
public static void Error(string message, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Error, behavior, filePath);
|
||||
/// <summary>
|
||||
/// 在不调用 Logger 的情况下,将信息直接发送到输出窗口。
|
||||
/// </summary>
|
||||
[Conditional("DEBUG")]
|
||||
public static void SendToDebug(string message, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "")
|
||||
=> Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{message}");
|
||||
/// <summary>
|
||||
/// 在不调用 Logger 的情况下,将信息直接发送到输出窗口。
|
||||
/// </summary>
|
||||
[Conditional("DEBUG")]
|
||||
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)}");
|
||||
|
||||
/// <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 内插优化
|
||||
|
||||
// VB.NET:由于不兼容 InterpolatedStringHandler,只能手动使用 Lambda
|
||||
|
||||
public static void Log(Func<string?> messageFactory, LogLevel level = LogLevel.Info, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
|
||||
if (Instance.MinLevel > level) return;
|
||||
Instance.Log(null, messageFactory() ?? string.Empty, level, behavior, filePath);
|
||||
}
|
||||
public static void Trace(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(messageFactory, LogLevel.Trace, behavior, filePath);
|
||||
public static void Info(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
|
||||
=> Log(messageFactory, LogLevel.Info, behavior, filePath);
|
||||
public static void Warn(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
|
||||
=> Log(messageFactory, LogLevel.Warn, behavior, filePath);
|
||||
public static void Error(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
|
||||
=> Log(messageFactory, LogLevel.Error, behavior, filePath);
|
||||
|
||||
// C#:仅当实际需要输出日志时,才格式化内插字符串,以优化性能
|
||||
|
||||
public static void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] ref LogInterpolatedStringHandler handler, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
|
||||
if (handler.isEnabled) Instance.Log(null, handler.ToStringAndClear(), level, behavior, filePath);
|
||||
}
|
||||
public static void Trace(ref LogInterpolatedStringHandler<TraceLogLevel> handler, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
|
||||
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Trace, behavior, filePath);
|
||||
}
|
||||
public static void Info(ref LogInterpolatedStringHandler<InfoLogLevel> handler, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
|
||||
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Info, behavior, filePath);
|
||||
}
|
||||
public static void Warn(ref LogInterpolatedStringHandler<WarnLogLevel> handler, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "") {
|
||||
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Warn, behavior, filePath);
|
||||
}
|
||||
public static void Error(ref LogInterpolatedStringHandler<ErrorLogLevel> handler, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "") {
|
||||
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Error, behavior, filePath);
|
||||
}
|
||||
|
||||
[InterpolatedStringHandler]
|
||||
public ref struct LogInterpolatedStringHandler {
|
||||
private StringBuilder? _sb;
|
||||
public readonly bool isEnabled;
|
||||
public LogInterpolatedStringHandler(int literalLength, LogLevel level, out bool isEnabled) {
|
||||
this.isEnabled = isEnabled = Logger.Instance.MinLevel <= level;
|
||||
_sb = this.isEnabled ? new StringBuilder(literalLength) : null;
|
||||
}
|
||||
public void AppendLiteral(string value) => _sb?.Append(value);
|
||||
public void AppendFormatted<T>(T value) => _sb?.Append(value);
|
||||
public void AppendFormatted<T>(T value, string? format) => _sb?.Append(value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString());
|
||||
public void AppendFormatted<T>(T value, int alignment) {
|
||||
if (_sb is null) return;
|
||||
var s = value?.ToString() ?? string.Empty;
|
||||
_sb.Append(alignment > 0 ? s.PadLeft(alignment) : alignment < 0 ? s.PadRight(-alignment) : s);
|
||||
}
|
||||
public void AppendFormatted<T>(T value, int alignment, string? format) {
|
||||
if (_sb is null) return;
|
||||
var s = value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString() ?? string.Empty;
|
||||
_sb.Append(alignment > 0 ? s.PadLeft(alignment) : alignment < 0 ? s.PadRight(-alignment) : s);
|
||||
}
|
||||
public void AppendFormatted(string? value) => _sb?.Append(value);
|
||||
public void AppendFormatted(object? value, int alignment = 0, string? format = null) {
|
||||
if (_sb is null) return;
|
||||
var s = value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString() ?? string.Empty;
|
||||
_sb.Append(alignment > 0 ? s.PadLeft(alignment) : alignment < 0 ? s.PadRight(-alignment) : s);
|
||||
}
|
||||
internal string ToStringAndClear() {
|
||||
var result = _sb?.ToString() ?? string.Empty;
|
||||
_sb = null;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
[InterpolatedStringHandler]
|
||||
public ref struct LogInterpolatedStringHandler<TLevel> where TLevel : struct, ILogLevelProvider {
|
||||
private LogInterpolatedStringHandler _inner;
|
||||
public bool IsEnabled => _inner.isEnabled;
|
||||
public LogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) => _inner = new(literalLength, default(TLevel).Level, out isEnabled);
|
||||
public void AppendLiteral(string value) => _inner.AppendLiteral(value);
|
||||
public void AppendFormatted<T>(T value) => _inner.AppendFormatted(value);
|
||||
public void AppendFormatted<T>(T value, string? format) => _inner.AppendFormatted(value, format);
|
||||
public void AppendFormatted<T>(T value, int alignment) => _inner.AppendFormatted(value, alignment);
|
||||
public void AppendFormatted<T>(T value, int alignment, string? format) => _inner.AppendFormatted(value, alignment, format);
|
||||
public void AppendFormatted(string? value) => _inner.AppendFormatted(value);
|
||||
public void AppendFormatted(object? value, int alignment = 0, string? format = null) => _inner.AppendFormatted(value, alignment, format);
|
||||
internal string ToStringAndClear() => _inner.ToStringAndClear();
|
||||
}
|
||||
|
||||
public readonly struct TraceLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Trace; }
|
||||
public readonly struct InfoLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Info; }
|
||||
public readonly struct WarnLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Warn; }
|
||||
public readonly struct ErrorLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Error; }
|
||||
public interface ILogLevelProvider { LogLevel Level { get; } }
|
||||
|
||||
#endregion
|
||||
|
||||
public static void Trace(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Trace, behavior, filePath);
|
||||
public static void Info(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Info, behavior, filePath);
|
||||
public static void Warning(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Warning, behavior, filePath);
|
||||
public static void Error(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Error, behavior, filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 最基础的日志实现。
|
||||
/// 仅将日志输出到 <see cref="Debug"/>,不实现 <see cref="LogBehaviors"/>。
|
||||
/// 仅将日志输出到 <see cref="Debug"/>,不实现 <see cref="LogBehavior"/>。
|
||||
/// </summary>
|
||||
public class BaseLogger {
|
||||
|
||||
/// <summary>
|
||||
/// 最低日志输出等级,低于此等级的日志将被忽略。
|
||||
/// </summary>
|
||||
public LogLevels MinLevel { get; set; } = LogLevels.Trace;
|
||||
public LogLevel MinLevel { get; set; } = LogLevel.Trace;
|
||||
|
||||
// 核心方法
|
||||
public virtual void Log(string message, LogLevels level, LogBehaviors behavior, string filePath) {
|
||||
public virtual void Log(Exception? ex, string? message, LogLevel level, LogBehavior behavior, string filePath) {
|
||||
if (ex?.IsCanceled() == true) {
|
||||
Log(null, $"操作已取消({message})", LogLevel.Info, LogBehavior.None, filePath);
|
||||
return;
|
||||
}
|
||||
if (MinLevel > level) return;
|
||||
try {
|
||||
var formattedMessage = Format(message, level, filePath, null);
|
||||
Output(formattedMessage, level);
|
||||
HandleBehavior(message, formattedMessage, behavior, null);
|
||||
} catch {}
|
||||
}
|
||||
public virtual void Log(Exception ex, string? message, LogLevels level, LogBehaviors behavior, string filePath) {
|
||||
if (MinLevel > level) return;
|
||||
if (ex is ThreadInterruptedException) return;
|
||||
try {
|
||||
var formattedMessage = (message is null ? "" : $"{message}:") + ex.GetDisplay(true);
|
||||
// 格式化文本
|
||||
var formattedMessage = ex is null ?
|
||||
(message ?? "") :
|
||||
(message is null ? "" : $"{message}:") + ex.GetDisplay(true);
|
||||
formattedMessage = Format(formattedMessage, level, filePath, ex);
|
||||
Output(formattedMessage, level);
|
||||
// 将格式化后的日志文本置入缓冲区
|
||||
if (available || queue.Count < 100) { // 在初始化前保留至多 100 条日志
|
||||
queue.Enqueue(new(level, formattedMessage));
|
||||
queuedEvent.Set();
|
||||
}
|
||||
// 执行事件
|
||||
HandleBehavior(message, formattedMessage, behavior, ex);
|
||||
} catch { }
|
||||
} catch (Exception logEx) {
|
||||
Logger.SendToDebug(logEx, "打印日志失败");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 格式化日志文本。
|
||||
/// </summary>
|
||||
protected virtual string Format(string text, LogLevels level, string filePath, Exception? ex) {
|
||||
string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{filePath.AfterLast(@"\").BeforeFirst(".")}] ";
|
||||
public virtual string Format(string text, LogLevel level, string filePath, Exception? ex) {
|
||||
string prefix = GetLogPrefix(level, filePath);
|
||||
if (string.IsNullOrEmpty(text)) return prefix;
|
||||
return text
|
||||
.ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries)
|
||||
.ReplaceLineEndings("\n", mergeMultiple: true).Split('\n', true)
|
||||
.Select(t => prefix + t)
|
||||
.Join("\r\n");
|
||||
}
|
||||
public static string GetLogPrefix(LogLevel level, string filePath)
|
||||
=> $"{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>
|
||||
/// 执行 <see cref="LogBehavior"/>。
|
||||
/// </summary>
|
||||
public virtual void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex) {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 输出格式化后的日志文本。
|
||||
/// </summary>
|
||||
protected virtual void Output(string formattedMessage, LogLevels level) {
|
||||
Debug.WriteLine(formattedMessage);
|
||||
public virtual void Output(LogEntry entry) {
|
||||
Debug.WriteLine(entry.message);
|
||||
}
|
||||
|
||||
public virtual void Init() { }
|
||||
|
||||
#region 缓冲区与初始化
|
||||
|
||||
internal volatile bool available = false;
|
||||
public record struct LogEntry(LogLevel Level, string message);
|
||||
internal readonly ConcurrentQueue<LogEntry> queue = new();
|
||||
internal readonly AutoResetEvent queuedEvent = new(false);
|
||||
|
||||
public BaseLogger() {
|
||||
var thread = new Thread(() => {
|
||||
try {
|
||||
Init();
|
||||
available = true;
|
||||
Logger.Info($"{GetType().Name} 日志初始化结束");
|
||||
while (available) {
|
||||
queuedEvent.WaitOne();
|
||||
Flush();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
available = false;
|
||||
Logger.SendToDebug(ex, "基础日志线程出错");
|
||||
}
|
||||
}) { Name = nameof(Logger), Priority = ThreadPriority.Lowest, IsBackground = true };
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在调用 Log 方法的线程执行 <see cref="LogBehaviors"/>。
|
||||
/// 立即输出缓冲区的日志。
|
||||
/// 不会抛出异常。
|
||||
/// </summary>
|
||||
protected virtual void HandleBehavior(string? rawMessage, string formattedMessage, LogBehaviors behavior, Exception? ex) {
|
||||
public void Flush() {
|
||||
try {
|
||||
if (!available) return;
|
||||
lock (flushLock) {
|
||||
while (queue.TryDequeue(out LogEntry entry)) Output(entry); // writer 指定了 AutoFlush
|
||||
}
|
||||
} catch (Exception logEx) {
|
||||
Logger.SendToDebug(logEx, "输出日志失败");
|
||||
}
|
||||
}
|
||||
private readonly object flushLock = new();
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将日志输出到 <see cref="Debug"/> 并写入指定的文件夹,最多保留 5 个文件。
|
||||
/// 不实现 <see cref="LogBehaviors"/>。
|
||||
/// 不实现 <see cref="LogBehavior"/>。
|
||||
/// </summary>
|
||||
public class FileLogger : BaseLogger {
|
||||
public class FileLogger : BaseLogger, IDisposable {
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void Output(string formattedText, LogLevels level) {
|
||||
base.Output(formattedText, level);
|
||||
if (!writerAvaliable && queue.Count >= 100) return; // 在 writer 就绪前,最多缓存 100 条日志
|
||||
queue.Enqueue(formattedText);
|
||||
queuedEvent.Set();
|
||||
}
|
||||
|
||||
private readonly ConcurrentQueue<string> queue = new();
|
||||
private readonly AutoResetEvent queuedEvent = new(false);
|
||||
public string logFolder = Path.Combine(Paths.Base, "logs");
|
||||
public string fileNamePrefix = "Log";
|
||||
public string fileNameSuffix = ".txt";
|
||||
private StreamWriter? writer;
|
||||
private volatile bool writerAvaliable = false;
|
||||
|
||||
/// <summary>
|
||||
/// 将日志立即写入文件。
|
||||
/// 不会抛出异常。
|
||||
/// </summary>
|
||||
public void Flush() {
|
||||
try {
|
||||
if (writer is null || !writerAvaliable) return;
|
||||
lock (flushLock)
|
||||
while (queue.TryDequeue(out string line)) writer.WriteLine(line); // writer 指定了 AutoFlush
|
||||
} catch { }
|
||||
}
|
||||
private readonly object flushLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 初始化此 Logger。
|
||||
/// 会在新线程中,将之前的日志文件依次后移,最多保留 5 个文件。
|
||||
/// </summary>
|
||||
public FileLogger(string logFolder, string fileNamePrefix = "Log", string fileNameSuffix = ".txt") {
|
||||
var thread = new Thread(() => {
|
||||
// 轮转日志文件,将 Log1.txt 留空
|
||||
Logger.Info("日志初始化开始");
|
||||
try {
|
||||
for (int i = 4; i >= 1; i--) {
|
||||
string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}");
|
||||
string olderFile = Path.Combine(logFolder, $"{fileNamePrefix}{i}{fileNameSuffix}");
|
||||
if (!FileUtils.Exists(olderFile)) continue;
|
||||
FileUtils.Copy(olderFile, newerFile);
|
||||
FileUtils.Delete(olderFile);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
Logger.Warning(ex, "可能同时开启了多个程序,这或许会导致未知问题", LogBehaviors.Toast);
|
||||
} catch (Exception ex) {
|
||||
Logger.Warning(ex, "整理日志文件失败");
|
||||
public override void Init() {
|
||||
// 轮转日志文件,将 Log1.txt 留空
|
||||
Logger.Info("开始轮转日志文件");
|
||||
try {
|
||||
for (int i = 4; i >= 1; i--) {
|
||||
string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}");
|
||||
string olderFile = Path.Combine(logFolder, $"{fileNamePrefix}{i}{fileNameSuffix}");
|
||||
if (!FileUtils.Exists(olderFile)) continue;
|
||||
FileUtils.Copy(olderFile, newerFile);
|
||||
FileUtils.Delete(olderFile);
|
||||
}
|
||||
// 写入新日志文件
|
||||
try {
|
||||
writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
|
||||
writerAvaliable = true;
|
||||
Logger.Info("日志初始化成功");
|
||||
while (true) {
|
||||
queuedEvent.WaitOne();
|
||||
Flush();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Logger.Warning(ex, "写入日志文件失败", LogBehaviors.Toast);
|
||||
writerAvaliable = false;
|
||||
}
|
||||
}) { Name = nameof(FileLogger), Priority = ThreadPriority.Lowest, IsBackground = true };
|
||||
thread.Start();
|
||||
} catch (IOException ex) {
|
||||
Logger.Warn(ex, "可能同时开启了多个程序,这或许会导致未知问题", LogBehavior.Toast);
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, "整理日志文件失败");
|
||||
}
|
||||
// 新建 writer
|
||||
string logFilePath = PathUtils.ForApi(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}"));
|
||||
DirectoryUtils.Create(logFolder);
|
||||
writer = new StreamWriter(logFilePath, append: true) { AutoFlush = true };
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Output(LogEntry entry) {
|
||||
base.Output(entry);
|
||||
writer?.WriteLine(entry.message); // writer 指定了 AutoFlush
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
available = false;
|
||||
if (writer is not null) ((IDisposable) writer).Dispose();
|
||||
queuedEvent.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,12 +15,12 @@ public static class MsDelta {
|
||||
public static void Create(string oldFilePath, string newFilePath, string deltaFilePath) {
|
||||
if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
|
||||
if (!FileUtils.Exists(newFilePath)) throw new FileNotFoundException($"新文件不存在:{newFilePath}", newFilePath);
|
||||
DirectoryUtils.Create(deltaFilePath, isFilePath: true);
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(deltaFilePath));
|
||||
Logger.Info($"正在生成补丁:{oldFilePath} → {newFilePath},补丁文件将输出到:{deltaFilePath}");
|
||||
// fileTypeSet:https://learn.microsoft.com/en-us/previous-versions/bb417345(v=msdn.10)?redirectedfrom=MSDN#file-type-sets (15L: DELTA_FILE_TYPE_SET_EXECUTABLES)
|
||||
// 131072L: IgnoreFileSizeLimit, 32u: Crc32
|
||||
if (!CreateDelta(15L, 131072L, 0L,
|
||||
PathUtils.WithLongPath(oldFilePath), PathUtils.WithLongPath(newFilePath), null, null, new DeltaInput(), IntPtr.Zero, 32u, PathUtils.WithLongPath(deltaFilePath)))
|
||||
PathUtils.ForApi(oldFilePath), PathUtils.ForApi(newFilePath), null, null, new DeltaInput(), IntPtr.Zero, 32u, PathUtils.ForApi(deltaFilePath)))
|
||||
throw new Win32Exception();
|
||||
}
|
||||
|
||||
@@ -32,14 +32,14 @@ public static class MsDelta {
|
||||
public static void Apply(string oldFilePath, string deltaFilePath, string newFilePath) {
|
||||
if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
|
||||
if (!FileUtils.Exists(deltaFilePath)) throw new FileNotFoundException($"补丁文件不存在:{deltaFilePath}", deltaFilePath);
|
||||
DirectoryUtils.Create(newFilePath, isFilePath: true);
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(newFilePath));
|
||||
Logger.Info($"正在应用补丁:原始文件 {oldFilePath} + 补丁文件 {deltaFilePath} → 输出至 {newFilePath}");
|
||||
// 1L: AllowLegacy
|
||||
if (!ApplyDelta(1L, PathUtils.WithLongPath(oldFilePath), PathUtils.WithLongPath(deltaFilePath), PathUtils.WithLongPath(newFilePath)))
|
||||
if (!ApplyDelta(1L, PathUtils.ForApi(oldFilePath), PathUtils.ForApi(deltaFilePath), PathUtils.ForApi(newFilePath)))
|
||||
throw new Win32Exception();
|
||||
}
|
||||
|
||||
|
||||
// API
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DeltaInput {
|
||||
public IntPtr Start;
|
||||
|
||||
+85
-68
@@ -1,64 +1,14 @@
|
||||
namespace MeloongCore;
|
||||
public readonly struct OneOf<T0, T1> {
|
||||
private readonly int _index;
|
||||
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!), _ => f1(_value1!)
|
||||
};
|
||||
/// <summary>
|
||||
/// 对不同类型执行不同的操作。
|
||||
/// </summary>
|
||||
public void Switch(Action<T0> f0, Action<T1> f1) {
|
||||
if (_index == 0) f0(_value0!);
|
||||
else if (_index == 1) f1(_value1!);
|
||||
}
|
||||
/// <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,则抛出 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;
|
||||
private readonly T0? _value0;
|
||||
namespace MeloongCore;
|
||||
public readonly struct OneOf<T1, T2> {
|
||||
private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
|
||||
private readonly T1? _value1;
|
||||
private readonly T2? _value2;
|
||||
public static implicit operator OneOf<T0, T1, T2>(T0 value) => new(0, value, default, default);
|
||||
public static implicit operator OneOf<T0, T1, T2>(T1 value) => new(1, default, value, default);
|
||||
public static implicit operator OneOf<T0, T1, T2>(T2 value) => new(2, default, default, value);
|
||||
public static implicit operator T0(OneOf<T0, T1, T2> value) => value.As<T0>();
|
||||
public static implicit operator T1(OneOf<T0, T1, T2> value) => value.As<T1>();
|
||||
public static implicit operator T2(OneOf<T0, T1, T2> value) => value.As<T2>();
|
||||
private OneOf(int index, T0? value0, T1? value1, T2? value2) {
|
||||
public static implicit operator OneOf<T1, T2>(T1 value) => new(1, value, default);
|
||||
public static implicit operator OneOf<T1, T2>(T2 value) => new(2, default, value);
|
||||
public static implicit operator T1(OneOf<T1, T2> value) => value.As<T1>();
|
||||
public static implicit operator T2(OneOf<T1, T2> value) => value.As<T2>();
|
||||
private OneOf(int index, T1? value1, T2? value2) {
|
||||
_index = index;
|
||||
_value0 = value0;
|
||||
_value1 = value1;
|
||||
_value2 = value2;
|
||||
}
|
||||
@@ -66,34 +16,101 @@ public readonly struct OneOf<T0, T1, T2> {
|
||||
/// <summary>
|
||||
/// 对不同类型执行不同的操作,并返回同一个值。
|
||||
/// </summary>
|
||||
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch {
|
||||
0 => f0(_value0!), 1 => f1(_value1!), _ => f2(_value2!)
|
||||
public TResult Switch<TResult>(Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch {
|
||||
1 => f1(_value1!),
|
||||
2 => f2(_value2!),
|
||||
_ => throw new InvalidOperationException()
|
||||
};
|
||||
/// <summary>
|
||||
/// 对不同类型执行不同的操作。
|
||||
/// </summary>
|
||||
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2) {
|
||||
if (_index == 0) f0(_value0!);
|
||||
else if (_index == 1) f1(_value1!);
|
||||
public void Switch(Action<T1> f1, Action<T2> f2) {
|
||||
if (_index == 1) f1(_value1!);
|
||||
else if (_index == 2) f2(_value2!);
|
||||
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,
|
||||
2 when typeof(T) == typeof(T2) => true,
|
||||
_ => false
|
||||
};
|
||||
public bool IsT1() => _index == 1;
|
||||
public bool IsT2() => _index == 2;
|
||||
/// <summary>
|
||||
/// 假定当前的类型为 T,并返回该值。
|
||||
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。
|
||||
/// 若当前值的类型不为 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!,
|
||||
2 when typeof(T) == typeof(T2) => (T) (object) _value2!,
|
||||
1 when typeof(T) == typeof(T1) => (T)(object)_value1!,
|
||||
2 when typeof(T) == typeof(T2) => (T)(object)_value2!,
|
||||
_ => 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() };
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsFinished => GetRaw().actual + GetRaw().skiped > 0.9999999;
|
||||
|
||||
private (double actual, double skiped) observedProgress = (0, 0);
|
||||
private double incrementProgress = 0;
|
||||
/// <summary>
|
||||
/// 获取一个在多次观测之间必定单调递增的进度值,范围为 [0, 1]。
|
||||
/// </summary>
|
||||
public double GetIncreasing() {
|
||||
lock (this) {
|
||||
(double actual, double skiped) current = GetRaw();
|
||||
if (current == observedProgress) return incrementProgress; // 未改变
|
||||
if (IsFinished) { // 已完成
|
||||
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.GetIncreasing();
|
||||
// TODO: 添加平缓过渡
|
||||
updateAction(progress);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 : 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),
|
||||
_ => 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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 { }
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace MeloongCore;
|
||||
public static class Main {
|
||||
|
||||
public static string AppName = "Meloong";
|
||||
public static void Init(string appName) {
|
||||
AppName = appName;
|
||||
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,20 +15,27 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="PolySharp" Version="1.15.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="ThrottleDebounce" Version="2.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="ThrottleDebounce" />
|
||||
<Using Include="System.Diagnostics.CodeAnalysis" />
|
||||
<Using Include="System.Collections" />
|
||||
<Using Include="System.Collections.Generic" />
|
||||
<Using Include="System.Collections.Concurrent" />
|
||||
<Using Include="System.Text" />
|
||||
<Using Include="System.Net" />
|
||||
<Using Include="System.Runtime.CompilerServices" />
|
||||
<Using Include="System.Runtime.InteropServices" />
|
||||
<Using Include="Newtonsoft.Json" />
|
||||
<Using Include="Newtonsoft.Json.Linq" />
|
||||
<Using Include="MeloongCore.Extensions" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
}
|
||||
+142
-39
@@ -1,81 +1,184 @@
|
||||
namespace MeloongCore;
|
||||
namespace MeloongCore;
|
||||
public static class DirectoryUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件夹,或文件所在的文件夹。
|
||||
/// 文件夹已存在时不会抛出异常。
|
||||
/// </summary>
|
||||
public static void Create(string path, bool isFilePath = false) {
|
||||
if (isFilePath) path = Path.GetDirectoryName(path);
|
||||
if (Exists(path)) return;
|
||||
Logger.Trace($"新建文件夹:{path}");
|
||||
path = PathUtils.WithLongPath(path);
|
||||
Directory.CreateDirectory(path);
|
||||
public static void Create(string folder) {
|
||||
if (DirectoryUtils.Exists(folder)) return;
|
||||
Logger.Trace($"新建文件夹:{folder}");
|
||||
Directory.CreateDirectory(PathUtils.ForApi(folder));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在临时文件夹下创建一个随机名称的文件夹,并返回其路径。
|
||||
/// </summary>
|
||||
public static string CreateRandom() {
|
||||
var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
|
||||
DirectoryUtils.Create(tempDir);
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断文件夹是否存在。
|
||||
/// </summary>
|
||||
public static bool Exists(string path) {
|
||||
return Directory.Exists(PathUtils.WithLongPath(path));
|
||||
}
|
||||
public static bool Exists(string folder)
|
||||
=> Directory.Exists(PathUtils.ForApi(folder));
|
||||
|
||||
/// <summary>
|
||||
/// 创建 <see cref="DirectoryInfo"/> 对象。
|
||||
/// 获取 <see cref="DirectoryInfo"/> 对象。
|
||||
/// </summary>
|
||||
public static DirectoryInfo GetInfo(string path) {
|
||||
return new(PathUtils.WithLongPath(path));
|
||||
}
|
||||
public static DirectoryInfo GetInfo(string folder)
|
||||
=> new(PathUtils.ForApi(folder));
|
||||
|
||||
/// <summary>
|
||||
/// 返回指定路径下的所有文件,不以 \\?\ 开头。
|
||||
/// 如果文件夹不存在,返回空列表。
|
||||
/// </summary>
|
||||
public static IEnumerable<string> GetFiles(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
|
||||
if (!Exists(path)) return [];
|
||||
Logger.Trace($"枚举文件({searchPattern},递归:{!topDirectoryOnly}):{path}");
|
||||
return Directory.EnumerateFiles(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
|
||||
Select(PathUtils.WithoutLongPath);
|
||||
public static IEnumerable<string> EnumerateFiles(string folder, bool includeSubDirectories = false, string searchPattern = "*") {
|
||||
if (!DirectoryUtils.Exists(folder)) return [];
|
||||
return Directory.EnumerateFiles(PathUtils.ForApi(folder), searchPattern, includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).
|
||||
Select(PathUtils.RemoveExtendedPrefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。
|
||||
/// 如果文件夹不存在,返回空列表。
|
||||
/// </summary>
|
||||
public static IEnumerable<string> GetDirectories(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
|
||||
if (!Exists(path)) return [];
|
||||
Logger.Trace($"枚举文件夹({searchPattern},递归:{!topDirectoryOnly}):{path}");
|
||||
return Directory.EnumerateDirectories(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
|
||||
Select(PathUtils.WithoutLongPath);
|
||||
public static IEnumerable<string> EnumerateDirectories(string folder, bool includeSubDirectories = false, string searchPattern = "*") {
|
||||
if (!DirectoryUtils.Exists(folder)) return [];
|
||||
return Directory.EnumerateDirectories(PathUtils.ForApi(folder), searchPattern, includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).
|
||||
Select(PathUtils.RemoveExtendedPrefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 该文件夹是否为空。
|
||||
/// 如果文件夹不存在,也返回 true。
|
||||
/// 如果文件夹不存在,返回 true。
|
||||
/// </summary>
|
||||
public static bool IsEmpty(string path) {
|
||||
if (!Exists(path)) return true;
|
||||
return !Directory.EnumerateFileSystemEntries(PathUtils.WithLongPath(path)).Any();
|
||||
public static bool IsEmpty(string folder) {
|
||||
if (!DirectoryUtils.Exists(folder)) return true;
|
||||
return !Directory.EnumerateFileSystemEntries(PathUtils.ForApi(folder)).Any();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 复制文件夹。
|
||||
/// 若复制自身到自身,则不执行操作;若仅大小写不同,则重命名此文件夹。
|
||||
/// </summary>
|
||||
public static void Copy(string sourceFolder, string destFolder) {
|
||||
sourceFolder = PathUtils.ForCompare(sourceFolder);
|
||||
destFolder = PathUtils.ForCompare(destFolder);
|
||||
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
|
||||
// 复制自身到自身,则不执行操作
|
||||
Logger.Trace($"复制文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
||||
} else if (PathUtils.IsSame(sourceFolder, destFolder)) {
|
||||
// 路径仅大小写不同,等效于重命名
|
||||
Logger.Trace($"复制文件夹到自身,但大小写不同,等效于重命名文件夹:{sourceFolder} → {destFolder}");
|
||||
DirectoryUtils.Move(sourceFolder, destFolder);
|
||||
} else {
|
||||
// 实际的复制
|
||||
Logger.Trace($"复制文件夹:{sourceFolder} → {destFolder}");
|
||||
foreach (var file in DirectoryUtils.EnumerateFiles(sourceFolder, includeSubDirectories: true).ToList()) FileUtils.Copy(file, file.Replace(sourceFolder, destFolder));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 剪切文件夹。
|
||||
/// 会创建对应文件夹、覆盖已有的文件夹。
|
||||
/// </summary>
|
||||
public static void Move(string sourceDirName, string destDirName) {
|
||||
if (!Exists(sourceDirName)) return;
|
||||
Create(destDirName);
|
||||
Logger.Trace($"剪切文件夹:{sourceDirName} → {destDirName}");
|
||||
Directory.Move(PathUtils.WithLongPath(sourceDirName), PathUtils.WithLongPath(destDirName));
|
||||
public static void Move(string sourceFolder, string destFolder) {
|
||||
SafetyCheck(sourceFolder);
|
||||
sourceFolder = PathUtils.ForCompare(sourceFolder);
|
||||
destFolder = PathUtils.ForCompare(destFolder);
|
||||
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
|
||||
// 剪切自身到自身,则不执行操作
|
||||
Logger.Trace($"剪切文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
||||
} else if (PathUtils.IsSame(sourceFolder, destFolder)) {
|
||||
// 路径仅大小写不同
|
||||
Logger.Trace($"剪切文件夹到自身,但大小写不同:{sourceFolder} → {destFolder}");
|
||||
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFolder), Path.GetRandomFileName());
|
||||
DirectoryUtils.Move(sourceFolder, temp);
|
||||
DirectoryUtils.Move(temp, destFolder);
|
||||
} else if (PathUtils.GetDiskName(sourceFolder) == PathUtils.GetDiskName(destFolder)) {
|
||||
// 同一磁盘剪切,直接调用 Move(这只修改文件夹名,效率更高)
|
||||
Logger.Trace($"剪切文件夹到同一磁盘:{sourceFolder} → {destFolder}");
|
||||
DirectoryUtils.Delete(destFolder); // Move 要求此前不存在对应文件夹
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
FileUtils.SetReadOnly(sourceFolder, false);
|
||||
Directory.Move(PathUtils.ForApi(sourceFolder), PathUtils.ForApi(destFolder));
|
||||
});
|
||||
} else {
|
||||
// 不同磁盘,必须先复制再删除,这就是我们傻逼微软
|
||||
Logger.Trace($"剪切文件夹到不同磁盘:{sourceFolder} → {destFolder}");
|
||||
DirectoryUtils.Copy(sourceFolder, destFolder);
|
||||
DirectoryUtils.Delete(sourceFolder);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除文件夹。
|
||||
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
|
||||
/// </summary>
|
||||
public static void Delete(string dirPath, bool toRecycleBin = false) {
|
||||
if (!Exists(dirPath)) return;
|
||||
Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{dirPath}");
|
||||
/// <returns>
|
||||
/// 如果文件夹不存在,返回 <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}");
|
||||
SafetyCheck(folder);
|
||||
// 删除到回收站
|
||||
if (toRecycleBin) {
|
||||
FileUtils.DeleteToRecycleBin(dirPath);
|
||||
} else {
|
||||
Directory.Delete(PathUtils.WithLongPath(dirPath));
|
||||
try {
|
||||
FileUtils.DeleteToRecycleBin(folder);
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"无法将文件夹删除到回收站,回退到永久删除:{folder}");
|
||||
}
|
||||
}
|
||||
// 永久删除
|
||||
DeleteInternal(folder);
|
||||
static void DeleteInternal(string folder) {
|
||||
try {
|
||||
folder = PathUtils.ForApi(folder);
|
||||
foreach (string filePath in DirectoryUtils.EnumerateFiles(folder)) FileUtils.Delete(filePath); // 删除文件
|
||||
foreach (string str in DirectoryUtils.EnumerateDirectories(folder)) DeleteInternal(str); // 递归删除子文件夹
|
||||
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>
|
||||
/// 进行安全检查:若尝试操作桌面、文档、下载、Windows、当前程序所在文件夹,则抛出异常。
|
||||
/// </summary>
|
||||
/// <exception cref="UnauthorizedAccessException" />
|
||||
private static void SafetyCheck(string folder) {
|
||||
folder = PathUtils.ForCompare(folder);
|
||||
if (PathUtils.IsSame(folder, Path.GetPathRoot(folder)))
|
||||
throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}");
|
||||
if (criticalFolders.Value.Any(f => PathUtils.IsParentOf(folder, f)))
|
||||
throw new UnauthorizedAccessException($"不应操作文件夹:{folder}");
|
||||
}
|
||||
private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] {
|
||||
Paths.Base,
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Windows),
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads") // 下载文件夹没有 SpecialFolder 枚举
|
||||
}.Where(f => f.Contains(Path.VolumeSeparatorChar)))); // 当缺少某个文件夹时,GetFolderPath 会返回空字符串(#8636)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace MeloongCore;
|
||||
public static class EnumUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 获取枚举的所有值。
|
||||
/// </summary>
|
||||
private static IEnumerable<T> GetAllValues<T>() where T : struct, Enum
|
||||
=> 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);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool HasFlagF<T>(this T value, T flag) where T : struct, Enum
|
||||
=> value.HasFlag(flag) && !EqualityComparer<T>.Default.Equals(flag, default);
|
||||
|
||||
/// <summary>
|
||||
/// 对于具有 <see cref="FlagsAttribute"/> 的枚举,返回其所有 Flag 值。
|
||||
/// 建议仅对没有极端值的正数枚举使用。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
|
||||
/// </remarks>
|
||||
public static List<T> GetAllFlags<T>() where T : struct, Enum {
|
||||
if (allFlagsCache.TryGetValue(typeof(T), out var cached)) return cached.Cast<T>().ToList();
|
||||
if (!typeof(T).IsDefined(typeof(FlagsAttribute), inherit: false)) throw new ArgumentException($"枚举 {typeof(T).FullName} 没有定义 FlagsAttribute。");
|
||||
var flags = new List<T>();
|
||||
foreach (var element in EnumUtils.GetAllValues<T>().Distinct()) {
|
||||
var number = Convert.ToInt64(element, CultureInfo.InvariantCulture);
|
||||
if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值
|
||||
flags.Add(element);
|
||||
}
|
||||
allFlagsCache[typeof(T)] = flags.Cast<Enum>().ToList();
|
||||
return flags;
|
||||
}
|
||||
private static readonly ConcurrentDictionary<Type, List<Enum>> allFlagsCache = new();
|
||||
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MeloongCore;
|
||||
public static class EscapeUtils {
|
||||
|
||||
/// <summary>
|
||||
/// XML 转义。
|
||||
/// </summary>
|
||||
public static string? XmlEscape(string? str) {
|
||||
if (str is null) return null;
|
||||
if (str.StartsWithF("{")) str = "{}" + str; // #4187
|
||||
return str
|
||||
.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("'", "'")
|
||||
.Replace("\"", """).ReplaceLineEndings("
");
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 正则表达式转义。等同于 Regex.Escape。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? RegexEscape(string? value) => Regex.Escape(value);
|
||||
|
||||
/// <summary>
|
||||
/// 正则表达式去转义。等同于 Regex.Unescape。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? RegexUnescape(string? value) => Regex.Unescape(value);
|
||||
|
||||
/// <summary>
|
||||
/// URL 转义。等同于 Uri.EscapeDataString。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? UrlEscape(string? value) => Uri.EscapeDataString(value);
|
||||
|
||||
/// <summary>
|
||||
/// URL 去转义。等同于 Uri.UnescapeDataString。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? UrlUnescape(string? value) => Uri.UnescapeDataString(value);
|
||||
|
||||
/// <summary>
|
||||
/// 表单转义。等同于 WebUtility.UrlEncode。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? FormUrlEscape(string? value) => WebUtility.UrlEncode(value);
|
||||
|
||||
/// <summary>
|
||||
/// 表单去转义。等同于 WebUtility.UrlDecode。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? FormUrlUnescape(string? value) => WebUtility.UrlDecode(value);
|
||||
|
||||
/// <summary>
|
||||
/// HTML 转义。等同于 WebUtility.HtmlEncode。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? HtmlEscape(string? value) => WebUtility.HtmlEncode(value);
|
||||
|
||||
/// <summary>
|
||||
/// HTML 去转义。等同于 WebUtility.HtmlDecode。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string? HtmlUnescape(string? value) => WebUtility.HtmlDecode(value);
|
||||
|
||||
}
|
||||
+403
-113
@@ -1,46 +1,237 @@
|
||||
using System.IO.Compression;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace MeloongCore;
|
||||
public static class FileUtils {
|
||||
|
||||
#region 写入
|
||||
#region 读取
|
||||
|
||||
/// <summary>
|
||||
/// 写入文件。
|
||||
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
|
||||
/// 打开指定文件的只读 <see cref="Stream"/>。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static void Write(string filePath, string text, Encoding? encoding = null) {
|
||||
Write(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
|
||||
public static Stream ReadAsStream(string filePath, Type? type = null) {
|
||||
if (type is null) {
|
||||
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>
|
||||
/// 写入文件。
|
||||
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
|
||||
/// 读取文件中的所有内容。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static void Write(string filePath, IEnumerable<byte> content) {
|
||||
Write(filePath, [..content]);
|
||||
public static byte[] ReadAsBytes(string filePath, Type? type = null) {
|
||||
using Stream fs = FileUtils.ReadAsStream(filePath, type); // 不能使用 File.ReadAllBytes,它不指定 FileShare.ReadWrite,会在文件被占用时抛出异常
|
||||
using MemoryStream ms = new();
|
||||
fs.CopyTo(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写入文件。
|
||||
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
|
||||
/// 读取文件中的所有内容。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static string ReadAsString(string filePath, Encoding? encoding = null, Type? type = null)
|
||||
=> FileUtils.ReadAsBytes(filePath, type).GetString(encoding);
|
||||
/// <summary>
|
||||
/// 读取文件中的所有内容。
|
||||
/// <para/>若文件不存在或读取失败,返回 <see langword="null"/>,而不是抛出异常。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static string? TryReadAsString(string filePath, Encoding? encoding = null, Type? type = null) {
|
||||
try {
|
||||
if (type == null && !FileUtils.Exists(filePath)) return null;
|
||||
return FileUtils.ReadAsBytes(filePath, type).GetString(encoding);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取文件中的所有内容,并按行分割。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static string[] ReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null, Type? type = null)
|
||||
=> FileUtils.ReadAsString(filePath, encoding, type).SplitLines(skipEmptyLines);
|
||||
/// <summary>
|
||||
/// 读取文件中的所有内容,并按行分割。
|
||||
/// <para/>若文件不存在或读取失败,返回空数组,而不是抛出异常。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static string[] TryReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null, Type? type = null)
|
||||
=> 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();
|
||||
/// <summary>
|
||||
/// 读取 JSON 文件中的所有内容。
|
||||
/// <para/>若指定了 <paramref name="type"/>,则会改为从该类型的程序集中读取嵌入的资源。
|
||||
/// </summary>
|
||||
public static T? ReadAsJson<T>(string filePath, Encoding? encoding = null, Type? type = null) where T : JToken
|
||||
=> FileUtils.ReadAsString(filePath, encoding, type).DeserializeJson<T>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region 创建 / 写入
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件,并将 <paramref name="text" /> 写入文件。
|
||||
/// 若文件已存在,则会覆盖原文件。
|
||||
/// </summary>
|
||||
public static void Write(string filePath, string text, Encoding? encoding = null)
|
||||
=> FileUtils.Write(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
|
||||
/// <summary>
|
||||
/// 创建文件,并将 <paramref name="content" /> 写入文件。
|
||||
/// 若文件已存在,则会覆盖原文件。
|
||||
/// </summary>
|
||||
public static void Write(string filePath, IEnumerable<byte> content)
|
||||
=> FileUtils.Write(filePath, [.. content]);
|
||||
/// <summary>
|
||||
/// 创建文件,并将 <paramref name="content" /> 写入文件。
|
||||
/// 若文件已存在,则会覆盖原文件。
|
||||
/// </summary>
|
||||
public static void Write(string filePath, byte[] content) {
|
||||
DirectoryUtils.Create(filePath, isFilePath: true);
|
||||
Logger.Trace(() => $"写入文件:{filePath}({content.Length} 字节)");
|
||||
File.WriteAllBytes(PathUtils.WithLongPath(filePath), content);
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
|
||||
Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
File.WriteAllBytes(PathUtils.ForApi(filePath), content);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 <paramref name="stream" /> 写入文件。
|
||||
/// 原子写入文件。写入失败时目标文件保持不变。
|
||||
/// </summary>
|
||||
public static void WriteAtomic(string filePath, string text, Encoding? encoding = null) =>
|
||||
FileUtils.WriteAtomic(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
|
||||
/// <summary>
|
||||
/// 原子写入文件。写入失败时目标文件保持不变。
|
||||
/// </summary>
|
||||
public static void WriteAtomic(string filePath, byte[] content) {
|
||||
string tempPath = $"{filePath}.{Guid.NewGuid():N}.tmp";
|
||||
try {
|
||||
FileUtils.Write(tempPath, content);
|
||||
if (FileUtils.Exists(filePath)) {
|
||||
File.Replace(PathUtils.ForApi(tempPath), PathUtils.ForApi(filePath), null, true);
|
||||
} else {
|
||||
File.Move(PathUtils.ForApi(tempPath), PathUtils.ForApi(filePath));
|
||||
}
|
||||
} finally {
|
||||
FileUtils.Delete(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件,并将 <paramref name="stream" /> 写入文件。
|
||||
/// 会将流的位置主动重置到开头。
|
||||
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
|
||||
/// 若文件已存在,则会覆盖原文件。
|
||||
/// </summary>
|
||||
public static void Write(string filePath, Stream stream) {
|
||||
using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath));
|
||||
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
|
||||
Logger.Trace(() => $"写入文件:{filePath}({stream.GetType().Name} {stream.Length} 字节)");
|
||||
stream.CopyTo(fileStream);
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
FileUtils.Delete(filePath);
|
||||
using FileStream fileStream = FileUtils.CreateAsStream(filePath);
|
||||
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
|
||||
Logger.Trace($"写入文件:{filePath}({stream.GetType().Name}{(stream.CanSeek ? $" {stream.Length} 字节" : "")})");
|
||||
stream.CopyTo(fileStream);
|
||||
});
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建文件,并打开 <see cref="FileMode.Create"/> 模式的 <see cref="FileStream"/>。
|
||||
/// 若文件已存在,则会覆盖原文件。
|
||||
/// </summary>
|
||||
public static FileStream CreateAsStream(string filePath) {
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
|
||||
Logger.Trace($"创建文件流:{filePath}");
|
||||
return Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _ => {
|
||||
FileUtils.Delete(filePath);
|
||||
return new FileStream(PathUtils.ForApi(filePath), FileMode.Create);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在临时文件夹下创建一个随机名称的文件,并返回其路径。
|
||||
/// </summary>
|
||||
public static string CreateRandom()
|
||||
=> Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
|
||||
=> Path.GetTempFileName());
|
||||
|
||||
/// <summary>
|
||||
/// 从 <paramref name="type"/> 的程序集中,读取指定 <paramref name="logicalName"/> 的嵌入的资源,写入到 <paramref name="localFilePath"/> 中。
|
||||
/// <para/> 如果文件已存在且内容相同,则不会写入。
|
||||
/// </summary>
|
||||
public static void ExtractResources(string logicalName, string localFilePath, Type type) {
|
||||
var content = ReadAsBytes(logicalName, type);
|
||||
if (Exists(localFilePath) && CryptographyUtils.ComputeFileHash(localFilePath) == CryptographyUtils.ComputeHash(content)) return;
|
||||
Logger.Info($"将资源写入到文件:{logicalName} → {localFilePath}");
|
||||
Write(localFilePath, content);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 复制 / 剪切
|
||||
|
||||
/// <summary>
|
||||
/// 复制文件。
|
||||
/// 会创建对应文件夹、覆盖已有的文件。
|
||||
/// 若复制自身到自身,则不执行操作;若仅大小写不同,则重命名此文件。
|
||||
/// </summary>
|
||||
public static void Copy(string sourceFilePath, string destFilePath) {
|
||||
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
||||
destFilePath = PathUtils.ForCompare(destFilePath);
|
||||
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
|
||||
// 复制自身到自身,则不执行操作
|
||||
Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
||||
} else if (PathUtils.IsSame(sourceFilePath, destFilePath)) {
|
||||
// 路径仅大小写不同,等效于重命名
|
||||
Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
|
||||
FileUtils.Move(sourceFilePath, destFilePath);
|
||||
} else {
|
||||
// 实际的复制
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
|
||||
Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 剪切文件。
|
||||
/// 会创建对应文件夹、覆盖已有的文件。
|
||||
/// 若指定了 <paramref name="toRecycleBin"/>,则在覆盖前将老文件删除到回收站。
|
||||
/// </summary>
|
||||
public static void Move(string sourceFilePath, string destFilePath, bool toRecycleBin = false) {
|
||||
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
||||
destFilePath = PathUtils.ForCompare(destFilePath);
|
||||
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
|
||||
// 剪切自身到自身,则不执行操作
|
||||
Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
||||
} else if (PathUtils.IsSame(sourceFilePath, destFilePath)) {
|
||||
// 路径仅大小写不同
|
||||
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
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(temp), PathUtils.ForApi(destFilePath));
|
||||
});
|
||||
} else {
|
||||
// 实际的剪切
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
|
||||
FileUtils.Delete(destFilePath, toRecycleBin);
|
||||
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
FileUtils.SetReadOnly(sourceFilePath, false);
|
||||
if (FileUtils.Exists(destFilePath)) FileUtils.SetReadOnly(destFilePath, false);
|
||||
File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -49,15 +240,31 @@ public static class FileUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 删除文件。
|
||||
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
|
||||
/// </summary>
|
||||
public static void Delete(string filePath, bool toRecycleBin = false) {
|
||||
if (!Exists(filePath)) return;
|
||||
/// <returns>
|
||||
/// 如果文件不存在,返回 <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}");
|
||||
// 删除到回收站
|
||||
if (toRecycleBin) {
|
||||
DeleteToRecycleBin(filePath);
|
||||
} else {
|
||||
File.Delete(PathUtils.WithLongPath(filePath));
|
||||
try {
|
||||
DeleteToRecycleBin(filePath);
|
||||
return true;
|
||||
} 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>
|
||||
@@ -65,12 +272,13 @@ public static class FileUtils {
|
||||
/// </summary>
|
||||
internal static void DeleteToRecycleBin(string target) {
|
||||
// 实际的删除方法
|
||||
static void Run(string filePath) {
|
||||
void Run() {
|
||||
IShellItem? item = null;
|
||||
IFileOperation? op = null;
|
||||
try {
|
||||
var iid = typeof(IShellItem).GUID;
|
||||
Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.WithoutLongPath(filePath), IntPtr.Zero, ref iid, out item));
|
||||
Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.RemoveExtendedPrefix(target), IntPtr.Zero, ref iid, out item));
|
||||
// ReSharper disable once SuspiciousTypeConversion.Global
|
||||
op = (IFileOperation) new FileOperation();
|
||||
op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
|
||||
op.DeleteItem(item, IntPtr.Zero);
|
||||
@@ -84,17 +292,23 @@ public static class FileUtils {
|
||||
}
|
||||
// 在 STA 线程中执行删除方法
|
||||
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
|
||||
Run(target);
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => Run());
|
||||
} else {
|
||||
System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
|
||||
var thread = new Thread(() => { try { Run(target); } catch (Exception ex) { internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); } });
|
||||
var thread = new Thread(() => {
|
||||
try {
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException or COMException, action: _ => Run());
|
||||
} catch (Exception ex) {
|
||||
internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex);
|
||||
}
|
||||
}) { IsBackground = true, Name = nameof(DeleteToRecycleBin) };
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
internalEx?.Throw();
|
||||
}
|
||||
}
|
||||
// 用于删除到回收站的接口
|
||||
// API
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
|
||||
static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
|
||||
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
@@ -127,36 +341,16 @@ public static class FileUtils {
|
||||
|
||||
#endregion
|
||||
|
||||
#region FileStream
|
||||
|
||||
/// <summary>
|
||||
/// 打开该文件的只读 <see cref="FileStream"/>。
|
||||
/// </summary>
|
||||
public static FileStream ReadAsStream(string filePath) {
|
||||
return new(PathUtils.WithLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在指定路径创建文件,并打开 <see cref="FileStream"/>。
|
||||
/// </summary>
|
||||
public static FileStream CreateAsStream(string filePath) {
|
||||
DirectoryUtils.Create(filePath, isFilePath: true);
|
||||
Logger.Trace($"创建文件流:{filePath}");
|
||||
return new(PathUtils.WithLongPath(filePath), FileMode.Create);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 压缩包
|
||||
#region 压缩 / 解压
|
||||
|
||||
/// <summary>
|
||||
/// 以只读模式打开压缩文件。
|
||||
/// 会先尝试 UTF8 编码,失败后换用 GB18030 编码。
|
||||
/// </summary>
|
||||
public static ZipArchive OpenZip(string zipFilePath) {
|
||||
public static ZipArchive OpenZip(string zipFilePath, CancellationToken c = default) {
|
||||
ZipArchive TryOpen(Encoding encoding) {
|
||||
Logger.Trace(() => $"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
|
||||
var result = ZipFile.Open(PathUtils.WithLongPath(zipFilePath), ZipArchiveMode.Read, encoding);
|
||||
Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
|
||||
var result = ZipFile.Open(PathUtils.ForApi(zipFilePath), ZipArchiveMode.Read, encoding);
|
||||
try {
|
||||
_ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException
|
||||
return result;
|
||||
@@ -165,66 +359,68 @@ public static class FileUtils {
|
||||
throw;
|
||||
}
|
||||
}
|
||||
try {
|
||||
try { // 尝试两种编码
|
||||
return TryOpen(new UTF8Encoding(false, true));
|
||||
} catch (DecoderFallbackException) {
|
||||
return TryOpen(Encoding.GetEncoding("GB18030"));
|
||||
return Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), maxAttempts:10, isRetryAllowed: ex => ex is IOException, cancellationToken: c, func: _ => {
|
||||
try {
|
||||
try { // 尝试两种编码
|
||||
return TryOpen(new UTF8Encoding(false, true));
|
||||
} catch (DecoderFallbackException) {
|
||||
return TryOpen(Encoding.GetEncoding("GB18030"));
|
||||
}
|
||||
} catch (InvalidDataException ex) {
|
||||
throw new InvalidDataException($"文件不是压缩包,或者文件已损坏({zipFilePath})", ex);
|
||||
}
|
||||
} catch (InvalidDataException ex) {
|
||||
throw new InvalidDataException($"文件不是压缩包,或者文件已损坏({zipFilePath})", ex);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
|
||||
/// 会自动创建文件夹。会覆盖已有文件,但不会删除多余文件。
|
||||
/// </summary>
|
||||
/// <param name="progressHandler">参数为已完成的总比例(0~1)。</param>
|
||||
public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressHandler = null) {
|
||||
compressionFile = PathUtils.WithLongPath(compressionFile);
|
||||
/// <param name="p">参数为已完成的总比例(0~1)。</param>
|
||||
public static void ExtractToDirectory(string compressionFile, string outputDirectory, CancellationToken c = default, ProgressProvider? p = null) {
|
||||
compressionFile = PathUtils.ForApi(compressionFile);
|
||||
DirectoryUtils.Create(outputDirectory);
|
||||
// 解压 gz(gz 不需要考虑编码)
|
||||
if (compressionFile.EndsWithF(".gz", true)) {
|
||||
string outFilePath = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(compressionFile));
|
||||
if (PathUtils.GetExtension(compressionFile) == "gz") {
|
||||
string outFilePath = Path.Combine(outputDirectory, PathUtils.GetFileNameWithoutExtension(compressionFile));
|
||||
Logger.Trace($"解压 gz 文件:{compressionFile} → {outFilePath}");
|
||||
using var fileStream = FileUtils.ReadAsStream(compressionFile);
|
||||
using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
|
||||
FileUtils.Write(outFilePath, gzipStream);
|
||||
progressHandler?.Invoke(1);
|
||||
p?.Finish();
|
||||
return;
|
||||
}
|
||||
// 解压 zip
|
||||
using var archive = FileUtils.OpenZip(compressionFile);
|
||||
int totalCount = archive.Entries.Count;
|
||||
using var archive = FileUtils.OpenZip(compressionFile, c);
|
||||
var entries = archive.Entries.Where(e => !string.IsNullOrEmpty(e.Name)).ToList(); // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
|
||||
int totalCount = entries.Count;
|
||||
int doneCount = 0;
|
||||
Logger.Trace($"解压 zip 文件:{compressionFile} → {outputDirectory}(共 {totalCount} 项)");
|
||||
foreach (var entry in archive.Entries) {
|
||||
foreach (var entry in entries) {
|
||||
c.ThrowIfCancellationRequested();
|
||||
doneCount++;
|
||||
if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount);
|
||||
if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
|
||||
if (totalCount > 0) p?.Set((double) doneCount / totalCount);
|
||||
// ZipSlip 修复
|
||||
string outputFilePath = PathUtils.WithLongPath(Path.GetFullPath(Path.Combine(outputDirectory, entry.FullName)));
|
||||
if (!outputFilePath.StartsWithF(PathUtils.WithSeparator(PathUtils.WithLongPath(Path.GetFullPath(outputDirectory))), ignoreCase:true))
|
||||
throw new ZipSlipException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
|
||||
string outputFilePath = Path.Combine(outputDirectory, entry.FullName);
|
||||
if (!PathUtils.IsParentOf(outputDirectory, outputFilePath))
|
||||
throw new InvalidDataException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
|
||||
// 实际的解压
|
||||
using var entryStream = entry.Open();
|
||||
FileUtils.Write(outputFilePath, entryStream);
|
||||
}
|
||||
}
|
||||
public class ZipSlipException(string message) : Exception(message) {}
|
||||
|
||||
/// <summary>
|
||||
/// 将指定文件夹的内容打包为 zip 文件。
|
||||
/// 会自动创建文件夹。会覆盖已有文件。
|
||||
/// </summary>
|
||||
public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) {
|
||||
outputFullPath = PathUtils.WithLongPath(outputFullPath);
|
||||
sourceDirectory = PathUtils.WithLongPath(sourceDirectory);
|
||||
DirectoryUtils.Create(outputFullPath, isFilePath: true);
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
|
||||
FileUtils.Delete(outputFullPath);
|
||||
Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}");
|
||||
ZipFile.CreateFromDirectory(sourceDirectory, outputFullPath);
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _
|
||||
=> ZipFile.CreateFromDirectory(PathUtils.ForApi(sourceDirectory), PathUtils.ForApi(outputFullPath)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -234,11 +430,11 @@ public static class FileUtils {
|
||||
public static void CreateZipFromFiles(string outputFullPath, params string[] sourceFiles) {
|
||||
var sources = new Dictionary<string, string>();
|
||||
foreach (var source in sourceFiles) {
|
||||
string fileName = Path.GetFileName(source);
|
||||
string fileName = PathUtils.GetLastPart(source);
|
||||
if (sources.ContainsKey(fileName)) throw new ArgumentException($"尝试将多个同文件名的文件放进压缩包中({fileName})", nameof(sourceFiles));
|
||||
sources.Add(fileName, source);
|
||||
}
|
||||
CreateZipFromFiles(outputFullPath, sources);
|
||||
FileUtils.CreateZipFromFiles(outputFullPath, sources);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -247,12 +443,12 @@ public static class FileUtils {
|
||||
/// </summary>
|
||||
/// <param name="sources">键为 zip 文件下的路径,值为文件的本地路径。</param>
|
||||
public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) {
|
||||
outputFullPath = PathUtils.WithLongPath(outputFullPath);
|
||||
DirectoryUtils.Create(outputFullPath, isFilePath: true);
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
|
||||
FileUtils.Delete(outputFullPath);
|
||||
using var archive = ZipFile.Open(outputFullPath, ZipArchiveMode.Create);
|
||||
Logger.Trace(() => $"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}");
|
||||
foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.WithLongPath(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal);
|
||||
using var archive = Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
|
||||
=> ZipFile.Open(PathUtils.ForApi(outputFullPath), ZipArchiveMode.Create));
|
||||
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);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -260,37 +456,131 @@ public static class FileUtils {
|
||||
/// <summary>
|
||||
/// 确定指定的文件是否存在。
|
||||
/// </summary>
|
||||
public static bool Exists(string filePath) {
|
||||
return File.Exists(PathUtils.WithLongPath(filePath));
|
||||
public static bool Exists(string filePath)
|
||||
=> File.Exists(PathUtils.ForApi(filePath));
|
||||
|
||||
/// <summary>
|
||||
/// 检查文件是否存在,且当前程序有独占的读写权限,未被其他进程占用。
|
||||
/// </summary>
|
||||
public static bool IsAvailable(string filePath) {
|
||||
if (!Exists(filePath)) return false;
|
||||
try {
|
||||
Retrier.Attempt(maxAttempts: 3, delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
using var unused = new FileStream(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.ReadWrite, FileShare.None);
|
||||
});
|
||||
return true;
|
||||
} catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建 <see cref="FileInfo"/> 对象。
|
||||
/// 获取 <see cref="FileInfo"/> 对象。
|
||||
/// </summary>
|
||||
public static FileInfo GetInfo(string path) {
|
||||
return new(PathUtils.WithLongPath(path));
|
||||
}
|
||||
public static FileInfo GetInfo(string path)
|
||||
=> new(PathUtils.ForApi(path));
|
||||
|
||||
/// <summary>
|
||||
/// 复制文件。
|
||||
/// 会创建对应文件夹、覆盖已有的文件。
|
||||
/// 设置文件或文件夹的只读属性。
|
||||
/// 对文件夹使用时,只会设置文件夹本身的属性,不会递归设置其中的文件或子文件夹。
|
||||
/// </summary>
|
||||
public static void Copy(string sourceFilePath, string destFilePath) {
|
||||
if (sourceFilePath == destFilePath) return; // 如果复制同一个文件则跳过
|
||||
DirectoryUtils.Create(destFilePath, isFilePath: true);
|
||||
Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
|
||||
File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 剪切文件。
|
||||
/// 会创建对应文件夹、覆盖已有的文件。
|
||||
/// </summary>
|
||||
public static void Move(string sourceFilePath, string destFilePath) {
|
||||
if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
|
||||
DirectoryUtils.Create(destFilePath, isFilePath: true);
|
||||
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
|
||||
File.Move(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath));
|
||||
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;
|
||||
|
||||
// TODO: 重构此函数,使它变成 void,并抛出异常
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Numerics;
|
||||
using System.Numerics;
|
||||
|
||||
namespace MeloongCore;
|
||||
public static class MathUtils {
|
||||
@@ -24,24 +24,37 @@ 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}.");
|
||||
realNum = realNum * fromRadix + digit;
|
||||
}
|
||||
return ConvertRadix(realNum * (isNegative ? -1 : 1), toRadix);
|
||||
return (realNum * (isNegative ? -1 : 1)).ConvertRadix(toRadix);
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换为 2 到 86 进制的字符串。
|
||||
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
|
||||
/// </summary>
|
||||
public static string ConvertRadix(this long input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
|
||||
public static string ConvertRadix(this long input, int toRadix)
|
||||
=> ConvertRadix((BigInteger) input, toRadix);
|
||||
/// <summary>
|
||||
/// 转换为 2 到 86 进制的字符串。
|
||||
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
|
||||
/// </summary>
|
||||
public static string ConvertRadix(this int input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
|
||||
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 byte input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
|
||||
private static string ConvertRadix(this BigInteger input, int toRadix) {
|
||||
public static string ConvertRadix(this int input, int toRadix)
|
||||
=> ConvertRadix((BigInteger) input, toRadix);
|
||||
/// <summary>
|
||||
/// 转换为 2 到 86 进制的字符串。
|
||||
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
|
||||
/// </summary>
|
||||
public static string ConvertRadix(this byte input, int toRadix)
|
||||
=> ConvertRadix((BigInteger) input, toRadix);
|
||||
/// <summary>
|
||||
/// 转换为 2 到 86 进制的字符串。
|
||||
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
|
||||
/// </summary>
|
||||
public static string ConvertRadix(this BigInteger input, int toRadix) {
|
||||
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
|
||||
if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86.");
|
||||
// 零与负数的预处理
|
||||
@@ -76,8 +89,8 @@ public static class MathUtils {
|
||||
/// 在一个范围中进行线性插值。
|
||||
/// 返回值将被舍入到小数点后 7 位,以解决浮点数误差问题。
|
||||
/// </summary>
|
||||
public static double Lerp(double start, double end, double percentage) =>
|
||||
Math.Round(start + (end - start) * percentage, 7);
|
||||
public static double Lerp(double start, double end, double percentage)
|
||||
=> Math.Round(start + (end - start) * percentage, 7);
|
||||
|
||||
/// <summary>
|
||||
/// 计算二阶贝塞尔曲线。
|
||||
@@ -87,11 +100,61 @@ public static class MathUtils {
|
||||
if (t > 0.9999999) return 1;
|
||||
double a = t;
|
||||
double b;
|
||||
int maxIterations = 1000;
|
||||
do {
|
||||
b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1);
|
||||
a += (t - b) * 0.5;
|
||||
} while (!(Math.Abs(b - t) < accuracy)); // 精度
|
||||
maxIterations--;
|
||||
} while (!(Math.Abs(b - t) < accuracy) && maxIterations > 0);
|
||||
return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断其是否近似等于目标值。
|
||||
/// </summary>
|
||||
/// <param name="tolerance">允许的最大容差,默认为 1e-6。</param>
|
||||
public static bool IsNear(this double value, double target, double tolerance = 1e-6)
|
||||
=> Math.Abs(value - target) < tolerance;
|
||||
|
||||
/// <summary>
|
||||
/// 对质数进行分解。
|
||||
/// </summary>
|
||||
public static IEnumerable<int> GetPrimeFactors(int num) {
|
||||
num = Math.Abs(num);
|
||||
while (num % 2 == 0 && num > 1) {
|
||||
yield return 2;
|
||||
num /= 2;
|
||||
}
|
||||
int i = 3;
|
||||
int maxFactor = (int) Math.Sqrt(num);
|
||||
while (i <= maxFactor) {
|
||||
while (num % i == 0) {
|
||||
yield return i;
|
||||
num /= i;
|
||||
maxFactor = (int) Math.Sqrt(num);
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
if (num > 2) yield return num;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算最大公约数。例如 12 和 16 的结果是 4。
|
||||
/// </summary>
|
||||
public static int Gcd(int a, int b) {
|
||||
a = Math.Abs(a);
|
||||
b = Math.Abs(b);
|
||||
while (b != 0) {
|
||||
int temp = b;
|
||||
b = a % b;
|
||||
a = temp;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
/// <summary>
|
||||
/// 计算最大公约数。例如 12 和 16 的结果是 4。
|
||||
/// </summary>
|
||||
public static int Gcd(double a, int b)
|
||||
=> Gcd((int) Math.Round(a), b);
|
||||
|
||||
}
|
||||
+255
-45
@@ -1,21 +1,19 @@
|
||||
namespace MeloongCore;
|
||||
namespace MeloongCore;
|
||||
public static class PathUtils {
|
||||
|
||||
#region 分隔符
|
||||
|
||||
/// <summary>
|
||||
/// 确保路径的结尾包含文件夹分隔符。
|
||||
/// 确保路径的末尾包含任意文件夹分隔符。
|
||||
/// </summary>
|
||||
public static string WithSeparator(string folder) {
|
||||
return folder.EndsWithF(Path.DirectorySeparatorChar) ? folder : folder + Path.DirectorySeparatorChar;
|
||||
}
|
||||
public static string AddSlashSuffix(string folder)
|
||||
=> folder + (folder.EndsWithF(Path.DirectorySeparatorChar) || folder.EndsWithF(Path.AltDirectorySeparatorChar) ? "" : Path.DirectorySeparatorChar);
|
||||
|
||||
/// <summary>
|
||||
/// 确保路径的结尾不包含文件夹分隔符。
|
||||
/// </summary>
|
||||
public static string WithoutSeparator(string folder) {
|
||||
return folder.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
}
|
||||
public static string RemoveSlashSuffix(string folder)
|
||||
=> folder.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -23,62 +21,274 @@ public static class PathUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 若路径较长,则尽量将其转换为短路径。
|
||||
/// 若输入的是文件夹路径,不保证其结尾是否有文件夹分隔符。
|
||||
/// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
|
||||
/// </summary>
|
||||
public static string ToShortPath(string fullName, bool keepFileName = false) {
|
||||
if (string.IsNullOrEmpty(fullName)) return fullName;
|
||||
fullName = PathUtils.WithoutLongPath( fullName.Replace('/', '\\'));
|
||||
if (fullName.Length <= 200) return fullName;
|
||||
|
||||
// 保留文件名
|
||||
public static string ToShortPath(string pathName) {
|
||||
// 快速返回
|
||||
if (string.IsNullOrEmpty(pathName)) return pathName;
|
||||
if (!pathName.Contains(":") || pathName.Contains("://")) return pathName;
|
||||
if (pathName.Length <= 220) return pathName;
|
||||
// 开始实际处理
|
||||
pathName = PathUtils.ForCompare(pathName);
|
||||
// 尽量保留原始文件名
|
||||
string pathToKeep = "";
|
||||
string pathToShorten = fullName;
|
||||
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
|
||||
if (keepFileName && FileUtils.Exists(fullName)) {
|
||||
pathToKeep = Path.GetFileName(fullName);
|
||||
pathToShorten = Path.GetDirectoryName(fullName);
|
||||
string pathToShorten = pathName;
|
||||
if (FileUtils.Exists(pathName)) {
|
||||
var fileName = PathUtils.GetLastPart(pathName);
|
||||
if (fileName.Length >= 180) {
|
||||
Logger.Warn($"文件名过长,将为文件名生成短路径:{pathName}", LogBehavior.None); // 部分程序,例如 Forge 的模块加载,依赖于读取文件名进行判断,因此对文件名生成短路径是有风险的
|
||||
} else {
|
||||
pathToKeep = fileName;
|
||||
pathToShorten = PathUtils.RemoveLastPart(pathName);
|
||||
}
|
||||
}
|
||||
|
||||
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
|
||||
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
|
||||
string parentPath = Path.GetDirectoryName(pathToShorten);
|
||||
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回
|
||||
pathToKeep = Path.Combine(Path.GetFileName(pathToShorten), pathToKeep);
|
||||
string? parentPath = Path.GetDirectoryName(pathToShorten);
|
||||
if (string.IsNullOrEmpty(parentPath) || PathUtils.IsSame(parentPath, pathToShorten)) return pathName; // 已经到达根目录,全都不存在,直接返回
|
||||
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
|
||||
pathToShorten = parentPath;
|
||||
}
|
||||
if (pathToShorten.Length <= 10) return fullName;
|
||||
|
||||
// 缩短路径
|
||||
char[] buffer = new char[260];
|
||||
int result = GetShortPathNameW(pathToShorten, buffer, buffer.Length);
|
||||
if (result == 0) return fullName;
|
||||
string shortPath = new(buffer, 0, result);
|
||||
return Path.Combine(shortPath, pathToKeep);
|
||||
if (pathToKeep.Length >= 200) {
|
||||
Logger.Warn($"路径中的大部分内容都尚未建立,无法在内容不存在时缩短路径:{pathName} → {pathToShorten}", LogBehavior.None);
|
||||
return pathName;
|
||||
}
|
||||
// 获取短路径
|
||||
Func<string, string> TryGetShortPath = static pathName => {
|
||||
char[] buffer = new char[220];
|
||||
int result = GetShortPathNameW(PathUtils.ForApi(pathName), buffer, buffer.Length);
|
||||
return result is 0 or > 220 ? pathName : new string(buffer, 0, result);
|
||||
};
|
||||
var shortPath = TryGetShortPath(pathToShorten);
|
||||
// 尝试生成新的短名称,以将长度降低到 220 以下(只会在 Windows 没有为其生成过短名称的情况下才会触发,大多数情况都不会进到这里)
|
||||
if (Path.Combine(shortPath, pathToKeep).Length > 220) {
|
||||
Logger.Warn($"{nameof(GetShortPathNameW)} 未能有效缩短路径,将尝试生成新的短名称:{pathToShorten} → {shortPath}", LogBehavior.None);
|
||||
var candidates = new List<(string Path, string Name)>();
|
||||
string? candidatePath = pathToShorten;
|
||||
while (!string.IsNullOrEmpty(candidatePath)) {
|
||||
string candidateName = PathUtils.GetLastPart(candidatePath);
|
||||
if (candidateName.Length > 12 &&
|
||||
string.Equals(PathUtils.GetLastPart(TryGetShortPath(candidatePath)), candidateName, StringComparison.OrdinalIgnoreCase)) {
|
||||
candidates.Add((candidatePath, candidateName));
|
||||
}
|
||||
candidatePath = Path.GetDirectoryName(candidatePath);
|
||||
}
|
||||
foreach (var candidate in candidates.OrderByDescending(candidate => candidate.Name.Length)) {
|
||||
using var handle = CreateFileW(PathUtils.ForApi(candidate.Path), 0x40010000, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero); // GENERIC_WRITE | DELETE;共享读、写、删除;OPEN_EXISTING;FILE_FLAG_BACKUP_SEMANTICS
|
||||
if (handle.IsInvalid) continue;
|
||||
bool created = false;
|
||||
try {
|
||||
unsafe {
|
||||
fixed (char* originalNameBuffer = candidate.Name) {
|
||||
char* shortNameBuffer = stackalloc char[12]; // 8.3 名称最长 12 个 Unicode 字符
|
||||
var name = new UnicodeString {Length = (ushort)(candidate.Name.Length * 2), MaximumLength = (ushort)((candidate.Name.Length + 1) * 2), Buffer = originalNameBuffer};
|
||||
var shortName = new UnicodeString {MaximumLength = 24, Buffer = shortNameBuffer};
|
||||
var context = new GenerateNameContext();
|
||||
for (int i = 0; i < 20; i++) { // 使用 Windows 自身的 8.3 名称生成算法,并通过 context 依次生成避让冲突的候选名
|
||||
shortName.Length = 0;
|
||||
if (RtlGenerate8dot3Name(ref name, 0, ref context, ref shortName) != 0) break;
|
||||
string generatedName = new(shortName.Buffer, 0, shortName.Length / 2);
|
||||
if (SetFileShortNameW(handle, generatedName)) { created = true; break; }
|
||||
if (Marshal.GetLastWin32Error() != 183) break; // ERROR_ALREADY_EXISTS
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (EntryPointNotFoundException) {}
|
||||
if (!created) continue;
|
||||
shortPath = TryGetShortPath(pathToShorten);
|
||||
if (Path.Combine(shortPath, pathToKeep).Length <= 220) break;
|
||||
}
|
||||
}
|
||||
return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.Combine(shortPath, pathToKeep)));
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private unsafe struct UnicodeString { public ushort Length, MaximumLength; public char* Buffer; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private unsafe struct GenerateNameContext { public ushort Checksum; public byte ChecksumInserted, NameLength; public fixed char NameBuffer[8]; public uint ExtensionLength; public fixed char ExtensionBuffer[4]; public uint LastIndexValue; }
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetShortPathNameW(string lpszLongPath, [Out] char[] buffer, int cchBuffer);
|
||||
private static extern int GetShortPathNameW(string lpszLongPath, [Out] char[]? buffer, int cchBuffer);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFileW(string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool SetFileShortNameW(Microsoft.Win32.SafeHandles.SafeFileHandle file, string shortName);
|
||||
[DllImport("ntdll.dll")]
|
||||
private static extern int RtlGenerate8dot3Name(ref UnicodeString name, byte allowExtendedCharacters, ref GenerateNameContext context, ref UnicodeString name8dot3);
|
||||
|
||||
/// <summary>
|
||||
/// 将完整路径转换为以 \\?\ 开头的标准长路径格式。
|
||||
/// 这会去除路径末尾的分隔符,且将 / 替换为 \。
|
||||
/// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。
|
||||
/// 这会去除路径末尾的分隔符,将 / 替换为 \。
|
||||
/// </summary>
|
||||
public static string WithLongPath(string path) {
|
||||
if (string.IsNullOrWhiteSpace(path)) return path;
|
||||
if (path.StartsWithF(@"\\?\")) return path; // 已经是长路径
|
||||
path = WithoutSeparator(path).Replace('/', '\\'); // API 要求这个格式……
|
||||
if (path.StartsWithF(@"\\")) {
|
||||
return $@"\\?\UNC\{path.Substring(2)}";
|
||||
public static string ToExtendedFormat(string pathName) {
|
||||
if (string.IsNullOrWhiteSpace(pathName)) return pathName;
|
||||
if (!pathName.Contains(@":")) return pathName; // 可能是相对路径,保持不变
|
||||
if (pathName.StartsWithF(@"\\?\")) return pathName; // 已经是长路径
|
||||
pathName = RemoveSlashSuffix(pathName).Replace('/', '\\'); // API 要求这个格式……
|
||||
if (pathName.StartsWithF(@"\\")) {
|
||||
return $@"\\?\UNC\{pathName[2..]}";
|
||||
} else {
|
||||
return $@"\\?\{path}";
|
||||
return $@"\\?\{pathName}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 去除路径开头的 \\?\。
|
||||
/// 去除路径开头的 <c>\\?\</c>。
|
||||
/// </summary>
|
||||
public static string WithoutLongPath(string path) =>
|
||||
path.AfterLast(@"\\?\");
|
||||
public static string RemoveExtendedPrefix(string pathName) {
|
||||
if (pathName.StartsWithF(@"\\?\UNC\")) return @"\\" + pathName.AfterLast(@"\\?\UNC\");
|
||||
if (pathName.StartsWithF(@"\\?\")) return pathName.AfterLast(@"\\?\");
|
||||
return pathName;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 路径处理
|
||||
|
||||
/// <summary>
|
||||
/// 去除路径的最后一级,并移除末尾的分隔符。
|
||||
/// <code>
|
||||
/// "C:\foo\bar.txt" → "C:\foo"
|
||||
/// "C:\foo\bar\" → "C:\foo"
|
||||
/// "C:\foo\bar" → "C:\foo"
|
||||
/// "C:\foo\" → "C:"
|
||||
/// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
|
||||
/// </code></summary>
|
||||
public static string RemoveLastPart(string pathName) {
|
||||
if (pathName.Contains("://")) { // 网络路径
|
||||
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
|
||||
}
|
||||
return PathUtils.RemoveSlashSuffix(pathName).BeforeLastOfAny([@"\", "/"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取路径的最后一级,即文件名,或当前文件夹名。
|
||||
/// <code>
|
||||
/// "C:\foo\bar.txt" → "bar.txt"
|
||||
/// "C:\foo\bar\" → "bar"
|
||||
/// "C:\foo\bar" → "bar"
|
||||
/// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip"
|
||||
/// </code></summary>
|
||||
public static string GetLastPart(string pathName) {
|
||||
if (pathName.Contains("://")) { // 网络路径
|
||||
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
|
||||
} else { // 文件路径
|
||||
pathName = PathUtils.RemoveSlashSuffix(pathName);
|
||||
}
|
||||
return pathName.AfterLastOfAny([@"\", "/"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取路径或文件名中,仅不包含最后一级扩展名的部分。
|
||||
/// <code>
|
||||
/// "C:\foo\bar.txt" → "bar"
|
||||
/// "create.jar.disabled" → "create.jar"
|
||||
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "page.xaml"
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static string GetFileNameWithoutExtension(string pathName)
|
||||
=> GetLastPart(pathName).BeforeLast(".");
|
||||
|
||||
/// <summary>
|
||||
/// 获取路径或文件名中的最后一级文件扩展名,不包含 <c>.</c>,固定小写。
|
||||
/// 如果没有 <c>.</c> 则返回空字符串。
|
||||
/// <code>
|
||||
/// "C:\FOO\BAR.TXT" → "txt"
|
||||
/// "create.jar.disabled" → "disabled"
|
||||
/// "C:\foo\bar" → ""
|
||||
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "vb"
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static string GetExtension(string pathName) {
|
||||
var name = GetLastPart(pathName);
|
||||
return name.Contains(".") ? name.AfterLast(".").Lower() : "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取路径的盘符,返回一个大写字母。
|
||||
/// 若路径不包含盘符,则返回 <c>null</c>。
|
||||
/// </summary>
|
||||
public static char? GetDiskName(string? pathName) {
|
||||
if (string.IsNullOrEmpty(pathName)) return null;
|
||||
pathName = PathUtils.RemoveExtendedPrefix(pathName!);
|
||||
if (pathName.StartsWithF(@"\\") || pathName.StartsWithF("/")) return null;
|
||||
return char.ToUpper(pathName[0]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 统一路径格式,以便比较。
|
||||
/// <para/>具体而言:将短路径展开,去除前导的 <c>\\?\</c>,将分隔符改为 \,去除末尾的分隔符。
|
||||
/// </summary>
|
||||
public static string ForCompare(string pathName) {
|
||||
try {
|
||||
return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.GetFullPath(pathName)).Replace("/", @"\"));
|
||||
} catch (ArgumentException ex) {
|
||||
throw new ArgumentException($"路径不正确:{pathName}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 比较两个路径是否相同。<c>null</c> 与空字符串视为相同的空路径。
|
||||
/// </summary>
|
||||
public static bool IsSame(string? path1, string? path2) {
|
||||
return PathUtils.Compare(path1, path2) == 0;
|
||||
}
|
||||
/// <summary>
|
||||
/// 比较两个路径,忽略大小写。
|
||||
/// <para/><c>null</c> 与空字符串视为相同的空路径,空路径排在非空路径之前。
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// 小于 0:<paramref name="path1"/> 排在 <paramref name="path2"/> 之前。
|
||||
/// <para/>等于 0:两个路径相等。
|
||||
/// <para/>大于 0:<paramref name="path1"/> 排在 <paramref name="path2"/> 之后。
|
||||
/// </returns>
|
||||
public static int Compare(string? path1, string? path2) {
|
||||
if (string.IsNullOrEmpty(path1)) return string.IsNullOrEmpty(path2) ? 0 : -1;
|
||||
if (string.IsNullOrEmpty(path2)) return 1;
|
||||
return string.Compare(PathUtils.ForCompare(path1!), PathUtils.ForCompare(path2!), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将路径转换为兼容各种 Windows API 的格式。
|
||||
/// <para/>具体而言:将分隔符改为 \。添加前导的 <c>\\?\</c>。若为驱动器则添加末尾分隔符,否则去除分隔符。
|
||||
/// </summary>
|
||||
public static string ForApi(string pathName) {
|
||||
pathName = PathUtils.ToExtendedFormat(pathName);
|
||||
if (pathName.EndsWithF(":")) pathName += @"\"; // 驱动器路径必须保留末尾的分隔符
|
||||
if (pathName.EndsWithF(@":\")) return pathName;
|
||||
return PathUtils.RemoveSlashSuffix(pathName);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 判断 <param name="parentPath"/> 是否为 <paramref name="childPath"/> 的父路径,或两者是否相同。
|
||||
/// </summary>
|
||||
public static bool IsParentOf(string parentPath, string childPath) {
|
||||
parentPath = PathUtils.ForCompare(parentPath);
|
||||
childPath = PathUtils.ForCompare(childPath);
|
||||
return childPath.StartsWithF(parentPath + @"\", true) || PathUtils.IsSame(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);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Microsoft.Win32;
|
||||
namespace MeloongCore;
|
||||
|
||||
public static class RegistryUtils {
|
||||
/// <summary>在注册表中表示 <c>null</c> 的标记字符串。</summary>
|
||||
public const string NULL_STRING = "__NULL__";
|
||||
|
||||
/// <summary>
|
||||
/// 读取注册表值。
|
||||
/// <para/>若键值为 <see cref="NULL_STRING"/>,则返回 <c>null</c>。
|
||||
/// </summary>
|
||||
public static (object? result, bool exists) Read(string folder, string entry) {
|
||||
using RegistryKey? folderKey = GetRegistryKey(folder);
|
||||
var result = folderKey?.GetValue(entry);
|
||||
if (result is null) return (null, false);
|
||||
return (result is string str && str == NULL_STRING ? null : result, true);
|
||||
}
|
||||
/// <summary>
|
||||
/// 读取注册表值,若该值不存在或发生异常则返回 <paramref name="defaultValue"/>。
|
||||
/// <para/>若键值为 <see cref="NULL_STRING"/>,则返回 <c>null</c>。
|
||||
/// </summary>
|
||||
public static object? TryRead(string folder, string entry, object? defaultValue = null) {
|
||||
try {
|
||||
var (result, exists) = Read(folder, entry);
|
||||
return exists ? result : defaultValue;
|
||||
} catch (Exception ex) {
|
||||
Logger.Warn(ex, $"读取注册表值失败({folder},{entry})");
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写入注册表值。
|
||||
/// <para/>会自动创建对应的子键。
|
||||
/// <para/>若 <paramref name="value"/> 为 <c>null</c>,则写入 <see cref="NULL_STRING"/>。
|
||||
/// </summary>
|
||||
public static void Write(string folder, string entry, object? value) {
|
||||
using RegistryKey folderKey = GetRegistryKey(folder, create: true)!;
|
||||
folderKey.SetValue(entry, value ?? NULL_STRING);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断对应的注册表值是否存在。
|
||||
/// </summary>
|
||||
public static bool Has(string folder, string entry) {
|
||||
using RegistryKey? folderKey = GetRegistryKey(folder);
|
||||
if (folderKey is null) return false;
|
||||
object notFound = new();
|
||||
return !ReferenceEquals(folderKey.GetValue(entry, notFound), notFound);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除注册表值。若不存在则不执行操作。
|
||||
/// </summary>
|
||||
public static void Delete(string folder, string entry) {
|
||||
using RegistryKey? folderKey = GetRegistryKey(folder, writable: true);
|
||||
folderKey?.DeleteValue(entry, throwOnMissingValue: false);
|
||||
}
|
||||
|
||||
private static RegistryKey? GetRegistryKey(string fullPath, bool writable = false, bool create = false) {
|
||||
using RegistryKey key = fullPath.BeforeFirst("\\").ToUpperInvariant() switch {
|
||||
"HKEY_CLASSES_ROOT" => Registry.ClassesRoot,
|
||||
"HKEY_CURRENT_USER" => Registry.CurrentUser,
|
||||
"HKEY_LOCAL_MACHINE" => Registry.LocalMachine,
|
||||
"HKEY_USERS" => Registry.Users,
|
||||
"HKEY_CURRENT_CONFIG" => Registry.CurrentConfig,
|
||||
_ => throw new ArgumentException($"注册表路径有误({fullPath})", nameof(fullPath))
|
||||
};
|
||||
string subKey = fullPath.AfterFirst("\\");
|
||||
return create ? key.CreateSubKey(subKey) : key.OpenSubKey(subKey, writable);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Globalization;
|
||||
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("&", "&").Replace("<", "<").Replace(">", ">").Replace("'", "'")
|
||||
.Replace("\"", """).ReplaceLineEndings("
");
|
||||
}
|
||||
|
||||
/// <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(CultureInfo.InvariantCulture);
|
||||
return $"{sign}{Math.Round(byteSize / 1024D, (3 - roundResult.Length).Clamp(0, 2))} K";
|
||||
} else if (byteSize < 1024 * 1024 * 1000) { // M 级
|
||||
var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
|
||||
return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} M";
|
||||
} else { // G 级
|
||||
var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
|
||||
return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
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, _) => {
|
||||
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, _) => {
|
||||
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();
|
||||
program.StartInfo = info;
|
||||
program.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>
|
||||
/// 当 HTTP 请求的状态码不指示成功时引发的异常。
|
||||
@@ -7,13 +7,9 @@ public class HttpRequestCodeException(string message, HttpStatusCode statusCode,
|
||||
/// <summary>
|
||||
/// HTTP 请求的状态码。
|
||||
/// </summary>
|
||||
public HttpStatusCode StatusCode = statusCode;
|
||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||
/// <summary>
|
||||
/// 远程服务器给予的回复。
|
||||
/// </summary>
|
||||
public string? Response { get; set; } = response;
|
||||
}
|
||||
|
||||
public static class HttpUtils {
|
||||
|
||||
public string? Response { get; } = response;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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: provider);
|
||||
|
||||
entry.Set(["Alpha", "中文", "123"]);
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<List<string>>("list", [], provider: 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: 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", [], provider: 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: provider);
|
||||
|
||||
entry.Set(null);
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("nullable", "fallback", provider: 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: provider);
|
||||
|
||||
entry.Set("plain text 中文");
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "fallback", provider: 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: provider);
|
||||
|
||||
entry.Set("pending 中文");
|
||||
ConfigUtils.SaveAll();
|
||||
ConfigUtils.SaveAll();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "fallback", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("pending 中文");
|
||||
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"text\": \"pending 中文\"");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JsonConfigProvider_Save_原子替换且不残留临时文件() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
FileUtils.Write(configFile, "{\"existing\":true}");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "", provider: provider);
|
||||
|
||||
entry.Set("updated");
|
||||
provider.Save();
|
||||
|
||||
Newtonsoft.Json.Linq.JObject config = FileUtils.ReadAsJson<Newtonsoft.Json.Linq.JObject>(configFile)!;
|
||||
await Assert.That(config.Value<bool>("existing")).IsTrue();
|
||||
await Assert.That(config.Value<string>("text")).IsEqualTo("updated");
|
||||
await Assert.That(DirectoryUtils.EnumerateFiles(tempFolder, searchPattern: "config.json.*.tmp")).IsEmpty();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JsonConfigProvider_Save_等待正在进行的保存() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "", provider: provider);
|
||||
using var firstStarted = new ManualResetEventSlim(false);
|
||||
using var secondStarted = new ManualResetEventSlim(false);
|
||||
Task firstSave, secondSave;
|
||||
bool firstBlocked, secondRunning, returnedEarly;
|
||||
|
||||
lock (provider) {
|
||||
entry.Set("pending");
|
||||
Thread? firstThread = null;
|
||||
firstSave = Task.Factory.StartNew(() => {
|
||||
firstThread = Thread.CurrentThread;
|
||||
firstStarted.Set();
|
||||
provider.Save();
|
||||
}, TaskCreationOptions.LongRunning);
|
||||
// 阻止首次保存写盘,稳定复现第二次 Save 在写盘完成前返回的窗口。
|
||||
firstBlocked = firstStarted.Wait(3000) && SpinWait.SpinUntil(
|
||||
() => (firstThread!.ThreadState & ThreadState.WaitSleepJoin) != 0, 3000);
|
||||
secondSave = Task.Factory.StartNew(() => {
|
||||
secondStarted.Set();
|
||||
provider.Save();
|
||||
}, TaskCreationOptions.LongRunning);
|
||||
secondRunning = secondStarted.Wait(3000);
|
||||
returnedEarly = secondSave.Wait(200);
|
||||
}
|
||||
await Task.WhenAll(firstSave, secondSave);
|
||||
|
||||
await Assert.That(firstBlocked).IsTrue();
|
||||
await Assert.That(secondRunning).IsTrue();
|
||||
await Assert.That(returnedEarly).IsFalse();
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("pending");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JsonConfigProvider_Save_写入失败后可直接重试() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "", provider: provider);
|
||||
entry.Set("before");
|
||||
provider.Save();
|
||||
|
||||
lock (provider) {
|
||||
entry.Set("after");
|
||||
using (var stream = new FileStream(PathUtils.ForApi(configFile), FileMode.Open, FileAccess.Read, FileShare.None)) {
|
||||
Assert.Throws<IOException>(() => provider.Save());
|
||||
}
|
||||
// 无需再次 Set,失败的内容仍应处于待保存状态。
|
||||
provider.Save();
|
||||
}
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("after");
|
||||
}
|
||||
|
||||
public class TestConfigItem {
|
||||
public string Name { get; set; } = "";
|
||||
public int Count { get; set; }
|
||||
public bool Enabled { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
@@ -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.GetIncreasing() - 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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<OutputType>Library</OutputType>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<Deterministic>true</Deterministic>
|
||||
<IsPackable>false</IsPackable>
|
||||
@@ -23,13 +23,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||
<PackageReference Include="System.IO.Compression" Version="4.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="TUnit" Version="1.43.38" />
|
||||
<PackageReference Include="PolySharp" Version="1.15.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
@@ -64,6 +59,7 @@
|
||||
<Using Include="System.Diagnostics.CodeAnalysis" />
|
||||
<Using Include="System.Collections" />
|
||||
<Using Include="System.Collections.Generic" />
|
||||
<Using Include="System.Collections.Concurrent" />
|
||||
<Using Include="System.Text" />
|
||||
<Using Include="System.Net" />
|
||||
<Using Include="System.Runtime.CompilerServices" />
|
||||
@@ -71,7 +67,6 @@
|
||||
<Using Include="MeloongCore" />
|
||||
<Using Include="MeloongCore.Extensions" />
|
||||
<Using Include="MeloongCore.Tests" />
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
+24
-7
@@ -1,32 +1,49 @@
|
||||
namespace MeloongCore.Tests;
|
||||
namespace MeloongCore.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 所有测试的基类。
|
||||
/// 会初始化 MeloongCore 并重定向日志输出。
|
||||
/// </summary>
|
||||
public abstract class TestBase {
|
||||
|
||||
public TestBase() {
|
||||
MeloongCore.Main.Init("MeloongCoreTest");
|
||||
Logger.Instance = new TestLogger();
|
||||
}
|
||||
private class TestLogger : BaseLogger {
|
||||
public override void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex)
|
||||
=> TestContext.Current!.OutputWriter.WriteLine(formattedMessage);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用于带文件测试的基类。
|
||||
/// 会在极端路径下创建测试用的临时文件夹。
|
||||
/// </summary>
|
||||
public abstract class TestWithFolder {
|
||||
public abstract class TestWithFolder : TestBase {
|
||||
|
||||
/// <summary>
|
||||
/// 测试用的临时文件夹路径。
|
||||
/// 这是一个包含特殊字符的长路径,不以 \\?\ 开头,以 \ 结尾。
|
||||
/// </summary>
|
||||
public readonly string tempFolder;
|
||||
public TestWithFolder() {
|
||||
public TestWithFolder() : base() {
|
||||
tempFolder = Path.Combine(
|
||||
Path.GetTempPath(), "PCL", "Tests",
|
||||
$"{GetType().Name}-{Guid.NewGuid()}",
|
||||
"文件夹 Dir_!@#$%^&()_+={}[];',_",
|
||||
new string('X', 200), new string('X', 200)) + @"\";
|
||||
Directory.CreateDirectory(@"\\?\" + tempFolder);
|
||||
DirectoryUtils.Create(tempFolder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 输出指定的测试用文件,返回文件路径。
|
||||
/// </summary>
|
||||
public string GetTestFile(string fileName) {
|
||||
var sourceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", GetType().Name.Replace("Test", ""), fileName);
|
||||
var distPath = Path.Combine(tempFolder, Path.GetFileName(sourceFilePath));
|
||||
File.Copy(sourceFilePath, @"\\?\" + distPath);
|
||||
var sourceFilePath = Path.Combine(Paths.Base, "TestFiles", GetType().Name.Replace("Test", ""), fileName);
|
||||
var distPath = Path.Combine(tempFolder, PathUtils.GetLastPart(sourceFilePath));
|
||||
FileUtils.Copy(sourceFilePath, distPath);
|
||||
return distPath;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
namespace MeloongCore.Tests;
|
||||
public class DirectoryUtilsTest : TestWithFolder {
|
||||
|
||||
#region 剪切、复制
|
||||
|
||||
[Test]
|
||||
[Arguments("Source", "目标文件夹")]
|
||||
[Arguments("Source", "Source")]
|
||||
[Arguments("Source", "soURCE")]
|
||||
public async Task 复制(string sourceName, string destName) {
|
||||
var src = Path.Combine(tempFolder, sourceName);
|
||||
DirectoryUtils.Create(Path.Combine(src, "sub"));
|
||||
FileUtils.Write(Path.Combine(src, "a.txt"), "aaa");
|
||||
FileUtils.Write(Path.Combine(src, "sub", "b file.txt"), "bbb");
|
||||
var dest = Path.Combine(tempFolder, destName);
|
||||
|
||||
DirectoryUtils.Copy(src, dest);
|
||||
|
||||
await Assert.That(FileUtils.ReadAsString(Path.Combine(src, "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(dest, "sub", "b file.txt"))).IsEqualTo("bbb");
|
||||
await Assert.That(DirectoryUtils.EnumerateDirectories(tempFolder, true)).Contains(dest); // 目标文件夹名
|
||||
}
|
||||
|
||||
[Test]
|
||||
[Arguments("Source", "目标文件夹")]
|
||||
[Arguments("Source", "Source")]
|
||||
[Arguments("Source", "soURCE")]
|
||||
public async Task 剪切(string sourceName, string destName) {
|
||||
var src = Path.Combine(tempFolder, sourceName);
|
||||
DirectoryUtils.Create(Path.Combine(src, "sub"));
|
||||
FileUtils.Write(Path.Combine(src, "a.txt"), "aaa");
|
||||
FileUtils.Write(Path.Combine(src, "sub", "b file.txt"), "bbb");
|
||||
var dest = Path.Combine(tempFolder, destName);
|
||||
|
||||
DirectoryUtils.Move(src, dest);
|
||||
|
||||
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");
|
||||
if (src != dest) await Assert.That(DirectoryUtils.EnumerateDirectories(tempFolder, true)).DoesNotContain(src);
|
||||
await Assert.That(DirectoryUtils.EnumerateDirectories(tempFolder, true)).Contains(dest); // 目标文件夹名
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task 剪切_不同磁盘() {
|
||||
// 寻找两个磁盘
|
||||
var drives = DriveInfo.GetDrives()
|
||||
.Where(d => d.IsReady && d.DriveType == DriveType.Fixed)
|
||||
.ToArray();
|
||||
if (drives.Length < 2) return;
|
||||
|
||||
var id = Guid.NewGuid().ToString("N");
|
||||
var srcRoot = Path.Combine(drives[0].RootDirectory.FullName, "Temp", $"MeloongTest_{id}");
|
||||
var destRoot = Path.Combine(drives[1].RootDirectory.FullName, "Temp", $"MeloongTest_{id}");
|
||||
var src = Path.Combine(srcRoot, "src");
|
||||
var dest = Path.Combine(destRoot, "dest");
|
||||
try {
|
||||
DirectoryUtils.Create(src);
|
||||
FileUtils.Write(Path.Combine(src, "a.txt"), "aaa");
|
||||
FileUtils.Write(Path.Combine(src, "sub", "b file.txt"), "bbb");
|
||||
|
||||
DirectoryUtils.Move(src, dest);
|
||||
|
||||
await Assert.That(DirectoryUtils.Exists(src)).IsFalse();
|
||||
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");
|
||||
} finally {
|
||||
DirectoryUtils.Delete(srcRoot);
|
||||
DirectoryUtils.Delete(destRoot);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void 剪切_安全检查()
|
||||
=> 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
|
||||
|
||||
}
|
||||
@@ -1,45 +1,72 @@
|
||||
namespace MeloongCore.Tests;
|
||||
public class FileUtilsTest : TestWithFolder {
|
||||
|
||||
#region 压缩包
|
||||
[Test]
|
||||
public async Task 文件可用性_只读与占用() {
|
||||
string path = Path.Combine(tempFolder, "available.txt");
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsTrue();
|
||||
FileUtils.Write(path, "test");
|
||||
string apiPath = PathUtils.ForApi(path);
|
||||
File.SetAttributes(apiPath, FileAttributes.ReadOnly);
|
||||
try {
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsTrue();
|
||||
await Assert.That((File.GetAttributes(apiPath) & FileAttributes.ReadOnly) != 0).IsTrue();
|
||||
} finally {
|
||||
File.SetAttributes(apiPath, FileAttributes.Normal);
|
||||
}
|
||||
using (var stream = new FileStream(apiPath, FileMode.Open, FileAccess.Read, FileShare.None)) {
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsFalse();
|
||||
}
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GB Encoding.zip")]
|
||||
[InlineData("UTF8 Encoding.zip")]
|
||||
public void Compression_ReadZip(string testFile) {
|
||||
double progress = 0;
|
||||
[Test]
|
||||
public async Task 文件可用性_短暂占用后重试() {
|
||||
string path = Path.Combine(tempFolder, "temporary-lock.txt");
|
||||
FileUtils.Write(path, "test");
|
||||
using var stream = new FileStream(PathUtils.ForApi(path), FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
var release = Task.Run(async () => {
|
||||
await Task.Delay(100);
|
||||
stream.Dispose();
|
||||
});
|
||||
bool available = FileUtils.IsAvailable(path);
|
||||
await release;
|
||||
await Assert.That(available).IsTrue();
|
||||
}
|
||||
|
||||
#region 解压
|
||||
|
||||
[Test]
|
||||
[Arguments("GB Encoding.zip")]
|
||||
[Arguments("UTF8 Encoding.zip")]
|
||||
public async Task 解压_ReadZip(string testFile) {
|
||||
string output = Path.Combine(tempFolder, "Extracted");
|
||||
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
|
||||
Assert.Equal(1, progress);
|
||||
Assert.True(DirectoryUtils.Exists(Path.Combine(output, "文件夹")));
|
||||
Assert.False(DirectoryUtils.Exists(Path.Combine(output, "空文件夹")));
|
||||
Assert.Contains("FabricLoader", File.ReadAllText(PathUtils.WithLongPath(Path.Combine(output, "fabricloader.log"))));
|
||||
Assert.Contains("测试内容", File.ReadAllText(PathUtils.WithLongPath(Path.Combine(output, "文件夹", "中文文件.txt"))));
|
||||
var p = new ProgressProvider();
|
||||
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p: p);
|
||||
await Assert.That(p.IsFinished).IsTrue();
|
||||
await Assert.That(DirectoryUtils.Exists(Path.Combine(output, "文件夹"))).IsTrue();
|
||||
await Assert.That(DirectoryUtils.Exists(Path.Combine(output, "空文件夹"))).IsFalse();
|
||||
await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, "fabricloader.log")))).Contains("FabricLoader");
|
||||
await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, "文件夹", "中文文件.txt")))).Contains("测试内容");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GZ.gz", "LTCat")]
|
||||
public void Compression_ReadGz(string testFile, string containsText) {
|
||||
double progress = 0;
|
||||
[Test]
|
||||
[Arguments("GZ.gz", "LTCat")]
|
||||
public async Task 解压_ReadGz(string testFile, string containsText) {
|
||||
string output = Path.Combine(tempFolder, "Extracted");
|
||||
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
|
||||
Assert.Equal(1, progress);
|
||||
Assert.Contains(containsText, File.ReadAllText(PathUtils.WithLongPath(Path.Combine(output, Path.GetFileNameWithoutExtension(testFile)))));
|
||||
var p = new ProgressProvider();
|
||||
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p: p);
|
||||
await Assert.That(p.IsFinished).IsTrue();
|
||||
await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, PathUtils.GetFileNameWithoutExtension(testFile))))).Contains(containsText);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Corrupted.zip")]
|
||||
[InlineData("Not zip.zip")]
|
||||
public void Compression_ReadBad(string testFile) {
|
||||
Assert.Throws<InvalidDataException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("DotDot ZipSlip.zip")]
|
||||
[InlineData("AbsPath ZipSlip.zip")]
|
||||
public void Compression_ZipSlip(string testFile) {
|
||||
Assert.Throws<FileUtils.ZipSlipException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
|
||||
}
|
||||
[Test]
|
||||
[Arguments("Corrupted.zip")]
|
||||
[Arguments("Not zip.zip")]
|
||||
[Arguments("DotDot ZipSlip.zip")]
|
||||
[Arguments("AbsPath ZipSlip.zip")]
|
||||
public void 解压_ReadBad(string testFile)
|
||||
=> Assert.Throws<InvalidDataException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
namespace MeloongCore.Tests;
|
||||
public class PathUtilsTests : TestBase {
|
||||
|
||||
#region 长路径
|
||||
|
||||
[Test]
|
||||
public async Task 长路径_ToShortPath_输出超过260字符() {
|
||||
string root = Path.Combine(Path.GetTempPath(), $"{nameof(PathUtilsTests)}-{Guid.NewGuid():N}");
|
||||
string path = root;
|
||||
for (int i = 0; i < 40; i++) path = Path.Combine(path, $"D{i:000000}");
|
||||
try {
|
||||
DirectoryUtils.Create(path);
|
||||
string result = PathUtils.ToShortPath(path);
|
||||
await Assert.That(result.Length > 260).IsTrue();
|
||||
await Assert.That(DirectoryUtils.Exists(result)).IsTrue();
|
||||
} finally {
|
||||
DirectoryUtils.Delete(root);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task 长路径_ToShortPath_创建短文件名() {
|
||||
string root = Path.Combine(Path.GetTempPath(), $"{nameof(PathUtilsTests)}-{Guid.NewGuid():N}");
|
||||
string path = Path.Combine(root, new string('A', 220), "versions", "test");
|
||||
try {
|
||||
DirectoryUtils.Create(path);
|
||||
string result = PathUtils.ToShortPath(path);
|
||||
await Assert.That(result.Length <= 200).IsTrue();
|
||||
await Assert.That(result.Length < path.Length).IsTrue();
|
||||
await Assert.That(DirectoryUtils.Exists(result)).IsTrue();
|
||||
} finally {
|
||||
DirectoryUtils.Delete(root);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 路径处理
|
||||
|
||||
[Test]
|
||||
[Arguments(@"\\?\C:\foo\bar.txt", @"\\?\C:\foo")]
|
||||
[Arguments(@"C:\foo\extra/bar.txt", @"C:\foo\extra")]
|
||||
[Arguments(@"C:\foo/extra/bar.txt", @"C:\foo/extra")]
|
||||
[Arguments(@"C:\foo/extra\bar.txt", @"C:\foo/extra")]
|
||||
[Arguments(@"C:\foo\bar.txt", @"C:\foo")]
|
||||
[Arguments(@"\\?\C:\foo\Bar", @"\\?\C:\foo")]
|
||||
[Arguments(@"C:\foo\bar", @"C:\foo")]
|
||||
[Arguments(@"C:\Foo\bar\", @"C:\Foo")]
|
||||
[Arguments(@"\\?\C:\foo\", @"\\?\C:")]
|
||||
[Arguments(@"C:\foo", @"C:")]
|
||||
[Arguments(@"C:\foo\", @"C:")]
|
||||
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", @"https://foo.bar/file\long")]
|
||||
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", @"https://foo.bar/file\long")]
|
||||
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", @"https://foo.bar/file/long")]
|
||||
[Arguments(@"https://foo.bar/file/long/pack.zip?arg=1", @"https://foo.bar/file/long")]
|
||||
[Arguments(@"https://foo.bar/file/", "https://foo.bar")]
|
||||
[Arguments(@"https://foo.bar/file/?arg=1", "https://foo.bar")]
|
||||
[Arguments(@"https://foo.bar/file?arg=1", "https://foo.bar")]
|
||||
public async Task 路径处理_RemoveLastPart(string input, string expected)
|
||||
=> await Assert.That(PathUtils.RemoveLastPart(input)).IsEqualTo(expected);
|
||||
|
||||
[Test]
|
||||
[Arguments(@"\\?\C:\foo\bar.txt", "bar.txt")]
|
||||
[Arguments(@"C:\foo\extra/bar.txt", "bar.txt")]
|
||||
[Arguments(@"C:\foo/extra/bar.txt", "bar.txt")]
|
||||
[Arguments(@"C:\foo/extra\bar.txt", "bar.txt")]
|
||||
[Arguments(@"C:\foo\bar.txt", "bar.txt")]
|
||||
[Arguments(@"C:\foo\bar.txt", "bar.txt")]
|
||||
[Arguments(@"\\?\C:\foo/bar", "bar")]
|
||||
[Arguments(@"C:\foo\bar", "bar")]
|
||||
[Arguments(@"C:\foo\bar\", "bar")]
|
||||
[Arguments(@"\\?\C:\foo\", "foo")]
|
||||
[Arguments(@"C:\foo", "foo")]
|
||||
[Arguments(@"C:\foo\", "foo")]
|
||||
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", "pack.zip")]
|
||||
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", "pack.zip")]
|
||||
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", "pack.zip")]
|
||||
[Arguments(@"https://foo.bar/file/long/pack.zip?arg=1", "pack.zip")]
|
||||
[Arguments(@"https://foo.bar/file/", "file")]
|
||||
[Arguments(@"https://foo.bar/file/?arg=1", "file")]
|
||||
[Arguments(@"https://foo.bar/File?arg=1", "File")]
|
||||
[Arguments(@"https://cdn.modrinth.com/data/RvfAlf4Z/versions/XauQUBeR\Redstone Tweaks 2.5.3.zip?mr_download_reason=modpack", "Redstone Tweaks 2.5.3.zip")]
|
||||
public async Task 路径处理_GetLastPart(string input, string expected)
|
||||
=> await Assert.That(PathUtils.GetLastPart(input)).IsEqualTo(expected);
|
||||
|
||||
[Test]
|
||||
[Arguments(@"\\?\C:\foo\bar.txt", "bar")]
|
||||
[Arguments(@"C:\foo\bar.2.txt", "bar.2")]
|
||||
[Arguments(@"\\?\C:\foo\bar", "bar")]
|
||||
[Arguments(@"C:\foo\bar", "bar")]
|
||||
[Arguments(@"C:\foo.bar\how/long\path.txt", "path")]
|
||||
[Arguments(@"C:\foo.bar\how/long/path.txt", "path")]
|
||||
[Arguments(@"C:\foo.bar\how\long/path.txt", "path")]
|
||||
[Arguments(@"C:\foo.bar\how\", "how")]
|
||||
[Arguments(@"\\?\C:\foo\", "foo")]
|
||||
[Arguments(@"C:\foo", "foo")]
|
||||
[Arguments(@"C:\foo\", "foo")]
|
||||
[Arguments(@"cREate.jar.disabled", "cREate.jar")]
|
||||
[Arguments(@"create.jar", "create")]
|
||||
[Arguments(@"create", "create")]
|
||||
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", "pack")]
|
||||
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", "pack")]
|
||||
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", "pack")]
|
||||
[Arguments(@"https://foo.bar/file/long/pack.zip?arg=1", "pack")]
|
||||
[Arguments(@"https://foo.bar/file/page.xaml.vb?arg=1", "page.xaml")]
|
||||
[Arguments(@"https://foo.bar/some.how/file/", "file")]
|
||||
[Arguments(@"https://foo.bar/file/?arg=1", "file")]
|
||||
[Arguments(@"https://foo.bar/file?arg=1", "file")]
|
||||
public async Task 路径处理_GetFileNameWithoutExtension(string input, string expected)
|
||||
=> await Assert.That(PathUtils.GetFileNameWithoutExtension(input)).IsEqualTo(expected);
|
||||
|
||||
[Test]
|
||||
[Arguments(@"\\?\C:\FOO\BAR.TXT", "txt")]
|
||||
[Arguments(@"C:\foo\bar.txt", "txt")]
|
||||
[Arguments(@"C:\foo.bar\how/long\path.txt", "txt")]
|
||||
[Arguments(@"C:\foo.bar\how/long/path.txt", "txt")]
|
||||
[Arguments(@"C:\foo.bar\how\long/path.txt", "txt")]
|
||||
[Arguments(@"\\?\C:\foo\bar", "")]
|
||||
[Arguments(@"C:\foo\bar", "")]
|
||||
[Arguments(@"C:\foo\bar\", "")]
|
||||
[Arguments(@"\\?\C:\foo\", "")]
|
||||
[Arguments(@"C:\foo", "")]
|
||||
[Arguments(@"C:\foo\", "")]
|
||||
[Arguments("create.jar.diSAbled", "disabled")]
|
||||
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", "zip")]
|
||||
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", "zip")]
|
||||
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", "zip")]
|
||||
[Arguments("https://foo.bar/file/page.xaml.vb?arg=1", "vb")]
|
||||
[Arguments("https://foo.bar/file/long/pack.ZIP?arg=1", "zip")]
|
||||
[Arguments("https://foo.bar/file/", "")]
|
||||
[Arguments("https://foo.bar/file/?arg=1", "")]
|
||||
[Arguments("https://foo.bar/file?arg=1", "")]
|
||||
public async Task 路径处理_GetExtension(string input, string expected)
|
||||
=> await Assert.That(PathUtils.GetExtension(input)).IsEqualTo(expected);
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
@@ -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.GetIncreasing()).IsEqualTo(0.5);
|
||||
continueSecond.SetResult(null);
|
||||
var results = await whenAll;
|
||||
await Assert.That(string.Join(",", results)).IsEqualTo("1,2");
|
||||
await Assert.That(progress.GetIncreasing()).IsEqualTo(1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
// 此文件主体由 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(() => RefreshCurrentOwner(reference)), 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 not null) {
|
||||
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;
|
||||
|
||||
// 重新从窗口根元素命中测试,避免弹窗出现后 Mouse.DirectlyOver 尚未刷新,继续命中已被遮挡的旧元素。
|
||||
if (PresentationSource.FromVisual(reference)?.RootVisual is UIElement root) {
|
||||
var rootHit = root.InputHitTest(Mouse.GetPosition(root)) as DependencyObject;
|
||||
owner = FindOwnerInAncestors(rootHit);
|
||||
if (owner is not null) return owner;
|
||||
if (rootHit is not null && !IsSameTreeBranch(rootHit, reference)) return null;
|
||||
}
|
||||
|
||||
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;
|
||||
// 禁用控件由原生 ToolTipOpening 确认命中,无法通过常规 InputHitTest 可靠地重新定位。
|
||||
if (owner.IsEnabled && !ReferenceEquals(owner, FindCurrentTooltipOwner(owner))) {
|
||||
Close(false);
|
||||
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,8 +1,9 @@
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace MeloongCore.Wpf.Extensions;
|
||||
public static class WpfExtensions {
|
||||
|
||||
public static bool Any(this UIElementCollection? Arr) => Arr?.Count > 0;
|
||||
public static bool Any(this UIElementCollection? arr)
|
||||
=> arr?.Count > 0;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace MeloongCore.Wpf;
|
||||
|
||||
public static class Dialogs {
|
||||
|
||||
/// <summary>
|
||||
/// 弹出 “保存” 弹窗,返回用户指定的路径,若取消则返回 <c>null</c>。
|
||||
/// <para/> <paramref name="filter"/> 中的扩展名不加 <c>.</c>。
|
||||
/// </summary>
|
||||
public static string? SaveFile(string title, string defaultFileName = "", string? defaultDirectory = null, IEnumerable<(string Extension, string Display)>? filter = null) {
|
||||
var filters = filter?.ToList();
|
||||
var dialog = new SaveFileDialog {
|
||||
AddExtension = true,
|
||||
Title = title,
|
||||
FileName = defaultFileName
|
||||
};
|
||||
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!);
|
||||
if (filters is not null) {
|
||||
dialog.Filter = filters.Select(f => $"{f.Display}(*.{f.Extension})|*.{f.Extension}").Join("|");
|
||||
}
|
||||
|
||||
Logger.Info($"保存弹窗:{dialog.Title}(FileName={dialog.FileName}, InitialDirectory={dialog.InitialDirectory}, Filter={dialog.Filter})");
|
||||
if (dialog.ShowDialog() != true) return null;
|
||||
|
||||
var result = dialog.FileName;
|
||||
Logger.Info($"保存弹窗返回:{result}");
|
||||
if (!result.Contains(Path.DirectorySeparatorChar)) return null;
|
||||
// AddExtension 可能失效,需要手动补全(#8214)
|
||||
if (filters != null && !string.IsNullOrEmpty(result) && !filters.Any(f => result.EndsWithF("." + f.Extension, true))) {
|
||||
result += "." + filters[dialog.FilterIndex - 1].Extension;
|
||||
Logger.Warn($"选择文件的返回无扩展名,将会手动添加,修改后为:{result}");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 弹出 “选择文件” 弹窗,返回用户选择的文件路径,若取消则返回空数组。
|
||||
/// <para/> 若使用扩展名 <paramref name="filter"/>,则扩展名不加 <c>.</c>。
|
||||
/// </summary>
|
||||
public static List<string> SelectFile(string title, bool multiselect, string? defaultDirectory = null, OneOf<IEnumerable<(string[] Extensions, string Display)>, string>? filter = null) {
|
||||
var dialog = new OpenFileDialog {
|
||||
AddExtension = true,
|
||||
CheckFileExists = true,
|
||||
Multiselect = multiselect,
|
||||
Title = title,
|
||||
ValidateNames = true
|
||||
};
|
||||
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!);
|
||||
if (filter is not null) {
|
||||
if (filter.Value.Is<string>()) {
|
||||
dialog.Filter = filter.Value.As<string>();
|
||||
} else {
|
||||
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})");
|
||||
if (dialog.ShowDialog() != true) return [];
|
||||
|
||||
var results = dialog.FileNames.Where(f => f.Contains(Path.DirectorySeparatorChar)).ToList();
|
||||
Logger.Info($"选择文件弹窗返回:{results.Join(",")}");
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 弹出 “选择文件夹” 弹窗,返回用户选择的文件夹路径(以分隔符结尾),若取消则返回空数组。
|
||||
/// </summary>
|
||||
public static List<string> SelectFolder(string title, bool multiselect, string? defaultDirectory = null) {
|
||||
var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog {
|
||||
ShowNewFolderButton = true,
|
||||
Description = title,
|
||||
Multiselect = multiselect,
|
||||
UseDescriptionForTitle = true
|
||||
};
|
||||
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.SelectedPath = defaultDirectory;
|
||||
|
||||
Logger.Info($"选择文件夹弹窗:{dialog.Description}(Multiselect={dialog.Multiselect}, SelectedPath={dialog.SelectedPath})");
|
||||
if (dialog.ShowDialog() != true) return [];
|
||||
|
||||
var results = dialog.SelectedPaths.Where(f => f.Contains(Path.DirectorySeparatorChar)).Select(PathUtils.AddSlashSuffix).ToList();
|
||||
Logger.Info($"选择文件夹弹窗返回:{results.Join(",")}");
|
||||
return results;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace MeloongCore.Wpf;
|
||||
|
||||
/// <summary>
|
||||
/// 对数据绑定进行加法运算,使用 <paramref name="parameter"/> 决定加数。
|
||||
/// </summary>
|
||||
public class AdditionConverter : IValueConverter {
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return 0;
|
||||
if (!double.TryParse(value.ToString(), out double before)) return 0;
|
||||
double scale = 1;
|
||||
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
|
||||
return before + scale;
|
||||
}
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return Binding.DoNothing;
|
||||
if (!double.TryParse(value.ToString(), out double before)) return Binding.DoNothing;
|
||||
double scale = 1;
|
||||
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
|
||||
return before - scale;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对数据绑定进行乘法运算,使用 <paramref name="parameter"/> 决定乘数。
|
||||
/// </summary>
|
||||
public class MultiplicationConverter : IValueConverter {
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return 0;
|
||||
if (!double.TryParse(value.ToString(), out double before)) return 0;
|
||||
double scale = 1;
|
||||
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
|
||||
return before * scale;
|
||||
}
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return Binding.DoNothing;
|
||||
if (!double.TryParse(value.ToString(), out double before)) return Binding.DoNothing;
|
||||
double scale = 1;
|
||||
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
|
||||
if (scale == 0) return Binding.DoNothing;
|
||||
return before / scale;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将取反的 <see cref="bool"/> 绑定到 <see cref="Visibility"/>。
|
||||
/// </summary>
|
||||
public class InverseBooleanToVisibilityConverter : IValueConverter {
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return Visibility.Visible;
|
||||
return bool.TryParse(value.ToString(), out bool boolValue) ? (boolValue ? Visibility.Collapsed : Visibility.Visible) : Visibility.Visible;
|
||||
}
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return false;
|
||||
return value is Visibility vis && vis != Visibility.Visible;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 <see cref="bool"/> 取反。
|
||||
/// </summary>
|
||||
public class InverseBooleanConverter : IValueConverter {
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return false;
|
||||
return bool.TryParse(value.ToString(), out bool boolValue) ? !boolValue : false;
|
||||
}
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
|
||||
if (value is null) return false;
|
||||
return bool.TryParse(value.ToString(), out bool boolValue) ? !boolValue : false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace MeloongCore.Wpf;
|
||||
public static class Main {
|
||||
|
||||
public static void Init() {
|
||||
ModernTooltipService.Init();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
@@ -15,6 +15,8 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="PolySharp" Version="1.15.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
@@ -25,10 +27,13 @@
|
||||
<Using Include="System.Diagnostics.CodeAnalysis" />
|
||||
<Using Include="System.Collections" />
|
||||
<Using Include="System.Collections.Generic" />
|
||||
<Using Include="System.Collections.Concurrent" />
|
||||
<Using Include="System.Text" />
|
||||
<Using Include="System.Net" />
|
||||
<Using Include="System.Runtime.CompilerServices" />
|
||||
<Using Include="System.Runtime.InteropServices" />
|
||||
<Using Include="Newtonsoft.Json" />
|
||||
<Using Include="Newtonsoft.Json.Linq" />
|
||||
<Using Include="MeloongCore" />
|
||||
<Using Include="MeloongCore.Extensions" />
|
||||
</ItemGroup>
|
||||
@@ -38,7 +43,10 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="PresentationFramework" />
|
||||
<Reference Include="System.Xaml" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Security.Principal;
|
||||
using System.Security.Principal;
|
||||
|
||||
namespace MeloongCore;
|
||||
public static class SystemUtils {
|
||||
public static class WindowsUtils {
|
||||
|
||||
/// <summary>
|
||||
/// 当前程序是否拥有管理员权限。
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"test": {
|
||||
"runner": "Microsoft.Testing.Platform"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user