Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -0,0 +1,88 @@
|
|||||||
|
# MeloongCore 项目架构
|
||||||
|
|
||||||
|
[返回 MeloongCore 仓库指示](../仓库指示.md)
|
||||||
|
|
||||||
|
## 1. 项目定位
|
||||||
|
|
||||||
|
`MeloongCore/Shared/MeloongCore.csproj` 是通用 C# 基础库,目标框架为 .NET Standard 2.0,使用 C# 13、Nullable、Implicit Usings 和 PolySharp。
|
||||||
|
|
||||||
|
它属于独立 Git 仓库,不应依赖具体上层应用或 WPF。其目标是为 Windows、macOS 及不同上层应用提供一致的基础能力。
|
||||||
|
|
||||||
|
## 2. 目录结构
|
||||||
|
|
||||||
|
```text
|
||||||
|
MeloongCore/Shared/
|
||||||
|
├─ Main.cs # 库初始化与应用名
|
||||||
|
├─ Extensions/ # 集合、字符串、异常、任务和网络扩展
|
||||||
|
├─ General/
|
||||||
|
│ ├─ Config.cs # JSON 配置抽象
|
||||||
|
│ ├─ Logger.cs # 日志抽象
|
||||||
|
│ ├─ Progress.cs # 进度模型
|
||||||
|
│ ├─ Worker/ # 限流与可重做 Worker
|
||||||
|
│ └─ 其他通用数据结构
|
||||||
|
└─ Utils/ # 文件、目录、路径、任务、网络、加密等工具
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. 主要能力
|
||||||
|
|
||||||
|
### 3.1 文件与路径
|
||||||
|
|
||||||
|
`FileUtils`、`DirectoryUtils` 和 `PathUtils` 封装文件读写、压缩包、目录遍历、路径标准化和父子关系判断,供不同上层应用复用。
|
||||||
|
|
||||||
|
### 3.2 异步与 Worker
|
||||||
|
|
||||||
|
- `TaskUtils` 提供程序执行、并发遍历、聚合等待等通用任务能力;
|
||||||
|
- `ProgressProvider` 支持切分与聚合子进度;
|
||||||
|
- `RateLimitedWorker` 合并或限制高频调用;
|
||||||
|
- `RedoableWorker` 管理可重做的异步工作。
|
||||||
|
|
||||||
|
上层应用可以按需使用这些抽象组织异步任务与进度。
|
||||||
|
|
||||||
|
### 3.3 配置
|
||||||
|
|
||||||
|
`IConfigProvider` 定义读、写、删除、缓存丢弃等能力。默认 `JsonConfigProvider`:
|
||||||
|
|
||||||
|
- 从 JSON 文件惰性读取;
|
||||||
|
- 缓存反序列化后的值;
|
||||||
|
- 通过 Worker 延迟 500 ms 合并写盘;
|
||||||
|
- 使用 `ConfigEntry<T>` 提供固定 provider 的强类型配置;
|
||||||
|
- 使用 `DynamicConfigEntry<T>` 支持运行时选择 provider。
|
||||||
|
|
||||||
|
默认配置位于应用数据目录的 `config.json`,敏感配置 provider 指向 `secret.json`。加密写入目前仍有未实现分支,使用前需要核对现状。
|
||||||
|
|
||||||
|
### 3.4 日志与通用类型
|
||||||
|
|
||||||
|
库提供可替换的 Logger、并发列表、OneOf、值范围、数学和字符串工具等。上层应用可以替换 Logger 实例,将底层日志接入自身日志系统。
|
||||||
|
|
||||||
|
## 4. 依赖
|
||||||
|
|
||||||
|
- `Microsoft.Win32.Registry`:跨目标框架暴露注册表能力;
|
||||||
|
- `Newtonsoft.Json`:配置与 JSON 工具;
|
||||||
|
- `ThrottleDebounce`:限流/防抖基础;
|
||||||
|
- `PolySharp`:为旧运行目标补足现代 C# 编译支持。
|
||||||
|
|
||||||
|
## 5. 架构边界
|
||||||
|
|
||||||
|
适合放入 MeloongCore 的代码应满足:
|
||||||
|
|
||||||
|
- 不依赖具体上层应用的页面、全局状态或业务领域;
|
||||||
|
- 不直接依赖 WPF 类型;
|
||||||
|
- API 对其他 .NET 应用也有合理含义;
|
||||||
|
- Windows 专属能力被清楚隔离,不阻塞 macOS 使用通用部分。
|
||||||
|
|
||||||
|
WPF 特有实现应进入 `MeloongCore.Wpf`,上层应用特有实现应保留在对应应用仓库中。
|
||||||
|
|
||||||
|
## 6. 优势与风险
|
||||||
|
|
||||||
|
优势:
|
||||||
|
|
||||||
|
- 目标框架和依赖方向支持跨项目复用;
|
||||||
|
- 工具与配置已有对应测试;
|
||||||
|
- 现代 C# API 提高了新代码的类型安全和可读性。
|
||||||
|
|
||||||
|
风险:
|
||||||
|
|
||||||
|
- 通用工具类较多,新增 API 时容易形成重复或过宽的职责;
|
||||||
|
- 注册表等 Windows 能力出现在 Shared 中,需要保持调用层面的平台防护;
|
||||||
|
- `JsonConfigProvider` 加密写入尚未实现完整;
|
||||||
|
- 作为公共依赖修改时,需要考虑已有引用方的兼容性和独立发布节奏。
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# MeloongCore.Tests 项目架构
|
||||||
|
|
||||||
|
[返回 MeloongCore 仓库指示](../仓库指示.md)
|
||||||
|
|
||||||
|
## 1. 项目定位
|
||||||
|
|
||||||
|
`MeloongCore/Tests/MeloongCore.Tests.csproj` 是基于 TUnit 的 .NET Framework 4.8 测试程序,同时引用 `MeloongCore` 与 `MeloongCore.Wpf`。
|
||||||
|
|
||||||
|
它主要保护通用基础库,不覆盖引用本库的上层应用业务。
|
||||||
|
|
||||||
|
## 2. 测试范围
|
||||||
|
|
||||||
|
| 测试文件 | 覆盖能力 |
|
||||||
|
| --- | --- |
|
||||||
|
| `General/ConfigTest.cs` | JSON 配置读写、默认值与缓存 |
|
||||||
|
| `General/ProgressTest.cs` | 进度切分与聚合 |
|
||||||
|
| `General/WorkerTest.cs` | Worker 调度、限流或重做语义 |
|
||||||
|
| `Utils/CryptographyUtilsTest.cs` | 加密工具 |
|
||||||
|
| `Utils/DirectoryUtilsTest.cs` | 目录操作 |
|
||||||
|
| `Utils/FileUtilsTest.cs` | 文件与压缩包处理 |
|
||||||
|
| `Utils/PathUtilsTest.cs` | 路径规范化和关系判断 |
|
||||||
|
| `Utils/TaskUtilsTest.cs` | 异步任务与进程能力 |
|
||||||
|
| `TestUtils.cs` | 测试公共支持 |
|
||||||
|
|
||||||
|
`TestFiles/FileUtils` 中包含正常、损坏、不同编码和恶意路径的压缩包样本,用于验证 Zip Slip 等边界。
|
||||||
|
|
||||||
|
## 3. 项目特点
|
||||||
|
|
||||||
|
- 输出类型为 `Exe`,由 TUnit 测试运行机制执行;
|
||||||
|
- 测试资源复制到输出目录;
|
||||||
|
- 同时引用 WPF 层,因此可以覆盖少量 WPF 相关基础能力。
|
||||||
|
|
||||||
|
## 4. 测试缺口
|
||||||
|
|
||||||
|
当前测试主要集中于 Shared 的通用工具、配置、进度与 Worker,Wpf 层的平台行为覆盖仍较少。
|
||||||
|
|
||||||
|
## 5. 建议
|
||||||
|
|
||||||
|
测试范围应保持在 MeloongCore 的公共行为内:
|
||||||
|
|
||||||
|
1. 保持本项目只测试 MeloongCore 与 WPF 适配层;
|
||||||
|
2. 上层应用的业务测试由对应应用仓库维护;
|
||||||
|
3. 新增公共能力时,优先补充与其行为和平台边界相对应的测试。
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# MeloongCore.Wpf 项目架构
|
||||||
|
|
||||||
|
[返回 MeloongCore 仓库指示](../仓库指示.md)
|
||||||
|
|
||||||
|
## 1. 项目定位
|
||||||
|
|
||||||
|
`MeloongCore/Wpf/MeloongCore.Wpf.csproj` 是 MeloongCore 的 WPF/Windows 适配层,面向 .NET Framework 4.8,依赖 `MeloongCore`。
|
||||||
|
|
||||||
|
它的存在使 Shared 项目无需引用 WPF,同时让多个上层 WPF 应用复用窗口、对话框、转换器与 Windows API 封装。
|
||||||
|
|
||||||
|
## 2. 源码组成
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
| --- | --- |
|
||||||
|
| `Main.cs` | WPF 层初始化 |
|
||||||
|
| `Controls/ModernTooltipService.cs` | 现代化 ToolTip 行为 |
|
||||||
|
| `Extensions/WpfExtensions.cs` | WPF 对象和控件扩展 |
|
||||||
|
| `General/Dialogs.cs` | 文件、文件夹和消息对话框封装 |
|
||||||
|
| `General/ValueConverters.cs` | WPF Binding 值转换器 |
|
||||||
|
| `Utils/WindowsUtils.cs` | Windows 权限、窗口和系统相关工具 |
|
||||||
|
|
||||||
|
## 3. 依赖
|
||||||
|
|
||||||
|
- `MeloongCore`;
|
||||||
|
- WPF 的 `PresentationCore`、`PresentationFramework`、`System.Xaml`;
|
||||||
|
- `System.Windows.Forms`,用于部分 Windows UI 互操作;
|
||||||
|
- `Ookii.Dialogs.Wpf`;
|
||||||
|
- `Newtonsoft.Json` 与 PolySharp。
|
||||||
|
|
||||||
|
## 4. 架构边界
|
||||||
|
|
||||||
|
此项目适合承载“可被多个 WPF 应用复用”的平台代码,例如:
|
||||||
|
|
||||||
|
- WPF 控件扩展和附加行为;
|
||||||
|
- 通用值转换器;
|
||||||
|
- Windows 窗口与权限操作;
|
||||||
|
- 文件夹选择等系统对话框。
|
||||||
|
|
||||||
|
它不适合承载:
|
||||||
|
|
||||||
|
- 特定上层应用的控件外观或页面逻辑;
|
||||||
|
- 具体应用的领域业务;
|
||||||
|
- 只被一个调用点使用的小型包装;
|
||||||
|
- 可以留在 Shared 的纯 .NET 逻辑。
|
||||||
|
|
||||||
|
## 5. 维护关注点
|
||||||
|
|
||||||
|
- 本项目承载 Windows/WPF 特有能力,而 Shared 仍需考虑 macOS;平台 API 必须留在本项目或明确受保护的代码路径中。
|
||||||
|
- `System.Windows.Forms` 与 WPF 混用时要注意 DPI、窗口句柄和线程模型。
|
||||||
|
- 该项目由多个上层应用和 Tests 引用,公共 API 变更影响面较大。
|
||||||
|
- 应避免把具体上层应用的全局日志、设置或窗口实例反向引入本项目。
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# MeloongCore 仓库指示
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
- 使用 C# 13、Nullable、Implicit Usings 和 PolySharp。
|
||||||
|
- `Shared` 面向 .NET Standard 2.0,不依赖 WPF。
|
||||||
|
- `Wpf` 与 `Tests` 面向 .NET Framework 4.8。
|
||||||
|
- 保持现代、清晰的 C# 写法,但不做过度抽象、优化或防御性检查。
|
||||||
|
- 简化类结构,少留空行,但保留必要的注释。
|
||||||
|
- 修改已有代码时优先保持最小改动,并删除修改后确定无用的内容。
|
||||||
|
- 不添加只有一两行的小型辅助方法;仅有一个引用的方法或变量应积极考虑内联。
|
||||||
|
|
||||||
|
## C# 代码风格
|
||||||
|
|
||||||
|
- 大括号不换行;变量名使用小驼峰,类型、属性和方法名使用大驼峰。
|
||||||
|
- 没有 `else`、逻辑较短且仅含一条语句的 `if` 写在一行并省略大括号,例如 `if (flag) break;`;`if` 一旦换行,必须添加大括号。
|
||||||
|
- 单行大括号内的内容前后不加空格,例如 `{element}`。
|
||||||
|
- 行尾注释与代码之间、`//` 与注释正文之间各留一个空格,例如 `break; // 注释`。XML 文档注释引用参数时使用 `<paramref name="..."/>`。
|
||||||
|
- 优先使用 C# 13 下更简洁且清晰的写法,例如 using 声明、本地函数和集合表达式。
|
||||||
|
- 使用 `""` 表示空字符串,不使用 `string.Empty`。
|
||||||
|
|
||||||
|
## 项目边界
|
||||||
|
|
||||||
|
- `Shared` 只存放可跨产品复用的通用能力,不得依赖具体上层应用的业务领域或 UI 页面。
|
||||||
|
- Windows 与 WPF 特有功能优先放入 `Wpf`,避免破坏 Shared 的 macOS 可用性。
|
||||||
|
- `Tests` 负责保护 Shared 与 Wpf 的公共行为,不应反向依赖引用本库的上层应用项目。
|
||||||
|
- 新增工具前先检查现有 Extensions、General 和 Utils,避免重复实现。
|
||||||
|
- 公共 API 会影响所有引用方,修改签名或语义前应检查兼容性。
|
||||||
|
|
||||||
|
## 仓库安全
|
||||||
|
|
||||||
|
- MeloongCore 是独立 Git 仓库,提交内容不得依赖特定引用方的私有目录结构或开发流程。
|
||||||
|
- 构建 WPF 工程时使用 Visual Studio 2022 的 `MSBuild.exe`。
|
||||||
|
- 保留用户已有的未提交修改,不覆盖或清理无关文件。
|
||||||
|
- 不提交密钥、访问令牌、构建产物、测试结果或本地环境文件。
|
||||||
+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,15 @@
|
|||||||
|
# Agents 指南
|
||||||
|
|
||||||
|
本仓库的详细开发指示保存在 `.agents` 目录中。
|
||||||
|
|
||||||
|
## 基础环境
|
||||||
|
|
||||||
|
- 使用中文沟通。
|
||||||
|
- 通用代码需要同时考虑 Windows 与 macOS;平台特有代码必须保持明确边界。
|
||||||
|
- 文本文件统一使用 UTF-8 无 BOM(代码页 65001)。使用 Windows PowerShell 读取或写入文本时必须显式指定 `-Encoding UTF8`。
|
||||||
|
|
||||||
|
处理本仓库内容前,必须完整读取并遵循:
|
||||||
|
|
||||||
|
- [MeloongCore 仓库指示](.agents/仓库指示.md)
|
||||||
|
|
||||||
|
该文件是本仓库规则的组成部分,不是可选参考资料。若指示文件无法读取,应先向用户说明,不得自行猜测或忽略缺失的规则。
|
||||||
@@ -254,7 +254,7 @@ public static class EnumerableExtensions {
|
|||||||
isFirst = false;
|
isFirst = false;
|
||||||
else
|
else
|
||||||
builder.Append(split);
|
builder.Append(split);
|
||||||
if (element is not null) builder.Append(element.ToString());
|
if (element is not null) builder.Append(element);
|
||||||
}
|
}
|
||||||
return builder.ToString();
|
return builder.ToString();
|
||||||
}
|
}
|
||||||
@@ -318,6 +318,13 @@ public static class EnumerableExtensions {
|
|||||||
foreach (var item in itemsToRemove) source.Remove(item);
|
foreach (var item in itemsToRemove) source.Remove(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从集合中移除另一个集合中的所有元素。
|
||||||
|
/// </summary>
|
||||||
|
public static void RemoveAll<T>(this ICollection<T> source, IEnumerable<T> itemsToRemove) {
|
||||||
|
foreach (var item in itemsToRemove) source.Remove(item);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 仅保留满足条件的元素,移除不满足条件的元素。
|
/// 仅保留满足条件的元素,移除不满足条件的元素。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -37,6 +37,12 @@ public static class StringExtensions {
|
|||||||
public static bool ContainsIgnoreCase(this string value, string subString)
|
public static bool ContainsIgnoreCase(this string value, string subString)
|
||||||
=> value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
|
=> value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 非区域性的 <see cref="string.Contains(string)"/>。
|
||||||
|
/// </summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static bool ContainsF(this string? value, string subString, bool ignoreCase = false)
|
||||||
|
=> value?.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 非区域性的 <see cref="string.IndexOf(string)"/>。
|
/// 非区域性的 <see cref="string.IndexOf(string)"/>。
|
||||||
@@ -134,7 +140,7 @@ public static class StringExtensions {
|
|||||||
/// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
|
/// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
|
||||||
/// <code>"2024/11-08".BeforeFirstOfAny(["/", "-"]) => "2024"</code>
|
/// <code>"2024/11-08".BeforeFirstOfAny(["/", "-"]) => "2024"</code>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string BeforeFirstOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
|
public static string BeforeFirstOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||||
if (texts == null) return str;
|
if (texts == null) return str;
|
||||||
int pos = -1;
|
int pos = -1;
|
||||||
foreach (string text in texts) {
|
foreach (string text in texts) {
|
||||||
@@ -159,7 +165,7 @@ public static class StringExtensions {
|
|||||||
/// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
|
/// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
|
||||||
/// <code>"2024/11-08".BeforeLastOfAny(["/", "-"]) => "2024/11"</code>
|
/// <code>"2024/11-08".BeforeLastOfAny(["/", "-"]) => "2024/11"</code>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string BeforeLastOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
|
public static string BeforeLastOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||||
if (texts == null) return str;
|
if (texts == null) return str;
|
||||||
int pos = -1;
|
int pos = -1;
|
||||||
foreach (string text in texts) {
|
foreach (string text in texts) {
|
||||||
@@ -175,8 +181,8 @@ public static class StringExtensions {
|
|||||||
/// 获取在子字符串第一次出现之后的部分,如果未找到子字符串则不裁切。
|
/// 获取在子字符串第一次出现之后的部分,如果未找到子字符串则不裁切。
|
||||||
/// <code>"2024/11/08".AfterFirst("/") => "11/08"</code>
|
/// <code>"2024/11/08".AfterFirst("/") => "11/08"</code>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string AfterFirst(this string str, string text, bool ignoreCase = false) {
|
public static string AfterFirst(this string str, string? text, bool ignoreCase = false) {
|
||||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
|
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
|
||||||
if (pos < 0) return str;
|
if (pos < 0) return str;
|
||||||
return str[(pos + text!.Length)..];
|
return str[(pos + text!.Length)..];
|
||||||
}
|
}
|
||||||
@@ -184,7 +190,7 @@ public static class StringExtensions {
|
|||||||
/// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
|
/// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
|
||||||
/// <code>"2024/11-08".AfterFirstOfAny(["/", "-"]) => "11-08"</code>
|
/// <code>"2024/11-08".AfterFirstOfAny(["/", "-"]) => "11-08"</code>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string AfterFirstOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
|
public static string AfterFirstOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||||
if (texts == null) return str;
|
if (texts == null) return str;
|
||||||
int pos = -1;
|
int pos = -1;
|
||||||
int len = 0;
|
int len = 0;
|
||||||
@@ -204,8 +210,8 @@ public static class StringExtensions {
|
|||||||
/// 获取在子字符串最后一次出现之后的部分,如果未找到子字符串则不裁切。
|
/// 获取在子字符串最后一次出现之后的部分,如果未找到子字符串则不裁切。
|
||||||
/// <code>"2024/11/08".AfterLast("/") => "08"</code>
|
/// <code>"2024/11/08".AfterLast("/") => "08"</code>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string AfterLast(this string str, string text, bool ignoreCase = false) {
|
public static string AfterLast(this string str, string? text, bool ignoreCase = false) {
|
||||||
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
|
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
|
||||||
if (pos < 0) return str;
|
if (pos < 0) return str;
|
||||||
return str[(pos + text!.Length)..];
|
return str[(pos + text!.Length)..];
|
||||||
}
|
}
|
||||||
@@ -213,7 +219,7 @@ public static class StringExtensions {
|
|||||||
/// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
|
/// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
|
||||||
/// <code>"2024/11-08".AfterLastOfAny(["/", "-"]) => "08"</code>
|
/// <code>"2024/11-08".AfterLastOfAny(["/", "-"]) => "08"</code>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string AfterLastOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
|
public static string AfterLastOfAny(this string str, IEnumerable<string>? texts, bool ignoreCase = false) {
|
||||||
if (texts == null) return str;
|
if (texts == null) return str;
|
||||||
int pos = -1;
|
int pos = -1;
|
||||||
int len = 0;
|
int len = 0;
|
||||||
@@ -407,8 +413,7 @@ public static class StringExtensions {
|
|||||||
throw new FormatException("JSON deserialize failed: " +
|
throw new FormatException("JSON deserialize failed: " +
|
||||||
(length > 2000
|
(length > 2000
|
||||||
? $"{data![..500]}...(total {length} characters)...{data[^500..]}"
|
? $"{data![..500]}...(total {length} characters)...{data[^500..]}"
|
||||||
: (data ?? "")),
|
: (data ?? "")), ex);
|
||||||
ex);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ namespace MeloongCore;
|
|||||||
/// 使用粗粒度锁的线程安全 <see cref="List{T}"/> 实现。
|
/// 使用粗粒度锁的线程安全 <see cref="List{T}"/> 实现。
|
||||||
/// 通常建议使用 <see cref="ConcurrentBag{T}"/> 或其他线程安全集合,它们具有更好的性能。
|
/// 通常建议使用 <see cref="ConcurrentBag{T}"/> 或其他线程安全集合,它们具有更好的性能。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> {
|
public class ConcurrentList<T> : IList<T>, IList {
|
||||||
|
|
||||||
private readonly List<T> _items = [];
|
private readonly List<T> _items = [];
|
||||||
|
|
||||||
|
|||||||
+103
-44
@@ -1,7 +1,8 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
namespace MeloongCore;
|
namespace MeloongCore;
|
||||||
|
|
||||||
|
#region ConfigProvider | 配置提供器
|
||||||
|
|
||||||
public interface IConfigProvider {
|
public interface IConfigProvider {
|
||||||
void Set<T>(string key, T? value, bool encrypted);
|
void Set<T>(string key, T? value, bool encrypted);
|
||||||
void Remove(string key);
|
void Remove(string key);
|
||||||
@@ -14,10 +15,12 @@ public class JsonConfigProvider : IConfigProvider {
|
|||||||
public static readonly ConcurrentBag<WeakReference<JsonConfigProvider>> allProviders = [];
|
public static readonly ConcurrentBag<WeakReference<JsonConfigProvider>> allProviders = [];
|
||||||
private readonly string filePath;
|
private readonly string filePath;
|
||||||
|
|
||||||
|
#pragma warning disable CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 'required' 修饰符或声明为可以为 null。
|
||||||
public JsonConfigProvider(string filePath) {
|
public JsonConfigProvider(string filePath) {
|
||||||
|
#pragma warning restore CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑添加 'required' 修饰符或声明为可以为 null。
|
||||||
this.filePath = filePath;
|
this.filePath = filePath;
|
||||||
allProviders.Add(new(this));
|
allProviders.Add(new(this));
|
||||||
saveAction = Throttler.Throttle(Save, TimeSpan.FromMilliseconds(500), leading: false, trailing: true);
|
saveWorker = new(Save, 500, RateLimitMode.WaitUnillNoNewInvoke);
|
||||||
InitJson();
|
InitJson();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,8 +51,8 @@ public class JsonConfigProvider : IConfigProvider {
|
|||||||
} else if (encrypted) {
|
} else if (encrypted) {
|
||||||
// 需要加密,在 JSON 中保存密文字符串
|
// 需要加密,在 JSON 中保存密文字符串
|
||||||
throw new NotImplementedException("加密需要改为使用识别码,现在尚未实现。");
|
throw new NotImplementedException("加密需要改为使用识别码,现在尚未实现。");
|
||||||
Logger.Trace($"配置已修改:{key} = 已加密({filePath})");
|
// Logger.Trace($"配置已修改:{key} = 已加密({filePath})");
|
||||||
json.Value[key] = CryptographyUtils.AesEncrypt(value is string str ? str : JsonConvert.SerializeObject(value));
|
// json.Value[key] = CryptographyUtils.AesEncrypt(value is string str ? str : JsonConvert.SerializeObject(value));
|
||||||
} else {
|
} else {
|
||||||
// 用 JToken 保留原始结构
|
// 用 JToken 保留原始结构
|
||||||
JToken token = JToken.FromObject(value);
|
JToken token = JToken.FromObject(value);
|
||||||
@@ -100,11 +103,11 @@ public class JsonConfigProvider : IConfigProvider {
|
|||||||
|
|
||||||
// ===================================== 保存 =====================================
|
// ===================================== 保存 =====================================
|
||||||
|
|
||||||
private readonly RateLimitedAction saveAction;
|
private readonly RateLimitedWorker saveWorker;
|
||||||
private bool isDirty = false;
|
private bool isDirty = false;
|
||||||
public void MakeDirty() {
|
public void MakeDirty() {
|
||||||
isDirty = true;
|
isDirty = true;
|
||||||
saveAction.Invoke();
|
saveWorker.Start();
|
||||||
}
|
}
|
||||||
public void Save() {
|
public void Save() {
|
||||||
if (!isDirty) return;
|
if (!isDirty) return;
|
||||||
@@ -113,60 +116,116 @@ public class JsonConfigProvider : IConfigProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ConfigUtils {
|
public static class ConfigProviders {
|
||||||
public static readonly JsonConfigProvider AppData = new(Path.Combine(Paths.AppDataThenName, "config.json"));
|
public static JsonConfigProvider Default = new(Path.Combine(Paths.AppDataThenName, "config.json"));
|
||||||
|
public static readonly JsonConfigProvider Secret = new(Path.Combine(Paths.AppData, "secret.json"));
|
||||||
/// <summary>
|
|
||||||
/// 立即保存所有配置。
|
|
||||||
/// </summary>
|
|
||||||
public static void SaveAll() {
|
|
||||||
foreach (var weakRef in JsonConfigProvider.allProviders) {
|
|
||||||
if (weakRef.TryGetTarget(out var provider)) provider.Save();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。
|
|
||||||
/// </summary>
|
|
||||||
public static string GetSecret(string key)
|
|
||||||
=> secret.Read<string>(key, null, false) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
|
|
||||||
private static readonly JsonConfigProvider secret = new(Path.Combine(Paths.AppData, "secret.json"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ConfigEntry<T>(string key, T? defaultValue, IConfigProvider? defaultProvider = null, bool encrypted = false) {
|
#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;
|
||||||
|
|
||||||
public IConfigProvider DefaultProvider => defaultProvider ?? ConfigUtils.AppData;
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 当设置项的值被改变时触发,参数为新值。新值可能和旧值相同。
|
/// 当调整配置项的值时触发,参数为新值。<para/>新值可能和旧值相同。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event Action<T?, IConfigProvider>? Changed;
|
public event Action<T?>? Changed;
|
||||||
|
/// <summary>
|
||||||
|
/// 当获取配置项的值时触发。
|
||||||
|
/// </summary>
|
||||||
|
public event Action<PreviewGetEventArgs<T>, IConfigProvider>? PreviewGet;
|
||||||
|
|
||||||
public void Edit(Func<T?, T?> editFunc, IConfigProvider? providerOverride = null) {
|
public void Edit(Func<T?, T?> editFunc) => Set(editFunc(Get()));
|
||||||
var provider = providerOverride ?? DefaultProvider;
|
public void Edit(RefAction editAction) {
|
||||||
Set(editFunc(Get(provider)), provider);
|
var current = Get();
|
||||||
|
editAction(ref current);
|
||||||
|
Set(current);
|
||||||
}
|
}
|
||||||
public void Edit(RefAction editAction, IConfigProvider? providerOverride = null) {
|
public delegate void RefAction(ref T? value);
|
||||||
var provider = providerOverride ?? DefaultProvider;
|
|
||||||
|
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);
|
var current = Get(provider);
|
||||||
editAction(ref current);
|
editAction(ref current);
|
||||||
Set(current, provider);
|
Set(current, provider);
|
||||||
}
|
}
|
||||||
public delegate void RefAction(ref T? value);
|
public delegate void RefAction(ref T? value);
|
||||||
|
|
||||||
public void Set(T? value, IConfigProvider? providerOverride = null) {
|
public void Set(T? value, IConfigProvider provider) {
|
||||||
var provider = providerOverride ?? DefaultProvider;
|
|
||||||
provider.Set(key, value, encrypted);
|
provider.Set(key, value, encrypted);
|
||||||
Changed?.Invoke(value, provider);
|
Changed?.Invoke(value);
|
||||||
}
|
}
|
||||||
public void Reset(IConfigProvider? providerOverride = null) {
|
public void Reset(IConfigProvider provider) {
|
||||||
var provider = providerOverride ?? DefaultProvider;
|
|
||||||
if (!provider.HasValue(key)) return; // 值未设置,无需重置
|
if (!provider.HasValue(key)) return; // 值未设置,无需重置
|
||||||
provider.Remove(key);
|
provider.Remove(key);
|
||||||
Changed?.Invoke(defaultValue, provider);
|
Changed?.Invoke(defaultValue);
|
||||||
}
|
}
|
||||||
public T? Get(IConfigProvider? providerOverride = null)
|
public T? Get(IConfigProvider provider) {
|
||||||
=> (providerOverride ?? DefaultProvider).Read(key, defaultValue, encrypted);
|
PreviewGetEventArgs<T> args = new(provider.Read(key, defaultValue, encrypted));
|
||||||
public bool HasValue(IConfigProvider? providerOverride = null)
|
PreviewGet?.Invoke(args, provider);
|
||||||
=> (providerOverride ?? DefaultProvider).HasValue(key);
|
return args.Value;
|
||||||
public static implicit operator T?(ConfigEntry<T> entry) => entry.Get();
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。</summary>
|
||||||
|
public static string GetSecret(string key)
|
||||||
|
=> ConfigProviders.Secret.Read<string>(key, null, false) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
|
||||||
|
|
||||||
}
|
}
|
||||||
+14
-15
@@ -122,12 +122,12 @@ public static class Logger {
|
|||||||
public ref struct LogInterpolatedStringHandler {
|
public ref struct LogInterpolatedStringHandler {
|
||||||
private StringBuilder? _sb;
|
private StringBuilder? _sb;
|
||||||
public readonly bool isEnabled;
|
public readonly bool isEnabled;
|
||||||
public LogInterpolatedStringHandler(int literalLength, int formattedCount, LogLevel level, out bool isEnabled) {
|
public LogInterpolatedStringHandler(int literalLength, LogLevel level, out bool isEnabled) {
|
||||||
this.isEnabled = isEnabled = Logger.Instance.MinLevel <= level;
|
this.isEnabled = isEnabled = Logger.Instance.MinLevel <= level;
|
||||||
_sb = this.isEnabled ? new StringBuilder(literalLength) : null;
|
_sb = this.isEnabled ? new StringBuilder(literalLength) : null;
|
||||||
}
|
}
|
||||||
public void AppendLiteral(string value) => _sb?.Append(value);
|
public void AppendLiteral(string value) => _sb?.Append(value);
|
||||||
public void AppendFormatted<T>(T value) => _sb?.Append(value?.ToString());
|
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, string? format) => _sb?.Append(value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString());
|
||||||
public void AppendFormatted<T>(T value, int alignment) {
|
public void AppendFormatted<T>(T value, int alignment) {
|
||||||
if (_sb is null) return;
|
if (_sb is null) return;
|
||||||
@@ -156,7 +156,7 @@ public static class Logger {
|
|||||||
public ref struct LogInterpolatedStringHandler<TLevel> where TLevel : struct, ILogLevelProvider {
|
public ref struct LogInterpolatedStringHandler<TLevel> where TLevel : struct, ILogLevelProvider {
|
||||||
private LogInterpolatedStringHandler _inner;
|
private LogInterpolatedStringHandler _inner;
|
||||||
public bool IsEnabled => _inner.isEnabled;
|
public bool IsEnabled => _inner.isEnabled;
|
||||||
public LogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) => _inner = new(literalLength, formattedCount, default(TLevel).Level, out 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 AppendLiteral(string value) => _inner.AppendLiteral(value);
|
||||||
public void AppendFormatted<T>(T value) => _inner.AppendFormatted(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, string? format) => _inner.AppendFormatted(value, format);
|
||||||
@@ -202,7 +202,7 @@ public class BaseLogger {
|
|||||||
(message is null ? "" : $"{message}:") + ex.GetDisplay(true);
|
(message is null ? "" : $"{message}:") + ex.GetDisplay(true);
|
||||||
formattedMessage = Format(formattedMessage, level, filePath, ex);
|
formattedMessage = Format(formattedMessage, level, filePath, ex);
|
||||||
// 将格式化后的日志文本置入缓冲区
|
// 将格式化后的日志文本置入缓冲区
|
||||||
if (avaliable || queue.Count < 100) { // 在初始化前保留至多 100 条日志
|
if (available || queue.Count < 100) { // 在初始化前保留至多 100 条日志
|
||||||
queue.Enqueue(new(level, formattedMessage));
|
queue.Enqueue(new(level, formattedMessage));
|
||||||
queuedEvent.Set();
|
queuedEvent.Set();
|
||||||
}
|
}
|
||||||
@@ -247,27 +247,23 @@ public class BaseLogger {
|
|||||||
|
|
||||||
#region 缓冲区与初始化
|
#region 缓冲区与初始化
|
||||||
|
|
||||||
internal volatile bool avaliable = false;
|
internal volatile bool available = false;
|
||||||
public record struct LogEntry(LogLevel Level, string message);
|
public record struct LogEntry(LogLevel Level, string message);
|
||||||
internal readonly ConcurrentQueue<LogEntry> queue = new();
|
internal readonly ConcurrentQueue<LogEntry> queue = new();
|
||||||
internal readonly AutoResetEvent queuedEvent = new(false);
|
internal readonly AutoResetEvent queuedEvent = new(false);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 初始化此 Logger。
|
|
||||||
/// 会在新线程中,将之前的日志文件依次后移,最多保留 5 个文件。
|
|
||||||
/// </summary>
|
|
||||||
public BaseLogger() {
|
public BaseLogger() {
|
||||||
var thread = new Thread(() => {
|
var thread = new Thread(() => {
|
||||||
try {
|
try {
|
||||||
Init();
|
Init();
|
||||||
avaliable = true;
|
available = true;
|
||||||
Logger.Info($"{GetType().Name} 日志初始化结束");
|
Logger.Info($"{GetType().Name} 日志初始化结束");
|
||||||
while (avaliable) {
|
while (available) {
|
||||||
queuedEvent.WaitOne();
|
queuedEvent.WaitOne();
|
||||||
Flush();
|
Flush();
|
||||||
}
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
avaliable = false;
|
available = false;
|
||||||
Logger.SendToDebug(ex, "基础日志线程出错");
|
Logger.SendToDebug(ex, "基础日志线程出错");
|
||||||
}
|
}
|
||||||
}) { Name = nameof(Logger), Priority = ThreadPriority.Lowest, IsBackground = true };
|
}) { Name = nameof(Logger), Priority = ThreadPriority.Lowest, IsBackground = true };
|
||||||
@@ -280,7 +276,7 @@ public class BaseLogger {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void Flush() {
|
public void Flush() {
|
||||||
try {
|
try {
|
||||||
if (!avaliable) return;
|
if (!available) return;
|
||||||
lock (flushLock) {
|
lock (flushLock) {
|
||||||
while (queue.TryDequeue(out LogEntry entry)) Output(entry); // writer 指定了 AutoFlush
|
while (queue.TryDequeue(out LogEntry entry)) Output(entry); // writer 指定了 AutoFlush
|
||||||
}
|
}
|
||||||
@@ -305,7 +301,10 @@ public class FileLogger : BaseLogger, IDisposable {
|
|||||||
public string fileNameSuffix = ".txt";
|
public string fileNameSuffix = ".txt";
|
||||||
private StreamWriter? writer;
|
private StreamWriter? writer;
|
||||||
|
|
||||||
/// <inheritdoc/>
|
/// <summary>
|
||||||
|
/// 初始化此 Logger。
|
||||||
|
/// 会在新线程中,将之前的日志文件依次后移,最多保留 5 个文件。
|
||||||
|
/// </summary>
|
||||||
public override void Init() {
|
public override void Init() {
|
||||||
// 轮转日志文件,将 Log1.txt 留空
|
// 轮转日志文件,将 Log1.txt 留空
|
||||||
Logger.Info("开始轮转日志文件");
|
Logger.Info("开始轮转日志文件");
|
||||||
@@ -335,7 +334,7 @@ public class FileLogger : BaseLogger, IDisposable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose() {
|
public void Dispose() {
|
||||||
avaliable = false;
|
available = false;
|
||||||
if (writer is not null) ((IDisposable) writer).Dispose();
|
if (writer is not null) ((IDisposable) writer).Dispose();
|
||||||
queuedEvent.Dispose();
|
queuedEvent.Dispose();
|
||||||
GC.SuppressFinalize(this);
|
GC.SuppressFinalize(this);
|
||||||
|
|||||||
@@ -159,16 +159,18 @@ public class ProgressProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool IsFinished => GetRaw().actual + GetRaw().skiped > 0.9999999;
|
||||||
|
|
||||||
private (double actual, double skiped) observedProgress = (0, 0);
|
private (double actual, double skiped) observedProgress = (0, 0);
|
||||||
private double incrementProgress = 0;
|
private double incrementProgress = 0;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取一个在多次观测之间必定单调递增的进度值,范围为 [0, 1]。
|
/// 获取一个在多次观测之间必定单调递增的进度值,范围为 [0, 1]。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public double GetIncrement() {
|
public double GetIncreasing() {
|
||||||
lock (this) {
|
lock (this) {
|
||||||
(double actual, double skiped) current = GetRaw();
|
(double actual, double skiped) current = GetRaw();
|
||||||
if (current == observedProgress) return incrementProgress; // 未改变
|
if (current == observedProgress) return incrementProgress; // 未改变
|
||||||
if (current.actual + current.skiped > 0.9999999) { // 已完成
|
if (IsFinished) { // 已完成
|
||||||
incrementProgress = 1;
|
incrementProgress = 1;
|
||||||
} else if (current.actual >= observedProgress.actual) { // 进度增加
|
} else if (current.actual >= observedProgress.actual) { // 进度增加
|
||||||
incrementProgress += (1 - incrementProgress) *
|
incrementProgress += (1 - incrementProgress) *
|
||||||
@@ -197,7 +199,7 @@ public class ProgressObserver : RateLimitedWorker {
|
|||||||
}
|
}
|
||||||
private void StartObserver((double actual, double skiped) raw) => Start();
|
private void StartObserver((double actual, double skiped) raw) => Start();
|
||||||
private static void Observe(ProgressProvider provider, Action<double> updateAction) {
|
private static void Observe(ProgressProvider provider, Action<double> updateAction) {
|
||||||
double progress = provider.GetIncrement();
|
double progress = provider.GetIncreasing();
|
||||||
// TODO: 添加平缓过渡
|
// TODO: 添加平缓过渡
|
||||||
updateAction(progress);
|
updateAction(progress);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ public sealed class ValueRange<T>(
|
|||||||
T? lower, T? upper,
|
T? lower, T? upper,
|
||||||
bool isLowerInclusive, bool isUpperInclusive,
|
bool isLowerInclusive, bool isUpperInclusive,
|
||||||
bool hasLower, bool hasUpper
|
bool hasLower, bool hasUpper
|
||||||
) : IEquatable<ValueRange<T>?> where T : notnull, IComparable<T> {
|
) : IEquatable<ValueRange<T>?> where T : IComparable<T> {
|
||||||
|
|
||||||
#region 基础字段
|
#region 基础字段
|
||||||
|
|
||||||
@@ -129,7 +129,7 @@ public sealed class ValueRange<T>(
|
|||||||
/// 取当前范围与另一个范围的交集。
|
/// 取当前范围与另一个范围的交集。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns> 若两个范围存在交集,则返回交集范围;否则返回 <see langword="null" />。 </returns>
|
/// <returns> 若两个范围存在交集,则返回交集范围;否则返回 <see langword="null" />。 </returns>
|
||||||
public ValueRange<T>? Intersect(ValueRange<T> other) {
|
public ValueRange<T> Intersect(ValueRange<T> other) {
|
||||||
T? lower = default;
|
T? lower = default;
|
||||||
T? upper = default;
|
T? upper = default;
|
||||||
var isLowerInclusive = true;
|
var isLowerInclusive = true;
|
||||||
@@ -200,12 +200,12 @@ public sealed class ValueRange<T>(
|
|||||||
}
|
}
|
||||||
public override int GetHashCode() {
|
public override int GetHashCode() {
|
||||||
int hashCode = 169504101;
|
int hashCode = 169504101;
|
||||||
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(Lower);
|
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(lower);
|
||||||
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(Upper);
|
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(upper);
|
||||||
hashCode=hashCode*-1521134295+HasLower.GetHashCode();
|
hashCode=hashCode*-1521134295+hasLower.GetHashCode();
|
||||||
hashCode=hashCode*-1521134295+HasUpper.GetHashCode();
|
hashCode=hashCode*-1521134295+hasUpper.GetHashCode();
|
||||||
hashCode=hashCode*-1521134295+IsLowerInclusive.GetHashCode();
|
hashCode=hashCode*-1521134295+isLowerInclusive.GetHashCode();
|
||||||
hashCode=hashCode*-1521134295+IsUpperInclusive.GetHashCode();
|
hashCode=hashCode*-1521134295+isUpperInclusive.GetHashCode();
|
||||||
return hashCode;
|
return hashCode;
|
||||||
}
|
}
|
||||||
#pragma warning disable CS8604 // 引用类型参数可能为 null。
|
#pragma warning disable CS8604 // 引用类型参数可能为 null。
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@ public class RateLimitedWorker(Action workload, double minimalIntervalMs, RateLi
|
|||||||
private readonly RateLimitedAction action = mode switch {
|
private readonly RateLimitedAction action = mode switch {
|
||||||
RateLimitMode.ImmediateThenMerge => Throttler.Throttle(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: true),
|
RateLimitMode.ImmediateThenMerge => Throttler.Throttle(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: true),
|
||||||
RateLimitMode.WaitUnillNoNewInvoke => Debouncer.Debounce(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: false, trailing: true),
|
RateLimitMode.WaitUnillNoNewInvoke => Debouncer.Debounce(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: false, trailing: true),
|
||||||
RateLimitMode.ImmediateThenIgnore => Debouncer.Debounce(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: false)
|
_ => Debouncer.Debounce(workload, TimeSpan.FromMilliseconds(minimalIntervalMs), leading: true, trailing: false)
|
||||||
};
|
};
|
||||||
|
|
||||||
public void Start() {
|
public void Start() {
|
||||||
File renamed without changes.
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>netstandard2.0</TargetFramework>
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
@@ -15,10 +15,13 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<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">
|
<PackageReference Include="PolySharp" Version="1.15.0">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="ThrottleDebounce" Version="2.0.2" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -36,15 +39,6 @@
|
|||||||
<Using Include="MeloongCore.Extensions" />
|
<Using Include="MeloongCore.Extensions" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Reference Include="ThrottleDebounce">
|
|
||||||
<HintPath>..\..\Plain Craft Launcher 2\Resources\ThrottleDebounce.dll</HintPath>
|
|
||||||
</Reference>
|
|
||||||
<Reference Include="Newtonsoft.Json">
|
|
||||||
<HintPath>..\..\Plain Craft Launcher 2\Resources\Newtonsoft.Json.dll</HintPath>
|
|
||||||
</Reference>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
<DefineConstants>$(DefineConstants);SNAPSHOT</DefineConstants>
|
<DefineConstants>$(DefineConstants);SNAPSHOT</DefineConstants>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|||||||
@@ -68,10 +68,10 @@ public static class DirectoryUtils {
|
|||||||
public static void Copy(string sourceFolder, string destFolder) {
|
public static void Copy(string sourceFolder, string destFolder) {
|
||||||
sourceFolder = PathUtils.ForCompare(sourceFolder);
|
sourceFolder = PathUtils.ForCompare(sourceFolder);
|
||||||
destFolder = PathUtils.ForCompare(destFolder);
|
destFolder = PathUtils.ForCompare(destFolder);
|
||||||
if (string.Compare(sourceFolder, destFolder, ignoreCase: false) == 0) {
|
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
|
||||||
// 复制自身到自身,则不执行操作
|
// 复制自身到自身,则不执行操作
|
||||||
Logger.Trace($"复制文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
Logger.Trace($"复制文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
||||||
} else if (string.Compare(sourceFolder, destFolder, ignoreCase: true) == 0) {
|
} else if (string.Compare(sourceFolder, destFolder, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||||
// 路径仅大小写不同,等效于重命名
|
// 路径仅大小写不同,等效于重命名
|
||||||
Logger.Trace($"复制文件夹到自身,但大小写不同,等效于重命名文件夹:{sourceFolder} → {destFolder}");
|
Logger.Trace($"复制文件夹到自身,但大小写不同,等效于重命名文件夹:{sourceFolder} → {destFolder}");
|
||||||
DirectoryUtils.Move(sourceFolder, destFolder);
|
DirectoryUtils.Move(sourceFolder, destFolder);
|
||||||
@@ -90,10 +90,10 @@ public static class DirectoryUtils {
|
|||||||
SafetyCheck(sourceFolder);
|
SafetyCheck(sourceFolder);
|
||||||
sourceFolder = PathUtils.ForCompare(sourceFolder);
|
sourceFolder = PathUtils.ForCompare(sourceFolder);
|
||||||
destFolder = PathUtils.ForCompare(destFolder);
|
destFolder = PathUtils.ForCompare(destFolder);
|
||||||
if (string.Compare(sourceFolder, destFolder, ignoreCase: false) == 0) {
|
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
|
||||||
// 剪切自身到自身,则不执行操作
|
// 剪切自身到自身,则不执行操作
|
||||||
Logger.Trace($"剪切文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
Logger.Trace($"剪切文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
||||||
} else if (string.Compare(sourceFolder, destFolder, ignoreCase: true) == 0) {
|
} else if (string.Compare(sourceFolder, destFolder, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||||
// 路径仅大小写不同
|
// 路径仅大小写不同
|
||||||
Logger.Trace($"剪切文件夹到自身,但大小写不同:{sourceFolder} → {destFolder}");
|
Logger.Trace($"剪切文件夹到自身,但大小写不同:{sourceFolder} → {destFolder}");
|
||||||
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFolder), Path.GetRandomFileName());
|
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFolder), Path.GetRandomFileName());
|
||||||
@@ -169,7 +169,7 @@ public static class DirectoryUtils {
|
|||||||
folder = PathUtils.ForCompare(folder);
|
folder = PathUtils.ForCompare(folder);
|
||||||
if (folder == PathUtils.ForCompare(Path.GetPathRoot(folder)))
|
if (folder == PathUtils.ForCompare(Path.GetPathRoot(folder)))
|
||||||
throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}");
|
throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}");
|
||||||
if (criticalFolders.Value.Any(f => PathUtils.IsParentOf(f, folder)))
|
if (criticalFolders.Value.Any(f => PathUtils.IsParentOf(folder, f)))
|
||||||
throw new UnauthorizedAccessException($"不应操作文件夹:{folder}");
|
throw new UnauthorizedAccessException($"不应操作文件夹:{folder}");
|
||||||
}
|
}
|
||||||
private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] {
|
private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] {
|
||||||
|
|||||||
+44
-22
@@ -69,6 +69,12 @@ public static class FileUtils {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static JToken? ReadAsJson(string filePath, Encoding? encoding = null, Type? type = null)
|
public static JToken? ReadAsJson(string filePath, Encoding? encoding = null, Type? type = null)
|
||||||
=> FileUtils.ReadAsString(filePath, encoding, type).DeserializeJson();
|
=> 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
|
#endregion
|
||||||
|
|
||||||
@@ -114,7 +120,7 @@ public static class FileUtils {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 创建文件,并打开 <see cref="FileStream"/>。
|
/// 创建文件,并打开 <see cref="FileMode.Create"/> 模式的 <see cref="FileStream"/>。
|
||||||
/// 若文件已存在,则会覆盖原文件。
|
/// 若文件已存在,则会覆盖原文件。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static FileStream CreateAsStream(string filePath) {
|
public static FileStream CreateAsStream(string filePath) {
|
||||||
@@ -133,6 +139,17 @@ public static class FileUtils {
|
|||||||
=> Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
|
=> Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, func: _
|
||||||
=> Path.GetTempFileName());
|
=> 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
|
#endregion
|
||||||
|
|
||||||
#region 复制 / 剪切
|
#region 复制 / 剪切
|
||||||
@@ -145,10 +162,10 @@ public static class FileUtils {
|
|||||||
public static void Copy(string sourceFilePath, string destFilePath) {
|
public static void Copy(string sourceFilePath, string destFilePath) {
|
||||||
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
||||||
destFilePath = PathUtils.ForCompare(destFilePath);
|
destFilePath = PathUtils.ForCompare(destFilePath);
|
||||||
if (string.Compare(sourceFilePath, destFilePath, ignoreCase:false) == 0) {
|
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
|
||||||
// 复制自身到自身,则不执行操作
|
// 复制自身到自身,则不执行操作
|
||||||
Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
||||||
} else if (string.Compare(sourceFilePath, destFilePath, ignoreCase:true) == 0) {
|
} else if (string.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||||
// 路径仅大小写不同,等效于重命名
|
// 路径仅大小写不同,等效于重命名
|
||||||
Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
|
Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
|
||||||
FileUtils.Move(sourceFilePath, destFilePath);
|
FileUtils.Move(sourceFilePath, destFilePath);
|
||||||
@@ -169,10 +186,10 @@ public static class FileUtils {
|
|||||||
public static void Move(string sourceFilePath, string destFilePath) {
|
public static void Move(string sourceFilePath, string destFilePath) {
|
||||||
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
||||||
destFilePath = PathUtils.ForCompare(destFilePath);
|
destFilePath = PathUtils.ForCompare(destFilePath);
|
||||||
if (string.Compare(sourceFilePath, destFilePath, ignoreCase: false) == 0) {
|
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
|
||||||
// 剪切自身到自身,则不执行操作
|
// 剪切自身到自身,则不执行操作
|
||||||
Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
||||||
} else if (string.Compare(sourceFilePath, destFilePath, ignoreCase: true) == 0) {
|
} else if (string.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||||
// 路径仅大小写不同
|
// 路径仅大小写不同
|
||||||
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
|
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
|
||||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||||
@@ -239,6 +256,7 @@ public static class FileUtils {
|
|||||||
try {
|
try {
|
||||||
var iid = typeof(IShellItem).GUID;
|
var iid = typeof(IShellItem).GUID;
|
||||||
Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.RemoveExtendedPrefix(target), 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 = (IFileOperation) new FileOperation();
|
||||||
op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
|
op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
|
||||||
op.DeleteItem(item, IntPtr.Zero);
|
op.DeleteItem(item, IntPtr.Zero);
|
||||||
@@ -307,7 +325,7 @@ public static class FileUtils {
|
|||||||
/// 以只读模式打开压缩文件。
|
/// 以只读模式打开压缩文件。
|
||||||
/// 会先尝试 UTF8 编码,失败后换用 GB18030 编码。
|
/// 会先尝试 UTF8 编码,失败后换用 GB18030 编码。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static ZipArchive OpenZip(string zipFilePath) {
|
public static ZipArchive OpenZip(string zipFilePath, CancellationToken c = default) {
|
||||||
ZipArchive TryOpen(Encoding encoding) {
|
ZipArchive TryOpen(Encoding encoding) {
|
||||||
Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
|
Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
|
||||||
var result = ZipFile.Open(PathUtils.ForApi(zipFilePath), ZipArchiveMode.Read, encoding);
|
var result = ZipFile.Open(PathUtils.ForApi(zipFilePath), ZipArchiveMode.Read, encoding);
|
||||||
@@ -319,23 +337,26 @@ public static class FileUtils {
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
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));
|
try { // 尝试两种编码
|
||||||
} catch (DecoderFallbackException) {
|
return TryOpen(new UTF8Encoding(false, true));
|
||||||
return TryOpen(Encoding.GetEncoding("GB18030"));
|
} catch (DecoderFallbackException) {
|
||||||
|
return TryOpen(Encoding.GetEncoding("GB18030"));
|
||||||
|
}
|
||||||
|
} catch (InvalidDataException ex) {
|
||||||
|
throw new InvalidDataException($"文件不是压缩包,或者文件已损坏({zipFilePath})", ex);
|
||||||
}
|
}
|
||||||
} catch (InvalidDataException ex) {
|
});
|
||||||
throw new InvalidDataException($"文件不是压缩包,或者文件已损坏({zipFilePath})", ex);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
|
/// 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
|
||||||
/// 会自动创建文件夹。会覆盖已有文件,但不会删除多余文件。
|
/// 会自动创建文件夹。会覆盖已有文件,但不会删除多余文件。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="progressHandler">参数为已完成的总比例(0~1)。</param>
|
/// <param name="p">参数为已完成的总比例(0~1)。</param>
|
||||||
public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressHandler = null) {
|
public static void ExtractToDirectory(string compressionFile, string outputDirectory, CancellationToken c = default, ProgressProvider? p = null) {
|
||||||
compressionFile = PathUtils.ForApi(compressionFile);
|
compressionFile = PathUtils.ForApi(compressionFile);
|
||||||
DirectoryUtils.Create(outputDirectory);
|
DirectoryUtils.Create(outputDirectory);
|
||||||
// 解压 gz(gz 不需要考虑编码)
|
// 解压 gz(gz 不需要考虑编码)
|
||||||
@@ -345,18 +366,19 @@ public static class FileUtils {
|
|||||||
using var fileStream = FileUtils.ReadAsStream(compressionFile);
|
using var fileStream = FileUtils.ReadAsStream(compressionFile);
|
||||||
using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
|
using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
|
||||||
FileUtils.Write(outFilePath, gzipStream);
|
FileUtils.Write(outFilePath, gzipStream);
|
||||||
progressHandler?.Invoke(1);
|
p?.Finish();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 解压 zip
|
// 解压 zip
|
||||||
using var archive = FileUtils.OpenZip(compressionFile);
|
using var archive = FileUtils.OpenZip(compressionFile, c);
|
||||||
int totalCount = archive.Entries.Count;
|
var entries = archive.Entries.Where(e => !string.IsNullOrEmpty(e.Name)).ToList(); // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
|
||||||
|
int totalCount = entries.Count;
|
||||||
int doneCount = 0;
|
int doneCount = 0;
|
||||||
Logger.Trace($"解压 zip 文件:{compressionFile} → {outputDirectory}(共 {totalCount} 项)");
|
Logger.Trace($"解压 zip 文件:{compressionFile} → {outputDirectory}(共 {totalCount} 项)");
|
||||||
foreach (var entry in archive.Entries) {
|
foreach (var entry in entries) {
|
||||||
|
c.ThrowIfCancellationRequested();
|
||||||
doneCount++;
|
doneCount++;
|
||||||
if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount);
|
if (totalCount > 0) p?.Set((double) doneCount / totalCount);
|
||||||
if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
|
|
||||||
// ZipSlip 修复
|
// ZipSlip 修复
|
||||||
string outputFilePath = Path.Combine(outputDirectory, entry.FullName);
|
string outputFilePath = Path.Combine(outputDirectory, entry.FullName);
|
||||||
if (!PathUtils.IsParentOf(outputDirectory, outputFilePath))
|
if (!PathUtils.IsParentOf(outputDirectory, outputFilePath))
|
||||||
|
|||||||
@@ -109,4 +109,52 @@ public static class MathUtils {
|
|||||||
return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1);
|
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);
|
||||||
|
|
||||||
}
|
}
|
||||||
+76
-18
@@ -23,36 +23,94 @@ public static class PathUtils {
|
|||||||
/// 若路径较长,则尽量将其转换为短路径。
|
/// 若路径较长,则尽量将其转换为短路径。
|
||||||
/// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
|
/// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string ToShortPath(string pathName, bool keepFileName = false) {
|
public static string ToShortPath(string pathName) {
|
||||||
if (string.IsNullOrEmpty(pathName)) return pathName;
|
if (string.IsNullOrEmpty(pathName)) return pathName;
|
||||||
if (!pathName.Contains(":")) return pathName;
|
if (!pathName.Contains(":")) return pathName;
|
||||||
if (pathName.Length <= 200) return pathName;
|
if (pathName.Length <= 220) return pathName; // 快速返回
|
||||||
pathName = PathUtils.ForCompare(pathName);
|
pathName = PathUtils.ForCompare(pathName);
|
||||||
// 保留文件名
|
// 尽量保留原始文件名
|
||||||
string pathToKeep = "";
|
string pathToKeep = "";
|
||||||
string pathToShorten = pathName;
|
string pathToShorten = pathName;
|
||||||
if (pathName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
|
if (FileUtils.Exists(pathName)) {
|
||||||
if (keepFileName && FileUtils.Exists(pathName)) {
|
var fileName = PathUtils.GetLastPart(pathName);
|
||||||
pathToKeep = PathUtils.GetLastPart(pathName);
|
if (fileName.Length >= 180) {
|
||||||
pathToShorten = PathUtils.RemoveLastPart(pathName);
|
Logger.Warn($"文件名过长,将为文件名生成短路径:{pathName}", LogBehavior.None); // 部分程序,例如 Forge 的模块加载,依赖于读取文件名进行判断,因此对文件名生成短路径是有风险的
|
||||||
|
} else {
|
||||||
|
pathToKeep = fileName;
|
||||||
|
pathToShorten = PathUtils.RemoveLastPart(pathName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
|
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
|
||||||
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
|
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
|
||||||
string parentPath = Path.GetDirectoryName(pathToShorten);
|
string? parentPath = Path.GetDirectoryName(pathToShorten);
|
||||||
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return pathName; // 已经到达根目录,全都不存在,直接返回
|
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return pathName; // 已经到达根目录,全都不存在,直接返回
|
||||||
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
|
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
|
||||||
pathToShorten = parentPath;
|
pathToShorten = parentPath;
|
||||||
}
|
}
|
||||||
if (pathToShorten.Length <= 10) return pathName;
|
if (pathToKeep.Length >= 200) {
|
||||||
// 实际缩短路径
|
Logger.Warn($"路径中的大部分内容都尚未建立,无法在内容不存在时缩短路径:{pathName} → {pathToShorten}", LogBehavior.None);
|
||||||
char[] buffer = new char[260];
|
return pathName;
|
||||||
int result = GetShortPathNameW(PathUtils.ForApi(pathToShorten), buffer, buffer.Length);
|
}
|
||||||
if (result == 0) return pathName;
|
// 获取短路径
|
||||||
string shortPath = new(buffer, 0, result);
|
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)));
|
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)]
|
[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>
|
/// <summary>
|
||||||
/// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。
|
/// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。
|
||||||
@@ -93,10 +151,10 @@ public static class PathUtils {
|
|||||||
/// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
|
/// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
|
||||||
/// </code></summary>
|
/// </code></summary>
|
||||||
public static string RemoveLastPart(string pathName) {
|
public static string RemoveLastPart(string pathName) {
|
||||||
if (pathName!.Contains("://")) { // 网络路径
|
if (pathName.Contains("://")) { // 网络路径
|
||||||
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
|
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
|
||||||
}
|
}
|
||||||
return PathUtils.RemoveSlashSuffix(pathName!).BeforeLastOfAny([@"\", "/"]);
|
return PathUtils.RemoveSlashSuffix(pathName).BeforeLastOfAny([@"\", "/"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -108,7 +166,7 @@ public static class PathUtils {
|
|||||||
/// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip"
|
/// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip"
|
||||||
/// </code></summary>
|
/// </code></summary>
|
||||||
public static string GetLastPart(string pathName) {
|
public static string GetLastPart(string pathName) {
|
||||||
if (pathName!.Contains("://")) { // 网络路径
|
if (pathName.Contains("://")) { // 网络路径
|
||||||
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
|
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
|
||||||
} else { // 文件路径
|
} else { // 文件路径
|
||||||
pathName = PathUtils.RemoveSlashSuffix(pathName);
|
pathName = PathUtils.RemoveSlashSuffix(pathName);
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Globalization;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
namespace MeloongCore;
|
namespace MeloongCore;
|
||||||
@@ -68,7 +69,7 @@ public static class StringUtils {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
public static string FormUrlEscape(string value)
|
public static string FormUrlEscape(string value)
|
||||||
=> WebUtility.UrlEncode(value);
|
=> WebUtility.UrlEncode(value)!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 表单去转义。
|
/// 表单去转义。
|
||||||
@@ -107,14 +108,14 @@ public static class StringUtils {
|
|||||||
if (byteSize < 1000) { // B 级
|
if (byteSize < 1000) { // B 级
|
||||||
return $"{sign}{byteSize} B";
|
return $"{sign}{byteSize} B";
|
||||||
} else if (byteSize < 1024 * 1000) { // K 级
|
} else if (byteSize < 1024 * 1000) { // K 级
|
||||||
var roundResult = Math.Round(byteSize / 1024D).ToString();
|
var roundResult = Math.Round(byteSize / 1024D).ToString(CultureInfo.InvariantCulture);
|
||||||
return $"{sign}{Math.Round(byteSize / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} K";
|
return $"{sign}{Math.Round(byteSize / 1024D, (3 - roundResult.Length).Clamp(0, 2))} K";
|
||||||
} else if (byteSize < 1024 * 1024 * 1000) { // M 级
|
} else if (byteSize < 1024 * 1024 * 1000) { // M 级
|
||||||
var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString();
|
var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
|
||||||
return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} M";
|
return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} M";
|
||||||
} else { // G 级
|
} else { // G 级
|
||||||
var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString();
|
var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
|
||||||
return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} G";
|
return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} G";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public static class TaskUtils {
|
|||||||
}
|
}
|
||||||
// 实际分割
|
// 实际分割
|
||||||
var progressEach = 1d / taskList.Count;
|
var progressEach = 1d / taskList.Count;
|
||||||
return Task.WhenAll(taskList.Select(async (task, index) => {
|
return Task.WhenAll(taskList.Select(async (task, _) => {
|
||||||
var cp = progress?.SplitBy(progressEach)[0];
|
var cp = progress?.SplitBy(progressEach)[0];
|
||||||
await task(cp).NoCapture();
|
await task(cp).NoCapture();
|
||||||
cp?.Finish();
|
cp?.Finish();
|
||||||
@@ -31,7 +31,7 @@ public static class TaskUtils {
|
|||||||
}
|
}
|
||||||
// 实际分割
|
// 实际分割
|
||||||
var progressEach = 1d / taskList.Count;
|
var progressEach = 1d / taskList.Count;
|
||||||
return Task.WhenAll(taskList.Select(async (task, index) => {
|
return Task.WhenAll(taskList.Select(async (task, _) => {
|
||||||
var cp = progress?.SplitBy(progressEach)[0];
|
var cp = progress?.SplitBy(progressEach)[0];
|
||||||
var result = await task(cp).NoCapture();
|
var result = await task(cp).NoCapture();
|
||||||
cp?.Finish();
|
cp?.Finish();
|
||||||
@@ -94,7 +94,9 @@ public static class TaskUtils {
|
|||||||
RedirectStandardOutput = true, StandardOutputEncoding = encoding,
|
RedirectStandardOutput = true, StandardOutputEncoding = encoding,
|
||||||
RedirectStandardError = true, StandardErrorEncoding = encoding
|
RedirectStandardError = true, StandardErrorEncoding = encoding
|
||||||
};
|
};
|
||||||
using var program = new Process { StartInfo = info, EnableRaisingEvents = true };
|
using var program = new Process();
|
||||||
|
program.StartInfo = info;
|
||||||
|
program.EnableRaisingEvents = true;
|
||||||
if (!program.Start()) throw new InvalidOperationException($"运行程序时出现意外错误:{file} {arguments}");
|
if (!program.Start()) throw new InvalidOperationException($"运行程序时出现意外错误:{file} {arguments}");
|
||||||
bool hasTimeout = timeoutMs is > 0;
|
bool hasTimeout = timeoutMs is > 0;
|
||||||
Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}");
|
Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}");
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public class ProgressTest : TestBase {
|
|||||||
progress.Set(0.75, skiped: true);
|
progress.Set(0.75, skiped: true);
|
||||||
|
|
||||||
await Assert.That(changedCount).IsEqualTo(2);
|
await Assert.That(changedCount).IsEqualTo(2);
|
||||||
await Assert.That(Math.Abs(progress.GetIncrement() - 2.0 / 3) < 0.000001).IsTrue();
|
await Assert.That(Math.Abs(progress.GetIncreasing() - 2.0 / 3) < 0.000001).IsTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
|
|||||||
@@ -75,6 +75,18 @@ public class DirectoryUtilsTest : TestWithFolder {
|
|||||||
public void 剪切_安全检查()
|
public void 剪切_安全检查()
|
||||||
=> Assert.Throws<UnauthorizedAccessException>(() => DirectoryUtils.Move(Paths.Base, Path.Combine(tempFolder, "SafetyCheckDest")));
|
=> Assert.Throws<UnauthorizedAccessException>(() => DirectoryUtils.Move(Paths.Base, Path.Combine(tempFolder, "SafetyCheckDest")));
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task 删除_安全检查_允许程序目录下的子文件夹() {
|
||||||
|
var folder = Path.Combine(Paths.Base, $"MeloongTest_{Guid.NewGuid():N}");
|
||||||
|
try {
|
||||||
|
DirectoryUtils.Create(folder);
|
||||||
|
DirectoryUtils.Delete(folder);
|
||||||
|
await Assert.That(DirectoryUtils.Exists(folder)).IsFalse();
|
||||||
|
} finally {
|
||||||
|
if (Directory.Exists(PathUtils.ForApi(folder))) Directory.Delete(PathUtils.ForApi(folder), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -7,10 +7,10 @@ public class FileUtilsTest : TestWithFolder {
|
|||||||
[Arguments("GB Encoding.zip")]
|
[Arguments("GB Encoding.zip")]
|
||||||
[Arguments("UTF8 Encoding.zip")]
|
[Arguments("UTF8 Encoding.zip")]
|
||||||
public async Task 解压_ReadZip(string testFile) {
|
public async Task 解压_ReadZip(string testFile) {
|
||||||
double progress = 0;
|
|
||||||
string output = Path.Combine(tempFolder, "Extracted");
|
string output = Path.Combine(tempFolder, "Extracted");
|
||||||
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
|
var p = new ProgressProvider();
|
||||||
await Assert.That(progress).IsEqualTo(1);
|
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, "文件夹"))).IsTrue();
|
||||||
await Assert.That(DirectoryUtils.Exists(Path.Combine(output, "空文件夹"))).IsFalse();
|
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, "fabricloader.log")))).Contains("FabricLoader");
|
||||||
@@ -20,10 +20,10 @@ public class FileUtilsTest : TestWithFolder {
|
|||||||
[Test]
|
[Test]
|
||||||
[Arguments("GZ.gz", "LTCat")]
|
[Arguments("GZ.gz", "LTCat")]
|
||||||
public async Task 解压_ReadGz(string testFile, string containsText) {
|
public async Task 解压_ReadGz(string testFile, string containsText) {
|
||||||
double progress = 0;
|
|
||||||
string output = Path.Combine(tempFolder, "Extracted");
|
string output = Path.Combine(tempFolder, "Extracted");
|
||||||
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
|
var p = new ProgressProvider();
|
||||||
await Assert.That(progress).IsEqualTo(1);
|
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);
|
await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, PathUtils.GetFileNameWithoutExtension(testFile))))).Contains(containsText);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,40 @@
|
|||||||
namespace MeloongCore.Tests;
|
namespace MeloongCore.Tests;
|
||||||
public class PathUtilsTests : TestBase {
|
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 路径处理
|
#region 路径处理
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
|
|||||||
@@ -21,11 +21,11 @@ public class TaskUtilsTest : TestBase {
|
|||||||
], progress);
|
], progress);
|
||||||
|
|
||||||
await Assert.That(ReferenceEquals(firstProgress, secondProgress)).IsFalse();
|
await Assert.That(ReferenceEquals(firstProgress, secondProgress)).IsFalse();
|
||||||
await Assert.That(progress.GetIncrement()).IsEqualTo(0.5);
|
await Assert.That(progress.GetIncreasing()).IsEqualTo(0.5);
|
||||||
continueSecond.SetResult(null);
|
continueSecond.SetResult(null);
|
||||||
var results = await whenAll;
|
var results = await whenAll;
|
||||||
await Assert.That(string.Join(",", results)).IsEqualTo("1,2");
|
await Assert.That(string.Join(",", results)).IsEqualTo("1,2");
|
||||||
await Assert.That(progress.GetIncrement()).IsEqualTo(1);
|
await Assert.That(progress.GetIncreasing()).IsEqualTo(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// 此文件主体由 AI 生成,应作为独立模块,尽量减少与其他内容的耦合。
|
// 此文件主体由 AI 生成,应作为独立模块,尽量减少与其他内容的耦合。
|
||||||
// 使用 ModernTooltipService 接管后,TooltipService 仅有 IsEnabled、ShowOnDisabled、InitialShowDelay 仍然有效,其他属性不再生效。
|
// 使用 ModernTooltipService 接管后,TooltipService 仅有 IsEnabled、ShowOnDisabled、InitialShowDelay 仍然有效,其他属性不再生效。
|
||||||
|
|
||||||
|
using System.ComponentModel;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
using System.Windows.Controls.Primitives;
|
using System.Windows.Controls.Primitives;
|
||||||
@@ -60,6 +61,8 @@ public static class ModernTooltipService {
|
|||||||
private static readonly Brush backgroundBrush = new SolidColorBrush(Colors.White);
|
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 borderBrush = new SolidColorBrush(Color.FromRgb(0xD6, 0xD6, 0xD6));
|
||||||
private static readonly Brush foregroundBrush = new SolidColorBrush(Color.FromRgb(0x52, 0x52, 0x52));
|
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 readonly DispatcherTimer openTimer = new();
|
||||||
@@ -70,6 +73,7 @@ public static class ModernTooltipService {
|
|||||||
private static Border? popupCard;
|
private static Border? popupCard;
|
||||||
private static ScaleTransform? popupScale;
|
private static ScaleTransform? popupScale;
|
||||||
private static FrameworkElement? currentOwner;
|
private static FrameworkElement? currentOwner;
|
||||||
|
private static FrameworkElement? observedToolTipOwner;
|
||||||
private static ToolTip? borrowedToolTip;
|
private static ToolTip? borrowedToolTip;
|
||||||
private static object? borrowedContent;
|
private static object? borrowedContent;
|
||||||
|
|
||||||
@@ -195,7 +199,11 @@ public static class ModernTooltipService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (owner is not null) BeginShow(owner, Mouse.GetPosition(owner));
|
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) {
|
private static FrameworkElement? FindCurrentTooltipOwner(FrameworkElement reference) {
|
||||||
@@ -212,6 +220,14 @@ public static class ModernTooltipService {
|
|||||||
var owner = FindOwnerInAncestors(Mouse.DirectlyOver as DependencyObject);
|
var owner = FindOwnerInAncestors(Mouse.DirectlyOver as DependencyObject);
|
||||||
if (owner is not null) return owner;
|
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
|
return reference.InputHitTest(Mouse.GetPosition(reference)) is DependencyObject hit
|
||||||
? FindOwnerInAncestors(hit)
|
? FindOwnerInAncestors(hit)
|
||||||
: null;
|
: null;
|
||||||
@@ -223,7 +239,9 @@ public static class ModernTooltipService {
|
|||||||
private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
|
private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
|
||||||
var raw = owner.ToolTip;
|
var raw = owner.ToolTip;
|
||||||
sourceToolTip = raw as ToolTip;
|
sourceToolTip = raw as ToolTip;
|
||||||
content = sourceToolTip?.Content ?? raw;
|
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);
|
return content is not null && (content is not string text || text.Length > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -297,6 +315,10 @@ public static class ModernTooltipService {
|
|||||||
|
|
||||||
private static void Show(FrameworkElement owner, Point point) {
|
private static void Show(FrameworkElement owner, Point point) {
|
||||||
if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
|
if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
|
||||||
|
if (!ReferenceEquals(owner, FindCurrentTooltipOwner(owner))) {
|
||||||
|
Close(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (popup is null) {
|
if (popup is null) {
|
||||||
popupScale = new ScaleTransform(closedScale, closedScale);
|
popupScale = new ScaleTransform(closedScale, closedScale);
|
||||||
@@ -316,10 +338,22 @@ public static class ModernTooltipService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
popup!.PlacementTarget = owner;
|
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!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
|
||||||
popupCard.FlowDirection = owner.FlowDirection;
|
popupCard.FlowDirection = owner.FlowDirection;
|
||||||
UpdatePosition(owner, point);
|
|
||||||
|
|
||||||
// 先还原上一次借出的 Visual,再挂载新的内容,避免同一元素拥有两个逻辑父级。
|
// 先还原上一次借出的 Visual,再挂载新的内容,避免同一元素拥有两个逻辑父级。
|
||||||
popupCard.Child = null;
|
popupCard.Child = null;
|
||||||
@@ -341,18 +375,35 @@ public static class ModernTooltipService {
|
|||||||
Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
|
Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
|
||||||
ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = contentMaxWidth
|
ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = contentMaxWidth
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
animationToken++;
|
private static void ObserveToolTip(FrameworkElement owner) {
|
||||||
popupCard.Opacity = 0;
|
if (ReferenceEquals(observedToolTipOwner, owner)) return;
|
||||||
popupScale!.ScaleX = closedScale;
|
StopObservingToolTip();
|
||||||
popupScale.ScaleY = closedScale;
|
observedToolTipOwner = owner;
|
||||||
popup.IsOpen = true;
|
toolTipPropertyDescriptor.AddValueChanged(owner, OnToolTipChanged);
|
||||||
Animate(1, 1, null);
|
}
|
||||||
|
|
||||||
|
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) {
|
private static void Close(bool animated) {
|
||||||
openTimer.Stop();
|
openTimer.Stop();
|
||||||
currentOwner = null;
|
currentOwner = null;
|
||||||
|
StopObservingToolTip();
|
||||||
|
|
||||||
if (popup is not { IsOpen: true } || popupCard is null || !animated) {
|
if (popup is not { IsOpen: true } || popupCard is null || !animated) {
|
||||||
HideImmediately();
|
HideImmediately();
|
||||||
@@ -369,6 +420,7 @@ public static class ModernTooltipService {
|
|||||||
private static void HideImmediately() {
|
private static void HideImmediately() {
|
||||||
openTimer.Stop();
|
openTimer.Stop();
|
||||||
animationToken++;
|
animationToken++;
|
||||||
|
StopObservingToolTip();
|
||||||
|
|
||||||
if (popup is not null) popup.IsOpen = false;
|
if (popup is not null) popup.IsOpen = false;
|
||||||
if (popupCard is not null) {
|
if (popupCard is not null) {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||||
<PackageReference Include="PolySharp" Version="1.15.0">
|
<PackageReference Include="PolySharp" Version="1.15.0">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
@@ -41,12 +42,6 @@
|
|||||||
<ProjectReference Include="..\Shared\MeloongCore.csproj" />
|
<ProjectReference Include="..\Shared\MeloongCore.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Reference Include="Newtonsoft.Json">
|
|
||||||
<HintPath>..\..\Plain Craft Launcher 2\Resources\Newtonsoft.Json.dll</HintPath>
|
|
||||||
</Reference>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Reference Include="System.Windows.Forms" />
|
<Reference Include="System.Windows.Forms" />
|
||||||
<Reference Include="PresentationCore" />
|
<Reference Include="PresentationCore" />
|
||||||
|
|||||||
Reference in new issue
Block a user