From e83447c86ebdb1a16c31a69c4d3d205ab64cac17 Mon Sep 17 00:00:00 2001 From: kaka <3635787394@qq.com> Date: Mon, 9 Nov 2026 16:38:55 +0800 Subject: [PATCH] =?UTF-8?q?Revert=20"feat:=20=E7=A7=BB=E6=A4=8D=20PCL=20?= =?UTF-8?q?=E7=95=8C=E9=9D=A2=E9=A3=8E=E6=A0=BC=E4=B8=8E=E5=8A=A8=E7=94=BB?= =?UTF-8?q?=EF=BC=8C=E6=96=B0=E5=A2=9E=E7=BD=91=E6=98=93=20NEMC=20?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E9=A1=B5"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ModPcGUI/src/ModPcGUI.csproj | 12 - ModPcGUI/src/PclStyles.xaml | 523 ----------- ModPcGUI/src/UI/AppHost.cs | 60 -- ModPcGUI/src/UI/Boot.cs | 45 +- ModPcGUI/src/UI/NemcDownload.cs | 869 ------------------ ModPcGUI/src/UI/PclAnim.cs | 319 ------- ModPcGUI/src/UI/PclMainWindow.Download.cs | 356 ------- ModPcGUI/src/UI/PclMainWindow.Layout.cs | 232 ++--- ModPcGUI/src/UI/PclMainWindow.cs | 61 +- ...77\347\224\250\350\257\264\346\230\216.md" | 17 +- README.md | 2 +- build.bat | 82 -- 12 files changed, 135 insertions(+), 2443 deletions(-) delete mode 100644 ModPcGUI/src/PclStyles.xaml delete mode 100644 ModPcGUI/src/UI/NemcDownload.cs delete mode 100644 ModPcGUI/src/UI/PclAnim.cs delete mode 100644 ModPcGUI/src/UI/PclMainWindow.Download.cs delete mode 100644 build.bat diff --git a/ModPcGUI/src/ModPcGUI.csproj b/ModPcGUI/src/ModPcGUI.csproj index 288e8ff..d6d9059 100644 --- a/ModPcGUI/src/ModPcGUI.csproj +++ b/ModPcGUI/src/ModPcGUI.csproj @@ -24,17 +24,6 @@ - - - - - pcl\PclStyles.xaml - pcl\PclStyles.xaml - PreserveNewest - @@ -65,7 +54,6 @@ - diff --git a/ModPcGUI/src/PclStyles.xaml b/ModPcGUI/src/PclStyles.xaml deleted file mode 100644 index 863a3f8..0000000 --- a/ModPcGUI/src/PclStyles.xaml +++ /dev/null @@ -1,523 +0,0 @@ - - - - - - - - - - - - - - - #343d4a - #0b5bcb - #1370f3 - #4890f5 - #96c0f9 - #d5e6fd - #e0eafd - #eaf2fe - #96c0f9 - #bee0eafd - #343d4a - #0b5bcb - #1370f3 - #4890f5 - #96c0f9 - #d5e6fd - #e0eafd - #eaf2fe - #96c0f9 - #bee0eafd - #404040 - #737373 - #8c8c8c - #a6a6a6 - #cccccc - #ebebeb - #f0f0f0 - #f5f5f5 - #404040 - #737373 - #8c8c8c - #a6a6a6 - #cccccc - #ebebeb - #f0f0f0 - #f5f5f5 - #80fbdddd - #ff4c4c - #ce2111 - - - - - #01eaf2fe - - - - - - - 0:0:0.09 - 0:0:0.18 - 0:0:0.25 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ModPcGUI/src/UI/AppHost.cs b/ModPcGUI/src/UI/AppHost.cs index 6eb4149..62ee075 100644 --- a/ModPcGUI/src/UI/AppHost.cs +++ b/ModPcGUI/src/UI/AppHost.cs @@ -36,13 +36,6 @@ public static void Init() Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); - // 运行时数据自愈:先保证 config.json 与 user\ 存在,再做任何依赖它们的事。 - // 官方发行包自带这两样,但从源码编译出来的 bin\Debug\net48 里没有 —— - // 缺了会让 CoreNative.CanLaunch 拿到 null 配置直接 NRE,账号列表也永远是空的 - // (点「登录」只会弹「还没有账号」)。 - try { EnsureRuntimeData(); } - catch (Exception ex) { Term.WriteLine("[init] 运行时数据自愈失败:" + ex.Message); } - try { string fpd; @@ -66,35 +59,6 @@ public static void Init() } } - /// - /// 补齐跑起来必需、但发行包里才有的运行时数据。 - /// 只补「缺了就直接白屏 / 功能全废」的两样,不动已有文件: - /// user\ —— 账号 json 的存放目录,缺了账号下拉永远是空的 - /// config.json —— 版本号 / 服务器地址 / 游戏路径,缺了 app.Temp 为 null - /// 默认值取网易正式包的当前值,只作为兜底,用户改过就永不覆盖。 - /// - private static void EnsureRuntimeData() - { - string baseDir = AppDomain.CurrentDomain.BaseDirectory; - - string userDir = Path.Combine(baseDir, "user"); - if (!Directory.Exists(userDir)) Directory.CreateDirectory(userDir); - - string cfgPath = Path.Combine(baseDir, "config.json"); - if (File.Exists(cfgPath)) return; - - var def = new Login.temp - { - Version = "1.21.130", - url = "https://x19obtcore.nie.netease.com:8443", - PE_url = "https://g79obtcore.nie.netease.com:8443", - engineVersion = "3.4.5.272725", - connect_log = true - }; - File.WriteAllText(cfgPath, JsonConvert.SerializeObject(def)); - Term.WriteLine("[init] 未找到 config.json,已生成默认配置(服务器 " + def.url + ")\r\n"); - } - public static string UserDir { get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "user"); } @@ -114,29 +78,6 @@ public static List ListAccounts() return list; } - /// - /// 账号文件自检。返回 null 表示看起来正常,否则返回人话描述的毛病。 - /// 典型坏法:手工粘贴 sauth 时内层引号没转义,外层 JSON 直接不成立 —— - /// 这种文件选中后点登录会一路静默失败(错误只写进设置页的日志框), - /// 表现就是「登录按钮点了没反应」,所以要在点之前就拦住。 - /// - public static string CheckAccount(string path) - { - try - { - if (!File.Exists(path)) return "文件不存在"; - string raw = File.ReadAllText(path).Trim(); - if (raw.Length == 0) return "文件是空的"; - if (raw.StartsWith("ey") || raw.StartsWith("SDK4399")) return null; // 纯 sauth JWT,无需解析 - Newtonsoft.Json.Linq.JObject.Parse(raw); - return null; - } - catch (Exception ex) - { - return "不是合法 JSON(" + ex.Message + ")"; - } - } - public static void AddAccount(string name, string cookie) { string dir = UserDir; @@ -160,7 +101,6 @@ public static void Login(string accountFile, string mode) { if (LoggingIn || Started) return; LoggingIn = true; - LastError = ""; Notify(); try diff --git a/ModPcGUI/src/UI/Boot.cs b/ModPcGUI/src/UI/Boot.cs index 86fc309..456deec 100644 --- a/ModPcGUI/src/UI/Boot.cs +++ b/ModPcGUI/src/UI/Boot.cs @@ -114,29 +114,7 @@ private static void Main(string[] args) // 一旦触发就是整进程闪退;这里记入 crash.log 并继续运行 wpf.DispatcherUnhandledException += (s, e) => { - try - { - var ex = e.Exception; - if (IsKnownPclNoise(ex)) - { - // 同一签名 60 秒内只记首次:这类异常由 DispatcherTimer 每秒重试, - // 全量记录会把 crash.log 刷到几 MB,反而盖住真正的新问题 - string key = (ex.StackTrace ?? "").Split('\n')[0].Trim(); - DateTime last; - _noiseStamp.TryGetValue(key, out last); - if ((DateTime.Now - last).TotalSeconds < 60) - { - e.Handled = true; - return; - } - _noiseStamp[key] = DateTime.Now; - Log("Dispatcher", ex.ToString()); - e.Handled = true; - return; - } - Log("Dispatcher", ex.ToString()); - } - catch { } + Log("Dispatcher", e.Exception.ToString()); e.Handled = true; }; wpf.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose; @@ -265,27 +243,6 @@ private static void Log(string tag, string msg) catch { } } - /// 已知噪音签名 -> 上次记录时间(用于 crash.log 去重) - private static readonly System.Collections.Generic.Dictionary _noiseStamp - = new System.Collections.Generic.Dictionary(); - - /// - /// 判断是否为「PCL 控件与宿主环境不兼容」导致的已知噪音异常。 - /// 只认两个确切签名,其余异常一律照常记录,避免掩盖新问题: - /// 1) Popup.OnWindowResize —— WPF(.NET Framework) 在弹层销毁期间重排时的 NRE; - /// 2) MyScrollViewer_IsVisibleChanged —— PCL 该回调未判空直接读 FrmMain(宿主无此单例)。 - /// 第 2 类已在 PclStyles.xaml 里通过改用原生 ScrollViewer 消除, - /// 这里只是兜底:万一别处又冒出同类异常,也不至于被每秒重试刷爆日志。 - /// - private static bool IsKnownPclNoise(Exception ex) - { - if (!(ex is NullReferenceException)) return false; - string st = ex.StackTrace; - if (string.IsNullOrEmpty(st)) return false; - return st.IndexOf("Popup.OnWindowResize", StringComparison.Ordinal) >= 0 - || st.IndexOf("MyScrollViewer_IsVisibleChanged", StringComparison.Ordinal) >= 0; - } - private static void SelfTest() { var sb = new System.Text.StringBuilder(); diff --git a/ModPcGUI/src/UI/NemcDownload.cs b/ModPcGUI/src/UI/NemcDownload.cs deleted file mode 100644 index 55ab74b..0000000 --- a/ModPcGUI/src/UI/NemcDownload.cs +++ /dev/null @@ -1,869 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; - -namespace ModPcGUI -{ - /// 网易客户端(NEMC)的一个可下载版本。 - internal sealed class NemcVersion - { - public string Version; - public string PackageUrl; - public string ManifestUrl; - public bool IsStandard; - - public override string ToString() { return Version ?? ""; } - } - - /// - /// 网易我的世界中国版客户端(Minecraft.Windows.exe)的版本列表与下载安装。 - /// 协议、接口、目录结构与 PCL NEMC 的 ModNemc 完全一致: - /// 版本列表走 x19 的 get-for-mcstudio 设置接口(user-id / user-token 鉴权), - /// 安装包从 patchlist 里的包地址下载,安装完后把游戏目录设为启动路径。 - /// 鉴权头用 x19Crypt.ComputeDynamicToken,与 ES Tool 其它 x19 请求同源。 - /// - internal static class NemcDownload - { - public const string GameExe = "Minecraft.Windows.exe"; - - // ---- 与 PCL NEMC ModNemc 一致的接口常量 ---- - private const string ClientHost = "https://x19mclobt.nie.netease.com"; - private const string ListPath = "/interconn/web/pack-setting/get-for-mcstudio"; - private const string ListBody = "{\"setting_name\":\"pc_sdkclient_full_patchlist\"}"; - private const string ManifestSuffix = "/patch.json"; - - // ---- 下载参数 ---- - private const long SegmentMin = 2L * 1024 * 1024; // 单段最小 2 MB - private const int SegmentMax = 32; // 最多 32 段(网易 CDN 按连接限速) - private const int SegRetryMax = 4; - private const int SegBuffer = 256 * 1024; - private const int StreamBuffer = 1024 * 1024; - private const long SafetyBuffer = 512L * 1024 * 1024; // 磁盘额外余量 - private const long UnknownFallback = 4L * 1024 * 1024 * 1024; - - /// 当前是否已有可用的 x19 登录态(entity_id + user token)。 - public static bool HasLogin - { - get - { - try - { - return !string.IsNullOrWhiteSpace(ConsoleAppLogin.NetEase.Http.UID) - && !string.IsNullOrWhiteSpace(ConsoleAppLogin.NetEase.Http.LoginSRCToken); - } - catch { return false; } - } - } - - // ==================== 版本列表 ==================== - - /// 拉取可下载版本列表:标准版本按版本号降序在前,其余按名称排在后面。 - public static List GetVersions() - { - if (!HasLogin) throw new Exception("请先在「启动」页完成登录(未登录拿不到版本列表)"); - - string token = Mark.x19Crypt.ComputeDynamicToken( - ListPath, ListBody, ConsoleAppLogin.NetEase.Http.LoginSRCToken); - string resp = PostJson(ListPath, ListBody, ConsoleAppLogin.NetEase.Http.UID, token); - if (string.IsNullOrWhiteSpace(resp)) throw new Exception("版本列表响应为空"); - - JObject root = JObject.Parse(resp); - JToken code = root["code"]; - if (code == null || code.ToString() != "0") - { - string msg = root["message"] == null ? "" : root["message"].ToString(); - throw new Exception(msg == "" ? "获取游戏版本列表失败" : "获取游戏版本列表失败:" + msg); - } - - JObject entity = root["entity"] as JObject; - if (entity == null) throw new Exception("版本列表缺少 entity 数据"); - JToken settingValue = entity["setting_value"]; - if (settingValue == null) throw new Exception("版本列表缺少 setting_value 数据"); - - JObject listRoot; - if (settingValue.Type == JTokenType.Object) listRoot = (JObject)settingValue; - else if (settingValue.Type == JTokenType.String) listRoot = JObject.Parse((string)settingValue); - else throw new Exception("版本列表 setting_value 数据无效"); - - List versions = ParseVersionList(listRoot); - if (versions.Count == 0) throw new Exception("未获取到可下载的游戏版本"); - return versions; - } - - private static string PostJson(string path, string body, string uid, string userToken) - { - using (var client = new HttpClient()) - { - client.DefaultRequestHeaders.ExpectContinue = false; - client.Timeout = TimeSpan.FromSeconds(30); - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "WPFLauncher/0.0.0.0"); - using (var req = new HttpRequestMessage(HttpMethod.Post, ClientHost + path)) - { - req.Content = new StringContent(body, Encoding.UTF8); - req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - req.Headers.TryAddWithoutValidation("user-id", uid); - req.Headers.TryAddWithoutValidation("user-token", userToken); - using (HttpResponseMessage resp = client.SendAsync(req).GetAwaiter().GetResult()) - { - string text = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - if (!resp.IsSuccessStatusCode) - throw new Exception("版本列表请求失败:HTTP " + (int)resp.StatusCode); - return text; - } - } - } - } - - private static List ParseVersionList(JObject root) - { - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); - - foreach (JProperty prop in root.Properties()) - { - if (IsReservedKey(prop.Name)) continue; - NemcVersion info = TryCreateVersion(prop.Name, prop.Value); - if (info != null) dict[prop.Name] = info; - } - - JToken entities = root["entities"]; - if (entities != null && entities.Type == JTokenType.Object) - { - foreach (JProperty prop in ((JObject)entities).Properties()) - { - NemcVersion info = TryCreateVersion(prop.Name, prop.Value); - if (info != null) dict[prop.Name] = info; - } - } - - List standard = dict.Values.Where(v => v.IsStandard).ToList(); - standard.Sort((a, b) => CompareVersions(b.Version, a.Version)); - List special = dict.Values.Where(v => !v.IsStandard) - .OrderBy(v => v.Version, StringComparer.Ordinal).ToList(); - standard.AddRange(special); - return standard; - } - - private static NemcVersion TryCreateVersion(string version, JToken element) - { - if (string.IsNullOrWhiteSpace(version)) return null; - string url = ExtractUrl(element); - if (!IsHttpUrl(url)) return null; - - string packageUrl = url; - string manifestUrl = ""; - if (packageUrl.EndsWith(ManifestSuffix, StringComparison.OrdinalIgnoreCase)) - { - manifestUrl = packageUrl; - packageUrl = packageUrl.Substring(0, packageUrl.Length - ManifestSuffix.Length) + ".zip"; - } - return new NemcVersion - { - Version = version, - PackageUrl = packageUrl, - ManifestUrl = manifestUrl, - IsStandard = IsStandardVersion(version) - }; - } - - private static string ExtractUrl(JToken element) - { - if (element == null) return null; - if (element.Type == JTokenType.String) - { - string s = (string)element; - if (IsHttpUrl(s)) return s; - } - if (element.Type != JTokenType.Object) return null; - foreach (JProperty prop in ((JObject)element).Properties()) - { - string n = prop.Name.ToLowerInvariant(); - if ((n == "url" || n == "download_url" || n == "package_url") && prop.Value.Type == JTokenType.String) - { - string s = (string)prop.Value; - if (IsHttpUrl(s)) return s; - } - } - return null; - } - - private static bool IsReservedKey(string key) - { - return key.Equals("entities", StringComparison.OrdinalIgnoreCase) - || key.Equals("beta", StringComparison.OrdinalIgnoreCase) - || key.Equals("stable", StringComparison.OrdinalIgnoreCase) - || key.Equals("test", StringComparison.OrdinalIgnoreCase); - } - - private static bool IsStandardVersion(string version) - { - if (string.IsNullOrWhiteSpace(version)) return false; - foreach (string part in version.Split('.')) - { - int v; - if (!int.TryParse(part, out v)) return false; - } - return true; - } - - private static int CompareVersions(string left, string right) - { - string[] lp = left.Split('.'); - string[] rp = right.Split('.'); - int len = Math.Max(lp.Length, rp.Length); - for (int i = 0; i < len; i++) - { - int lv = 0, rv = 0; - if (i < lp.Length) int.TryParse(lp[i], out lv); - if (i < rp.Length) int.TryParse(rp[i], out rv); - if (lv != rv) return lv.CompareTo(rv); - } - return 0; - } - - private static bool IsHttpUrl(string url) - { - if (string.IsNullOrWhiteSpace(url)) return false; - Uri u; - return Uri.TryCreate(url, UriKind.Absolute, out u) - && (u.Scheme == Uri.UriSchemeHttp || u.Scheme == Uri.UriSchemeHttps); - } - - // ==================== 下载 + 安装 ==================== - - /// - /// 下载并安装指定版本,返回游戏目录(Minecraft.Windows.exe 所在目录)。 - /// progress(百分比,-1 表示不确定进度,状态文本);isCancelled 返回 true 时抛 OperationCanceledException。 - /// - public static string DownloadAndInstall(NemcVersion version, string installDir, - Action progress, Func isCancelled) - { - if (version == null) throw new Exception("未选择版本"); - if (string.IsNullOrWhiteSpace(version.PackageUrl)) throw new Exception("选中的版本缺少安装包地址"); - if (string.IsNullOrWhiteSpace(installDir)) throw new Exception("下载路径不能为空"); - if (!HasLogin) throw new Exception("请先完成登录后再下载游戏"); - - string fullDir = Path.GetFullPath(installDir); - string versionDir = Path.Combine(fullDir, SanitizeFileName(version.Version)); - if (Directory.Exists(Lp(versionDir)) && - Directory.EnumerateFileSystemEntries(Lp(versionDir)).Any()) - { - throw new Exception("版本目录已存在且不是空目录:" + versionDir); - } - - Report(progress, -1, "正在获取安装包元数据..."); - long? size; - string hash, hashAlgo; - ResolveMetadata(version, out size, out hash, out hashAlgo); - - Report(progress, -1, size.HasValue - ? "安装包约 " + FormatBytes(size.Value) + ",正在检查磁盘空间..." - : "未获取到安装包大小,按 " + FormatBytes(UnknownFallback) + " 预留空间检查..."); - EnsureDiskSpace(fullDir, size); - - Directory.CreateDirectory(Lp(fullDir)); - // 暂存目录名要短:安装包里有 80+ 字符的顶层目录,路径很容易顶到 260 - string stagingDir = Path.Combine(fullDir, ".nemc-" + Guid.NewGuid().ToString("N").Substring(0, 8)); - Directory.CreateDirectory(Lp(stagingDir)); - string archivePath = Path.Combine(fullDir, "minecraft-" + SanitizeFileName(version.Version) + ".zip"); - - try - { - Report(progress, 0, "正在连接下载服务器..."); - DownloadPackage(version.PackageUrl, archivePath, size, progress, isCancelled); - - if (!string.IsNullOrEmpty(hash) && !string.IsNullOrEmpty(hashAlgo)) - { - Report(progress, -1, "正在校验安装包(" + hashAlgo.ToUpperInvariant() + ")..."); - VerifyHash(archivePath, hashAlgo, hash); - Report(progress, 100, "安装包校验通过"); - } - else - { - Report(progress, 100, "未获取到校验信息,已跳过安装包校验"); - } - - ThrowIfCancelled(isCancelled); - Report(progress, 0, "正在解压游戏文件..."); - ExtractArchive(archivePath, stagingDir, progress, isCancelled); - - Report(progress, -1, "正在整理版本目录..."); - string gameDir = NormalizeInstalledDir(stagingDir, versionDir); - Report(progress, 100, "安装完成:" + version.Version); - return gameDir; - } - finally - { - TryDeleteFile(archivePath); - TryDeleteDir(stagingDir); - } - } - - // ---------- 元数据 ---------- - - private sealed class MetaCandidate - { - public string Url = ""; - public long? Size; - public string Hash = ""; - public string Algo = ""; - public bool UrlMatch; - public int Score - { - get { return (UrlMatch ? 4 : 0) + (Hash != "" && Algo != "" ? 2 : 0) + (Size.HasValue ? 1 : 0); } - } - } - - private static void ResolveMetadata(NemcVersion version, out long? size, out string hash, out string algo) - { - size = null; hash = ""; algo = ""; - - if (!string.IsNullOrEmpty(version.ManifestUrl)) - { - try - { - using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }) - { - string content = client.GetStringAsync(version.ManifestUrl).GetAwaiter().GetResult(); - if (!string.IsNullOrWhiteSpace(content)) - { - var candidates = new List(); - CollectManifestCandidates(JToken.Parse(content), version.PackageUrl, candidates); - MetaCandidate best = candidates.OrderByDescending(c => c.Score).FirstOrDefault(); - if (best != null) - { - size = best.Size; - if (best.Hash != "" && best.Algo != "") { hash = best.Hash; algo = best.Algo; } - } - } - } - } - catch { } - } - - if (!size.HasValue) - { - try - { - using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }) - using (var req = new HttpRequestMessage(HttpMethod.Head, version.PackageUrl)) - using (HttpResponseMessage resp = client.SendAsync(req).GetAwaiter().GetResult()) - { - if (resp.IsSuccessStatusCode) size = resp.Content.Headers.ContentLength; - } - } - catch { } - } - } - - private static void CollectManifestCandidates(JToken element, string packageUrl, List list) - { - if (element == null) return; - if (element.Type == JTokenType.Object) - { - var c = new MetaCandidate(); - foreach (JProperty prop in ((JObject)element).Properties()) - { - string n = prop.Name.ToLowerInvariant(); - JToken v = prop.Value; - if ((n == "url" || n == "download_url" || n == "package_url") - && v.Type == JTokenType.String && IsHttpUrl((string)v)) - { - c.Url = (string)v; - } - else if (n == "size" || n == "package_size" || n == "download_size") - { - long l; - if (TryGetLong(v, out l)) c.Size = l; - } - else if (n == "md5" && v.Type == JTokenType.String && ((string)v).Trim() != "") - { - c.Hash = ((string)v).Trim(); c.Algo = "md5"; - } - else if ((n == "sha1" || n == "sha_1") && v.Type == JTokenType.String && ((string)v).Trim() != "") - { - c.Hash = ((string)v).Trim(); c.Algo = "sha1"; - } - else if ((n == "hash" || n == "checksum") && v.Type == JTokenType.String && ((string)v).Trim() != "") - { - c.Hash = ((string)v).Trim(); - if (c.Algo == "") c.Algo = DetectAlgo(c.Hash); - } - else if ((n == "hash_type" || n == "hash_algorithm" || n == "algorithm") - && v.Type == JTokenType.String && ((string)v).Trim() != "") - { - c.Algo = NormalizeAlgo((string)v); - } - } - if (c.Size.HasValue || (c.Hash != "" && c.Algo != "")) - { - c.UrlMatch = string.Equals(c.Url, packageUrl, StringComparison.OrdinalIgnoreCase); - list.Add(c); - } - foreach (JProperty prop in ((JObject)element).Properties()) - CollectManifestCandidates(prop.Value, packageUrl, list); - } - else if (element.Type == JTokenType.Array) - { - foreach (JToken item in (JArray)element) - CollectManifestCandidates(item, packageUrl, list); - } - } - - private static bool TryGetLong(JToken token, out long value) - { - value = 0; - if (token == null) return false; - if (token.Type == JTokenType.Integer) { value = (long)token; return true; } - if (token.Type == JTokenType.Float) { value = (long)(double)token; return true; } - if (token.Type == JTokenType.String) return long.TryParse(((string)token).Trim(), out value); - return false; - } - - private static string DetectAlgo(string hash) - { - string h = (hash ?? "").Trim(); - if (h.Length == 32) return "md5"; - if (h.Length == 40) return "sha1"; - if (h.Length == 64) return "sha256"; - return ""; - } - - private static string NormalizeAlgo(string algo) - { - string a = (algo ?? "").Trim().ToLowerInvariant().Replace("-", "").Replace("_", ""); - if (a == "sha1") return "sha1"; - if (a == "sha256") return "sha256"; - if (a == "md5") return "md5"; - return a; - } - - private static void EnsureDiskSpace(string dir, long? size) - { - try - { - long need = (size ?? UnknownFallback) + SafetyBuffer; - string root = Path.GetPathRoot(Path.GetFullPath(dir)); - if (string.IsNullOrEmpty(root)) return; - var drive = new DriveInfo(root); - if (drive.IsReady && drive.AvailableFreeSpace < need) - { - throw new Exception("磁盘剩余空间不足:需要约 " + FormatBytes(need) - + ",当前可用 " + FormatBytes(drive.AvailableFreeSpace)); - } - } - catch (Exception ex) - { - // 只把「空间不足」当致命错误,其它(如网络盘)忽略 - if (ex.Message.StartsWith("磁盘剩余空间不足")) throw; - } - } - - // ---------- 下载 ---------- - - private static void DownloadPackage(string url, string path, long? expected, - Action progress, Func isCancelled) - { - ThrowIfCancelled(isCancelled); - - long total = expected ?? 0; - bool rangeOk = false; - try { Probe(url, ref total, ref rangeOk); } catch { rangeOk = false; } - if (total <= 0) throw new Exception("无法获取安装包大小,已中止下载"); - - int segments = rangeOk ? ChooseSegments(total) : 1; - if (segments <= 1) - { - DownloadSingle(url, path, total, progress, isCancelled, rangeOk); - return; - } - - try - { - DownloadSegmented(url, path, total, segments, progress, isCancelled); - } - catch (OperationCanceledException) { throw; } - catch (Exception ex) - { - // 分段失败退回单连接,避免整次下载白跑 - Report(progress, 0, "分段下载失败,改用单连接重试(" + ex.Message + ")"); - TryDeleteFile(path); - DownloadSingle(url, path, total, progress, isCancelled, rangeOk); - } - } - - /// 探测是否支持 Range 与真实大小。 - private static void Probe(string url, ref long total, ref bool rangeOk) - { - using (var client = NewDownloadClient()) - using (var req = new HttpRequestMessage(HttpMethod.Get, url)) - { - req.Headers.Range = new RangeHeaderValue(0, 0); - using (HttpResponseMessage resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead) - .GetAwaiter().GetResult()) - { - if ((int)resp.StatusCode == 206) - { - rangeOk = true; - ContentRangeHeaderValue cr = resp.Content.Headers.ContentRange; - if (cr != null && cr.Length.HasValue) total = cr.Length.Value; - } - else if (resp.IsSuccessStatusCode && resp.Content.Headers.ContentLength.HasValue) - { - total = resp.Content.Headers.ContentLength.Value; - } - } - } - } - - private static int ChooseSegments(long total) - { - if (total < 8L * 1024 * 1024) return 1; - int n = (int)(total / SegmentMin); - if (n < 2) n = 2; - if (n > SegmentMax) n = SegmentMax; - return n; - } - - private static void DownloadSingle(string url, string path, long total, - Action progress, Func isCancelled, bool rangeOk) - { - using (var client = NewDownloadClient()) - using (var req = new HttpRequestMessage(HttpMethod.Get, url)) - using (HttpResponseMessage resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead) - .GetAwaiter().GetResult()) - { - if (!resp.IsSuccessStatusCode) throw new Exception("下载请求失败:HTTP " + (int)resp.StatusCode); - if (resp.Content.Headers.ContentLength.HasValue && resp.Content.Headers.ContentLength.Value > 0) - total = resp.Content.Headers.ContentLength.Value; - - using (var input = resp.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) - using (var output = new FileStream(Lp(path), FileMode.Create, FileAccess.Write, FileShare.None)) - { - byte[] buffer = new byte[StreamBuffer]; - long done = 0; - var sw = Stopwatch.StartNew(); - long lastMs = 0; - while (true) - { - ThrowIfCancelled(isCancelled); - int read = input.Read(buffer, 0, buffer.Length); - if (read <= 0) break; - output.Write(buffer, 0, read); - done += read; - if (sw.ElapsedMilliseconds - lastMs > 200 || done >= total) - { - lastMs = sw.ElapsedMilliseconds; - Report(progress, total > 0 ? done * 100.0 / total : -1, - BuildStatus(done, total, sw.Elapsed)); - } - } - if (total > 0 && done < total) - throw new Exception("下载不完整:" + FormatBytes(done) + " / " + FormatBytes(total)); - } - } - } - - private static void DownloadSegmented(string url, string path, long total, int segments, - Action progress, Func isCancelled) - { - try - { - using (var fs = new FileStream(Lp(path), FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) - fs.SetLength(total); - } - catch { } - - long done = 0; - var sw = Stopwatch.StartNew(); - long lastMs = 0; - object gate = new object(); - - Action onBytes = n => - { - long now = Interlocked.Add(ref done, n); - lock (gate) - { - if (sw.ElapsedMilliseconds - lastMs < 200 && now < total) return; - lastMs = sw.ElapsedMilliseconds; - } - Report(progress, now * 100.0 / total, BuildStatus(now, total, sw.Elapsed)); - }; - - var tasks = new List(); - for (int i = 0; i < segments; i++) - { - long start = total * i / segments; - long end = total * (i + 1) / segments - 1; - if (end < start) continue; - tasks.Add(Task.Run(() => DownloadSegment(url, path, start, end, onBytes, isCancelled))); - } - try { Task.WaitAll(tasks.ToArray()); } - catch (AggregateException ex) - { - Exception inner = ex.Flatten().InnerExceptions.FirstOrDefault(); - if (inner is OperationCanceledException) throw new OperationCanceledException("已取消下载"); - throw inner ?? ex; - } - - var fi = new FileInfo(Lp(path)); - if (fi.Length != total) throw new Exception("分段下载长度异常:" + FormatBytes(fi.Length)); - } - - private static void DownloadSegment(string url, string path, long start, long end, - Action onBytes, Func isCancelled) - { - long pos = start; - Exception last = null; - for (int attempt = 0; attempt <= SegRetryMax; attempt++) - { - ThrowIfCancelled(isCancelled); - try - { - using (var client = NewDownloadClient()) - using (var req = new HttpRequestMessage(HttpMethod.Get, url)) - { - req.Headers.Range = new RangeHeaderValue(pos, end); - using (HttpResponseMessage resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead) - .GetAwaiter().GetResult()) - { - if ((int)resp.StatusCode != 206) - throw new Exception("服务器未按分段返回(HTTP " + (int)resp.StatusCode + ")"); - using (var input = resp.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) - using (var output = new FileStream(Lp(path), FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) - { - output.Seek(pos, SeekOrigin.Begin); - byte[] buffer = new byte[SegBuffer]; - while (pos <= end) - { - ThrowIfCancelled(isCancelled); - int want = (int)Math.Min(buffer.Length, end - pos + 1); - int read = input.Read(buffer, 0, want); - if (read <= 0) break; - output.Write(buffer, 0, read); - pos += read; - onBytes(read); - } - } - } - } - if (pos > end) return; - last = new Exception("连接提前结束"); - } - catch (OperationCanceledException) { throw; } - catch (Exception ex) - { - last = ex; - try { Thread.Sleep(300 * (attempt + 1)); } catch { } - } - } - throw last ?? new Exception("分段下载失败"); - } - - private static HttpClient NewDownloadClient() - { - var client = new HttpClient(); - client.Timeout = Timeout.InfiniteTimeSpan; - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "WPFLauncher/0.0.0.0"); - return client; - } - - private static string BuildStatus(long done, long total, TimeSpan elapsed) - { - double speed = elapsed.TotalSeconds > 0.2 ? done / elapsed.TotalSeconds : 0; - string pct = total > 0 ? (done * 100.0 / total).ToString("0.0") + "%" : ""; - string left = total > 0 ? FormatBytes(done) + " / " + FormatBytes(total) : FormatBytes(done); - string sp = speed > 0 ? " · " + FormatBytes((long)speed) + "/s" : ""; - return "正在下载 " + pct + " · " + left + sp; - } - - // ---------- 校验 ---------- - - private static void VerifyHash(string path, string algo, string expected) - { - string actual; - using (var stream = new FileStream(Lp(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - HashAlgorithm ha; - string a = (algo ?? "").ToLowerInvariant(); - if (a == "md5") ha = MD5.Create(); - else if (a == "sha1") ha = SHA1.Create(); - else if (a == "sha256") ha = SHA256.Create(); - else return; // 未知算法:跳过校验,不误报失败 - using (ha) - { - actual = BitConverter.ToString(ha.ComputeHash(stream)).Replace("-", "").ToLowerInvariant(); - } - } - if (!string.Equals(actual, (expected ?? "").Trim().ToLowerInvariant(), StringComparison.Ordinal)) - throw new Exception("安装包校验失败(" + algo + " 不匹配),已中止安装"); - } - - // ---------- 解压 ---------- - - private static void ExtractArchive(string archivePath, string destDir, - Action progress, Func isCancelled) - { - using (var fs = new FileStream(Lp(archivePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - using (var zip = new ZipArchive(fs, ZipArchiveMode.Read)) - { - long totalBytes = 0; - foreach (ZipArchiveEntry e in zip.Entries) totalBytes += e.Length; - long done = 0; - var sw = Stopwatch.StartNew(); - long lastMs = 0; - - string baseFull = Path.GetFullPath(destDir); - if (!baseFull.EndsWith(Path.DirectorySeparatorChar.ToString())) - baseFull += Path.DirectorySeparatorChar; - - foreach (ZipArchiveEntry entry in zip.Entries) - { - ThrowIfCancelled(isCancelled); - string rel = entry.FullName.Replace('\\', '/'); - if (rel.EndsWith("/")) - { - Directory.CreateDirectory(Lp(Path.Combine(destDir, rel))); - continue; - } - - // 目录穿越防护:解压目标必须落在暂存目录内 - string target = Path.GetFullPath(Path.Combine(baseFull, rel)); - if (!target.StartsWith(baseFull, StringComparison.OrdinalIgnoreCase)) - throw new Exception("压缩包包含非法路径,已中止解压"); - - string dir = Path.GetDirectoryName(target); - if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(Lp(dir)); - - using (Stream input = entry.Open()) - using (var output = new FileStream(Lp(target), FileMode.Create, FileAccess.Write, FileShare.None)) - { - byte[] buffer = new byte[StreamBuffer]; - int read; - while ((read = input.Read(buffer, 0, buffer.Length)) > 0) - { - output.Write(buffer, 0, read); - done += read; - if (sw.ElapsedMilliseconds - lastMs > 200) - { - lastMs = sw.ElapsedMilliseconds; - Report(progress, totalBytes > 0 ? done * 100.0 / totalBytes : -1, - "正在解压 " + FormatBytes(done) + " / " + FormatBytes(totalBytes)); - } - } - } - } - } - } - - private static string NormalizeInstalledDir(string stagingDir, string versionDir) - { - string extracted = FindGameDir(stagingDir); - - if (Directory.Exists(Lp(versionDir))) - { - if (Directory.EnumerateFileSystemEntries(Lp(versionDir)).Any()) - throw new Exception("版本目录已存在且不是空目录:" + versionDir); - Directory.Delete(Lp(versionDir)); - } - string parent = Path.GetDirectoryName(versionDir); - if (!string.IsNullOrWhiteSpace(parent)) Directory.CreateDirectory(Lp(parent)); - Directory.Move(Lp(extracted), Lp(versionDir)); - - if (!File.Exists(Lp(Path.Combine(versionDir, GameExe)))) - throw new Exception("整理后的游戏目录无效(缺少 " + GameExe + ")"); - return versionDir; - } - - private static string FindGameDir(string root) - { - if (File.Exists(Lp(Path.Combine(root, GameExe)))) return root; - - string found = null; - foreach (string f in Directory.EnumerateFiles(Lp(root), GameExe, SearchOption.AllDirectories)) - { - if (found == null || f.Length < found.Length) found = f; - } - if (string.IsNullOrEmpty(found)) - throw new Exception("未在解压目录中找到有效的游戏目录(" + GameExe + ")"); - - found = StripLongPath(found); - string dir = Path.GetDirectoryName(found); - if (string.IsNullOrWhiteSpace(dir)) throw new Exception("解压后的游戏目录无效"); - return dir; - } - - // ---------- 工具 ---------- - - private static void Report(Action progress, double pct, string msg) - { - if (progress == null) return; - try { progress(pct, msg); } catch { } - } - - private static void ThrowIfCancelled(Func isCancelled) - { - if (isCancelled != null && isCancelled()) throw new OperationCanceledException("已取消下载"); - } - - private static string SanitizeFileName(string value) - { - char[] invalid = Path.GetInvalidFileNameChars(); - var sb = new StringBuilder(); - foreach (char c in value ?? "") - sb.Append(Array.IndexOf(invalid, c) >= 0 ? '_' : c); - string s = sb.ToString().Trim(); - return string.IsNullOrWhiteSpace(s) ? "package" : s; - } - - /// 超过 240 字符时加 \\?\ 前缀,绕过 MAX_PATH(安装包里目录层级很深)。 - private static string Lp(string path) - { - if (string.IsNullOrEmpty(path)) return path; - if (path.StartsWith(@"\\?\")) return path; - string full = path; - try { if (!Path.IsPathRooted(path)) full = Path.GetFullPath(path); } catch { full = path; } - if (full.Length < 240) return full; - if (full.StartsWith(@"\\")) return @"\\?\UNC\" + full.Substring(2); - return @"\\?\" + full; - } - - private static string StripLongPath(string path) - { - if (string.IsNullOrEmpty(path)) return path; - if (path.StartsWith(@"\\?\UNC\", StringComparison.Ordinal)) return @"\\" + path.Substring(8); - if (path.StartsWith(@"\\?\", StringComparison.Ordinal)) return path.Substring(4); - return path; - } - - private static void TryDeleteFile(string path) - { - try { if (File.Exists(Lp(path))) File.Delete(Lp(path)); } catch { } - } - - private static void TryDeleteDir(string path) - { - try { if (Directory.Exists(Lp(path))) Directory.Delete(Lp(path), true); } catch { } - } - - public static string FormatBytes(long bytes) - { - if (bytes < 0) return "-"; - string[] units = { "B", "KB", "MB", "GB", "TB" }; - double v = bytes; - int i = 0; - while (v >= 1024 && i < units.Length - 1) { v /= 1024; i++; } - return v.ToString(i == 0 ? "0" : "0.0") + " " + units[i]; - } - } -} diff --git a/ModPcGUI/src/UI/PclAnim.cs b/ModPcGUI/src/UI/PclAnim.cs deleted file mode 100644 index 30403d1..0000000 --- a/ModPcGUI/src/UI/PclAnim.cs +++ /dev/null @@ -1,319 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; -using System.Windows.Media.Animation; - -namespace ModPcGUI -{ - /// - /// ES Tool 的动画层 —— 时长、曲线、缓动全部照抄 PCL2 的 ModAnimation - /// (`PCL NEMC/Plain Craft Launcher 2/Modules/Base/ModAnimation.vb`)。 - /// - /// 两条执行路径: - /// 1. 宿主有 pcl\PCL.Core.dll 时,直接调 PCL 自己的引擎 - /// (PCL.ModAnimation.AaOpacity / AaTranslateY / AniStart)。 - /// 这样曲线、时序、帧循环和 MyCard 的悬停变色跑在同一套 AniGroups 里, - /// 不会出现两套动画互相抢属性的情况。 - /// 这里走反射而不是强类型引用:PCL.Core.dll 缺失、或版本里的方法签名变了, - /// 都只会退化成路径 2,不会让整个项目编译不过。 - /// 2. 引擎不可用时退回 WPF 原生 Storyboard,曲线取 PCL 公式的等价缓动 - /// (AniEaseOutFluent(p=3) 就是 1-(1-t)^3,与 CubicEase/EaseOut 完全一致)。 - /// - /// 约定:只做“加法”动画 —— 先把初始状态直接写死(Opacity / RenderTransform), - /// 再让动画推到目标值,不用 Storyboard 的 From,避免首帧闪一下。 - /// - internal static class PclAnim - { - // PCL 常用时长(毫秒),取自 MyCard.vb / MyListItem.xaml.vb 的实参 - public const int Fast = 90; // 悬停变色 - public const int Normal = 200; // 位移、淡入 - public const int Slow = 260; // 面板整体入场 - public const int Step = 25; // 列表逐项出现的间隔(AaStack 默认值) - - // ---------------- PCL 引擎反射句柄 ---------------- - private static bool _probed; - private static bool _engineReady; - private static Type _mod; // PCL.ModAnimation - private static MethodInfo _aaOpacity, _aaTranslateY, _aaTranslateX, _aniStart, _aniStartLoop; - private static PropertyInfo _aniRunning; - private static object _easeOutStrong; // PCL.ModAnimation+AniEaseOutFluent(ExtraStrong) - - private static void Probe() - { - if (_probed) return; - _probed = true; - try - { - // PCL.MyButton 是本项目已经强类型引用的类型,拿它的程序集最稳 - var asm = typeof(PCL.MyButton).Assembly; - _mod = asm.GetType("PCL.ModAnimation", false); - if (_mod == null) return; - - _aaOpacity = FindAa("AaOpacity"); - _aaTranslateY = FindAa("AaTranslateY"); - _aaTranslateX = FindAa("AaTranslateX"); - - foreach (var m in _mod.GetMethods(BindingFlags.Public | BindingFlags.Static)) - { - if (m.Name != "AniStart") continue; - var ps = m.GetParameters(); - if (ps.Length == 0) _aniStartLoop = m; // AniStart():拉起动画线程 - else if (ps.Length == 3 && ps[0].ParameterType == typeof(IList)) - _aniStart = m; // AniStart(IList, String, Boolean) - } - _aniRunning = _mod.GetProperty("AniRunning", BindingFlags.Public | BindingFlags.Static); - - // 缓动:AniEasePower.ExtraStrong = 5 - var powerEnum = asm.GetType("PCL.ModAnimation+AniEasePower", false); - var easeType = asm.GetType("PCL.ModAnimation+AniEaseOutFluent", false); - if (powerEnum != null && easeType != null) - { - var strong = Enum.ToObject(powerEnum, 5); - _easeOutStrong = Activator.CreateInstance(easeType, new[] { strong }); - } - - _engineReady = _aaOpacity != null && _aniStart != null; - } - catch - { - _engineReady = false; - } - } - - private static MethodInfo FindAa(string name) - { - foreach (var m in _mod.GetMethods(BindingFlags.Public | BindingFlags.Static)) - if (m.Name == name) return m; - return null; - } - - /// - /// PCL 的 Aa* 只把动画注册进 AniGroups,真正逐帧执行靠常驻动画线程。 - /// 线程没起来的话动画永远停在注册那一刻 —— 元素会卡在 Opacity=0 不显示。 - /// 这里读 PCL 自己的 AniRunning 标记,没跑才拉起,避免重复开线程。 - /// - private static void EnsureLoop() - { - try - { - bool running = false; - if (_aniRunning != null) - { - var v = _aniRunning.GetValue(null, null); - running = v is bool && (bool)v; - } - if (!running && _aniStartLoop != null) _aniStartLoop.Invoke(null, null); - } - catch { } - } - - /// 把一组 AniData 交给 PCL 引擎执行;失败返回 false 让调用方降级。 - private static bool Run(params object[] anis) - { - Probe(); - if (!_engineReady) return false; - try - { - var list = new ArrayList(); - foreach (var a in anis) - if (a != null) list.Add(a); - if (list.Count == 0) return false; - EnsureLoop(); - _aniStart.Invoke(null, new object[] { list, "", false }); - return true; - } - catch - { - return false; - } - } - - private static object Aa(MethodInfo mi, object obj, double value, int ms, int delay) - { - if (mi == null) return null; - try - { - // (Obj, Value, Time, Delay, Ease, After) - return mi.Invoke(null, new object[] { obj, value, ms, delay, _easeOutStrong, false }); - } - catch - { - try { return mi.Invoke(null, new object[] { obj, value, ms, delay, null, false }); } - catch { return null; } - } - } - - /// - /// 保证元素上的 RenderTransform 就是一个直接的 TranslateTransform。 - /// 不能套 TransformGroup:PCL 的 AaTranslateY 只判断「RenderTransform 是不是 - /// TranslateTransform」,遇到别的类型会直接把 RenderTransform 重置成新的 - /// TranslateTransform(0,0),包在 Group 里的原变换会整个丢掉。 - /// - private static TranslateTransform EnsureTranslate(FrameworkElement e) - { - var tt = e.RenderTransform as TranslateTransform; - if (tt != null) return tt; - tt = new TranslateTransform(); - e.RenderTransform = tt; - return tt; - } - - // ---------------- 对外 API ---------------- - - /// 淡入:元素透明度 from → 1。 - public static void FadeIn(UIElement e, int ms = Normal, int delay = 0, double from = 0) - { - if (e == null) return; - e.Opacity = from; - if (Run(Aa(_aaOpacity, e, 1 - from, ms, delay))) return; - e.BeginAnimation(UIElement.OpacityProperty, - new DoubleAnimation(1, TimeSpan.FromMilliseconds(ms)) - { - BeginTime = TimeSpan.FromMilliseconds(delay), - EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }, - FillBehavior = FillBehavior.HoldEnd - }); - } - - /// 上浮淡入:从下方 dy 像素处移到原位并淡入。PCL 页面/面板入场的常用手感。 - public static void SlideFadeIn(FrameworkElement e, double dy = 12, int ms = Slow, int delay = 0, double from = 0) - { - if (e == null) return; - e.Opacity = from; - var tt = EnsureTranslate(e); - tt.Y = dy; - - var anis = new List(); - var a1 = Aa(_aaOpacity, e, 1 - from, ms, delay); - if (a1 != null) anis.Add(a1); - var a2 = Aa(_aaTranslateY, e, -dy, ms, delay); - if (a2 != null) anis.Add(a2); - if (anis.Count > 0 && Run(anis.ToArray())) return; - - var ease = new CubicEase { EasingMode = EasingMode.EaseOut }; - e.BeginAnimation(UIElement.OpacityProperty, - new DoubleAnimation(1, TimeSpan.FromMilliseconds(ms)) - { BeginTime = TimeSpan.FromMilliseconds(delay), EasingFunction = ease }); - tt.BeginAnimation(TranslateTransform.YProperty, - new DoubleAnimation(0, TimeSpan.FromMilliseconds(ms)) - { BeginTime = TimeSpan.FromMilliseconds(delay), EasingFunction = ease }); - } - - /// 横向滑入:从 dx 像素处滑到原位,dx 的符号决定方向(切换页面用)。 - public static void SlideX(FrameworkElement e, double dx = 16, int ms = Normal, int delay = 0) - { - if (e == null) return; - var tt = EnsureTranslate(e); - tt.X = dx; - - if (Run(Aa(_aaTranslateX, e, -dx, ms, delay))) return; - tt.BeginAnimation(TranslateTransform.XProperty, - new DoubleAnimation(0, TimeSpan.FromMilliseconds(ms)) - { - BeginTime = TimeSpan.FromMilliseconds(delay), - EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } - }); - } - - /// 按下回弹:按下缩到 scale,松手自动弹回。对应 MyCard 的点击反馈。 - public static void Press(FrameworkElement e, double scale = 0.97, int ms = 110) - { - if (e == null) return; - if (e.RenderTransformOrigin == new Point(0, 0)) - e.RenderTransformOrigin = new Point(0.5, 0.5); - - var st = FindScale(e); - if (st == null) - { - st = new ScaleTransform(1, 1); - var group = e.RenderTransform as TransformGroup; - if (group == null) - { - group = new TransformGroup(); - if (e.RenderTransform != null && !e.RenderTransform.Value.IsIdentity) - group.Children.Add(e.RenderTransform); - group.Children.Add(st); - e.RenderTransform = group; - } - else - { - group.Children.Add(st); - } - } - - var a = new DoubleAnimation(scale, TimeSpan.FromMilliseconds(ms)) - { - EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }, - AutoReverse = true, - FillBehavior = FillBehavior.Stop - }; - st.BeginAnimation(ScaleTransform.ScaleXProperty, a); - st.BeginAnimation(ScaleTransform.ScaleYProperty, a.Clone()); - } - - private static ScaleTransform FindScale(FrameworkElement e) - { - if (e.RenderTransform is ScaleTransform s) return s; - if (e.RenderTransform is TransformGroup g) - foreach (var t in g.Children) - if (t is ScaleTransform ss) return ss; - return null; - } - - /// 十六进制重载:HoverBackground(row, "#1B1F23", "#232A31")。 - public static void HoverBackground(Border border, string normalHex, string hoverHex, int ms = Fast) - { - if (border == null) return; - HoverBackground(border, ParseColor(normalHex), ParseColor(hoverHex), ms); - } - - private static Color ParseColor(string hex) - { - try { return (Color)ColorConverter.ConvertFromString(hex); } - catch { return Colors.Transparent; } - } - - /// - /// 给 Border 挂 PCL 式悬停变色:90ms 过渡到 hover 色,离开再过渡回来。 - /// MyCard 用的就是 AaColor + 90ms,这里保持同一时长与曲线。 - /// - public static void HoverBackground(Border border, Color normal, Color hover, int ms = Fast) - { - if (border == null) return; - - // 每个 Border 必须独立画刷,否则动画会串到共享画刷上 - var brush = new SolidColorBrush(normal); - border.Background = brush; - - border.MouseEnter += (s, e) => AnimateBrush(brush, hover, ms); - border.MouseLeave += (s, e) => AnimateBrush(brush, normal, ms); - } - - private static void AnimateBrush(SolidColorBrush brush, Color to, int ms) - { - if (brush == null || brush.IsFrozen) return; - brush.BeginAnimation(SolidColorBrush.ColorProperty, - new ColorAnimation(to, TimeSpan.FromMilliseconds(ms)) - { - EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }, - FillBehavior = FillBehavior.HoldEnd - }); - } - - /// 列表逐项入场:第 i 项延迟 i*Step 毫秒,与 PCL 的 AaStack 一致。 - public static void Cascade(IEnumerable items, double dy = 10, int ms = Normal, int step = Step) - { - if (items == null) return; - int i = 0; - foreach (var it in items) - { - if (it != null) SlideFadeIn(it, dy, ms, i * step); - i++; - } - } - } -} diff --git a/ModPcGUI/src/UI/PclMainWindow.Download.cs b/ModPcGUI/src/UI/PclMainWindow.Download.cs deleted file mode 100644 index 03bf32d..0000000 --- a/ModPcGUI/src/UI/PclMainWindow.Download.cs +++ /dev/null @@ -1,356 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using System.Windows.Media; -using Wpf = System.Windows; -using WpfC = System.Windows.Controls; -using WinForms = System.Windows.Forms; - -namespace ModPcGUI -{ - /// - /// 「下载」页 —— 与 PCL NEMC 的 PageDownloadNemc 同一套功能: - /// 下载路径 + 版本下拉 + 刷新 + 下载/取消 + 状态 + 进度条, - /// 只是把 WPF 原生控件换成了 PCL2 的 MyTextBox / MyComboBox / MyButton / MyCard。 - /// - public sealed partial class PclMainWindow - { - /// 「下载」页在导航里的下标(NavNames:启动 / 下载 / 联机大厅 / 设置 / 更多) - internal const int DownloadPageIndex = 1; - - private PCL.MyTextBox _dlPathBox; - private PCL.MyComboBox _dlVerBox; - private PCL.MyButton _dlBtn; - private PCL.MyButton _dlCancelBtn; - private WpfC.ProgressBar _dlBar; - private WpfC.TextBlock _dlStatus; - - private readonly List _dlVersions = new List(); - private bool _dlBusy; - private volatile bool _dlCancel; - /// 上一次自动填入的下载路径:用户没改过时,进入页面可以跟着配置重新算 - private string _dlPathAuto = ""; - - // ==================== 页面 ==================== - - private Wpf.FrameworkElement BuildDownloadPage(SolidColorBrush blue, SolidColorBrush text, SolidColorBrush sub) - { - var sv = new WpfC.ScrollViewer { VerticalScrollBarVisibility = WpfC.ScrollBarVisibility.Auto }; - var root = new WpfC.StackPanel { Margin = new Wpf.Thickness(20, 16, 20, 16) }; - sv.Content = root; - - root.Children.Add(new WpfC.TextBlock - { - Text = "下载并安装网易我的世界中国版客户端", - FontSize = 11, - Foreground = sub, - Margin = new Wpf.Thickness(2, 0, 0, 12) - }); - - // ---- 卡片:网易客户端(PCL NEMC 下载页同款布局) ---- - var card = new PCL.MyCard { Title = "网易客户端", Margin = new Wpf.Thickness(0, 0, 0, 14) }; - var sp = new WpfC.StackPanel { Margin = new Wpf.Thickness(15, 35, 15, 15) }; - - sp.Children.Add(Label("下载路径", sub)); - var pathRow = new WpfC.Grid { Margin = new Wpf.Thickness(0, 0, 0, 14) }; - pathRow.ColumnDefinitions.Add(new WpfC.ColumnDefinition { Width = new Wpf.GridLength(1, Wpf.GridUnitType.Star) }); - pathRow.ColumnDefinitions.Add(new WpfC.ColumnDefinition { Width = Wpf.GridLength.Auto }); - - _dlPathBox = new PCL.MyTextBox - { - Height = 30, - FontSize = 12, - HintText = "客户端会安装到该目录下的版本子文件夹" - }; - WpfC.Grid.SetColumn(_dlPathBox, 0); - pathRow.Children.Add(_dlPathBox); - - var bBrowse = new PCL.MyButton { Text = "浏览", Width = 76, Height = 30, Margin = new Wpf.Thickness(10, 0, 0, 0) }; - bBrowse.Click += (s, e) => BrowseDownloadPath(); - WpfC.Grid.SetColumn(bBrowse, 1); - pathRow.Children.Add(bBrowse); - sp.Children.Add(pathRow); - - sp.Children.Add(Label("游戏版本", sub)); - var verRow = new WpfC.Grid { Margin = new Wpf.Thickness(0, 0, 0, 16) }; - verRow.ColumnDefinitions.Add(new WpfC.ColumnDefinition { Width = new Wpf.GridLength(1, Wpf.GridUnitType.Star) }); - verRow.ColumnDefinitions.Add(new WpfC.ColumnDefinition { Width = Wpf.GridLength.Auto }); - - _dlVerBox = new PCL.MyComboBox { Height = 30 }; - _dlVerBox.SelectedIndex = -1; - WpfC.Grid.SetColumn(_dlVerBox, 0); - verRow.Children.Add(_dlVerBox); - - var bRefresh = new PCL.MyButton { Text = "刷新版本", Width = 96, Height = 30, Margin = new Wpf.Thickness(10, 0, 0, 0) }; - bRefresh.Click += (s, e) => LoadVersions(true); - WpfC.Grid.SetColumn(bRefresh, 1); - verRow.Children.Add(bRefresh); - sp.Children.Add(verRow); - - var btnRow = new WpfC.StackPanel { Orientation = WpfC.Orientation.Horizontal, Margin = new Wpf.Thickness(0, 0, 0, 4) }; - _dlBtn = new PCL.MyButton - { - Text = "下载并安装", - Width = 120, - Height = 34, - ColorType = PCL.MyButton.ColorState.Highlight - }; - _dlBtn.Click += (s, e) => StartDownload(); - btnRow.Children.Add(_dlBtn); - - _dlCancelBtn = new PCL.MyButton - { - Text = "取消", - Width = 88, - Height = 34, - IsEnabled = false, - Margin = new Wpf.Thickness(10, 0, 0, 0) - }; - _dlCancelBtn.Click += (s, e) => CancelDownload(); - btnRow.Children.Add(_dlCancelBtn); - sp.Children.Add(btnRow); - - _dlStatus = new WpfC.TextBlock - { - Text = "未加载版本", - FontSize = 11, - Foreground = sub, - TextTrimming = Wpf.TextTrimming.CharacterEllipsis, - Margin = new Wpf.Thickness(2, 10, 0, 6) - }; - sp.Children.Add(_dlStatus); - - _dlBar = new WpfC.ProgressBar - { - Height = 6, - Minimum = 0, - Maximum = 100, - Value = 0, - Foreground = blue, - Background = Brush("#E3E7EE"), - BorderThickness = new Wpf.Thickness(0), - Visibility = Wpf.Visibility.Collapsed - }; - sp.Children.Add(_dlBar); - - var hint = new PCL.MyHint - { - Text = "安装包走网易官方 CDN,体积约 1–2 GB;下载完成后会自动把游戏路径指向该版本目录。\r\n" - + "版本列表需要登录后才能获取。", - Theme = PCL.MyHint.Themes.Yellow, - Margin = new Wpf.Thickness(0, 14, 0, 0) - }; - sp.Children.Add(hint); - - card.Children.Add(sp); - root.Children.Add(card); - - return sv; - } - - // ==================== 交互 ==================== - - /// 切到下载页时补默认路径、按需拉一次版本列表(PCL 的 PageLoaded 同款时机)。 - private void EnsureDownloadPageReady() - { - try - { - if (_dlPathBox != null) - { - // 页面构造时 _pathBox 还没从 ui.json 读出来,所以默认路径要在这里重算一次 - string auto = DefaultDownloadPath(); - string current = (_dlPathBox.Text ?? "").Trim(); - if (current.Length == 0 || current == _dlPathAuto) - { - _dlPathBox.Text = auto; - _dlPathAuto = auto; - } - } - if (!_dlBusy && _dlVersions.Count == 0 && NemcDownload.HasLogin) - LoadVersions(false); - else if (!_dlBusy && _dlVersions.Count == 0 && _dlStatus != null) - _dlStatus.Text = "未登录:请先在「启动」页登录,再点「刷新版本」"; - } - catch { } - } - - private string DefaultDownloadPath() - { - try - { - string configured = (_pathBox.Text ?? "").Trim(); - if (configured.Length > 0) - { - string parent = Path.GetDirectoryName(configured.TrimEnd('\\', '/')); - if (!string.IsNullOrWhiteSpace(parent)) return parent; - } - } - catch { } - return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "NEMC"); - } - - private void BrowseDownloadPath() - { - using (var dlg = new WinForms.FolderBrowserDialog()) - { - dlg.Description = "选择网易客户端下载目录"; - string current = (_dlPathBox.Text ?? "").Trim(); - if (Directory.Exists(current)) dlg.SelectedPath = current; - if (dlg.ShowDialog() == WinForms.DialogResult.OK) _dlPathBox.Text = dlg.SelectedPath; - } - } - - private void LoadVersions(bool showHint) - { - if (_dlBusy) return; - if (!NemcDownload.HasLogin) - { - _dlStatus.Text = "未登录:请先在「启动」页登录,再点「刷新版本」"; - if (showHint) Wpf.MessageBox.Show("请先在「启动」页登录后再获取版本列表。", "ES Tool"); - return; - } - - _dlStatus.Text = "正在获取版本列表..."; - _dlBtn.IsEnabled = false; - Task.Run(() => - { - List list = null; - string error = null; - try { list = NemcDownload.GetVersions(); } - catch (Exception ex) { error = ex.Message; } - - Dispatcher.BeginInvoke(new Action(() => - { - if (error != null) - { - _dlStatus.Text = "获取版本列表失败:" + error; - AppendLog("[下载] 获取版本列表失败:" + error + "\r\n"); - } - else - { - _dlVersions.Clear(); - _dlVersions.AddRange(list); - _dlVerBox.Items.Clear(); - foreach (NemcVersion v in list) - _dlVerBox.Items.Add(new PCL.MyComboBoxItem { Content = v.Version }); - if (list.Count > 0) _dlVerBox.SelectedIndex = 0; - _dlStatus.Text = "已获取 " + list.Count + " 个可下载版本"; - if (showHint) AppendLog("已刷新版本列表:" + list.Count + " 个版本\r\n"); - } - if (!_dlBusy) _dlBtn.IsEnabled = true; - })); - }); - } - - private void StartDownload() - { - if (_dlBusy) return; - if (!NemcDownload.HasLogin) - { - Wpf.MessageBox.Show("请先在「启动」页登录后再下载客户端。", "ES Tool"); - return; - } - - int idx = _dlVerBox.SelectedIndex; - NemcVersion ver = (idx >= 0 && idx < _dlVersions.Count) ? _dlVersions[idx] : null; - if (ver == null) - { - Wpf.MessageBox.Show("请先选择要下载的版本(可点「刷新版本」)。", "ES Tool"); - return; - } - - string dir = (_dlPathBox.Text ?? "").Trim(); - if (dir.Length == 0) - { - Wpf.MessageBox.Show("请先选择下载路径。", "ES Tool"); - return; - } - - _dlBusy = true; - _dlCancel = false; - UpdateDownloadUi(true); - _dlBar.Value = 0; - _dlBar.Visibility = Wpf.Visibility.Visible; - _dlStatus.Text = "准备下载..."; - AppendLog("› 开始下载网易客户端 " + ver.Version + "\r\n"); - - NemcVersion target = ver; - string installDir = dir; - Task.Run(() => - { - try - { - string gameDir = NemcDownload.DownloadAndInstall(target, installDir, - (pct, msg) => Dispatcher.BeginInvoke(new Action(() => - { - if (pct >= 0) _dlBar.Value = Math.Max(0, Math.Min(100, pct)); - _dlStatus.Text = msg; - })), - () => _dlCancel); - - Dispatcher.BeginInvoke(new Action(() => - { - _dlBar.Value = 100; - _dlStatus.Text = "安装完成:" + gameDir; - - // PCL 同款收尾:把游戏目录设为启动路径 - _pathBox.Text = gameDir; - SaveUi(); - if (AppHost.Started) - { - try { Term.Submit("setpath"); Term.Submit(gameDir); } catch { } - } - AppendLog("✓ 客户端安装完成:" + gameDir + "\r\n"); - AppendLog(" 已把游戏路径切换到这个版本\r\n"); - })); - } - catch (OperationCanceledException) - { - Dispatcher.BeginInvoke(new Action(() => - { - _dlBar.Value = 0; - _dlStatus.Text = "已取消下载"; - AppendLog("已取消下载\r\n"); - })); - } - catch (Exception ex) - { - Dispatcher.BeginInvoke(new Action(() => - { - _dlStatus.Text = "下载失败:" + ex.Message; - AppendLog("[下载失败] " + ex.Message + "\r\n"); - })); - } - finally - { - Dispatcher.BeginInvoke(new Action(() => - { - _dlBusy = false; - UpdateDownloadUi(false); - })); - } - }); - } - - private void CancelDownload() - { - if (!_dlBusy) return; - _dlCancel = true; - _dlCancelBtn.IsEnabled = false; - _dlStatus.Text = "正在取消..."; - } - - private void UpdateDownloadUi(bool busy) - { - try - { - _dlBtn.IsEnabled = !busy; - _dlCancelBtn.IsEnabled = busy; - _dlPathBox.IsEnabled = !busy; - _dlVerBox.IsEnabled = !busy; - } - catch { } - } - } -} diff --git a/ModPcGUI/src/UI/PclMainWindow.Layout.cs b/ModPcGUI/src/UI/PclMainWindow.Layout.cs index 22089ff..9a8cbd6 100644 --- a/ModPcGUI/src/UI/PclMainWindow.Layout.cs +++ b/ModPcGUI/src/UI/PclMainWindow.Layout.cs @@ -35,20 +35,19 @@ private sealed class NavEntry private int _navIndex; private bool _navGuard; - private static readonly string[] NavNames = { "启动", "下载", "联机大厅", "设置", "更多" }; + private static readonly string[] NavNames = { "启动", "联机大厅", "功能", "设置", "更多" }; // PCL FormMain.xaml 标题栏 RadioButton 的原版图标路径与 LogoScale,1:1 private static readonly string[] NavLogos = { "M52.1,164.5c-1.4,0-3.1-0.5-4.2-1.3c-2.6-1.7-4-4.2-4-7V43.8c0-2.9,1.6-5.8,4.1-7c1.2-0.8,2.7-1.2,4.1-1.2c1.5,0,2.9,0.4,4.2,1.2L153.1,93c0,0,0.1,0,0.1,0.1c2.6,1.7,4,4.2,4,7c0,3-1.7,5.8-4.2,7.1l-96.8,56.2C55.1,164,53.5,164.5,52.1,164.5z M60.4,142.1l72.1-42.1L60.4,58.2V142.1z", - // 下载:PCL FormMain BtnTitleSelect1 原版图标与 LogoScale - "M955 610h-59c-15 0-29 13-29 29v196c0 15-13 29-29 29h-649c-15 0-29-13-29-29v-196c0-15-13-29-29-29h-59c-15 0-29 13-29 29V905c0 43 35 78 78 78h787c43 0 78-35 78-78V640c0-15-13-29-29-29zM492 740c11 11 29 11 41 0l265-265c11-11 11-29 0-41l-41-41c-11-11-29-11-41 0l-110 110c-11 11-33 3-33-13V68C571 53 555 39 541 39h-59c-15 0-29 13-29 29v417c0 17-21 25-33 13l-110-110c-11-11-29-11-41 0L226 433c-11 11-11 29 0 41L492 740z", // 联机大厅:三层同心(大厅/房间/玩家) "M10,0 L20,10 L10,20 L0,10 Z M10,4.6 L15.4,10 L10,15.4 L4.6,10 Z", + "M955 610h-59c-15 0-29 13-29 29v196c0 15-13 29-29 29h-649c-15 0-29-13-29-29v-196c0-15-13-29-29-29h-59c-15 0-29 13-29 29V905c0 43 35 78 78 78h787c43 0 78-35 78-78V640c0-15-13-29-29-29zM492 740c11 11 29 11 41 0l265-265c11-11 11-29 0-41l-41-41c-11-11-29-11-41 0l-110 110c-11 11-33 3-33-13V68C571 53 555 39 541 39h-59c-15 0-29 13-29 29v417c0 17-21 25-33 13l-110-110c-11-11-29-11-41 0L226 433c-11 11-11 29 0 41L492 740z", "M940.4 463.7L773.3 174.2c-17.3-30-49.2-48.4-83.8-48.4H340.2c-34.6 0-66.5 18.5-83.8 48.4L89.2 463.7c-17.3 30-17.3 66.9 0 96.8L256.4 850c17.3 30 49.2 48.4 83.8 48.4h349.2c34.6 0 66.5-18.5 83.8-48.4l167.2-289.5c17.3-29.9 17.3-66.8 0-96.8z m-94.6 96.8L725.9 768.1c-17.3 30-49.2 48.4-83.8 48.4H387.5c-34.6 0-66.5-18.5-83.8-48.4L183.9 560.5c-17.3-30-17.3-66.9 0-96.8l119.8-207.5c17.3-30 49.2-48.4 83.8-48.4h254.6c34.6 0 66.5 18.5 83.8 48.4l119.8 207.5c17.3 30 17.3 66.9 0.1 96.8z M522.3 321.2c-2.5-0.1-5-0.2-7.5-0.2-119.9 0-214 110.3-186.3 235 15.8 70.9 71.5 126.6 142.4 142.4 17.5 3.9 34.7 5.4 51.4 4.7 102.1-3.9 183.6-87.9 183.6-191 0.1-103-81.5-187-183.6-190.9z m68.6 269.1c-18.5 18-43 28.9-68.6 30.7l-6 0.3c-30.2 0.4-58.6-11.4-79.7-33-19.5-20.1-30.7-47-30.9-75-0.3-29.6 11.1-57.4 32-78.3 20.6-20.6 48-32 77.2-32 2.5 0 5 0.1 7.5 0.3 26.7 1.8 51.5 13.2 70.5 32.5 19.6 20 30.8 46.9 31.2 74.9 0.2 30.2-11.5 58.6-33.2 79.6z", "M364 0h-273C40 0 0 40 0 91v273C0 414 40 455 91 455h273C414 455 455 414 455 364V91C455 40 414 0 364 0zM341 341H113V113h227v227zM933 0h-273C609 0 568 40 568 91v273c0 50 40 91 91 91h273C983 455 1024 414 1024 364V91c0-50-40-91-90-91zM910 341h-227V113h227v227zM364 568h-273C40 568 0 609 0 659v273c0 50 40 91 91 91h273C414 1024 455 983 455 932v-273C455 609 414 568 364 568zM341 910H113v-227h227v227zM933 568h-273c-50 0-91 40-91 91v273c0 50 40 91 91 91h273c50 0 90-40 90-91v-273c0-50-40-90-90-90zM910 910h-227v-227h227v227z" }; - private static readonly double[] NavLogoScales = { 0.9, 0.9, 1.0, 1.1, 0.93 }; + private static readonly double[] NavLogoScales = { 0.9, 1.0, 0.9, 1.1, 0.93 }; public PclMainWindow() { @@ -69,11 +68,22 @@ public PclMainWindow() var app = Wpf.Application.Current; if (app != null && app.Resources["PclStylesLoaded"] == null) { - // 走和 Boot 同一条加载路径:读 pcl\PclStyles.xaml 再 XamlReader.Parse。 - // 不能再用 `Source = new Uri("PclStyles.xaml", UriKind.Relative)`—— - // 那份资源已经改成运行时文件(csproj 里从 Page 移除),程序集里没有它, - // 这条 URI 会直接抛 IOException,把 PCL UI 顶回经典界面。 - LoadPclStyles(app); + // PCL2 完整前端资源(颜色 + 控件样式/模板,原样取自其 Application.xaml) + // 若 Boot 已合并过(PclStylesLoaded 标记)则跳过 + if (app.Resources["PclStylesLoaded"] == null) + { + try + { + System.Reflection.Assembly.LoadFrom( + System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pcl", "PCL.Core.dll")); + } + catch { } + app.Resources.MergedDictionaries.Add(new Wpf.ResourceDictionary + { + Source = new Uri("PclStyles.xaml", UriKind.Relative) + }); + } + app.Resources["PclStylesLoaded"] = true; } var blue = Brush("#1370f3"); // PCL ColorBrush3 @@ -218,14 +228,12 @@ public PclMainWindow() }; Term.OnOutput += (t, nl, c) => { - string chunk = (t ?? "") + (nl ? "\r\n" : ""); try { Dispatcher.BeginInvoke(new Action(() => { - _logBox.AppendText(chunk); + _logBox.AppendText((t ?? "") + (nl ? "\r\n" : "")); _logBox.ScrollToEnd(); - LogToFile(chunk); // 与界面日志同源,登录/下载出问题能事后查 })); } catch { } @@ -236,20 +244,13 @@ public PclMainWindow() }; Loaded += (s, e) => { - // PCL 式窗口入场:左右面板错峰上浮淡入(PCL FormMain 在 Loaded 里起 AniStart 同款) - try - { - PclAnim.SlideFadeIn(leftPanel, 10, PclAnim.Slow, 20); - PclAnim.SlideFadeIn(rightPanel, 10, PclAnim.Slow, 70); - } - catch { } - try { AppHost.Init(); } catch (Exception ex) { AppendLog("[init] " + ex.Message + "\r\n"); } RefreshAccounts(); LoadUi(); RefreshState(); UpdateLaunchCaption(); AppendLog("ES Tool 已就绪(PCL2 原生 UI)\r\n"); + AppendLog("共 " + Commands.All.Count + " 条命令可用,切到「功能」查看\r\n"); }; } @@ -340,18 +341,7 @@ private WpfC.Panel BuildLeftPanel(SolidColorBrush blue, SolidColorBrush text, So Margin = new Wpf.Thickness(0, 0, 5, 0) }; WpfC.TextBlock.SetFontSize(bLogin, 13); - // Click + PreviewMouseLeftButtonUp 双通道:PCL 的 MyButton 模板在少数情况下 - // 会把 Click 吃掉(SetNameDialog.cs 里踩过同一个坑),这里用 400ms 防抖保证 - // 一次点击只跑一次 DoLogin,但绝不会「点了没反应」。 - DateTime lastLogin = DateTime.MinValue; - Action fireLogin = () => - { - if ((DateTime.UtcNow - lastLogin).TotalMilliseconds < 400) return; - lastLogin = DateTime.UtcNow; - DoLogin(); - }; - bLogin.Click += (s, e) => fireLogin(); - bLogin.PreviewMouseLeftButtonUp += (s, e) => fireLogin(); + bLogin.Click += (s, e) => DoLogin(); var bAdd = new PCL.MyButton { Text = "添加账号", @@ -449,8 +439,8 @@ private WpfC.Panel BuildLeftPanel(SolidColorBrush blue, SolidColorBrush text, So private void BuildPages(SolidColorBrush blue, SolidColorBrush text, SolidColorBrush sub) { _pages[0] = BuildLaunchPage(blue, text, sub); - _pages[1] = BuildDownloadPage(blue, text, sub); - _pages[2] = BuildLobbyPage(blue, text, sub); + _pages[1] = BuildLobbyPage(blue, text, sub); + _pages[2] = BuildFeaturePage(blue, text, sub); _pages[3] = BuildSetupPage(blue, text, sub); _pages[4] = BuildMorePage(blue, text, sub); foreach (var kv in _pages) @@ -505,7 +495,7 @@ private Wpf.FrameworkElement BuildLaunchPage(SolidColorBrush blue, SolidColorBru Margin = new Wpf.Thickness(0, 2, 0, 2), Child = _rbLobby }; - lobbyHit.MouseLeftButtonUp += (s, e) => NavTo(2); + lobbyHit.MouseLeftButtonUp += (s, e) => NavTo(1); sp.Children.Add(lobbyHit); var addrRow = new WpfC.Grid { Margin = new Wpf.Thickness(0, 8, 0, 4) }; @@ -605,7 +595,93 @@ private Wpf.FrameworkElement BuildLaunchPage(SolidColorBrush blue, SolidColorBru card.Children.Add(sp); root.Children.Add(card); - // 运行日志卡片在「设置」页(BuildSetupPage) + // 运行日志卡片已按需求移到「功能」页(BuildFeaturePage) + + return sv; + } + + private Wpf.FrameworkElement BuildFeaturePage(SolidColorBrush blue, SolidColorBrush text, SolidColorBrush sub) + { + var sv = new WpfC.ScrollViewer { VerticalScrollBarVisibility = WpfC.ScrollBarVisibility.Auto }; + var root = new WpfC.StackPanel { Margin = new Wpf.Thickness(20, 16, 20, 16) }; + sv.Content = root; + + root.Children.Add(new WpfC.TextBlock + { + Text = "原程序全部 184 条命令,按 11 类分组", + FontSize = 11, + Foreground = sub, + Margin = new Wpf.Thickness(2, 0, 0, 12) + }); + + var card = new PCL.MyCard { Title = "命令分类", Margin = new Wpf.Thickness(0, 0, 0, 14) }; + var wrap = new WpfC.WrapPanel { Margin = new Wpf.Thickness(15, 35, 15, 15) }; + foreach (var c in Commands.CategoryOrder) + { + var b = new PCL.MyButton + { + Text = c + " (" + Commands.ByCategory(c).Count + ")", + Width = 168, + Height = 34, + Margin = new Wpf.Thickness(0, 0, 10, 10) + }; + WpfC.TextBlock.SetFontSize(b, 12.5); + b.Click += (s, e) => OpenFeatures(); + wrap.Children.Add(b); + } + card.Children.Add(wrap); + root.Children.Add(card); + + var card2 = new PCL.MyCard { Title = "高级 · 直接发送命令", Margin = new Wpf.Thickness(0, 0, 0, 14) }; + var sp2 = new WpfC.StackPanel { Margin = new Wpf.Thickness(15, 35, 15, 15) }; + var row = new WpfC.Grid(); + row.ColumnDefinitions.Add(new WpfC.ColumnDefinition { Width = new Wpf.GridLength(1, Wpf.GridUnitType.Star) }); + row.ColumnDefinitions.Add(new WpfC.ColumnDefinition { Width = Wpf.GridLength.Auto }); + var raw = new PCL.MyTextBox { Height = 30, FontSize = 12, HintText = "输入任意命令后回车,例如 list" }; + WpfC.Grid.SetColumn(raw, 0); + row.Children.Add(raw); + var send = new PCL.MyButton + { + Text = "发送", + Width = 80, + Height = 30, + ColorType = PCL.MyButton.ColorState.Highlight, + Margin = new Wpf.Thickness(8, 0, 0, 0) + }; + WpfC.TextBlock.SetFontSize(send, 12); + WpfC.Grid.SetColumn(send, 1); + row.Children.Add(send); + Action submit = () => + { + string t = raw.Text.TrimEnd('\r', '\n'); + raw.Text = ""; + if (t.Length == 0) return; + if (!AppHost.Started) { AppendLog("还没有登录\r\n"); return; } + AppendLog("› " + t + "\r\n"); + Term.Submit(t); + }; + send.Click += (s, e) => submit(); + raw.KeyDown += (s, e) => { if (e.Key == Wpf.Input.Key.Enter) { submit(); e.Handled = true; } }; + sp2.Children.Add(row); + card2.Children.Add(sp2); + root.Children.Add(card2); + + // ---- 卡片:运行日志(自启动页移入功能页) ---- + var logCard = new PCL.MyCard { Title = "运行日志", Margin = new Wpf.Thickness(0, 0, 0, 14) }; + var lsp = new WpfC.StackPanel { Margin = new Wpf.Thickness(15, 35, 15, 15) }; + _logBox.Height = 150; + _logBox.IsReadOnly = true; + _logBox.AcceptsReturn = true; + _logBox.TextWrapping = Wpf.TextWrapping.NoWrap; + _logBox.VerticalScrollBarVisibility = WpfC.ScrollBarVisibility.Auto; + _logBox.FontSize = 11; + lsp.Children.Add(_logBox); + _uid.FontSize = 10.5; + _uid.Foreground = sub; + _uid.Margin = new Wpf.Thickness(2, 8, 0, 0); + lsp.Children.Add(_uid); + logCard.Children.Add(lsp); + root.Children.Add(logCard); return sv; } @@ -678,23 +754,6 @@ private Wpf.FrameworkElement BuildSetupPage(SolidColorBrush blue, SolidColorBrus card.Children.Add(sp); root.Children.Add(card); - // ---- 卡片:运行日志(原「功能」页已删除,日志随诊断一起放在设置页) ---- - var logCard = new PCL.MyCard { Title = "运行日志", Margin = new Wpf.Thickness(0, 0, 0, 14) }; - var lsp = new WpfC.StackPanel { Margin = new Wpf.Thickness(15, 35, 15, 15) }; - _logBox.Height = 150; - _logBox.IsReadOnly = true; - _logBox.AcceptsReturn = true; - _logBox.TextWrapping = Wpf.TextWrapping.NoWrap; - _logBox.VerticalScrollBarVisibility = WpfC.ScrollBarVisibility.Auto; - _logBox.FontSize = 11; - lsp.Children.Add(_logBox); - _uid.FontSize = 10.5; - _uid.Foreground = sub; - _uid.Margin = new Wpf.Thickness(2, 8, 0, 0); - lsp.Children.Add(_uid); - logCard.Children.Add(lsp); - root.Children.Add(logCard); - return sv; } @@ -780,6 +839,16 @@ private Wpf.FrameworkElement BuildMorePage(SolidColorBrush blue, SolidColorBrush }); } + var bMore = new PCL.MyButton + { + Text = "打开全部命令", + Width = 160, + Height = 30, + Margin = new Wpf.Thickness(0, 14, 0, 0), + ColorType = PCL.MyButton.ColorState.Highlight + }; + bMore.Click += (s, e) => OpenFeatures(); + sp.Children.Add(bMore); card.Children.Add(sp); root.Children.Add(card); @@ -789,7 +858,6 @@ private Wpf.FrameworkElement BuildMorePage(SolidColorBrush blue, SolidColorBrush // ---------- 导航 ---------- private void NavTo(int idx) { - int prev = _navIndex; _navIndex = idx; if (!_navGuard) { @@ -802,26 +870,11 @@ private void NavTo(int idx) catch { } finally { _navGuard = false; } } - // 先收弹层再切可见性,避免 Popup 在布局更新期间被销毁(见 CloseOpenDropDowns 注释) - if (prev != idx) CloseOpenDropDowns(); foreach (var kv in _pages) kv.Value.Visibility = kv.Key == idx ? Wpf.Visibility.Visible : Wpf.Visibility.Collapsed; - // 页面切换:新页面淡入 + 轻微上浮,曲线/时长与 PCL 的 MyCard 页面切换同源 - if (prev != idx) - { - Wpf.FrameworkElement page; - if (_pages.TryGetValue(idx, out page) && page != null) - { - try { PclAnim.SlideFadeIn(page, 10, PclAnim.Normal); } catch { } - } - } - - // 下载页:首次进入补默认路径并按需拉版本列表(对应 PCL 的 PageLoaded) - if (idx == DownloadPageIndex) EnsureDownloadPageReady(); - // 联机大厅:第一次进去且已登录,自动拉一次全服在线地图池,不用先点搜索 - if (idx == 2 && !_lbLoaded && AppHost.Started) + if (idx == 1 && !_lbLoaded && AppHost.Started) { _lbLoaded = true; LobbySearch(); @@ -996,45 +1049,6 @@ private static bool InInteractive(Wpf.DependencyObject d) return false; } - /// - /// 收掉所有还开着的下拉弹层。 - /// WPF for .NET Framework 有个已知缺陷:Popup 在布局更新期间被销毁会在 - /// Popup.OnWindowResize 里抛 NullReferenceException,而且销毁流程被打断后会 - /// 由 DispatcherTimer 反复重试,日志里就是每秒重复的两条 NRE。 - /// 切页会触发整棵树的可见性级联 + UpdateLayout,正好撞上,所以切页前先主动关闭。 - /// - private void CloseOpenDropDowns() - { - try - { - var list = new System.Collections.Generic.List(); - CollectVisuals(this, list); - for (int i = 0; i < list.Count; i++) - { - try { if (list[i].IsDropDownOpen) list[i].IsDropDownOpen = false; } - catch { } - } - } - catch { } - } - - private static void CollectVisuals(Wpf.DependencyObject root, System.Collections.Generic.List sink) - where T : Wpf.DependencyObject - { - int n; - try { n = System.Windows.Media.VisualTreeHelper.GetChildrenCount(root); } - catch { return; } - for (int i = 0; i < n; i++) - { - Wpf.DependencyObject c; - try { c = System.Windows.Media.VisualTreeHelper.GetChild(root, i); } - catch { continue; } - var hit = c as T; - if (hit != null) sink.Add(hit); - CollectVisuals(c, sink); - } - } - private static SolidColorBrush Brush(string hex) { var c = (Color)ColorConverter.ConvertFromString(hex); diff --git a/ModPcGUI/src/UI/PclMainWindow.cs b/ModPcGUI/src/UI/PclMainWindow.cs index ff92e7e..3b664d3 100644 --- a/ModPcGUI/src/UI/PclMainWindow.cs +++ b/ModPcGUI/src/UI/PclMainWindow.cs @@ -53,26 +53,6 @@ private void AppendLog(string s) { _logBox.AppendText(s); _logBox.ScrollToEnd(); - LogToFile(s); - } - - /// - /// 同步落盘 run.log。界面日志在「设置」页,用户在「启动」页操作时看不到任何反馈, - /// 事后也无从查证 —— 登录/下载出问题时这份文件是唯一的现场。 - /// 超过 512 KB 自动重来,避免无限增长。 - /// - private void LogToFile(string s) - { - try - { - if (string.IsNullOrEmpty(s)) return; - string f = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "run.log"); - var fi = new FileInfo(f); - if (fi.Exists && fi.Length > 512 * 1024) File.Delete(f); - File.AppendAllText(f, "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + s, - System.Text.Encoding.UTF8); - } - catch { } } // ---------- 业务逻辑(复用原 ES Tool) ---------- @@ -93,30 +73,13 @@ private void RefreshAccounts() private void RefreshState() { bool run = AppHost.Started; - bool busy = AppHost.LoggingIn; - string err = AppHost.LastError; - - _status.Text = run ? "● 已连接控制台" : (busy ? "● 正在登录…" : "● 未登录"); + _status.Text = run ? "● 已连接控制台" : "● 未登录"; _uid.Text = "UID: " + (string.IsNullOrEmpty(Http.UID) ? "-" : Http.UID) - + " · 命令 " + Commands.All.Count + " 条"; + + " · 「功能」里有全部 184 条命令"; try { if (_statePill != null) - _statePill.Text = run ? "已连接控制台 · 网易渠道" - : (busy ? "正在登录 · 请稍候" : "已就绪 · 网易渠道"); - } - catch { } - // 启动页顶部提示:登录进度和失败原因必须出现在用户眼皮底下。 - // 之前这些信息只写进「设置」页的日志框,用户在启动页点登录就是「一片安静」。 - try - { - if (_pageHint != null) - { - if (run) _pageHint.Text = "已登录,点「启动游戏」进入客户端"; - else if (busy) _pageHint.Text = "正在登录,请稍候…(若弹出浏览器,请完成验证)"; - else if (!string.IsNullOrEmpty(err)) _pageHint.Text = "上次登录失败:" + err; - else _pageHint.Text = "选择账号并登录,然后启动客户端"; - } + _statePill.Text = run ? "已连接控制台 · 网易渠道" : "已就绪 · 网易渠道"; } catch { } // 登录成功后隐藏「登录 / 添加账号」按钮行,把空间让给账号区 @@ -154,18 +117,6 @@ private void DoLogin() if (item == null) { Wpf.MessageBox.Show("还没有账号,先点「添加账号」。", "ES Tool"); return; } string f = item.Path; - // 账号文件先自检:坏文件(比如手工粘贴时内层引号没转义)会让登录静默失败, - // 而错误信息只写进设置页的日志框 —— 表现就是「点了登录没反应」。这里直接说清楚。 - string bad = AppHost.CheckAccount(f); - if (bad != null) - { - Wpf.MessageBox.Show( - "这个账号文件不能用:\n" + bad + "\n\n" + f - + "\n\n请删掉它重新「添加账号」,或修正 JSON 后再试。", - "ES Tool", Wpf.MessageBoxButton.OK, Wpf.MessageBoxImage.Warning); - return; - } - string mode = "auto"; if (_modeBox.SelectedIndex == 1) mode = "pc"; else if (_modeBox.SelectedIndex == 2) mode = "pe"; @@ -476,10 +427,8 @@ private void RenderCandidates(List cands) Child = grid }; row.MouseLeftButtonUp += (s, e) => QueryCandidate(captured); - // PCL 式悬停:90ms 颜色过渡,不再是硬切(与 MyCard 的 AaColor 参数一致) - PclAnim.HoverBackground(row, "#1B1F23", "#232A31"); - // 候选逐条上浮出现,步长 25ms(PCL AaStack 的默认间隔) - PclAnim.SlideFadeIn(row, 8, PclAnim.Normal, _roomCandList.Children.Count * PclAnim.Step); + row.MouseEnter += (s, e) => row.Background = Brush("#232A31"); + row.MouseLeave += (s, e) => row.Background = Brush("#1B1F23"); _roomCandList.Children.Add(row); } diff --git "a/ModPcGUI/\344\275\277\347\224\250\350\257\264\346\230\216.md" "b/ModPcGUI/\344\275\277\347\224\250\350\257\264\346\230\216.md" index 1b1e4ad..51e8a43 100644 --- "a/ModPcGUI/\344\275\277\347\224\250\350\257\264\346\230\216.md" +++ "b/ModPcGUI/\344\275\277\347\224\250\350\257\264\346\230\216.md" @@ -13,7 +13,7 @@ ``` ┌────────────────────────────────────────────────────────┐ -│ ES Tool (▶启动) (⇩下载) (◈联机) (◎设置) (▦更多) ─ × │ 蓝色顶栏 48px +│ ES Tool (▶启动) (⇩功能) (◎设置) (▦更多) ─ × │ 蓝色顶栏 48px ├───────────────────┬────────────────────────────────────┤ │ 已就绪·网易渠道 │ 启动设置 │ │ [史蒂夫头] 账号 │ ┌──────────────────────────────┐ │ @@ -34,11 +34,7 @@ 账号下拉+删除、登录/添加账号、启动模式下拉、 **54px 高亮「启动游戏」按钮(版本/服务器小字叠在按钮内)**、 底部 35px「一键布吉岛 / 一键 EC」按钮行 -- 右侧内容区按导航切换:启动设置 / 网易客户端下载 / 联机大厅 / config 编辑 / 关于 -- 下载页对齐 PCL NEMC 的 `PageDownloadNemc`:下载路径 + 版本下拉 + 刷新 + - 下载/取消 + 状态 + 进度条。版本列表走 x19 `get-for-mcstudio`(同 PCL 的 ModNemc), - 安装包从 patchlist 里的包地址下载,支持 Range 分段并发、sha1/md5 校验、 - 长路径解压;装完自动把游戏路径指到该版本目录 +- 右侧内容区按导航切换:启动设置与日志 / 命令快捷入口 / config 编辑 / 关于 ### 接入链路 @@ -49,11 +45,9 @@ CLR 按文件名找程序集时找不到,`UI/Boot.cs` 的 `AssemblyResolve` 里做了映射 2. 从 exe 的 `PCL.Resources.resources` 提取内嵌依赖 (`MeloongCore` / `MeloongCore.Wpf` / `PCLCS` / `Newtonsoft.Json` 等)到 `pcl\` -3. `PclStyles.xaml`(**完整资源字典**:颜色 + 全部控件样式/模板)已内置在 - `src/PclStyles.xaml`,取自 PCL NEMC 的 `Application.xaml`;构建时按 - `pcl\PclStyles.xaml` 拷进输出目录,运行时 `XamlReader.Parse` 合并进 - `Application.Resources`(PCL 程序集名带空格,无法走编译期合并)。 - 这一份不用再手工从 exe / 源码里抽。 +3. 从 `Application.xaml` 抽取**完整资源字典**(颜色 + 全部控件样式/模板)→ + `PclStyles.xaml`,运行时 `XamlReader.Parse` 合并进 `Application.Resources` + (PCL 程序集名带空格,无法走编译期合并) 4. 宿主启动时补齐 PCL 原版 `Application_Startup` 的三件初始化 (`UI/PclMainWindow.Layout.cs → EnsurePclRuntime`): `MeloongCore.Main.Init("PCL")` + `MeloongCore.Wpf.Main.Init()`、 @@ -71,7 +65,6 @@ ModPc\ ├── pcl\ PCL2 运行时(约 9 MB,必须和 exe 同目录) │ ├── PCL.Core.dll 原 PCL2 程序集(改名的 Plain Craft Launcher 2.exe) │ ├── MeloongCore.dll / MeloongCore.Wpf.dll / PCLCS.dll -│ ├── PclStyles.xaml 样式表(构建时从 src\ 自动拷入;换配色改这一份) │ ├── head.png 从 PCL 资源裁出的史蒂夫头像 │ └── ...(其余依赖) ├── config.json diff --git a/README.md b/README.md index 30718bb..15de46a 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ LICENSE ## 开发者 - **kaka**([ESCc13](https://github.com/ESCc13)) -- **Publish VarInt** ([Github](https://github.com/public-claude)) +- **Publish VarInt** - **BivUraMLP** ## 声明 diff --git a/build.bat b/build.bat deleted file mode 100644 index 06aa85b..0000000 --- a/build.bat +++ /dev/null @@ -1,82 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion -cd /d "%~dp0" - -echo ============================================ -echo ES Tool 编译 + 部署 -echo ============================================ -echo. - -if not exist "ModPcGUI\pcl\PCL.Core.dll" ( - echo [警告] ModPcGUI\pcl\PCL.Core.dll 不存在。 - echo 请先按 使用说明.md 第 1 步把 PCL2 的 exe 改名为 PCL.Core.dll 放进 pcl\ - echo 缺它编译能过,但运行起来没有 PCL 原生界面。 - echo. -) - -set SRC=ModPcGUI\src -set OUT=%SRC%\bin\Debug\net48 - -echo [1/3] 编译 %SRC% ... -pushd "%SRC%" -dotnet build -v m -if errorlevel 1 ( - popd - echo. - echo [失败] 编译不通过,已中止部署。 - goto :end -) -popd - -echo. -echo [2/3] 检查编译产物 ... -if not exist "%OUT%\ModPcGUI.exe" ( - echo [失败] 没找到 %OUT%\ModPcGUI.exe - goto :end -) -echo %OUT%\ModPcGUI.exe - -REM ---- 部署目标:优先同级的 ES_Tool_data(运行时数据所在目录)---- -set DEST= -if exist "..\ES_Tool_data\config.json" set DEST=..\ES_Tool_data -if "!DEST!"=="" if exist "ES_Tool_data\config.json" set DEST=ES_Tool_data - -echo. -echo [3/3] 部署 ... -if "!DEST!"=="" ( - echo [跳过] 没找到 ES_Tool_data,只保留编译产物。 - echo 若要单独运行,把 %OUT% 整个目录复制走即可 - echo (程序首次启动会自动补 config.json 和 user\)。 - goto :end -) - -echo 目标:!DEST! -tasklist /FI "IMAGENAME eq ModPcGUI.exe" 2>nul | find /I "ModPcGUI.exe" >nul -if not errorlevel 1 ( - echo. - echo [警告] 检测到 ModPcGUI.exe 正在运行,请先关闭它,否则部署会失败。 - echo. - pause -) - -if exist "!DEST!\ModPcGUI.exe" copy /y "!DEST!\ModPcGUI.exe" "!DEST!\ModPcGUI.exe.bak" >nul -copy /y "%OUT%\ModPcGUI.exe" "!DEST!\ModPcGUI.exe" >nul -if errorlevel 1 ( - echo [失败] 复制 exe 失败(文件被占用?关掉程序再试)。 - goto :end -) - -REM 样式表按需同步:改了 PclStyles.xaml 才需要 -if exist "%OUT%\pcl\PclStyles.xaml" ( - copy /y "%OUT%\pcl\PclStyles.xaml" "!DEST!\pcl\PclStyles.xaml" >nul -) -if exist "!DEST!\crash.log" move /y "!DEST!\crash.log" "!DEST!\crash.log.prev" >nul - -echo 已部署:!DEST!\ModPcGUI.exe -echo. -echo [完成] 双击 !DEST!\ModPcGUI.exe 运行。 - -:end -echo. -pause