diff --git a/README.md b/README.md index d720f0f..9a935ba 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ 2. 解压到固定目录,例如 `%LOCALAPPDATA%\LightTranslate`,双击 `LightTranslate.exe`。 3. 在桌面应用中选中英文,查看鼠标旁的译文。 -启动后,系统托盘会出现“译”图标。右键可开关自动翻译、打开设置文件或退出; +启动后,系统托盘会出现“译”图标。右键可开关自动翻译、打开设置面板、打开设置文件或退出; 双击图标可直接切换自动翻译。 轻译面向支持复制选区的桌面应用,默认跳过终端和纯中文选区,每次最多选择 2,000 个字符。 @@ -32,14 +32,39 @@ ## 按自己的习惯设置 -设置保存在应用目录的 `settings.json`。退出轻译后修改,重新启动即可生效。 -可以通过 `ExcludedApps` 排除指定应用,填写进程名称,例如: +在托盘“译”图标上右键,选择 **设置…**。面板分为“翻译、浮层、启动”三页,保存后生效: + +- **翻译**:自动划词开关、剪贴板取词开关、微软在线目标语言、单次选区长度上限、排除应用和最低英文占比。托盘开关会立即生效并同步到已打开的面板;面板中的改动在保存后应用。关闭剪贴板取词后不获取选区。目标语言只影响微软在线翻译,本地词库和腾讯备用仍输出中文。 +- **启动**:读取实际的当前用户启动项,显示当前目录是否开机自启;只有改变选择并保存时才创建或移除启动快捷方式。不写入 `settings.json` 的自启标志,也不默认开启自启。保存失败会显示错误;配置保存失败时会尝试恢复启动项,恢复失败会显示实际状态供检查。 + +“浮层”页保留以下阅读设置;最低英文占比在“翻译”页: + +- **字体和字号**:选择已安装字体,字号范围为 10–48,默认 14。 +- **背景色**:留空跟随系统明暗主题,或使用选色器 / `#RRGGBB`;文字颜色自动调整,保持至少 4.5:1 的对比度。 +- **自动消失**:默认按译文长度停留 6–22 秒,也可设置 1–120 秒。鼠标悬停时续时;移远、打字、点击外部、滚动外部页面或切换应用仍会提前收起。等待和错误提示保留原来的时长,短停留时间不会提前中断等待中的翻译。 +- **最低英文占比**:范围 0–100%。大于 0% 时,A–Z/a–z 字母数占全部 Unicode 文字字母数的比例达到阈值(含等于)才翻译;中文和其他语言字母计入分母,标点、空白、数字、表情及组合音调符号不计入。全角字母和带重音字母计入分母,但不计为 A–Z/a–z。例如 `abc中文` 为 60%,`Hello中文` 约为 71%。 + +默认 0% 关闭新增比例限制,保留原有的非中文语言过滤(包括原先可翻译的其他语言); +纯符号、纯数字、空白和纯中文选区仍跳过。大于 0% 时,选区必须含 A–Z/a–z。 +这只是字符规则,不是自然语言识别。 + +保存后配置立即生效并写入应用目录的 `settings.json`;开机自启保存在当前用户启动文件夹。 +取消或关闭窗口不会保存配置,也不会改动启动项。 +“恢复配置默认值”只恢复面板里的配置输入,保留自启选择,点击保存后才生效;不修改隐藏的诊断开关。 +旧配置缺少新字段时沿用原有字体、主题、停留时间和语言过滤。 +诊断开关保留为开发排查用的文件配置,不在普通面板中显示。缓存仍为进程内部行为。 +排除应用每行一个进程名称,可带或不带 `.exe`,也可用逗号或分号分隔;原有配置未改动的值会保留。例如: ```json "ExcludedApps": ["SomeApp", "AnotherApp"] ``` -如需开机启动,在解压目录使用 PowerShell 7 运行: +开机自启沿用 `startup.ps1` 的当前用户 `LightTranslate.lnk`,无需从面板运行脚本。 +指向其他副本的同名启动项、无法读取的状态或 Windows 禁用记录不会被覆盖;面板会提示检查并可刷新。 +Windows 已禁用的启动项需在系统启动应用中处理,面板不会更改系统审批或防护设置。 +便携目录移动后,应先检查原启动项。 + +现有命令行脚本仍保留。如需手动创建开机启动项,在解压目录使用 PowerShell 7 运行: ```powershell pwsh -File .\startup.ps1 diff --git a/build.ps1 b/build.ps1 index 09c88c7..3cddb97 100644 --- a/build.ps1 +++ b/build.ps1 @@ -14,11 +14,12 @@ $references = @('System.dll','System.Core.dll','System.Net.Http.dll','System.Dra ForEach-Object { '/r:' + (Join-Path $framework $_) } $references += @('WindowsBase.dll','PresentationCore.dll','PresentationFramework.dll') | ForEach-Object { '/r:' + (Join-Path $framework ('WPF\' + $_)) } +$sourceFiles = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'src') -Filter '*.cs' -File | ForEach-Object { $_.FullName }) & $compiler /nologo /target:winexe /platform:x64 /optimize+ ` ('/out:' + (Join-Path $outputPath 'LightTranslate.exe')) ` ('/win32manifest:' + (Join-Path $PSScriptRoot 'src\LightTranslate.manifest')) ` ('/win32icon:' + (Join-Path $PSScriptRoot 'assets\LightTranslate.ico')) ` - @references (Join-Path $PSScriptRoot 'src\LightTranslate.cs') + @references @sourceFiles if ($LASTEXITCODE -ne 0) { throw 'Compilation failed.' } Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'src\LightTranslate.exe.config'), (Join-Path $PSScriptRoot 'LICENSE'), (Join-Path $PSScriptRoot 'README.md'), diff --git a/docs/TESTING.md b/docs/TESTING.md index 0525b8e..fef41a0 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -17,6 +17,16 @@ pwsh -File .\scripts\test.ps1 请求取消、对象回收和浮层窗口样式。它会创建自己的测试控件并渲染浮层, 不会显示窗口或向其他桌面应用注入输入。 +阅读设置自检额外覆盖旧配置兼容、非法数值回退、字体/背景/时间/比例保存、 +表单校验、保存失败不应用、取消与恢复默认值不误保存。配置写入先使用临时文件, +再原子替换原配置。测试只在输出目录创建自己的临时配置并在结束时清理。 +自检还覆盖悬停续时、移远宽限期和超时边界,以及英文比例的等号边界、混合文字、 +补充平面 Unicode 和标点/数字/空白/表情排除。背景文字对比度检查采样 4,096 个 RGB 颜色。 + +输出目录中会生成 `reading-settings-preview.png`、`reading-settings-custom-preview.png` +和 `reading-settings-error-preview.png`,使用真实 WPF 控件离屏渲染默认、定制及错误状态。 +这些渲染图不代替实际桌面的焦点、键盘、选色器、DPI 和滚动交互验收。 + 输入监听回归测试会阻塞 UI 调度器,检查独立监听线程仍能处理消息; 随后移除本进程的原生监听,检查恢复机制自动重新安装,并确认捕获的消息交回 UI 调度器。 @@ -39,7 +49,8 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 ## 配置字段 -修改应用目录的 `settings.json`,重启后生效。 +托盘“设置…”分为翻译、浮层和启动三页。配置保存后立即生效,修改应用目录的 `settings.json` 则重启后生效。 +自动翻译的托盘快捷切换与已打开面板同步;保存开关失败会恢复托盘勾选并提示错误。 `Diagnostics` 开关每两秒读取一次,可在排查后直接关闭,无需重启。 | 字段 | 默认值 | 作用 | @@ -50,9 +61,39 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 | `MaxSelectionLength` | `2000` | 单次选区字符数上限 | | `ExcludedApps` | `[]` | 排除的进程名称,可带或不带 `.exe` | | `Diagnostics` | `false` | 触发诊断日志开关 | +| `BubbleFontFamily` | `Microsoft YaHei UI` | 浮层字体族,使用已安装的字体;缺失或未知字体回退默认 | +| `BubbleFontSize` | `14` | 浮层字号,10–48 DIP(随系统 DPI 缩放) | +| `BubbleBackground` | `""` | 空字符串跟随系统主题,或不透明的 `#RRGGBB`;自动选择对比度 ≥4.5:1 的文字颜色 | +| `AutoHideSeconds` | `0` | 0 沿用原有译文时长(6–22 秒);1–120 为译文固定秒数,保留悬停续时及提前收起规则。等待和错误提示仍使用原来的时长,避免短设置值中断请求 | +| `MinEnglishPercent` | `0` | 0 关闭新增过滤并保留旧语言规则;1–100 为 A–Z/a–z ÷ 全部 Unicode 字母的最低百分比,等于阈值也触发 | + +这些新字段缺失时保留原有默认行为;手动写入越界或非有限字号、非法颜色、未知字体时回退对应默认值。 +英文比例排除空白、标点、数字、表情及组合音调符号;中文和其他语言字母计入分母。 +补充平面的字母按 Unicode 标量计一次,全角 Latin / 重音字母计入分母但不计英文分子。 +大于 0% 时没有 A–Z/a–z 的文本不触发;0% 时无文字字母或纯中文仍被原有规则跳过。 `ClipboardFallback` 沿用早期字段名,当前取词路径统一使用剪贴板。 +面板纳入 `Enabled`、`ClipboardFallback`、`Target`、`MaxSelectionLength`、`ExcludedApps` +和五项阅读选项。目标语言只校验修改后输入的语言标签语法,不联网获取语言列表;服务是否支持自定义标签由微软决定。 +修改后的选区上限要求正整数,排除应用支持换行及中英文逗号/分号,按进程名校验、去重。 +未改动的原有自定义目标、长度和排除数组逐值保留;隐藏的 `Diagnostics` 克隆保留,不因普通设置或恢复默认值而重置。 + +### 开机自启 + +开机自启以当前用户启动文件夹的 `LightTranslate.lnk` 和实际目标路径为准,不额外持久化一个可能失真的 JSON 布尔值。 +读取还会保守检查当前用户 `StartupApproved/StartupFolder` 的常见 12 字节记录:已禁用或未知状态不视为启用,且不修改审批注册表。 +同名快捷方式指向其他目标或带有参数时不覆盖/删除;读取失败显示无法确认,其他配置仍可保存。 +仅用户改变自启选择并保存时写入当前目录的快捷方式,不使用服务、计划任务、提权或安全设置变更。 +写入后重新读取验证;配置保存失败时恢复启动项原字节,无法恢复时明确报错并显示重新读取的状态。 +回滚发现启动项已被其他程序更改时拒绝覆盖新内容。 + +统一设置测试使用模拟后端覆盖往返、取消、保存失败、部分失败、未知/禁用状态及托盘同步; +真实 WScript 快捷方式测试使用输出目录中的独立临时文件夹,验证创建/读取/移除、原字节恢复、异目标保护及 I/O 失败, +不使用真实 Startup 目录、不读取或写入真实审批值。测试结束清理自身临时文件。 +另生成 `settings-translation-preview.png`、`settings-startup-preview.png` 和 `settings-startup-error-preview.png`。 +图中的自启状态是明确标注的隔离/模拟样例,不代表测试机真实状态。 + ## 取词与数据处理 程序使用带内部标记的 `Ctrl+C` 获取选区,并尝试保存、恢复原剪贴板的各格式。 @@ -85,7 +126,7 @@ Windows 的低级监听超时机制见 [Microsoft 文档](https://learn.microsof 从普通权限进程获取管理员应用的选区受 Windows 权限限制。 当前功能聚焦划词阅读:本地词库可离线,句子翻译使用网络。 -OCR、朗读、翻译历史、原位替换、AI 润色、图形设置、自动更新、安装器和代码签名暂未实现。 +OCR、朗读、翻译历史、原位替换、AI 润色、自动更新、安装器和代码签名暂未实现。 ## 手动验证清单 @@ -100,3 +141,9 @@ OCR、朗读、翻译历史、原位替换、AI 润色、图形设置、自动 7. 连续快速选择不同文字,检查旧响应是否影响当前译文。 8. 检查终端、密码框、排除应用、多显示器、DPI 和屏幕边缘。 9. 持续运行数小时,并在重启 Windows 后检查自启动与划词。 +10. 在设置的浮层页选择不同字体、10/48 字号及浅/深/中等亮度背景;确认实际浮层、预览、文字对比度、缩放和长译文滚动。 +11. 将时间设为 1/10/120 秒,鼠标停在选区附近但不覆盖浮层检查超时;悬停后移回附近检查重新计时,移远和外部操作仍提前收起。 +12. 比例设为 60%,选择 `abc中文` 应翻译,设为 61% 则不触发;选择 `abc中文!? 123` 的结果相同。100% 时纯英文触发、中英混合不触发;0% 保留旧过滤。 +13. 输入非法颜色、字号、秒数或比例,确认就地报错且不保存;取消和关闭设置不应用,重启后保留已保存的值且不改动自动翻译开关等其他设置。 +14. 打开面板后切换托盘自动翻译,再保存其他选项,确认开关不会被旧值覆盖;目标语言、选区上限、排除应用和取词开关即时应用,取消不应用。 +15. 自启验证只在隔离目录或模拟后端完成;打开、勾选、恢复配置默认值和取消均不得写入,只有保存才能修改;覆盖禁用/未知/异目标以及保存和回滚失败状态。真实用户启动项由用户自行选择,不作为自动测试动作。 diff --git a/settings.example.json b/settings.example.json index 5a36cf1..814ec0d 100644 --- a/settings.example.json +++ b/settings.example.json @@ -4,5 +4,10 @@ "Target": "zh-Hans", "MaxSelectionLength": 2000, "ExcludedApps": [], - "Diagnostics": false + "Diagnostics": false, + "BubbleFontFamily": "Microsoft YaHei UI", + "BubbleFontSize": 14, + "BubbleBackground": "", + "AutoHideSeconds": 0, + "MinEnglishPercent": 0 } diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index ded4c79..3b4ee70 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -84,20 +84,72 @@ internal sealed class Settings public int MaxSelectionLength = 2000; public string[] ExcludedApps = new string[0]; public bool Diagnostics = false; + public string BubbleFontFamily = "Microsoft YaHei UI"; + public double BubbleFontSize = 14; + public string BubbleBackground = ""; + public int AutoHideSeconds = 0; + public int MinEnglishPercent = 0; + internal event Action Changed; public static Settings Load() + { return Load(Path.Combine(Program.Folder, "settings.json")); } + internal static Settings Load(string path) { try { - var path = Path.Combine(Program.Folder, "settings.json"); - if (File.Exists(path)) return new JavaScriptSerializer().Deserialize(File.ReadAllText(path)); + if (File.Exists(path)) + { + var loaded = new JavaScriptSerializer().Deserialize(File.ReadAllText(path)); + if (loaded != null) { loaded.NormalizeReading(); return loaded; } + } } catch { } return new Settings(); } + internal void NormalizeReading() + { + BubbleFontFamily = BubbleAppearance.ResolveFont(BubbleFontFamily).Source; + if (double.IsNaN(BubbleFontSize) || double.IsInfinity(BubbleFontSize) || BubbleFontSize < 10 || BubbleFontSize > 48) BubbleFontSize = 14; + Color color; + BubbleBackground = BubbleAppearance.TryParseBackground(BubbleBackground, out color) ? BubbleBackground.Trim().ToUpperInvariant() : ""; + if (AutoHideSeconds < 0 || AutoHideSeconds > 120) AutoHideSeconds = 0; + if (MinEnglishPercent < 0 || MinEnglishPercent > 100) MinEnglishPercent = 0; + } + internal Settings Clone() + { return new JavaScriptSerializer().Deserialize(new JavaScriptSerializer().Serialize(this)); } + internal void CopyReadingFrom(Settings other) + { + BubbleFontFamily = other.BubbleFontFamily; BubbleFontSize = other.BubbleFontSize; + BubbleBackground = other.BubbleBackground; AutoHideSeconds = other.AutoHideSeconds; + MinEnglishPercent = other.MinEnglishPercent; + } + internal void CopyUserFrom(Settings other) + { + Enabled = other.Enabled; ClipboardFallback = other.ClipboardFallback; + Target = other.Target; MaxSelectionLength = other.MaxSelectionLength; + ExcludedApps = other.ExcludedApps == null ? null : (string[])other.ExcludedApps.Clone(); + CopyReadingFrom(other); + if (Changed != null) Changed(); + } + internal bool TrySetEnabled(bool enabled, string path) + { + var next = Clone(); next.Enabled = enabled; + if (!next.TrySave(path)) return false; + CopyUserFrom(next); return true; + } public void Save() + { TrySave(Path.Combine(Program.Folder, "settings.json")); } + internal bool TrySave(string path) { - try { File.WriteAllText(Path.Combine(Program.Folder, "settings.json"), new JavaScriptSerializer().Serialize(this), Encoding.UTF8); } - catch { } + string temporary = path + ".tmp-" + Guid.NewGuid().ToString("N"); + try + { + File.WriteAllText(temporary, new JavaScriptSerializer().Serialize(this), Encoding.UTF8); + if (File.Exists(path)) File.Replace(temporary, path, null); + else File.Move(temporary, path); + return true; + } + catch { return false; } + finally { try { if (File.Exists(temporary)) File.Delete(temporary); } catch { } } } } @@ -118,8 +170,8 @@ internal sealed class Controller : IDisposable private Native.POINT downPoint, previousUp, anchor; private IntPtr downWindow, sourceWindow; private uint lastUpTime; - private DateTime shownAt, awayAt; - private int displaySeconds; + private readonly BubbleLifetime lifetime = new BubbleLifetime(); + private SettingsWindow settingsWindow; private readonly Queue diagnosticQueue = new Queue(); private long mouseEvents, mouseDowns, mouseUps, selections; private DateTime nextHeartbeat, nextHealthLog, nextSettingsCheck; @@ -132,11 +184,22 @@ public Controller(Application app) translator = new Translator(); var warming = translator.WarmConnection(); bubble = new Bubble(); + bubble.ApplySettings(settings); tray = new Forms.NotifyIcon { Text = "轻译 · 选中即译", Icon = MakeIcon(), Visible = true }; var menu = new Forms.ContextMenuStrip(); enabledItem = new Forms.ToolStripMenuItem("自动划词翻译") { Checked = settings.Enabled, CheckOnClick = true }; - enabledItem.Click += delegate { settings.Enabled = enabledItem.Checked; settings.Save(); Dismiss(true); }; + enabledItem.Click += delegate + { + if (!settings.TrySetEnabled(enabledItem.Checked, Path.Combine(Program.Folder, "settings.json"))) + { + enabledItem.Checked = settings.Enabled; + tray.ShowBalloonTip(4000, "轻译", "无法保存自动翻译开关,请检查应用目录是否可写。", Forms.ToolTipIcon.Error); + return; + } + Dismiss(true); + }; menu.Items.Add(enabledItem); + menu.Items.Add("设置…", null, delegate { OpenSettings(); }); menu.Items.Add("打开设置文件", null, delegate { Process.Start("notepad.exe", Path.Combine(Program.Folder, "settings.json")); }); menu.Items.Add(new Forms.ToolStripSeparator()); menu.Items.Add("退出轻译", null, delegate { app.Shutdown(); }); @@ -150,6 +213,19 @@ public Controller(Application app) Program.Log("started", "hooks=dedicated-thread recovery=enabled capture=clipboard dictionary=" + lexicon.Count); } + private void OpenSettings() + { + Dismiss(true); + if (settingsWindow != null) + { + if (settingsWindow.WindowState == WindowState.Minimized) settingsWindow.WindowState = WindowState.Normal; + settingsWindow.Activate(); return; + } + settingsWindow = new SettingsWindow(settings, delegate { enabledItem.Checked = settings.Enabled; Dismiss(true); bubble.ApplySettings(settings); }); + settingsWindow.Closed += delegate { settingsWindow = null; }; + settingsWindow.Show(); + } + internal static System.Drawing.Icon MakeIcon() { using (var bmp = new System.Drawing.Bitmap(32, 32)) @@ -243,7 +319,7 @@ private void Dismiss(bool immediate) generation++; if (pending != null) { pending.Cancel(); pending = null; } if (bubble.IsVisible) bubble.Dismiss(immediate); - awayAt = DateTime.MinValue; + lifetime.Reset(); } private async void BeginSelection(IntPtr window, Native.POINT point) @@ -274,7 +350,7 @@ private async void BeginSelection(IntPtr window, Native.POINT point) Trace("clipboard chars=" + (text == null ? 0 : text.Length)); if (!Valid(version, window) || string.IsNullOrWhiteSpace(text)) { Trace("selection discarded valid=" + Valid(version, window)); return; } text = text.Trim(); - if (!SelectionReader.HasForeignText(text)) { Trace("Chinese-only selection skipped"); return; } + if (!SelectionReader.ShouldTranslate(text, settings.MinEnglishPercent)) { Trace("selection language threshold skipped"); return; } anchor = point; sourceWindow = window; if (text.Length > settings.MaxSelectionLength) @@ -285,7 +361,7 @@ private async void BeginSelection(IntPtr window, Native.POINT point) string translated = lexicon.Lookup(text); if (translated != null || translator.TryCached(text, settings.Target, out translated)) { - ShowText(translated, point, ReadingSeconds(translated)); + ShowText(translated, point, ReadingSeconds(translated), true); return; } var request = translator.Translate(text, settings.Target, ct); @@ -293,7 +369,7 @@ private async void BeginSelection(IntPtr window, Native.POINT point) ShowText("…", point, 8); translated = await request; if (!Valid(version, window)) return; - ShowText(translated, point, ReadingSeconds(translated)); + ShowText(translated, point, ReadingSeconds(translated), true); } catch (OperationCanceledException) { } catch (Exception ex) @@ -312,11 +388,9 @@ private bool Valid(int version, IntPtr window) return !disposed && version == generation && settings.Enabled && Native.GetForegroundWindow() == window; } private static int ReadingSeconds(string text) { return Math.Max(6, Math.Min(22, 4 + text.Length / 12)); } - private void ShowText(string text, Native.POINT point, int seconds) + private void ShowText(string text, Native.POINT point, int seconds, bool translated = false) { - displaySeconds = seconds; - shownAt = DateTime.UtcNow; - awayAt = DateTime.MinValue; + lifetime.Start(DateTime.UtcNow, BubbleLifetime.DisplaySeconds(settings.AutoHideSeconds, seconds, translated)); bubble.Present(text, point); Trace("bubble visible=" + bubble.IsVisible + " chars=" + text.Length); } @@ -354,15 +428,7 @@ private void CheckDismissal() Native.GetCursorPos(out point); bool near = Math.Abs(point.x - anchor.x) < 120 && Math.Abs(point.y - anchor.y) < 90; bool over = bubble.Contains(point); - var now = DateTime.UtcNow; - if (over) { shownAt = now; awayAt = DateTime.MinValue; return; } - if (!near) - { - if (awayAt == DateTime.MinValue) awayAt = now; - if ((now - awayAt).TotalMilliseconds > 550 && (now - shownAt).TotalMilliseconds > 900) { Dismiss(false); return; } - } - else awayAt = DateTime.MinValue; - if ((now - shownAt).TotalSeconds > displaySeconds) Dismiss(false); + if (lifetime.ShouldDismiss(DateTime.UtcNow, near, over)) Dismiss(false); } public void Dispose() { @@ -374,6 +440,7 @@ public void Dispose() tray.Visible = false; tray.Icon.Dispose(); tray.Dispose(); + if (settingsWindow != null) settingsWindow.Close(); bubble.Close(); translator.Dispose(); lexicon.Dispose(); @@ -605,6 +672,23 @@ public static bool HasForeignText(string text) { return text.Any(c => char.IsLetter(c) && !(c >= '\u3400' && c <= '\u9fff')); } + internal static bool ShouldTranslate(string text, int minimumPercent) + { + if (string.IsNullOrWhiteSpace(text) || !HasForeignText(text)) return false; + // Zero disables the new ratio filter, preserving the existing language guard. + if (minimumPercent <= 0) return true; + int english = 0, letters = 0; + for (int i = 0; i < text.Length; i++) + { + if (char.IsLetter(text, i)) + { + letters++; + if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) english++; + } + if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])) i++; + } + return english > 0 && english * 100L >= letters * (long)minimumPercent; + } public static async Task CopySelection(IntPtr window, CancellationToken ct, Action trace) { if (Native.GetForegroundWindow() != window || Native.ModifierDown()) { trace("copy skipped focus/modifier"); return null; } @@ -711,19 +795,7 @@ public Bubble() Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 18, Opacity = 0.15, ShadowDepth = 3 } }; Content = new Border { Padding = new Thickness(12), Child = card }; - try - { - using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")) - { - if (key != null && Convert.ToInt32(key.GetValue("AppsUseLightTheme", 1)) == 0) - { - card.Background = new SolidColorBrush(Color.FromRgb(37, 40, 47)); - card.BorderBrush = new SolidColorBrush(Color.FromArgb(38, 255, 255, 255)); - content.Foreground = new SolidColorBrush(Color.FromRgb(237, 239, 243)); - } - } - } - catch { } + ApplySettings(new Settings()); SourceInitialized += delegate { var handle = new WindowInteropHelper(this).Handle; @@ -735,6 +807,16 @@ public Bubble() }); }; } + internal void ApplySettings(Settings settings) + { + var background = BubbleAppearance.Background(settings.BubbleBackground); + content.FontFamily = BubbleAppearance.ResolveFont(settings.BubbleFontFamily); + content.FontSize = settings.BubbleFontSize; + content.LineHeight = settings.BubbleFontSize * 23 / 14; + content.Foreground = new SolidColorBrush(BubbleAppearance.Foreground(background)); + card.Background = new SolidColorBrush(background); + card.BorderBrush = new SolidColorBrush(BubbleAppearance.Border(background)); + } public bool Contains(Native.POINT p) { if (!IsVisible) return false; @@ -1115,6 +1197,8 @@ public static int Run(bool offline) if (SelectionReader.HasForeignText("这是中文") || !SelectionReader.HasForeignText("Read this text")) throw new Exception("Language guard failed"); results["clipboardSnapshot"] = "text + HTML preserved"; results["guards"] = "terminal + language passed"; + ReadingSettingsTests.Run(results); + UnifiedSettingsTests.Run(results); Program.Log("self-test", "dictionary and clipboard snapshot passed"); if (System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies().Any(a => a.Name == "UIAutomationClient")) throw new Exception("Unsafe UIA client dependency remains"); diff --git a/src/ReadingSettings.cs b/src/ReadingSettings.cs new file mode 100644 index 0000000..2f2fb94 --- /dev/null +++ b/src/ReadingSettings.cs @@ -0,0 +1,385 @@ +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + // Same hover and pointer-away behavior as the original controller, with a configurable deadline. + internal sealed class BubbleLifetime + { + private DateTime shownAt, awayAt; + private int seconds; + internal static int DisplaySeconds(int configuredSeconds, int automaticSeconds, bool translated) + { return translated && configuredSeconds > 0 ? configuredSeconds : automaticSeconds; } + internal void Start(DateTime now, int displaySeconds) + { shownAt = now; awayAt = DateTime.MinValue; seconds = displaySeconds; } + internal void Reset() { awayAt = DateTime.MinValue; } + internal bool ShouldDismiss(DateTime now, bool near, bool over) + { + if (over) { shownAt = now; awayAt = DateTime.MinValue; return false; } + if (!near) + { + if (awayAt == DateTime.MinValue) awayAt = now; + if ((now - awayAt).TotalMilliseconds > 550 && (now - shownAt).TotalMilliseconds > 900) return true; + } + else awayAt = DateTime.MinValue; + return (now - shownAt).TotalSeconds > seconds; + } + } + + internal static class BubbleAppearance + { + internal static FontFamily ResolveFont(string name) + { + string requested = (name ?? "").Trim(); + return Fonts.SystemFontFamilies.FirstOrDefault(f => string.Equals(f.Source, requested, StringComparison.OrdinalIgnoreCase)) + ?? new FontFamily("Microsoft YaHei UI"); + } + internal static bool TryParseBackground(string text, out Color color) + { + color = Colors.Transparent; + if (string.IsNullOrWhiteSpace(text)) return false; + string value = text.Trim(); + int rgb; + if (value.Length != 7 || value[0] != '#' || !value.Substring(1).All(Uri.IsHexDigit) || !int.TryParse(value.Substring(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgb)) return false; + color = Color.FromRgb((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); + return true; + } + internal static Color Background(string text) + { + Color color; + if (TryParseBackground(text, out color)) return color; + try + { + using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")) + if (key != null && Convert.ToInt32(key.GetValue("AppsUseLightTheme", 1)) == 0) return Color.FromRgb(37, 40, 47); + } + catch { } + return Color.FromRgb(252, 252, 253); + } + private static double Channel(byte value) + { + double channel = value / 255.0; + return channel <= 0.04045 ? channel / 12.92 : Math.Pow((channel + 0.055) / 1.055, 2.4); + } + internal static double Luminance(Color color) + { return 0.2126 * Channel(color.R) + 0.7152 * Channel(color.G) + 0.0722 * Channel(color.B); } + internal static double Contrast(Color first, Color second) + { + double a = Luminance(first), b = Luminance(second); + return (Math.Max(a, b) + 0.05) / (Math.Min(a, b) + 0.05); + } + internal static Color Foreground(Color background) + { + var dark = Color.FromRgb(36, 40, 48); + var light = Color.FromRgb(237, 239, 243); + Color preferred = Luminance(background) < 0.35 ? light : dark; + if (Contrast(background, preferred) >= 4.5) return preferred; + // Opaque RGB backgrounds guarantee that black or white reaches at least 4.5:1. + return Contrast(background, Colors.Black) >= Contrast(background, Colors.White) ? Colors.Black : Colors.White; + } + internal static Color Border(Color background) + { return Luminance(background) < 0.35 ? Color.FromArgb(38, 255, 255, 255) : Color.FromArgb(35, 40, 48, 64); } + } + + internal sealed class SettingsWindow : Window + { + private const string Automatic = "自动(按译文长度)"; + private static readonly string[] Languages = { + "简体中文 · zh-Hans", "繁体中文 · zh-Hant", "英语 · en", "日语 · ja", "韩语 · ko", + "法语 · fr", "德语 · de", "西班牙语 · es", "俄语 · ru" + }; + private readonly Settings settings; + private readonly Action saved; + private readonly IStartupRegistration startup; + private readonly CheckBox enabled, clipboard, autoStart; + private readonly ComboBox language, fontFamily, fontSize, autoHide; + private readonly TextBox maxSelection, excludedApps, background, englishPercent; + private readonly TextBlock error, previewText, startupStatus; + private readonly Border preview; + private readonly Grid layout; + private readonly TabControl tabs; + private bool refreshingStartup, startupDirty; + private bool? observedStartup; + + internal SettingsWindow(Settings settings, Action saved, IStartupRegistration startup = null) + { + this.settings = settings; this.saved = saved; + this.startup = startup ?? StartupRegistration.CurrentUser(); + Title = "轻译 · 设置"; + Width = 620; Height = 790; MinWidth = 480; MinHeight = 450; + MaxHeight = Math.Max(450, SystemParameters.WorkArea.Height - 40); + WindowStartupLocation = WindowStartupLocation.CenterScreen; + FontFamily = new FontFamily("Microsoft YaHei UI"); FontSize = 14; + Background = Brushes.White; + layout = new Grid { Background = Brushes.White }; + layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); + layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + Content = layout; + var header = new StackPanel { Margin = new Thickness(24, 20, 24, 16) }; + header.Children.Add(new TextBlock { Text = "轻译设置", FontSize = 22, FontWeight = FontWeights.SemiBold, Foreground = Ink() }); + header.Children.Add(Help("保存后生效;取消保留当前配置和开机自启状态。")); + layout.Children.Add(header); + tabs = new TabControl { Margin = new Thickness(20, 0, 20, 0) }; + Grid.SetRow(tabs, 1); layout.Children.Add(tabs); + + var translation = NewTab("翻译"); + enabled = Toggle("自动划词翻译"); + clipboard = Toggle("通过剪贴板获取选中文字"); + translation.Children.Add(enabled); translation.Children.Add(clipboard); + translation.Children.Add(Help("托盘开关立即生效并同步到这里;面板修改在保存后生效。取词会临时复制选区并尝试恢复剪贴板,关闭取词后不获取选区。")); + language = new ComboBox { IsEditable = true, ItemsSource = Languages, MinHeight = 32 }; + AddField(translation, "目标语言(微软)", language); + translation.Children.Add(Help("可直接输入语言代码,如 en、ja。该选项只用于微软在线翻译;本地词库和腾讯备用仍输出中文。")); + maxSelection = Input(); + AddField(translation, "选区字符数上限", maxSelection); + translation.Children.Add(Help("正整数,默认 2,000。超过上限只提示分段选择,不发送该选区。")); + excludedApps = new TextBox { AcceptsReturn = true, MinHeight = 82, MaxHeight = 100, VerticalScrollBarVisibility = ScrollBarVisibility.Auto }; + AddField(translation, "排除应用", excludedApps); + translation.Children.Add(Help("每行一个进程名,也可用逗号或分号分隔,如 SomeApp 或 SomeApp.exe;不要填写路径。")); + englishPercent = Input(); + AddField(translation, "最低英文占比(%)", englishPercent); + translation.Children.Add(Help("0–100%。A–Z/a–z 字母数 ÷ 全部文字字母数;中文及其他语言计入分母,标点、空白、数字不计。Hello中文约为 71%。")); + translation.Children.Add(Help("0% 保留原语言过滤;纯中文和没有字母的选区仍跳过。大于 0% 时必须含 A–Z/a–z。")); + + var appearance = NewTab("浮层"); + appearance.Children.Add(Heading("外观")); + fontFamily = new ComboBox { ItemsSource = Fonts.SystemFontFamilies.Select(f => f.Source).OrderBy(x => x).ToArray(), MinHeight = 32 }; + AddField(appearance, "字体", fontFamily); + fontSize = new ComboBox { IsEditable = true, ItemsSource = new[] { "10", "12", "14", "16", "18", "20", "24", "32", "48" }, MinHeight = 32 }; + AddField(appearance, "字号", fontSize); + background = Input(); + var colorRow = new Grid(); + colorRow.ColumnDefinitions.Add(new ColumnDefinition()); colorRow.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + colorRow.Children.Add(background); + var pick = Button("选色…"); pick.Margin = new Thickness(8, 0, 0, 0); Grid.SetColumn(pick, 1); + AutomationProperties.SetName(pick, "选择浮层背景色"); + pick.Click += delegate { PickColor(); }; colorRow.Children.Add(pick); + AddField(appearance, "背景色", colorRow); AutomationProperties.SetName(background, "浮层背景色"); + appearance.Children.Add(Help("留空跟随系统明暗主题,或填写 #RRGGBB。文字颜色自动保持对比度。")); + previewText = new TextBlock { Text = "译文会使用这个字体和背景。\nSelect text to translate.", TextWrapping = TextWrapping.Wrap }; + preview = new Border { + Padding = new Thickness(15, 10, 15, 11), Margin = new Thickness(0, 12, 0, 20), CornerRadius = new CornerRadius(11), + BorderThickness = new Thickness(1), MinHeight = 82, MaxHeight = 180, + Child = new ScrollViewer { Content = previewText, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled } + }; + AutomationProperties.SetName(preview, "浮层外观示例预览"); appearance.Children.Add(preview); + appearance.Children.Add(Heading("停留时间")); + autoHide = new ComboBox { IsEditable = true, ItemsSource = new[] { Automatic, "3", "6", "10", "15", "30", "60", "120" }, MinHeight = 32 }; + AddField(appearance, "自动消失(秒)", autoHide); + appearance.Children.Add(Help("译文自动停留 6–22 秒,也可填 1–120 秒。悬停时续时,移远或继续操作仍会提前收起;等待和错误提示保留原时长。")); + + var launch = NewTab("启动"); + launch.Children.Add(Heading("登录 Windows 后启动")); + autoStart = Toggle("开机自启(仅当前用户)"); launch.Children.Add(autoStart); + startupStatus = Help(""); startupStatus.Margin = new Thickness(0, 0, 0, 14); launch.Children.Add(startupStatus); + var refresh = Button("刷新启动状态"); refresh.HorizontalAlignment = HorizontalAlignment.Left; + refresh.Click += delegate { RefreshStartup(); }; launch.Children.Add(refresh); + launch.Children.Add(Help("只有修改此选项并保存时才创建或移除当前目录的启动快捷方式。不会提权,不使用服务或计划任务,也不会修改 Windows 的审批或防护设置。")); + launch.Children.Add(Help("若存在指向其他副本的同名启动项,或 Windows 已禁用它,会提示原因并保留原状态。移动便携目录后,请检查原启动项。")); + + AutomationProperties.SetHelpText(fontSize, "范围 10 到 48,默认 14,随系统缩放"); + AutomationProperties.SetHelpText(background, "留空跟随系统主题,或输入不透明六位十六进制颜色 #RRGGBB"); + AutomationProperties.SetHelpText(autoHide, "自动,或 1 到 120 秒;鼠标悬停保留浮层"); + AutomationProperties.SetHelpText(englishPercent, "范围 0 到 100,分母为全部 Unicode 字母,不含空白、数字和标点"); + + var footer = new StackPanel { Margin = new Thickness(24, 12, 24, 18) }; + error = new TextBlock { Foreground = new SolidColorBrush(Color.FromRgb(180, 35, 24)), TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 10), Visibility = Visibility.Collapsed }; + AutomationProperties.SetName(error, "设置错误"); footer.Children.Add(error); + var actions = new Grid(); actions.ColumnDefinitions.Add(new ColumnDefinition()); actions.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + var reset = Button("恢复配置默认值"); reset.HorizontalAlignment = HorizontalAlignment.Left; + AutomationProperties.SetHelpText(reset, "只恢复配置输入,不改变开机自启选择;保存后才生效"); + reset.Click += delegate { Fill(new Settings()); }; actions.Children.Add(reset); + var right = new StackPanel { Orientation = Orientation.Horizontal }; + var cancel = Button("取消"); cancel.Click += delegate { Close(); }; right.Children.Add(cancel); + var save = Button("保存"); save.IsDefault = true; save.Margin = new Thickness(8, 0, 0, 0); + save.Background = new SolidColorBrush(Color.FromRgb(56, 112, 210)); save.Foreground = Brushes.White; + save.Click += delegate { Apply(Path.Combine(Program.Folder, "settings.json")); }; right.Children.Add(save); + Grid.SetColumn(right, 1); actions.Children.Add(right); footer.Children.Add(actions); + Grid.SetRow(footer, 2); layout.Children.Add(footer); + fontFamily.SelectionChanged += delegate { UpdatePreview(); }; + fontSize.AddHandler(System.Windows.Controls.Primitives.TextBoxBase.TextChangedEvent, new TextChangedEventHandler(delegate { UpdatePreview(); })); + background.TextChanged += delegate { UpdatePreview(); }; + autoStart.Checked += delegate { StartupChoiceChanged(); }; autoStart.Unchecked += delegate { StartupChoiceChanged(); }; + PreviewKeyDown += delegate(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { e.Handled = true; Close(); } }; + settings.Changed += SyncEnabled; + Closed += delegate { settings.Changed -= SyncEnabled; }; + Activated += delegate { RefreshStartup(); }; + Fill(settings); RefreshStartup(); + } + private StackPanel NewTab(string name) + { + var form = new StackPanel { Margin = new Thickness(16, 16, 16, 20) }; + tabs.Items.Add(new TabItem { Header = name, Content = new ScrollViewer { Content = form, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled } }); + return form; + } + private static Brush Ink() { return new SolidColorBrush(Color.FromRgb(36, 40, 48)); } + private static TextBlock Help(string text) + { return new TextBlock { Text = text, Foreground = new SolidColorBrush(Color.FromRgb(83, 91, 105)), FontSize = 12, LineHeight = 19, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 5, 0, 6) }; } + private static TextBlock Heading(string text) + { return new TextBlock { Text = text, FontWeight = FontWeights.SemiBold, Foreground = Ink(), Margin = new Thickness(0, 0, 0, 10) }; } + private static Button Button(string text) + { return new Button { Content = text, Padding = new Thickness(14, 7, 14, 7), MinHeight = 32, MinWidth = 64 }; } + private static TextBox Input() { return new TextBox { MinHeight = 32, VerticalContentAlignment = VerticalAlignment.Center }; } + private static CheckBox Toggle(string text) + { return new CheckBox { Content = text, VerticalContentAlignment = VerticalAlignment.Center, MinHeight = 30, Margin = new Thickness(0, 0, 0, 4) }; } + private static void AddField(Panel form, string label, FrameworkElement control) + { + var row = new Grid { Margin = new Thickness(0, 0, 0, 10) }; + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(150) }); row.ColumnDefinitions.Add(new ColumnDefinition()); + row.Children.Add(new Label { Content = label, Target = control, Padding = new Thickness(0, 5, 8, 0), Foreground = Ink() }); + AutomationProperties.SetName(control, label); Grid.SetColumn(control, 1); row.Children.Add(control); form.Children.Add(row); + } + private static string LanguageLabel(string code) + { return Languages.FirstOrDefault(x => x.EndsWith(" · " + code, StringComparison.Ordinal)) ?? code ?? ""; } + private static string AppsText(string[] apps) { return apps == null ? "" : string.Join("\n", apps); } + internal void Fill(Settings value) + { + if (error != null) error.Visibility = Visibility.Collapsed; + enabled.IsChecked = value.Enabled; clipboard.IsChecked = value.ClipboardFallback; + language.Text = LanguageLabel(value.Target); + maxSelection.Text = value.MaxSelectionLength.ToString(CultureInfo.CurrentCulture); + excludedApps.Text = AppsText(value.ExcludedApps); + fontFamily.SelectedItem = BubbleAppearance.ResolveFont(value.BubbleFontFamily).Source; + fontSize.Text = value.BubbleFontSize.ToString(CultureInfo.CurrentCulture); + background.Text = value.BubbleBackground; + autoHide.Text = value.AutoHideSeconds == 0 ? Automatic : value.AutoHideSeconds.ToString(CultureInfo.CurrentCulture); + englishPercent.Text = value.MinEnglishPercent.ToString(CultureInfo.CurrentCulture); + UpdatePreview(); + } + private void SyncEnabled() { enabled.IsChecked = settings.Enabled; } + private void UpdatePreview() + { + if (preview == null) return; + double size; + if (!double.TryParse(fontSize.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out size) || size < 10 || size > 48 || double.IsNaN(size)) size = 14; + var color = BubbleAppearance.Background(background.Text); + previewText.FontFamily = BubbleAppearance.ResolveFont(fontFamily.SelectedItem as string); + previewText.FontSize = size; previewText.LineHeight = size * 23 / 14; + previewText.Foreground = new SolidColorBrush(BubbleAppearance.Foreground(color)); + preview.Background = new SolidColorBrush(color); preview.BorderBrush = new SolidColorBrush(BubbleAppearance.Border(color)); + } + private void PickColor() + { + using (var dialog = new Forms.ColorDialog { FullOpen = true }) + { + Color color; + if (BubbleAppearance.TryParseBackground(background.Text, out color)) dialog.Color = System.Drawing.Color.FromArgb(color.R, color.G, color.B); + var owner = new Forms.NativeWindow(); owner.AssignHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle); + try { + if (dialog.ShowDialog(owner) == Forms.DialogResult.OK) + background.Text = string.Format(CultureInfo.InvariantCulture, "#{0:X2}{1:X2}{2:X2}", dialog.Color.R, dialog.Color.G, dialog.Color.B); + } + finally { owner.ReleaseHandle(); } + } + } + private void StartupChoiceChanged() + { + if (refreshingStartup) return; + startupDirty = autoStart.IsChecked != observedStartup; + RefreshStartup(); + } + internal void RefreshStartup() + { + var state = startup.Read(); + refreshingStartup = true; + try { + autoStart.IsEnabled = state.CanChoose; + if (!startupDirty) { observedStartup = state.Enabled; autoStart.IsThreeState = state.Enabled == null; autoStart.IsChecked = state.Enabled; } + startupStatus.Text = state.Message + (startupDirty ? (autoStart.IsChecked == true ? "\n待保存:开启开机自启。" : "\n待保存:关闭开机自启。") : ""); + } + finally { refreshingStartup = false; } + } + private void RefreshAfterFailure() + { startupDirty = false; RefreshStartup(); } + internal bool Apply(string path) + { + double size; int seconds, percent, length; Color color; + if (!double.TryParse(fontSize.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out size) || double.IsNaN(size) || double.IsInfinity(size) || size < 10 || size > 48) + return Invalid("字号请输入 10–48 之间的数字。", fontSize, 1); + if (!string.IsNullOrWhiteSpace(background.Text) && !BubbleAppearance.TryParseBackground(background.Text, out color)) + return Invalid("背景色请留空,或填写 #RRGGBB,例如 #25282F。", background, 1); + if (autoHide.Text.Trim() == Automatic || autoHide.Text.Trim() == "0") seconds = 0; + else if (!int.TryParse(autoHide.Text.Trim(), out seconds) || seconds < 1 || seconds > 120) + return Invalid("自动消失时间请选择“自动”,或填写 1–120 秒。", autoHide, 1); + if (!int.TryParse(englishPercent.Text.Trim(), out percent) || percent < 0 || percent > 100) + return Invalid("最低英文占比请输入 0–100 的整数百分比。", englishPercent, 0); + var next = settings.Clone(); + next.Enabled = enabled.IsChecked == true; next.ClipboardFallback = clipboard.IsChecked == true; + if (language.Text != LanguageLabel(settings.Target)) + { + string choice = Languages.FirstOrDefault(x => x == language.Text); + string code = choice == null ? language.Text.Trim() : choice.Substring(choice.LastIndexOf(" · ", StringComparison.Ordinal) + 3); + if (!System.Text.RegularExpressions.Regex.IsMatch(code, "^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$")) + return Invalid("请选择目标语言,或输入语言代码,例如 zh-Hans、en、ja。", language, 0); + next.Target = code; + } + if (maxSelection.Text != settings.MaxSelectionLength.ToString(CultureInfo.CurrentCulture)) + { + if (!int.TryParse(maxSelection.Text.Trim(), out length) || length < 1) + return Invalid("选区字符数上限请输入正整数,例如 2000。", maxSelection, 0); + next.MaxSelectionLength = length; + } + if (excludedApps.Text != AppsText(settings.ExcludedApps)) + { + string[] apps = excludedApps.Text.Split(new[] { '\r', '\n', ',', ';', ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).Where(x => x.Length != 0).ToArray(); + if (apps.Any(x => x.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || Path.GetFileNameWithoutExtension(x).Length == 0)) + return Invalid("排除应用请填写进程名称,不要包含路径或通配符。", excludedApps, 0); + next.ExcludedApps = apps.Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + } + next.BubbleFontFamily = BubbleAppearance.ResolveFont(fontFamily.SelectedItem as string).Source; + next.BubbleFontSize = size; next.BubbleBackground = background.Text.Trim().ToUpperInvariant(); + next.AutoHideSeconds = seconds; next.MinEnglishPercent = percent; + Action rollback = null; string startupError; + if (startupDirty && !startup.TrySet(autoStart.IsChecked == true, out rollback, out startupError)) + { + RefreshAfterFailure(); return Invalid(startupError, autoStart, 2); + } + if (!next.TrySave(path)) + { + string message = "无法保存设置。请检查应用目录是否可写;当前配置未改变。"; + if (rollback != null) + { + try { rollback(); } + catch { message += " 启动项恢复失败,请检查“启动”页显示的实际状态。"; } + } + RefreshAfterFailure(); return Invalid(message, null, rollback == null ? tabs.SelectedIndex : 2); + } + settings.CopyUserFrom(next); + if (saved != null) saved(); + Close(); return true; + } + private bool Invalid(string message, Control control, int tab) + { + tabs.SelectedIndex = tab; error.Text = message; error.Visibility = Visibility.Visible; + AutomationProperties.SetHelpText(this, message); + if (IsVisible && control != null) { control.BringIntoView(); control.Focus(); } + return false; + } + internal void RenderPreview(string file, int tab = 1) + { + tabs.SelectedIndex = tab; + layout.Measure(new Size(600, 740)); layout.Arrange(new Rect(0, 0, 600, 740)); layout.UpdateLayout(); + var bitmap = new RenderTargetBitmap(600, 740, 96, 96, PixelFormats.Pbgra32); bitmap.Render(layout); + var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); + using (var stream = File.Create(file)) encoder.Save(stream); + } + internal void SetInputForTest(string size, string color, string seconds, string percent) + { fontSize.Text = size; background.Text = color; autoHide.Text = seconds; englishPercent.Text = percent; } + internal void SetBehaviorForTest(bool on, bool capture, string target, string maximum, string apps) + { enabled.IsChecked = on; clipboard.IsChecked = capture; language.Text = target; maxSelection.Text = maximum; excludedApps.Text = apps; } + internal void SetStartupForTest(bool value) { autoStart.IsChecked = value; } + internal bool EnabledForTest { get { return enabled.IsChecked == true; } } + internal bool? StartupForTest { get { return autoStart.IsChecked; } } + internal string ErrorForTest { get { return error.Text; } } + } +} diff --git a/src/ReadingSettingsTests.cs b/src/ReadingSettingsTests.cs new file mode 100644 index 0000000..0f42a08 --- /dev/null +++ b/src/ReadingSettingsTests.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Windows.Media; + +namespace LightTranslate +{ + internal static class ReadingSettingsTests + { + private static void Check(bool condition, string message) + { if (!condition) throw new Exception("Reading settings: " + message); } + internal static void Run(Dictionary results) + { + // The 0% default deliberately retains the old non-Han language guard. + Check(SelectionReader.ShouldTranslate("Hello中文", 0), "mixed default"); + Check(SelectionReader.ShouldTranslate("Привет", 0), "legacy non-English default"); + Check(!SelectionReader.ShouldTranslate("纯中文", 0), "Chinese-only default"); + Check(!SelectionReader.ShouldTranslate(null, 0) && !SelectionReader.ShouldTranslate(" ", 0), "empty selection"); + Check(!SelectionReader.ShouldTranslate("123 !? 😀", 0) && !SelectionReader.ShouldTranslate("123 !? 😀", 50), "no letters"); + Check(SelectionReader.ShouldTranslate("abc中文", 60), "exact threshold equality"); + Check(!SelectionReader.ShouldTranslate("abc中文", 61), "below threshold"); + Check(SelectionReader.ShouldTranslate("abc中文!? 12345 😀", 60), "ignore punctuation, spaces, numbers and emoji"); + Check(SelectionReader.ShouldTranslate("a\U00020000", 50) && !SelectionReader.ShouldTranslate("a\U00020000", 51), "supplementary Han counted once"); + Check(SelectionReader.ShouldTranslate("e\u0301", 100), "combining marks are not letters"); + Check(!SelectionReader.ShouldTranslate("éПривет中文", 1), "requires ASCII English letters"); + Check(!SelectionReader.ShouldTranslate("ABC", 1), "full-width letters are denominator only"); + Check(SelectionReader.ShouldTranslate("English 123!?", 100), "English-only 100 percent"); + Check(!SelectionReader.ShouldTranslate("English中文", 100), "100 percent excludes mixed letters"); + results["englishThreshold"] = "default compatibility, exact boundaries, mixed scripts, supplementary Unicode and non-letter exclusions passed"; + + var start = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var lifetime = new BubbleLifetime(); + Check(BubbleLifetime.DisplaySeconds(0, 22, true) == 22, "automatic reading duration preserved"); + Check(BubbleLifetime.DisplaySeconds(1, 22, true) == 1, "fixed translated-text duration"); + Check(BubbleLifetime.DisplaySeconds(1, 8, false) == 8 && BubbleLifetime.DisplaySeconds(120, 3, false) == 3, "short reading duration does not cut off pending translation or alter error hints"); + lifetime.Start(start, 1); + Check(!lifetime.ShouldDismiss(start.AddSeconds(1), true, false), "deadline equality retains original > comparison"); + Check(lifetime.ShouldDismiss(start.AddMilliseconds(1001), true, false), "one second timeout"); + lifetime.Start(start, 3); + Check(!lifetime.ShouldDismiss(start.AddSeconds(50), false, true), "hover always retains bubble"); + Check(!lifetime.ShouldDismiss(start.AddSeconds(53), true, false), "hover renews full lifetime"); + Check(lifetime.ShouldDismiss(start.AddMilliseconds(53001), true, false), "timeout after hover"); + lifetime.Start(start, 120); + Check(!lifetime.ShouldDismiss(start.AddMilliseconds(700), false, false), "away grace begins"); + Check(lifetime.ShouldDismiss(start.AddMilliseconds(1251), false, false), "pointer-away still closes early with long timeout"); + lifetime.Start(start, 120); + Check(!lifetime.ShouldDismiss(start.AddSeconds(1), false, false), "first away event"); + Check(!lifetime.ShouldDismiss(start.AddMilliseconds(1400), true, false), "returning near resets away grace"); + Check(!lifetime.ShouldDismiss(start.AddMilliseconds(1500), false, false), "new away grace"); + Check(lifetime.ShouldDismiss(start.AddMilliseconds(2051), false, false), "new away grace expires"); + results["bubbleLifetime"] = "automatic/fixed reading deadline, unchanged waiting/error durations, hover renewal, pointer-away grace and near-pointer reset passed"; + + Color parsed; + Check(BubbleAppearance.TryParseBackground("#aabbcc", out parsed) && parsed == Color.FromRgb(170, 187, 204), "RGB color parsing"); + foreach (string invalid in new[] { "#ABC", "#80112233", "red", "# 12345", "#XYZABC", "", "https://example.com" }) + Check(!BubbleAppearance.TryParseBackground(invalid, out parsed), "reject invalid color " + invalid); + double minimumContrast = double.MaxValue; + for (int r = 0; r <= 255; r += 17) + for (int g = 0; g <= 255; g += 17) + for (int b = 0; b <= 255; b += 17) + { + var background = Color.FromRgb((byte)r, (byte)g, (byte)b); + double contrast = BubbleAppearance.Contrast(background, BubbleAppearance.Foreground(background)); + minimumContrast = Math.Min(minimumContrast, contrast); + Check(contrast >= 4.5, "foreground contrast below 4.5:1"); + } + results["backgroundContrast"] = new { samples = 4096, minimumRatio = minimumContrast }; + + string directory = Path.Combine(Program.Folder, "self-test-settings-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string path = Path.Combine(directory, "settings.json"); + File.WriteAllText(path, "{\"Enabled\":false,\"Target\":\"fr\",\"ExcludedApps\":[\"KeepMe\"]}"); + var old = Settings.Load(path); + Check(!old.Enabled && old.Target == "fr" && old.ExcludedApps[0] == "KeepMe", "legacy fields preserved"); + Check(old.BubbleFontSize == 14 && old.BubbleBackground == "" && old.AutoHideSeconds == 0 && old.MinEnglishPercent == 0, "old file gets compatible defaults"); + old.BubbleFontFamily = "not an installed font"; old.BubbleFontSize = double.NaN; + old.BubbleBackground = "# 12345"; old.AutoHideSeconds = 121; old.MinEnglishPercent = -1; + old.NormalizeReading(); + Check(old.BubbleFontFamily == "Microsoft YaHei UI" && old.BubbleFontSize == 14 && old.BubbleBackground == "" && old.AutoHideSeconds == 0 && old.MinEnglishPercent == 0, "invalid values use defaults"); + File.WriteAllText(path, "null"); Check(Settings.Load(path) != null, "JSON null safe"); + File.WriteAllText(path, "{invalid"); Check(Settings.Load(path).BubbleFontSize == 14, "malformed JSON safe"); + File.WriteAllText(path, "{\"BubbleFontSize\":48,\"AutoHideSeconds\":120,\"MinEnglishPercent\":100,\"BubbleBackground\":\"#abcdef\"}"); + var bounds = Settings.Load(path); + Check(bounds.BubbleFontSize == 48 && bounds.AutoHideSeconds == 120 && bounds.MinEnglishPercent == 100 && bounds.BubbleBackground == "#ABCDEF", "upper bounds and normalization"); + + var target = new Settings { Enabled = false, ClipboardFallback = false, Target = "fr", ExcludedApps = new[] { "KeepMe" } }; + int saved = 0; + var window = new SettingsWindow(target, delegate { saved++; }, new FakeStartupRegistration()); + window.RenderPreview(Path.Combine(Program.Folder, "reading-settings-preview.png")); + window.SetInputForTest("9", "", "10", "50"); Check(!window.Apply(path), "invalid font blocked"); + window.SetInputForTest("14", "#GGGGGG", "10", "50"); Check(!window.Apply(path), "invalid background blocked"); + window.SetInputForTest("14", "", "121", "50"); Check(!window.Apply(path), "invalid duration blocked"); + window.SetInputForTest("14", "", "10", "101"); Check(!window.Apply(path), "invalid threshold blocked"); + Check(saved == 0 && target.BubbleFontSize == 14 && Settings.Load(path).BubbleFontSize == 48, "validation failure changes neither memory nor file"); + window.SetInputForTest("18", "#25282F", "10", "60"); + Check(!window.Apply(Path.Combine(directory, "missing", "settings.json")), "unwritable destination reported"); + Check(saved == 0 && target.BubbleBackground == "", "write failure does not apply settings"); + window.RenderPreview(Path.Combine(Program.Folder, "reading-settings-error-preview.png")); + var customized = target.Clone(); + customized.BubbleFontFamily = "Segoe UI"; customized.BubbleFontSize = 18; + customized.BubbleBackground = "#25282F"; customized.AutoHideSeconds = 10; customized.MinEnglishPercent = 60; + window.Fill(customized); + window.RenderPreview(Path.Combine(Program.Folder, "reading-settings-custom-preview.png")); + Check(window.Apply(path) && saved == 1, "valid GUI save succeeds"); + var roundTrip = Settings.Load(path); + Check(roundTrip.BubbleFontFamily == "Segoe UI" && roundTrip.BubbleFontSize == 18 && roundTrip.BubbleBackground == "#25282F" && roundTrip.AutoHideSeconds == 10 && roundTrip.MinEnglishPercent == 60, "font family and reading settings persisted"); + Check(!roundTrip.Enabled && !roundTrip.ClipboardFallback && roundTrip.Target == "fr" && roundTrip.ExcludedApps[0] == "KeepMe", "GUI preserves unrelated settings"); + Check(target.BubbleFontSize == 18 && target.MinEnglishPercent == 60, "live settings updated"); + var cancel = new SettingsWindow(target, null, new FakeStartupRegistration()); + cancel.Fill(new Settings()); cancel.Close(); + Check(target.BubbleFontSize == 18 && Settings.Load(path).MinEnglishPercent == 60, "reset preview and cancel do not save"); + results["readingSettings"] = "legacy load, defaults, invalid values, validation, atomic save, live apply and cancel passed; window previews rendered without showing windows"; + } + finally { Directory.Delete(directory, true); } + } + } +} diff --git a/src/StartupRegistration.cs b/src/StartupRegistration.cs new file mode 100644 index 0000000..b96372f --- /dev/null +++ b/src/StartupRegistration.cs @@ -0,0 +1,182 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace LightTranslate +{ + internal enum StartupKind { Off, On, WindowsDisabled, OtherTarget, Unknown } + internal enum StartupApproval { Allowed, Disabled, Unknown } + internal sealed class StartupStatus + { + internal readonly StartupKind Kind; + internal readonly string Message; + internal StartupStatus(StartupKind kind, string message) { Kind = kind; Message = message; } + internal bool? Enabled { get { return Kind == StartupKind.Unknown ? (bool?)null : Kind == StartupKind.On; } } + internal bool CanChoose { get { return Kind == StartupKind.On || Kind == StartupKind.Off; } } + } + internal interface IStartupRegistration + { + StartupStatus Read(); + bool TrySet(bool enabled, out Action rollback, out string error); + } + + // The same current-user .lnk as startup.ps1. Never writes StartupApproved or security settings. + // Directory and approval reader are explicit dependencies so tests cannot touch real startup settings. + internal sealed class StartupRegistration : IStartupRegistration + { + private readonly string directory, executable, shortcut; + private readonly Func approval; + internal StartupRegistration(string directory, string executable, Func approval) + { + if (string.IsNullOrWhiteSpace(directory) || string.IsNullOrWhiteSpace(executable) || approval == null) throw new ArgumentException("Startup dependencies required"); + this.directory = Path.GetFullPath(directory); this.executable = Path.GetFullPath(executable); + shortcut = Path.Combine(this.directory, "LightTranslate.lnk"); this.approval = approval; + } + internal static IStartupRegistration CurrentUser() + { + try { return new StartupRegistration(Environment.GetFolderPath(Environment.SpecialFolder.Startup), Path.Combine(Program.Folder, "LightTranslate.exe"), ReadCurrentApproval); } + catch { return new UnavailableStartupRegistration(); } + } + private static StartupApproval ReadCurrentApproval() + { + using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder")) + return DecodeApproval(key == null ? null : key.GetValue("LightTranslate.lnk")); + } + internal static StartupApproval DecodeApproval(object value) + { + if (value == null) return StartupApproval.Allowed; + var bytes = value as byte[]; + if (bytes == null || bytes.Length != 12) return StartupApproval.Unknown; + // Recognize common shell states conservatively; an unknown record is never assumed enabled. + uint state = BitConverter.ToUInt32(bytes, 0); + if (state == 2 || state == 6) return StartupApproval.Allowed; + if (state == 3 || state == 7) return StartupApproval.Disabled; + return StartupApproval.Unknown; + } + public StartupStatus Read() + { + try + { + if (File.Exists(shortcut)) + { + string target, arguments; + ReadLink(shortcut, out target, out arguments); + if (string.IsNullOrWhiteSpace(target) || !string.Equals(Path.GetFullPath(target), executable, StringComparison.OrdinalIgnoreCase) || !string.IsNullOrWhiteSpace(arguments)) + return new StartupStatus(StartupKind.OtherTarget, "已有同名启动项指向其他目录或带有参数,本面板不会覆盖它。请先检查旧启动项,再刷新状态。"); + } + var permission = approval(); + if (permission == StartupApproval.Disabled) + return new StartupStatus(StartupKind.WindowsDisabled, "Windows 已禁用此启动项。请在 Windows 的启动应用中处理后刷新;本面板不会更改系统审批记录。"); + if (permission == StartupApproval.Unknown) + return new StartupStatus(StartupKind.Unknown, "无法确认 Windows 保存的启动状态,本次不修改开机自启。其他设置仍可保存。"); + return File.Exists(shortcut) + ? new StartupStatus(StartupKind.On, "当前目录已配置为登录 Windows 后启动。") + : new StartupStatus(StartupKind.Off, "当前目录未设置开机自启。"); + } + catch { return new StartupStatus(StartupKind.Unknown, "无法读取开机自启状态,请检查启动目录访问权限。其他设置仍可保存。"); } + } + public bool TrySet(bool enabled, out Action rollback, out string error) + { + rollback = null; error = null; + var current = Read(); + if (!current.CanChoose) { error = current.Message; return false; } + if (current.Enabled == enabled) return true; + byte[] before = null, after = null; + bool changed = false; + try + { + before = File.Exists(shortcut) ? File.ReadAllBytes(shortcut) : null; + if (enabled) + { + if (before != null) throw new IOException("启动项已变化,请刷新后重试。"); + Directory.CreateDirectory(directory); + // A failed COM Save may leave a partial file; mark it for guarded recovery first. + changed = true; + WriteLink(shortcut, executable); + after = File.ReadAllBytes(shortcut); + } + else + { + if (before == null) throw new IOException("启动项已变化,请刷新后重试。"); + var refreshed = Read(); + if (refreshed.Kind != StartupKind.On || !SameBytes(before, File.ReadAllBytes(shortcut))) throw new IOException("启动项已变化,请刷新后重试。"); + File.Delete(shortcut); changed = true; + } + var verified = Read(); + if (verified.Enabled != enabled || !verified.CanChoose) throw new IOException("保存后未能确认启动状态。" + verified.Message); + byte[] original = before, written = after; + rollback = delegate { Restore(original, written); }; + return true; + } + catch (Exception ex) + { + error = "无法修改开机自启:" + ex.Message; + if (changed) + { + try + { + // On a partial create, only remove a link still owned by this executable. + if (enabled && after == null && File.Exists(shortcut)) + { + string target, args; ReadLink(shortcut, out target, out args); + if (!string.Equals(target, executable, StringComparison.OrdinalIgnoreCase) || !string.IsNullOrWhiteSpace(args)) throw new IOException("启动项内容无法确认,未删除。"); + after = File.ReadAllBytes(shortcut); + } + Restore(before, after); + } + catch { error += " 无法恢复启动项,请检查当前实际状态。"; } + } + return false; + } + } + private void Restore(byte[] original, byte[] written) + { + byte[] current = File.Exists(shortcut) ? File.ReadAllBytes(shortcut) : null; + if (!SameBytes(current, written)) throw new IOException("启动项已被其他程序修改,未覆盖其新内容。"); + if (original == null) { if (current != null) File.Delete(shortcut); } + else File.WriteAllBytes(shortcut, original); + byte[] restored = File.Exists(shortcut) ? File.ReadAllBytes(shortcut) : null; + if (!SameBytes(restored, original)) throw new IOException("启动项恢复验证失败。"); + } + private static bool SameBytes(byte[] a, byte[] b) + { return a == null || b == null ? a == b : a.SequenceEqual(b); } + private static object Invoke(object value, string member, BindingFlags flags, params object[] arguments) + { return value.GetType().InvokeMember(member, flags, null, value, arguments); } + private static void Release(object value) { if (value != null && Marshal.IsComObject(value)) Marshal.FinalReleaseComObject(value); } + private static void ReadLink(string path, out string target, out string arguments) + { + object shell = null, link = null; + try + { + shell = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell", true)); + link = Invoke(shell, "CreateShortcut", BindingFlags.InvokeMethod, path); + target = Convert.ToString(Invoke(link, "TargetPath", BindingFlags.GetProperty)); + arguments = Convert.ToString(Invoke(link, "Arguments", BindingFlags.GetProperty)); + } + finally { Release(link); Release(shell); } + } + internal static void WriteLink(string path, string executable) + { + object shell = null, link = null; + try + { + shell = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell", true)); + link = Invoke(shell, "CreateShortcut", BindingFlags.InvokeMethod, path); + Invoke(link, "TargetPath", BindingFlags.SetProperty, executable); + Invoke(link, "WorkingDirectory", BindingFlags.SetProperty, Path.GetDirectoryName(executable)); + Invoke(link, "Arguments", BindingFlags.SetProperty, ""); + Invoke(link, "Description", BindingFlags.SetProperty, "LightTranslate automatic selection translation"); + Invoke(link, "IconLocation", BindingFlags.SetProperty, executable + ",0"); + Invoke(link, "Save", BindingFlags.InvokeMethod); + } + finally { Release(link); Release(shell); } + } + } + internal sealed class UnavailableStartupRegistration : IStartupRegistration + { + public StartupStatus Read() { return new StartupStatus(StartupKind.Unknown, "无法确定当前用户启动目录。本次不修改开机自启,其他设置仍可保存。"); } + public bool TrySet(bool enabled, out Action rollback, out string error) { rollback = null; error = Read().Message; return false; } + } +} diff --git a/src/UnifiedSettingsTests.cs b/src/UnifiedSettingsTests.cs new file mode 100644 index 0000000..83cf725 --- /dev/null +++ b/src/UnifiedSettingsTests.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace LightTranslate +{ + internal sealed class FakeStartupRegistration : IStartupRegistration + { + internal StartupKind Kind = StartupKind.Off; + internal bool FailWrites, FailRollback; + internal int Writes; + public StartupStatus Read() + { + string message = Kind == StartupKind.On ? "当前目录已配置登录后启动(隔离测试示例)。" : Kind == StartupKind.Off ? "当前目录未设置开机自启(隔离测试示例)。" : "启动状态受限制或无法确认(模拟测试示例)。"; + return new StartupStatus(Kind, message); + } + public bool TrySet(bool enabled, out Action rollback, out string error) + { + rollback = null; error = null; + if (!Read().CanChoose || FailWrites) { error = "模拟启动项保存失败"; return false; } + if (Read().Enabled == enabled) return true; + var before = Kind; Kind = enabled ? StartupKind.On : StartupKind.Off; Writes++; + rollback = delegate { if (FailRollback) throw new IOException("模拟恢复失败"); Kind = before; }; + return true; + } + } + internal static class UnifiedSettingsTests + { + private static void Check(bool value, string message) { if (!value) throw new Exception("Unified settings: " + message); } + internal static void Run(Dictionary results) + { + string root = Path.Combine(Program.Folder, "self-test-unified-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + string path = Path.Combine(root, "settings.json"); + var target = new Settings { Enabled = false, ClipboardFallback = false, Target = "fr", MaxSelectionLength = 9000, + ExcludedApps = new[] { "Keep.exe", "KEEP.exe" }, Diagnostics = true, BubbleFontSize = 18, MinEnglishPercent = 60 }; + Check(target.TrySave(path), "fixture saved"); + var startup = new FakeStartupRegistration(); + var window = new SettingsWindow(target, null, startup); + window.RenderPreview(Path.Combine(Program.Folder, "settings-translation-preview.png"), 0); + window.RenderPreview(Path.Combine(Program.Folder, "settings-startup-preview.png"), 2); + Check(startup.Writes == 0 && window.StartupForTest == false, "open and rendering never change startup"); + window.SetBehaviorForTest(false, false, "invalid code !", "9000", "Keep.exe\nKEEP.exe"); + Check(!window.Apply(path), "invalid changed language rejected"); + window.SetBehaviorForTest(false, false, "fr", "0", "Keep.exe\nKEEP.exe"); + Check(!window.Apply(path), "invalid changed maximum rejected"); + window.SetBehaviorForTest(false, false, "fr", "9000", @"C:\new\app.exe"); + Check(!window.Apply(path), "changed excluded path rejected"); + Check(!target.Enabled && Settings.Load(path).MaxSelectionLength == 9000, "validation changes neither memory nor disk"); + window.SetBehaviorForTest(true, true, "ja", "500", "One.exe;Two,One.exe"); + window.SetStartupForTest(true); + Check(startup.Writes == 0, "checking startup does not write before save"); + Check(window.Apply(path) && startup.Kind == StartupKind.On && startup.Writes == 1, "save applies startup exactly once"); + var saved = Settings.Load(path); + Check(saved.Enabled && saved.ClipboardFallback && saved.Target == "ja" && saved.MaxSelectionLength == 500, "original user options round trip"); + Check(saved.ExcludedApps.SequenceEqual(new[] { "One.exe", "Two" }), "app list separators and deduplication"); + Check(saved.Diagnostics && saved.BubbleFontSize == 18 && saved.MinEnglishPercent == 60, "hidden diagnostics and prior reading settings preserved"); + + var sync = new SettingsWindow(target, null, startup); + sync.SetInputForTest("24", "#FFFFFF", "10", "70"); + Check(target.TrySetEnabled(false, path) && !sync.EnabledForTest, "tray off immediately synchronizes open panel"); + Check(target.TrySetEnabled(true, path) && sync.EnabledForTest, "tray on immediately synchronizes open panel"); + Check(!target.TrySetEnabled(false, Path.Combine(root, "missing", "settings.json")) && target.Enabled && sync.EnabledForTest, "failed tray save reverts without notifying stale state"); + Check(sync.Apply(path), "panel saves latest tray state"); + Check(Settings.Load(path).Enabled && Settings.Load(path).BubbleFontSize == 24, "tray sync does not erase unrelated unsaved edits"); + + var cancelBackend = new FakeStartupRegistration { Kind = StartupKind.On }; + var cancel = new SettingsWindow(target, null, cancelBackend); + cancel.SetStartupForTest(false); cancel.Fill(new Settings()); + Check(cancel.StartupForTest == false && cancelBackend.Writes == 0, "reset changes configuration inputs but not startup choice or registration"); + cancel.Close(); + Check(cancelBackend.Kind == StartupKind.On && Settings.Load(path).BubbleFontSize == 24, "cancel preserves configuration and startup"); + + var unchanged = new Settings { Enabled = false, ClipboardFallback = false, Target = "x-legacy-custom", MaxSelectionLength = 0, + ExcludedApps = new[] { @"C:\legacy\Keep.exe", "Keep.exe", "Keep.exe" }, Diagnostics = true }; + var legacy = new SettingsWindow(unchanged, null, new FakeStartupRegistration()); + Check(legacy.Apply(path), "unchanged legacy custom values remain savable"); + var legacySaved = Settings.Load(path); + Check(legacySaved.Target == unchanged.Target && legacySaved.MaxSelectionLength == 0 && legacySaved.ExcludedApps.SequenceEqual(unchanged.ExcludedApps), "unchanged legacy values preserved verbatim"); + Check(legacySaved.Diagnostics, "diagnostics never reset by normal panel"); + + var failureTarget = new Settings(); + var failedStartup = new FakeStartupRegistration { FailWrites = true }; + var failure = new SettingsWindow(failureTarget, null, failedStartup); + failure.SetInputForTest("22", "", "10", "50"); failure.SetStartupForTest(true); + byte[] previous = File.ReadAllBytes(path); + Check(!failure.Apply(path) && failedStartup.Kind == StartupKind.Off && failureTarget.BubbleFontSize == 14, "startup failure does not apply configuration"); + Check(File.ReadAllBytes(path).SequenceEqual(previous) && failure.ErrorForTest.Contains("失败"), "startup failure visibly reported, existing file unchanged"); + failure.RenderPreview(Path.Combine(Program.Folder, "settings-startup-error-preview.png"), 2); failure.Close(); + var rollbackBackend = new FakeStartupRegistration(); + var rollbackWindow = new SettingsWindow(failureTarget, null, rollbackBackend); + rollbackWindow.SetStartupForTest(true); + Check(!rollbackWindow.Apply(Path.Combine(root, "missing", "settings.json")) && rollbackBackend.Kind == StartupKind.Off && rollbackWindow.StartupForTest == false, + "configuration failure restores startup and refreshes actual state"); + rollbackWindow.Close(); + var partialBackend = new FakeStartupRegistration { FailRollback = true }; + var partial = new SettingsWindow(failureTarget, null, partialBackend); partial.SetStartupForTest(true); + Check(!partial.Apply(Path.Combine(root, "missing", "settings.json")) && partial.StartupForTest == true && partial.ErrorForTest.Contains("恢复失败"), + "rollback failure reported without pretending startup unchanged"); partial.Close(); + foreach (var kind in new[] { StartupKind.Unknown, StartupKind.OtherTarget, StartupKind.WindowsDisabled }) + { + var restricted = new FakeStartupRegistration { Kind = kind }; + var restrictedWindow = new SettingsWindow(failureTarget, null, restricted); + if (kind == StartupKind.Unknown) Check(restrictedWindow.StartupForTest == null, "unreadable startup is indeterminate, not falsely disabled"); + restrictedWindow.SetInputForTest("18", "", "10", "50"); + Check(restrictedWindow.Apply(path) && restricted.Writes == 0, "unavailable startup does not prevent independent configuration save"); + } + var changedBackend = new FakeStartupRegistration(); + var changedWindow = new SettingsWindow(failureTarget, null, changedBackend); + changedWindow.SetStartupForTest(true); changedBackend.Kind = StartupKind.OtherTarget; + previous = File.ReadAllBytes(path); + Check(!changedWindow.Apply(path) && changedBackend.Writes == 0 && File.ReadAllBytes(path).SequenceEqual(previous), + "external startup target change during editing blocks save without overwriting it"); changedWindow.Close(); + results["unifiedSettings"] = "original option round trip, legacy values, hidden diagnostics, validation, tray sync, cancel and save/rollback failures passed with fake startup"; + + TestShortcutBackend(root); + results["startupRegistration"] = "real .lnk create/read/remove/byte-exact rollback, foreign shortcut protection, concurrent changes, OS approval states and I/O failure passed in isolated test directories only"; + } + finally { Directory.Delete(root, true); } + } + private static void TestShortcutBackend(string root) + { + Check(StartupRegistration.DecodeApproval(null) == StartupApproval.Allowed, "missing approval record"); + foreach (byte state in new byte[] { 2, 6 }) { var record = new byte[12]; record[0] = state; Check(StartupRegistration.DecodeApproval(record) == StartupApproval.Allowed, "known enabled approval"); } + foreach (byte state in new byte[] { 3, 7 }) { var record = new byte[12]; record[0] = state; Check(StartupRegistration.DecodeApproval(record) == StartupApproval.Disabled, "known disabled approval"); } + Check(StartupRegistration.DecodeApproval(new byte[] { 2, 0, 0, 0 }) == StartupApproval.Unknown && StartupRegistration.DecodeApproval("bad") == StartupApproval.Unknown, "truncated approval never enabled"); + var unknown = new byte[12]; unknown[0] = 99; + Check(StartupRegistration.DecodeApproval(unknown) == StartupApproval.Unknown, "unknown approval never enabled"); + string directory = Path.Combine(root, "isolated-startup"); + string executable = Path.Combine(Program.Folder, "LightTranslate.exe"), link = Path.Combine(directory, "LightTranslate.lnk"); + var approval = StartupApproval.Allowed; + var service = new StartupRegistration(directory, executable, delegate { return approval; }); + Action undo; string error; + Check(service.Read().Kind == StartupKind.Off && !File.Exists(link), "isolated initial state"); + Check(service.TrySet(true, out undo, out error) && service.Read().Kind == StartupKind.On, "real shortcut enable and read-back"); + undo(); Check(!File.Exists(link), "created shortcut rollback"); + Check(service.TrySet(true, out undo, out error), "fixture shortcut recreate"); + byte[] original = File.ReadAllBytes(link); + Check(service.TrySet(false, out undo, out error) && !File.Exists(link), "real shortcut disable"); + undo(); Check(File.ReadAllBytes(link).SequenceEqual(original), "removed shortcut byte-exact restore"); + approval = StartupApproval.Disabled; + Check(service.Read().Kind == StartupKind.WindowsDisabled && !service.TrySet(true, out undo, out error), "OS disabled record respected without writes"); + Check(File.ReadAllBytes(link).SequenceEqual(original), "disabled record preserves shortcut"); + approval = StartupApproval.Unknown; Check(service.Read().Enabled == null, "unknown OS state visible"); + approval = StartupApproval.Allowed; + StartupRegistration.WriteLink(link, Path.Combine(root, "other.exe")); + byte[] foreign = File.ReadAllBytes(link); + Check(service.Read().Kind == StartupKind.OtherTarget && !service.TrySet(false, out undo, out error), "foreign target never removed"); + Check(File.ReadAllBytes(link).SequenceEqual(foreign), "foreign target contents preserved"); + File.Delete(link); + Check(service.TrySet(true, out undo, out error), "concurrency fixture"); + StartupRegistration.WriteLink(link, Path.Combine(root, "other.exe")); foreign = File.ReadAllBytes(link); + bool refused = false; try { undo(); } catch (IOException) { refused = true; } + Check(refused && File.ReadAllBytes(link).SequenceEqual(foreign), "rollback does not overwrite a concurrent foreign change"); + string occupied = Path.Combine(root, "occupied"); File.WriteAllText(occupied, "fixture"); + var blocked = new StartupRegistration(occupied, executable, delegate { return StartupApproval.Allowed; }); + Check(!blocked.TrySet(true, out undo, out error) && !string.IsNullOrEmpty(error), "real startup directory write failure reported"); + } + } +}