ref: 将 MeloongCore 的 WPF 部分独立到另一个子工程

This commit is contained in:
龙腾猫跃 committed 2026-04-28 21:40:00 +08:00
1 parent 1036bc9642
commit 1910e96567
13 files changed
+103 -29

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
namespace MeloongCore;
public static class DirectoryUtils {
/// <summary>
/// 确保路径以 / 或 \ 结尾。
/// </summary>
public static string ToDirectoryFormat(string folder) => IsDirectoryFormat(folder) ? folder : folder + Path.DirectorySeparatorChar;
/// <summary>
/// 检查路径是否以 / 或 \ 结尾。
/// </summary>
public static bool IsDirectoryFormat(string path) => path.EndsWithF("/") || path.EndsWithF("\\");
/// <summary>
/// 创建文件夹,或文件所在的文件夹。
/// 支持长路径。
/// 文件夹已存在时不会抛出异常。
/// </summary>
public static void Create(string path, bool isFilePath = false) {
path = FileUtils.ShortenPath(path);
if (isFilePath) path = Path.GetDirectoryName(path);
Directory.CreateDirectory(path);
}
}
+80
View File
@@ -0,0 +1,80 @@
using System.Text.RegularExpressions;
namespace MeloongCore;
public static class EscapeUtils {
/// <summary>
/// XML 转义。
/// </summary>
public static string? XmlEscape(string? str) {
if (str is null) return null;
if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str
.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
.Replace("\"", "&quot;").ReplaceLineEndings("&#xa;");
}
/// <summary>
/// VB.NET 的 Like 关键字转义。
/// </summary>
public static string LikePatternEscape(string input) {
var builder = new StringBuilder();
foreach (char c in input) {
if (c is '[' or ']' or '*' or '?' or '#') {
builder.Append('[').Append(c).Append(']');
} else {
builder.Append(c);
}
}
return builder.ToString();
}
/// <summary>
/// 正则表达式转义。等同于 Regex.Escape。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexEscape(string? value) => Regex.Escape(value);
/// <summary>
/// 正则表达式去转义。等同于 Regex.Unescape。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexUnescape(string? value) => Regex.Unescape(value);
/// <summary>
/// URL 转义。等同于 Uri.EscapeDataString。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlEscape(string? value) => Uri.EscapeDataString(value);
/// <summary>
/// URL 去转义。等同于 Uri.UnescapeDataString。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlUnescape(string? value) => Uri.UnescapeDataString(value);
/// <summary>
/// 表单转义。等同于 WebUtility.UrlEncode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlEscape(string? value) => WebUtility.UrlEncode(value);
/// <summary>
/// 表单去转义。等同于 WebUtility.UrlDecode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlUnescape(string? value) => WebUtility.UrlDecode(value);
/// <summary>
/// HTML 转义。等同于 WebUtility.HtmlEncode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlEscape(string? value) => WebUtility.HtmlEncode(value);
/// <summary>
/// HTML 去转义。等同于 WebUtility.HtmlDecode。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlUnescape(string? value) => WebUtility.HtmlDecode(value);
}
+78
View File
@@ -0,0 +1,78 @@
namespace MeloongCore;
public static class FileUtils {
#region 写入
/// <summary>
/// 写入文件。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, string text, Encoding? encoding = null) {
DirectoryUtils.Create(filePath, isFilePath: true);
File.WriteAllText(filePath, text, encoding ?? new UTF8Encoding());
}
/// <summary>
/// 写入文件。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, byte[] content) {
DirectoryUtils.Create(filePath, isFilePath: true);
File.WriteAllBytes(filePath, content);
}
/// <summary>
/// 将 <paramref name="stream" /> 写入文件。
/// 会将流的位置主动重置到开头。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, Stream stream) {
DirectoryUtils.Create(filePath, isFilePath: true);
using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write);
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
}
#endregion
#region 短路径
/// <summary>
/// 若路径较长,则尽量将其转换为短路径。
/// 若输入的是文件夹路径,不保证其结尾是否有 \ 。
/// </summary>
public static string ShortenPath(string fullName, bool keepFileName = false) {
if (string.IsNullOrEmpty(fullName) || fullName.Length <= 200) return fullName;
fullName = fullName.Replace('/', '\\');
// 保留文件名
string pathToKeep = "";
string pathToShorten = fullName;
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && File.Exists(fullName)) {
pathToKeep = Path.GetFileName(fullName);
pathToShorten = Path.GetDirectoryName(fullName);
}
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
while (!Directory.Exists(pathToShorten) && !File.Exists(pathToShorten)) { // 如果路径不存在
string parentPath = Path.GetDirectoryName(pathToShorten);
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回
pathToKeep = Path.Combine(Path.GetFileName(pathToShorten), pathToKeep);
pathToShorten = parentPath;
}
if (pathToShorten.Length <= 10) return fullName;
// 缩短路径
char[] buffer = new char[260];
int result = GetShortPathNameW(pathToShorten, buffer, buffer.Length);
if (result == 0) return fullName;
string shortPath = new(buffer, 0, result);
return Path.Combine(shortPath, pathToKeep);
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetShortPathNameW(string lpszLongPath, [Out] char[] buffer, int cchBuffer);
#endregion
}
+97
View File
@@ -0,0 +1,97 @@
using System.Numerics;
namespace MeloongCore;
public static class MathUtils {
#region 进制转换
/// <summary>
/// 将字符串作为数字,转换为指定进制的形式。
/// 进制数需在 2 到 86 之间,且输入字符串中的每个字符都必须在该进制的字符集中。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this string input, int fromRadix, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (fromRadix < 2 || fromRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(fromRadix), $"{nameof(fromRadix)} must be between 2 and 86.");
// 零与负数的预处理
if (string.IsNullOrEmpty(input)) return "0";
bool isNegative = input.StartsWithF("-");
if (isNegative) input = input.TrimStart('-');
// 转换为十进制
BigInteger realNum = 0;
foreach (char c in input) {
int digit = digits.IndexOf(c);
if (digit == -1 || digit >= fromRadix) throw new ArgumentException($"Character '{c}' in input '{input}' is not a valid digit for radix {fromRadix}.");
realNum = realNum * fromRadix + digit;
}
return ConvertRadix(realNum * (isNegative ? -1 : 1), toRadix);
}
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this long input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this int input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this byte input, int toRadix) => ConvertRadix((BigInteger) input, toRadix);
private static string ConvertRadix(this BigInteger input, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86.");
// 零与负数的预处理
if (input == 0) return "0";
bool isNegative = input < 0;
// 转换为指定进制
var results = new List<char>();
BigInteger remaining = BigInteger.Abs(input);
BigInteger bigRadix = toRadix;
while (remaining > 0) {
remaining = BigInteger.DivRem(remaining, bigRadix, out BigInteger remainder);
results.Add(digits[(int) remainder]);
}
// 负数的结束处理与返回
if (isNegative) results.Add('-');
results.Reverse();
return new([..results]);
}
#endregion
/// <summary>
/// 将值限制在指定范围内。
/// </summary>
public static T Clamp<T>(this T value, T min, T max) where T : IComparable<T> {
if (value.CompareTo(min) < 0) return min;
if (value.CompareTo(max) > 0) return max;
return value;
}
/// <summary>
/// 在一个范围中进行线性插值。
/// 返回值将被舍入到小数点后 7 位,以解决浮点数误差问题。
/// </summary>
public static double Lerp(double start, double end, double percentage) =>
Math.Round(start + (end - start) * percentage, 7);
/// <summary>
/// 计算二阶贝塞尔曲线。
/// </summary>
public static double Bezier(double t, double x1, double y1, double x2, double y2, double accuracy = 0.01) {
if (t < 0.0000001 || double.IsNaN(t)) return 0;
if (t > 0.9999999) return 1;
double a = t;
double b;
do {
b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1);
a += (t - b) * 0.5;
} while (!(Math.Abs(b - t) < accuracy)); // 精度
return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1);
}
}