From 2b4ae3eebbd0155c8a23b309a54789e8208528bc Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Mon, 12 Oct 2026 22:02:55 +0800 Subject: [PATCH] Add configurable reading appearance, lifetime and English threshold --- README.md | 18 ++- build.ps1 | 3 +- docs/TESTING.md | 28 +++- settings.example.json | 7 +- src/LightTranslate.cs | 127 ++++++++++++----- src/ReadingSettings.cs | 274 ++++++++++++++++++++++++++++++++++++ src/ReadingSettingsTests.cs | 117 +++++++++++++++ 7 files changed, 532 insertions(+), 42 deletions(-) create mode 100644 src/ReadingSettings.cs create mode 100644 src/ReadingSettingsTests.cs diff --git a/README.md b/README.md index d720f0f..1066f34 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ 2. 解压到固定目录,例如 `%LOCALAPPDATA%\LightTranslate`,双击 `LightTranslate.exe`。 3. 在桌面应用中选中英文,查看鼠标旁的译文。 -启动后,系统托盘会出现“译”图标。右键可开关自动翻译、打开设置文件或退出; +启动后,系统托盘会出现“译”图标。右键可开关自动翻译、打开阅读设置、打开设置文件或退出; 双击图标可直接切换自动翻译。 轻译面向支持复制选区的桌面应用,默认跳过终端和纯中文选区,每次最多选择 2,000 个字符。 @@ -32,7 +32,21 @@ ## 按自己的习惯设置 -设置保存在应用目录的 `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`;取消不会保存。 +“恢复阅读默认值”仅重置这五项阅读选项的预览,点击保存后才生效。 +旧配置缺少新字段时沿用原有字体、主题、停留时间和语言过滤。 +其他高级配置仍可退出轻译后修改文件、重启生效。 可以通过 `ExcludedApps` 排除指定应用,填写进程名称,例如: ```json 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..255d3a5 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,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 ## 配置字段 -修改应用目录的 `settings.json`,重启后生效。 +托盘“阅读设置…”保存后立即生效;修改应用目录的 `settings.json` 则重启后生效。 `Diagnostics` 开关每两秒读取一次,可在排查后直接关闭,无需重启。 | 字段 | 默认值 | 作用 | @@ -50,6 +60,16 @@ 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` 沿用早期字段名,当前取词路径统一使用剪贴板。 @@ -85,7 +105,7 @@ Windows 的低级监听超时机制见 [Microsoft 文档](https://learn.microsof 从普通权限进程获取管理员应用的选区受 Windows 权限限制。 当前功能聚焦划词阅读:本地词库可离线,句子翻译使用网络。 -OCR、朗读、翻译历史、原位替换、AI 润色、图形设置、自动更新、安装器和代码签名暂未实现。 +OCR、朗读、翻译历史、原位替换、AI 润色、自动更新、安装器和代码签名暂未实现。 ## 手动验证清单 @@ -100,3 +120,7 @@ OCR、朗读、翻译历史、原位替换、AI 润色、图形设置、自动 7. 连续快速选择不同文字,检查旧响应是否影响当前译文。 8. 检查终端、密码框、排除应用、多显示器、DPI 和屏幕边缘。 9. 持续运行数小时,并在重启 Windows 后检查自启动与划词。 +10. 在阅读设置中选择不同字体、10/48 字号及浅/深/中等亮度背景;确认实际浮层、预览、文字对比度、缩放和长译文滚动。 +11. 将时间设为 1/10/120 秒,鼠标停在选区附近但不覆盖浮层检查超时;悬停后移回附近检查重新计时,移远和外部操作仍提前收起。 +12. 比例设为 60%,选择 `abc中文` 应翻译,设为 61% 则不触发;选择 `abc中文!? 123` 的结果相同。100% 时纯英文触发、中英混合不触发;0% 保留旧过滤。 +13. 输入非法颜色、字号、秒数或比例,确认就地报错且不保存;取消和关闭设置不应用,重启后保留已保存的值且不改动自动翻译开关等其他设置。 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..93968dd 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -84,20 +84,57 @@ 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; 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; + } 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 +155,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 ReadingSettingsWindow readingSettings; private readonly Queue diagnosticQueue = new Queue(); private long mouseEvents, mouseDowns, mouseUps, selections; private DateTime nextHeartbeat, nextHealthLog, nextSettingsCheck; @@ -132,11 +169,13 @@ 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); }; menu.Items.Add(enabledItem); + menu.Items.Add("阅读设置…", null, delegate { OpenReadingSettings(); }); 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 +189,15 @@ public Controller(Application app) Program.Log("started", "hooks=dedicated-thread recovery=enabled capture=clipboard dictionary=" + lexicon.Count); } + private void OpenReadingSettings() + { + Dismiss(true); + if (readingSettings != null) { readingSettings.Activate(); return; } + readingSettings = new ReadingSettingsWindow(settings, delegate { Dismiss(true); bubble.ApplySettings(settings); }); + readingSettings.Closed += delegate { readingSettings = null; }; + readingSettings.Show(); + } + internal static System.Drawing.Icon MakeIcon() { using (var bmp = new System.Drawing.Bitmap(32, 32)) @@ -243,7 +291,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 +322,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 +333,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 +341,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 +360,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 +400,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 +412,7 @@ public void Dispose() tray.Visible = false; tray.Icon.Dispose(); tray.Dispose(); + if (readingSettings != null) readingSettings.Close(); bubble.Close(); translator.Dispose(); lexicon.Dispose(); @@ -605,6 +644,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 +767,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 +779,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 +1169,7 @@ 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); 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..72223a0 --- /dev/null +++ b/src/ReadingSettings.cs @@ -0,0 +1,274 @@ +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 ReadingSettingsWindow : Window + { + private const string Automatic = "自动(按译文长度)"; + private readonly Settings settings; + private readonly Action saved; + private readonly ComboBox fontFamily, fontSize, autoHide; + private readonly TextBox background, englishPercent; + private readonly TextBlock error, previewText; + private readonly Border preview; + private readonly Grid layout; + + internal ReadingSettingsWindow(Settings settings, Action saved) + { + this.settings = settings; + this.saved = saved; + Title = "轻译 · 阅读设置"; + Width = 560; Height = 760; MinWidth = 460; 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); + + var form = new StackPanel { Margin = new Thickness(24, 0, 24, 16) }; + var scroll = new ScrollViewer { Content = form, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }; + Grid.SetRow(scroll, 1); layout.Children.Add(scroll); + form.Children.Add(Heading("浮层外观")); + fontFamily = new ComboBox { ItemsSource = Fonts.SystemFontFamilies.Select(f => f.Source).OrderBy(x => x).ToArray(), MinHeight = 32 }; + AddField(form, "字体", fontFamily); + fontSize = new ComboBox { IsEditable = true, ItemsSource = new[] { "10", "12", "14", "16", "18", "20", "24", "32", "48" }, MinHeight = 32 }; + AddField(form, "字号", fontSize); + background = new TextBox { MinHeight = 32, VerticalContentAlignment = VerticalAlignment.Center }; + 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(form, "背景色", colorRow); + AutomationProperties.SetName(background, "浮层背景色"); + form.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, "浮层外观示例预览"); form.Children.Add(preview); + + form.Children.Add(Heading("显示与触发")); + autoHide = new ComboBox { IsEditable = true, ItemsSource = new[] { Automatic, "3", "6", "10", "15", "30", "60", "120" }, MinHeight = 32 }; + AddField(form, "自动消失(秒)", autoHide); + form.Children.Add(Help("译文自动停留 6–22 秒,也可填 1–120 秒。悬停时续时,移远或继续操作仍会提前收起;等待和错误提示保留原时长。")); + englishPercent = new TextBox { MinHeight = 32, VerticalContentAlignment = VerticalAlignment.Center }; + AddField(form, "最低英文占比(%)", englishPercent); + form.Children.Add(Help("0–100%。A–Z/a–z 字母数 ÷ 所有文字字母数;中文及其他语言计入分母,标点、空白、数字不计。Hello中文约为 71%。")); + form.Children.Add(Help("0% 关闭比例限制,保留原有语言过滤;纯中文和没有字母的选区仍不触发。大于 0% 时必须含 A–Z/a–z。")); + 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; + reset.Click += delegate { Fill(new Settings()); error.Visibility = Visibility.Collapsed; }; 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(); }; + PreviewKeyDown += delegate(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { e.Handled = true; Close(); } }; + Fill(settings); + } + 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, 0) }; } + 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 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); + } + internal void Fill(Settings value) + { + if (error != null) error.Visibility = Visibility.Collapsed; + 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 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 handle = new System.Windows.Interop.WindowInteropHelper(this).Handle; + var owner = new Forms.NativeWindow(); + owner.AssignHandle(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(); } + } + } + internal bool Apply(string path) + { + double size; int seconds, percent; 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); + if (!string.IsNullOrWhiteSpace(background.Text) && !BubbleAppearance.TryParseBackground(background.Text, out color)) + return Invalid("背景色请留空,或填写 #RRGGBB,例如 #25282F。", background); + 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); + if (!int.TryParse(englishPercent.Text.Trim(), out percent) || percent < 0 || percent > 100) + return Invalid("最低英文占比请输入 0–100 的整数百分比。", englishPercent); + var next = settings.Clone(); + next.BubbleFontFamily = BubbleAppearance.ResolveFont(fontFamily.SelectedItem as string).Source; + next.BubbleFontSize = size; next.BubbleBackground = background.Text.Trim().ToUpperInvariant(); + next.AutoHideSeconds = seconds; next.MinEnglishPercent = percent; + if (!next.TrySave(path)) return Invalid("无法保存设置。请检查应用目录是否可写;当前设置未改变。", null); + settings.CopyReadingFrom(next); + if (saved != null) saved(); + Close(); return true; + } + private bool Invalid(string message, Control control) + { + error.Text = message; error.Visibility = Visibility.Visible; + AutomationProperties.SetHelpText(this, message); + if (IsVisible && control != null) control.Focus(); + return false; + } + internal void RenderPreview(string file) + { + layout.Measure(new Size(540, 725)); layout.Arrange(new Rect(0, 0, 540, 725)); layout.UpdateLayout(); + var bitmap = new RenderTargetBitmap(540, 725, 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; } + } +} diff --git a/src/ReadingSettingsTests.cs b/src/ReadingSettingsTests.cs new file mode 100644 index 0000000..82e2cbd --- /dev/null +++ b/src/ReadingSettingsTests.cs @@ -0,0 +1,117 @@ +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 ReadingSettingsWindow(target, delegate { saved++; }); + 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")); + window.Fill(new Settings { BubbleFontFamily = "Segoe UI", BubbleFontSize = 18, BubbleBackground = "#25282F", AutoHideSeconds = 10, MinEnglishPercent = 60 }); + 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 ReadingSettingsWindow(target, null); + 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); } + } + } +}