From 8597ad9e1e4113b577baee19fe88b605a9373ae2 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:03:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=9C=80=E6=98=8E=E7=A1=AE?= =?UTF-8?q?=E5=85=81=E8=AE=B8=E7=9A=84=E5=89=AA=E8=B4=B4=E6=9D=BF=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E5=8F=96=E8=AF=8D=E5=85=9C=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 3 + README.md | 5 +- docs/TESTING.md | 10 ++ scripts/test-overwrite.ps1 | 10 ++ settings.example.json | 1 + src/ClipboardCapture.cs | 84 +++++++++++-- src/ClipboardCaptureTests.cs | 3 +- src/ClipboardNativeTests.cs | 32 ++++- src/ClipboardOverwrite.cs | 56 +++++++++ src/ClipboardOverwriteConfirmation.cs | 46 +++++++ src/ClipboardOverwriteTests.cs | 169 ++++++++++++++++++++++++++ src/IsolatedSelectionReader.cs | 2 +- src/LightTranslate.cs | 105 +++++++++++++++- src/ReadingSettings.cs | 27 +++- 14 files changed, 528 insertions(+), 25 deletions(-) create mode 100644 scripts/test-overwrite.ps1 create mode 100644 src/ClipboardOverwrite.cs create mode 100644 src/ClipboardOverwriteConfirmation.cs create mode 100644 src/ClipboardOverwriteTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c093c12..63b4038 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,6 +20,9 @@ jobs: - name: Clipboard workflow regression shell: pwsh run: ./scripts/test-clipboard.ps1 + - name: Clipboard overwrite consent and race regression + shell: pwsh + run: ./scripts/test-overwrite.ps1 - name: Native window gesture boundaries shell: pwsh run: ./scripts/test-gestures.ps1 diff --git a/README.md b/README.md index 61e6b89..7a50f8c 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,10 @@ Index 单次翻译总期限为 60 秒,429 最多尝试三次,按 Retry-After 额度和费用以 [DeepL 当前 API 套餐](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。 译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。 先由独立的 `LightTranslate.SelectionHost.exe` 判断操作区域并读取 Windows UI Automation 文本选区。空选区、图标列表、树等非文本交互直接结束,不访问剪贴板;不会按应用名全局排除资源管理器,列表内重命名编辑框仍可取词。辅助进程限时退出,主程序不持有 UIA/COM 对象。分发或移动程序时请保留该辅助文件。 -仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法安全备份时不复制,并显示读取失败提示;不清空剪贴板,也不退回 OLE 快照。未知区域或尚未确认文本上下文的探测失败会安静结束并保留固定诊断码,不会发送复制命令;已确认文本区域的读取失败以及辅助程序缺失仍有明确提示。系统或剪贴板管理器仍可能保留实际执行过的临时复制记录。 +仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法完整备份时,默认不复制,而是准确提示原因,并提供“本次覆盖并取词”。点击即允许这次复制替换原剪贴板,原图片、文字或私有格式可能丢失;Windows 剪贴板历史不保证恢复。单次许可最多保留 15 秒,失焦、新操作、设置变化或原剪贴板更新后失效。 +“翻译”设置页另有默认关闭的“取词优先,允许覆盖”。勾选时需确认风险,保存后才生效;取消或保存失败不启用。开启后仅对稳定的、不支持保留/过大/无法完整读取的剪贴板使用覆盖兜底,能完整备份时仍优先恢复原内容。剪贴板暂时无法打开或已经变化时会取消并提示重试,不自动覆盖竞争中的数据。 +覆盖兜底不预先清空剪贴板,不恢复旧备份,也不放开未知格式或 OLE 反序列化。只有看到新的剪贴板序列号并确认复制来源为源应用后才读取 Unicode 文本;复制失败、空结果、超时、取消、失焦或可检测的并发变化不会翻译旧内容。用户随后复制的新内容不会被旧备份恢复覆盖。未知区域或尚未确认文本上下文的探测失败仍安静结束,不发送复制命令;已确认文本区域的读取失败以及辅助程序缺失仍有明确提示。系统或剪贴板管理器可能保留实际执行过的临时复制记录。 +发出复制后再取消,只能停止后续取词和翻译;原剪贴板可能已经被替换,不会尝试用旧数据回滚覆盖新的剪贴板内容。 ## 从源码构建 diff --git a/docs/TESTING.md b/docs/TESTING.md index fc9c71f..6f7b474 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -362,3 +362,13 @@ text-unsupported,修复后均返回 non-text;比较不读取文件名、选 仅在明确授权后使用 `-Online`:依次向三档发送同一固定公开短句 `The window closes automatically.`,将请求模型、返回模型、HTTP 状态、尝试次数、耗时、公开句译文和错误写入 `index-live-test.json`。它不读取用户选区、剪贴板或外部文档。文档列出的模型不等同于在线测试成功;以该文件中各档的实际结果为准。 原 `--self-test-offline` 也包含 Index 模拟测试;剪贴板、托盘、手势、外部选区辅助程序和已有翻译源测试继续保留。Index 的等待浮层最多等待至 60 秒请求期限;鼠标移开、切换窗口、开始新操作或保存设置仍会取消旧请求。 + +## 剪贴板覆盖候选验证 + +`scripts/test-overwrite.ps1 -OutputDirectory <独立输出目录>` 或 `--self-test-overwrite` 仅使用模拟剪贴板和临时配置,不访问用户真实剪贴板正文。覆盖原因分类、默认关闭、能备份时仍恢复、明确许可后覆盖且永不恢复旧备份、复制失败与空结果、有限次等待、来源/序列号校验、取消/失焦、并发用户复制、重复操作,以及单次许可的上下文、15 秒期限与不可重放检查。 + +配置用例验证拒绝风险提示、确认后待保存、取消、失败回滚、保存回填、旧配置默认关闭和原 Index 设置保留。实际 WPF 浮层、风险确认框和设置页均可离屏渲染;按钮取消、重复点击和提示收起后不再执行动作。 + +`--self-test-clipboard-native` 先切换到独立 window station 和 desktop,隔离失败即终止,随后才使用该私有剪贴板内的合成数据验证原生取词和覆盖。新增不支持格式时零复制、明确允许后真实 TextBox.Copy 只保留新文字、复制无变化时不返回旧文字等用例。测试不覆盖用户真实剪贴板,不依赖保存/恢复用户数据实现隔离。 + +此候选未自动替换或启动本机运行版。真实 Steam 窗口点击、复杂第三方剪贴板管理器、不同 DPI 和持续使用仍需后续授权验收。Windows 延迟渲染等原生调用可能阻塞,轮询次数上限不是对每个原生提供方的绝对执行时限保证。 diff --git a/scripts/test-overwrite.ps1 b/scripts/test-overwrite.ps1 new file mode 100644 index 0000000..dd27857 --- /dev/null +++ b/scripts/test-overwrite.ps1 @@ -0,0 +1,10 @@ +[CmdletBinding()] +param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\LightTranslate')) +$ErrorActionPreference = 'Stop' +$outputPath = [IO.Path]::GetFullPath($OutputDirectory) +$exe = Join-Path $outputPath 'LightTranslate.exe' +if (-not (Test-Path -LiteralPath $exe)) { throw 'Build the independent candidate first.' } +$test = Start-Process -FilePath $exe -ArgumentList '--self-test-overwrite' -WindowStyle Hidden -PassThru +if (-not $test.WaitForExit(30000)) { throw ('Test still running; inspect PID ' + $test.Id) } +if ($test.ExitCode -ne 0) { throw ('Overwrite test failed; see ' + (Join-Path $outputPath 'status.log')) } +Get-Content -LiteralPath (Join-Path $outputPath 'clipboard-overwrite-test.json') -Raw -Encoding utf8 diff --git a/settings.example.json b/settings.example.json index d369029..aa35573 100644 --- a/settings.example.json +++ b/settings.example.json @@ -1,6 +1,7 @@ { "Enabled": true, "ClipboardFallback": true, + "AllowClipboardOverwrite": false, "Target": "zh-Hans", "TranslationProvider": "auto", "IndexModel": "Index-Translate-35B-A3B", diff --git a/src/ClipboardCapture.cs b/src/ClipboardCapture.cs index 00ff1f6..cee34a7 100644 --- a/src/ClipboardCapture.cs +++ b/src/ClipboardCapture.cs @@ -30,7 +30,8 @@ internal static class ClipboardCapture private static readonly SemaphoreSlim gate = new SemaphoreSlim(1, 1); internal static async Task Read(ISelectionClipboard clipboard, IntPtr source, - Func valid, Action copy, Action trace, Func wait, Func> withoutClipboard = null) + Func valid, Action copy, Action trace, Func wait, Func> withoutClipboard = null, + ClipboardCapturePolicy policy = null) { // Do not queue stale selections or snapshot another capture's temporary clipboard. if (!gate.Wait(0)) { trace("copy skipped busy"); return null; } @@ -38,14 +39,31 @@ internal static async Task Read(ISelectionClipboard clipboard, IntPtr so { ClipboardSnapshot saved; if (!valid()) return null; + uint initial = clipboard.Sequence; + if (policy != null && policy.RequiredSequence.HasValue && policy.RequiredSequence.Value != initial) + throw new ClipboardBackupException(ClipboardBackupFailure.Changed, initial); if (!clipboard.TrySnapshot(out saved)) { trace("clipboard snapshot skipped"); + if (!valid()) return null; + if (policy != null) + { + var diagnostics = clipboard as IClipboardBackupDiagnostics; + var reason = diagnostics == null ? ClipboardBackupFailure.Unreadable : diagnostics.BackupFailure; + uint current = clipboard.Sequence; + if (initial == 0 || current != initial) reason = ClipboardBackupFailure.Changed; + trace("clipboard backup reason=" + reason); + if (policy.AllowOverwrite && ClipboardBackupException.MayOverwrite(reason)) + return await ReadWithoutRestore(clipboard, source, current, valid, copy, trace, wait); + throw new ClipboardBackupException(reason, current); + } if (withoutClipboard == null || !valid()) return null; string selected = await withoutClipboard(); return valid() ? selected : null; } if (!valid() || clipboard.Sequence != saved.Sequence) return null; + if (policy != null && policy.RequiredSequence.HasValue && saved.Sequence != policy.RequiredSequence.Value) + throw new ClipboardBackupException(ClipboardBackupFailure.Changed, clipboard.Sequence); copy(); for (int i = 0; i < 12; i++) { @@ -62,6 +80,7 @@ internal static async Task Read(ISelectionClipboard clipboard, IntPtr so var result = clipboard.Restore(saved, copied, valid); if (result != RestoreResult.Busy) { + if (result == RestoreResult.Changed) { trace("clipboard changed before restore; result discarded"); return null; } if (result == RestoreResult.Failed) trace("clipboard restore failed"); return valid() ? text : null; } @@ -74,17 +93,47 @@ internal static async Task Read(ISelectionClipboard clipboard, IntPtr so } finally { gate.Release(); } } + + private static async Task ReadWithoutRestore(ISelectionClipboard clipboard, IntPtr source, uint before, + Func valid, Action copy, Action trace, Func wait) + { + if (!valid()) return null; + if (before == 0 || clipboard.Sequence != before) + throw new ClipboardBackupException(ClipboardBackupFailure.Changed, clipboard.Sequence); + // Do not clear the clipboard first. A failed Ctrl+C must never return the old data. + // This path has no backup and must never call Restore, even after cancellation. + trace("clipboard overwrite authorized"); + try { copy(); } + catch (OperationCanceledException) { throw; } + catch { if (!valid()) return null; throw new SelectionUnavailableException("未能向源应用发送本次复制,未读取旧剪贴板。原剪贴板可能已改变。"); } + for (int i = 0; i < 32; i++) + { + await wait(); + if (!valid()) return null; + uint observed = clipboard.Sequence; + if (observed == before) continue; + uint copied; string text; + if (!clipboard.TryReadText(source, observed, out copied, out text) || copied != observed || clipboard.Sequence != copied) + throw new SelectionUnavailableException("剪贴板已变化或复制来源无法确认,已取消本次取词;未翻译旧内容。"); + if (!valid()) return null; + if (string.IsNullOrWhiteSpace(text)) + throw new SelectionUnavailableException("这次复制没有产生可读取的新文字,未翻译旧内容。原剪贴板可能已改变。"); + return text; + } + throw new SelectionUnavailableException("这次复制超时,没有收到可验证的新文字;未翻译旧内容。原剪贴板可能已改变。"); + } } // Read only documented HGLOBAL text formats. Never materialize IDataObject/OLE objects. // Unknown formats reject the entire snapshot before Ctrl+C, rather than losing rich data. - internal sealed class NativeSelectionClipboard : ISelectionClipboard, IDisposable + internal sealed class NativeSelectionClipboard : ISelectionClipboard, IClipboardBackupDiagnostics, IDisposable { internal const int MaxFormatBytes = 8 * 1024 * 1024; private const int MaxSnapshotBytes = 16 * 1024 * 1024; private readonly Forms.NativeWindow window = new Forms.NativeWindow(); internal IntPtr Handle { get { return window.Handle; } } public uint Sequence { get { return Native.GetClipboardSequenceNumber(); } } + public ClipboardBackupFailure BackupFailure { get; private set; } internal NativeSelectionClipboard() { @@ -102,52 +151,65 @@ internal static bool Supported(uint format) } internal static bool TryFormats(out List formats) + { ClipboardBackupFailure reason; return TryFormats(out formats, out reason); } + private static bool TryFormats(out List formats, out ClipboardBackupFailure reason) { + reason = ClipboardBackupFailure.None; formats = new List(); uint format = 0; while (true) { ClipboardNative.SetLastError(0); format = ClipboardNative.EnumClipboardFormats(format); - if (format == 0) return Marshal.GetLastWin32Error() == 0; - if (formats.Count >= 64 || !Supported(format) || formats.Contains(format)) return false; + if (format == 0) { if (Marshal.GetLastWin32Error() != 0) { reason = ClipboardBackupFailure.Unreadable; return false; } return true; } + if (formats.Count >= 64) { reason = ClipboardBackupFailure.TooLarge; return false; } + if (!Supported(format)) { reason = ClipboardBackupFailure.UnsupportedFormat; return false; } + if (formats.Contains(format)) { reason = ClipboardBackupFailure.Unreadable; return false; } formats.Add(format); } } internal static bool TryBytes(uint format, out byte[] bytes) + { ClipboardBackupFailure reason; return TryBytes(format, out bytes, out reason); } + private static bool TryBytes(uint format, out byte[] bytes, out ClipboardBackupFailure reason) { + reason = ClipboardBackupFailure.Unreadable; bytes = null; IntPtr handle = ClipboardNative.GetClipboardData(format); if (handle == IntPtr.Zero) return false; ulong size = ClipboardNative.GlobalSize(handle).ToUInt64(); - if (size == 0 || size > MaxFormatBytes) return false; + if (size > MaxFormatBytes) { reason = ClipboardBackupFailure.TooLarge; return false; } + if (size == 0) return false; IntPtr pointer = ClipboardNative.GlobalLock(handle); if (pointer == IntPtr.Zero) return false; - try { bytes = new byte[(int)size]; Marshal.Copy(pointer, bytes, 0, bytes.Length); return true; } + try { bytes = new byte[(int)size]; Marshal.Copy(pointer, bytes, 0, bytes.Length); reason = ClipboardBackupFailure.None; return true; } finally { ClipboardNative.GlobalUnlock(handle); } } public bool TrySnapshot(out ClipboardSnapshot snapshot) { snapshot = null; - if (!ClipboardNative.OpenClipboard(Handle)) return false; + BackupFailure = ClipboardBackupFailure.None; + if (!ClipboardNative.OpenClipboard(Handle)) { BackupFailure = ClipboardBackupFailure.Busy; return false; } try { var saved = new ClipboardSnapshot { Sequence = Sequence }; - if (saved.Sequence == 0) return false; + if (saved.Sequence == 0) { BackupFailure = ClipboardBackupFailure.Changed; return false; } List formats; - if (!TryFormats(out formats)) return false; + ClipboardBackupFailure reason; + if (!TryFormats(out formats, out reason)) { BackupFailure = reason; return false; } int total = 0; foreach (uint format in formats) { byte[] bytes; - if (!TryBytes(format, out bytes) || (total += bytes.Length) > MaxSnapshotBytes) return false; + if (!TryBytes(format, out bytes, out reason)) { BackupFailure = reason; return false; } + if ((total += bytes.Length) > MaxSnapshotBytes) { BackupFailure = ClipboardBackupFailure.TooLarge; return false; } saved.Formats.Add(new KeyValuePair(format, bytes)); } // Rendering a delayed format may change the sequence or advertise more formats. List after; - if (saved.Sequence != Sequence || !TryFormats(out after) || !formats.SequenceEqual(after)) return false; + if (saved.Sequence != Sequence || !TryFormats(out after, out reason) || !formats.SequenceEqual(after)) + { BackupFailure = ClipboardBackupFailure.Changed; return false; } snapshot = saved; return true; } diff --git a/src/ClipboardCaptureTests.cs b/src/ClipboardCaptureTests.cs index d614331..8e168d3 100644 --- a/src/ClipboardCaptureTests.cs +++ b/src/ClipboardCaptureTests.cs @@ -60,8 +60,7 @@ internal static void Run(Dictionary results) var canceled = new Fake(); canceled.OnSnapshot = delegate { canceled.Valid = false; }; Check(canceled.Run(tick).Result == null && canceled.Copies == 0, "canceled snapshot never copies"); var userCopy = new Fake(); userCopy.OnRestore = delegate { userCopy.Version++; }; - userCopy.Run(tick).GetAwaiter().GetResult(); - Check(userCopy.Restores == 0, "newer clipboard is not overwritten"); + Check(userCopy.Run(tick).GetAwaiter().GetResult() == null && userCopy.Restores == 0, "newer clipboard is not overwritten and stale capture is discarded"); var cancelAfter = new Fake(); cancelAfter.OnRead = delegate { cancelAfter.Valid = false; }; Check(cancelAfter.Run(tick).Result == null && cancelAfter.Restores == 0, "cancellation before restore preserves clipboard"); var wrongOwner = new Fake { ReadWorks = false }; diff --git a/src/ClipboardNativeTests.cs b/src/ClipboardNativeTests.cs index fe9f04d..e00bce7 100644 --- a/src/ClipboardNativeTests.cs +++ b/src/ClipboardNativeTests.cs @@ -82,7 +82,7 @@ internal static int Run() worker.Start(); worker.Join(); if (failure != null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); File.WriteAllText(Path.Combine(Program.Folder, "clipboard-native-test.json"), - new JavaScriptSerializer().Serialize(new { isolation = "private window station", result = "passed", cases = "text, HTML/RTF, exact bytes, empty, unknown, oversized, busy, stale/canceled restore, delayed rendering" })); + new JavaScriptSerializer().Serialize(new { isolation = "private window station", result = "passed", cases = "text, HTML/RTF, exact bytes, empty, unknown, oversized, busy, stale/canceled restore, delayed rendering", overwriteCases = "unsupported-format refusal without copy, explicit real edit-copy leaves fresh text, failed copy never reads stale text or clears clipboard; all on the private station" })); return 0; } finally @@ -132,13 +132,41 @@ private static void RunCases(IntPtr desktop) Put(clipboard.Handle, Text("keep"), new KeyValuePair(unknown, new byte[] { 1, 2, 3 })); uint before = clipboard.Sequence; Check(!clipboard.TrySnapshot(out restored) && clipboard.Sequence == before, "unknown mixed format skips without mutation"); + Check(clipboard.BackupFailure == ClipboardBackupFailure.UnsupportedFormat, "unsupported format failure classified"); + // Every destructive case below runs on this private window station's clipboard. + using (var form = new Forms.Form()) + using (var edit = new Forms.TextBox { Text = "prefix reversible suffix" }) + { + form.Controls.Add(edit); IntPtr root = form.Handle; edit.Select(7, 10); + bool offered = false; int copies = 0; + try { + SelectionIntegrationTests.Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, + delegate { copies++; edit.Copy(); }, delegate { }, delegate { return System.Threading.Tasks.Task.Delay(15); }, null, + new ClipboardCapturePolicy())); + } + catch (ClipboardBackupException ex) { offered = ex.CanOffer; } + Check(offered && copies == 0 && clipboard.Sequence == before, "default unsafe snapshot offers without changing private clipboard"); + string overwriteText = SelectionIntegrationTests.Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, edit.Copy, + delegate { }, delegate { return System.Threading.Tasks.Task.Delay(15); }, null, + new ClipboardCapturePolicy { AllowOverwrite = true, RequiredSequence = before })); + Check(overwriteText == "reversible" && !ClipboardNative.IsClipboardFormatAvailable(unknown), "explicit private clipboard overwrite captures fresh text and leaves new content"); + Put(clipboard.Handle, Text("old fixture must never be translated"), new KeyValuePair(unknown, new byte[] { 1, 2, 3 })); + uint failedBefore = clipboard.Sequence; bool timedOut = false; + try { + SelectionIntegrationTests.Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, delegate { }, + delegate { }, delegate { return System.Threading.Tasks.Task.Delay(1); }, null, + new ClipboardCapturePolicy { AllowOverwrite = true })); + } + catch (SelectionUnavailableException ex) { timedOut = ex.Message.Contains("超时"); } + Check(timedOut && clipboard.Sequence == failedBefore, "failed copy never reads stale text or clears even private clipboard"); + } Put(clipboard.Handle); Check(clipboard.TrySnapshot(out original) && original.Formats.Count == 0, "empty clipboard snapshot"); Put(clipboard.Handle, Text("temporary")); Check(clipboard.Restore(original, clipboard.Sequence, delegate { return true; }) == RestoreResult.Restored, "empty restore"); Check(clipboard.TrySnapshot(out restored) && restored.Formats.Count == 0, "empty preserved"); Put(clipboard.Handle, new KeyValuePair(13, new byte[NativeSelectionClipboard.MaxFormatBytes + 2])); - Check(!clipboard.TrySnapshot(out restored), "oversize snapshot rejected"); + Check(!clipboard.TrySnapshot(out restored) && clipboard.BackupFailure == ClipboardBackupFailure.TooLarge, "oversize snapshot rejected with reason"); Put(clipboard.Handle, Text("busy")); using (var opened = new ManualResetEvent(false)) using (var release = new ManualResetEvent(false)) diff --git a/src/ClipboardOverwrite.cs b/src/ClipboardOverwrite.cs new file mode 100644 index 0000000..8b32a7c --- /dev/null +++ b/src/ClipboardOverwrite.cs @@ -0,0 +1,56 @@ +using System; +using System.Threading; + +namespace LightTranslate +{ + internal enum ClipboardBackupFailure { None, UnsupportedFormat, TooLarge, Unreadable, Busy, Changed } + internal interface IClipboardBackupDiagnostics + { ClipboardBackupFailure BackupFailure { get; } } + + internal sealed class ClipboardCapturePolicy + { + internal bool AllowOverwrite; + internal uint? RequiredSequence; + } + + internal sealed class ClipboardBackupException : SelectionUnavailableException + { + internal readonly ClipboardBackupFailure Reason; + internal readonly uint Sequence; + internal bool CanOffer { get { return Sequence != 0 && MayOverwrite(Reason); } } + internal const string Risk = "覆盖后,原剪贴板中的图片、文字或应用专用数据可能丢失。Windows 剪贴板历史不保证能够恢复。能完整备份时,仍按原方式取词后恢复。"; + internal ClipboardBackupException(ClipboardBackupFailure reason, uint sequence) : base(MessageFor(reason)) + { Reason = reason; Sequence = sequence; } + internal static bool MayOverwrite(ClipboardBackupFailure reason) + { return reason == ClipboardBackupFailure.UnsupportedFormat || reason == ClipboardBackupFailure.TooLarge || reason == ClipboardBackupFailure.Unreadable; } + internal static string MessageFor(ClipboardBackupFailure reason) + { + switch (reason) + { + case ClipboardBackupFailure.UnsupportedFormat: return "当前剪贴板含有无法完整保留的数据格式,尚未执行复制。"; + case ClipboardBackupFailure.TooLarge: return "当前剪贴板数据超过安全备份上限,尚未执行复制。"; + case ClipboardBackupFailure.Busy: return "当前剪贴板暂时无法打开,尚未执行复制。请稍后重新选词。"; + case ClipboardBackupFailure.Changed: return "剪贴板已被其他操作更新,已取消本次取词。请重新选择文字。"; + default: return "当前剪贴板无法完整读取和备份,尚未执行复制。"; + } + } + } + + // No selected text is retained. A button authorizes one stable source/clipboard/generation only. + internal sealed class ClipboardOverwritePermit + { + private int consumed; + internal readonly int Generation; + internal readonly IntPtr Source; + internal readonly uint Sequence; + internal readonly DateTime Expires; + internal ClipboardOverwritePermit(int generation, IntPtr source, uint sequence, DateTime now) + { Generation = generation; Source = source; Sequence = sequence; Expires = now.AddSeconds(15); } + internal bool TryConsume(int generation, IntPtr foreground, uint sequence, bool enabled, DateTime now) + { + if (Interlocked.Exchange(ref consumed, 1) != 0) return false; + return enabled && generation == Generation && Source != IntPtr.Zero && foreground == Source + && Sequence != 0 && sequence == Sequence && now < Expires; + } + } +} diff --git a/src/ClipboardOverwriteConfirmation.cs b/src/ClipboardOverwriteConfirmation.cs new file mode 100644 index 0000000..9bd7387 --- /dev/null +++ b/src/ClipboardOverwriteConfirmation.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace LightTranslate +{ + internal sealed class ClipboardOverwriteConfirmation : Window + { + private readonly Grid layout; + internal ClipboardOverwriteConfirmation(Window owner = null) + { + if (owner != null) Owner = owner; + Title = "允许覆盖原剪贴板?"; Width = 500; Height = 360; + ResizeMode = ResizeMode.NoResize; ShowInTaskbar = false; + WindowStartupLocation = owner == null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner; + FontFamily = new FontFamily("Microsoft YaHei UI"); FontSize = 14; Background = Brushes.White; + Foreground = new SolidColorBrush(Color.FromRgb(36, 40, 48)); + layout = new Grid { Margin = new Thickness(24), Background = Brushes.White }; + layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + layout.RowDefinitions.Add(new RowDefinition()); + layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + layout.Children.Add(new TextBlock { Text = "开启取词优先,允许覆盖", FontSize = 19, FontWeight = FontWeights.SemiBold, Margin = new Thickness(0, 0, 0, 14) }); + var warning = new TextBlock { Text = "仅在无法完整备份时,直接复制选区并覆盖原剪贴板。\n\n" + ClipboardBackupException.Risk + "\n\n本选项将在设置页点击“保存”后生效。", TextWrapping = TextWrapping.Wrap }; + Grid.SetRow(warning, 1); layout.Children.Add(warning); + var actions = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right }; + var cancel = new Button { Content = "取消", IsDefault = true, IsCancel = true, Padding = new Thickness(16, 6, 16, 6), Margin = new Thickness(0, 14, 8, 0) }; + cancel.Click += delegate { DialogResult = false; }; actions.Children.Add(cancel); + var allow = new Button { Content = "了解风险,继续启用", Padding = new Thickness(14, 6, 14, 6), Margin = new Thickness(0, 14, 0, 0) }; + allow.Click += delegate { DialogResult = true; }; actions.Children.Add(allow); + Grid.SetRow(actions, 2); layout.Children.Add(actions); Content = layout; + } + internal void RenderPreview(string file) + { + layout.Measure(new Size(500, 321)); layout.Arrange(new Rect(0, 0, 500, 321)); layout.UpdateLayout(); + var bitmap = new RenderTargetBitmap(500, 321, 96, 96, PixelFormats.Pbgra32); + var background = new DrawingVisual(); + using (var drawing = background.RenderOpen()) drawing.DrawRectangle(Brushes.White, null, new Rect(0, 0, 500, 321)); + bitmap.Render(background); + bitmap.Render(layout); var png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(bitmap)); + using (var stream = File.Create(file)) png.Save(stream); + } + } +} diff --git a/src/ClipboardOverwriteTests.cs b/src/ClipboardOverwriteTests.cs new file mode 100644 index 0000000..72b876f --- /dev/null +++ b/src/ClipboardOverwriteTests.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using System.Web.Script.Serialization; + +namespace LightTranslate +{ + internal static class ClipboardOverwriteTests + { + private static void Check(bool ok, string message) { if (!ok) throw new Exception("Clipboard overwrite: " + message); } + private sealed class Fake : ISelectionClipboard, IClipboardBackupDiagnostics + { + internal uint Version = 10; + internal bool SnapshotWorks, Valid = true, CopyWorks = true, SourceOwned = true; + internal string Selected = "fresh selected text"; + internal int Copies, Restores, Reads, Snapshots, Waits; + internal Action OnSnapshot, OnWait, OnRead, OnCopy; + internal ClipboardBackupFailure Failure = ClipboardBackupFailure.UnsupportedFormat; + public ClipboardBackupFailure BackupFailure { get { return Failure; } } + public uint Sequence { get { return Version; } } + public bool TrySnapshot(out ClipboardSnapshot snapshot) + { + Snapshots++; snapshot = new ClipboardSnapshot { Sequence = Version }; + if (OnSnapshot != null) OnSnapshot(); return SnapshotWorks; + } + public bool TryReadText(IntPtr source, uint expected, out uint sequence, out string text) + { + Reads++; sequence = Version; text = Selected; + if (OnRead != null) OnRead(); + return SourceOwned && expected == Version && sequence == Version; + } + public RestoreResult Restore(ClipboardSnapshot snapshot, uint expected, Func valid) + { + if (!valid() || Version != expected) return RestoreResult.Changed; + Restores++; Version++; return RestoreResult.Restored; + } + internal Task Run(bool allow, uint? required = null, Func wait = null) + { + return ClipboardCapture.Read(this, new IntPtr(1), () => Valid, + delegate { Copies++; if (CopyWorks) Version++; if (OnCopy != null) OnCopy(); }, delegate { }, + wait ?? delegate { Waits++; if (OnWait != null) OnWait(); return Task.FromResult(0); }, null, + new ClipboardCapturePolicy { AllowOverwrite = allow, RequiredSequence = required }); + } + } + private static ClipboardBackupException BackupFails(Fake fake, bool allow, uint? required = null) + { + try { fake.Run(allow, required).GetAwaiter().GetResult(); throw new Exception("Expected backup failure"); } + catch (ClipboardBackupException ex) { return ex; } + } + private static void CaptureFails(Fake fake, string expected) + { + try { fake.Run(true).GetAwaiter().GetResult(); throw new Exception("Expected capture failure"); } + catch (SelectionUnavailableException ex) { Check(ex.Message.Contains(expected), "accurate failure " + expected); } + Check(fake.Restores == 0, "overwrite failure never restores old data"); + } + internal static int RunStandalone() + { + var results = new Dictionary(); Run(results); + File.WriteAllText(Path.Combine(Program.Folder, "clipboard-overwrite-test.json"), new JavaScriptSerializer().Serialize(results)); + return 0; + } + internal static void Run(Dictionary results) + { + Workflow(); Permits(); SettingsAndUi(); + results["clipboardOverwrite"] = "fake clipboard only: default refusal, reason classification, complete backup preferred, explicit overwrite without restore, fresh sequence/source checks, failed/empty copy, bounded timeout, cancellation/focus loss, user-copy races, overlapping operations and next-request recovery passed"; + results["overwriteConsent"] = "single-use source/generation/sequence/expiry permit, double-click guard, legacy default-off, explicit opt-in confirmation, reject/cancel/save/reopen/reset/failure rollback passed; risk dialog and non-activating bubble rendered without touching real clipboard"; + } + private static void Workflow() + { + var safe = new Fake { SnapshotWorks = true }; + Check(safe.Run(true).Result == "fresh selected text" && safe.Restores == 1, "complete backup preferred even when overwrite enabled"); + var denied = new Fake(); var warning = BackupFails(denied, false); + Check(warning.Reason == ClipboardBackupFailure.UnsupportedFormat && warning.CanOffer && warning.Sequence == 10 && denied.Copies == 0 && denied.Reads == 0, "default does not copy/read and can offer one-time choice"); + foreach (var reason in new[] { ClipboardBackupFailure.UnsupportedFormat, ClipboardBackupFailure.TooLarge, ClipboardBackupFailure.Unreadable }) + { + var allowed = new Fake { Failure = reason }; + Check(allowed.Run(true).Result == "fresh selected text" && allowed.Copies == 1 && allowed.Restores == 0, "allowed stable failure " + reason); + } + foreach (var reason in new[] { ClipboardBackupFailure.Busy, ClipboardBackupFailure.Changed }) + { + var blocked = new Fake { Failure = reason }; var ex = BackupFails(blocked, true); + Check(!ex.CanOffer && blocked.Copies == 0, "busy/changed data never auto-overwritten"); + } + var before = new Fake(); Check(BackupFails(before, true, 9).Reason == ClipboardBackupFailure.Changed && before.Snapshots == 0 && before.Copies == 0, "one-time sequence checked before snapshot"); + var during = new Fake(); during.OnSnapshot = () => during.Version++; + Check(BackupFails(during, true).Reason == ClipboardBackupFailure.Changed && during.Copies == 0, "snapshot race cancels overwrite"); + var canceled = new Fake { Valid = false }; Check(canceled.Run(true).Result == null && canceled.Copies == 0, "canceled before capture"); + var cancelSnapshot = new Fake(); cancelSnapshot.OnSnapshot = () => cancelSnapshot.Valid = false; + Check(cancelSnapshot.Run(true).Result == null && cancelSnapshot.Copies == 0, "canceled during snapshot"); + var lostFocus = new Fake(); lostFocus.OnCopy = () => lostFocus.Valid = false; + Check(lostFocus.Run(true).Result == null && lostFocus.Reads == 0 && lostFocus.Restores == 0, "focus lost after Ctrl+C discards result"); + var failedCopy = new Fake { CopyWorks = false, Selected = "stale preexisting text" }; + CaptureFails(failedCopy, "超时"); Check(failedCopy.Waits == 32 && failedCopy.Reads == 0 && failedCopy.Version == 10, "copy failure never reads old clipboard and has bounded polling"); + var sendFailure = new Fake(); sendFailure.OnCopy = delegate { throw new InvalidOperationException("synthetic partial SendInput failure"); }; + CaptureFails(sendFailure, "未能向源应用发送"); Check(sendFailure.Reads == 0, "copy dispatch exception never reads stale data"); + var empty = new Fake { Selected = " " }; CaptureFails(empty, "没有产生"); + var other = new Fake(); other.OnWait = delegate { other.Version++; other.SourceOwned = false; }; + CaptureFails(other, "来源无法确认"); + var userCopy = new Fake(); userCopy.OnWait = delegate { userCopy.Version++; userCopy.Valid = false; }; + Check(userCopy.Run(true).Result == null && userCopy.Reads == 0 && userCopy.Restores == 0, "concurrent user key/copy cancels before reading"); + var readRace = new Fake(); readRace.OnRead = () => readRace.Version++; + CaptureFails(readRace, "来源无法确认"); + var signal = new TaskCompletionSource(); var first = new Fake(); + var pending = first.Run(true, null, () => signal.Task); var second = new Fake(); + Check(second.Run(true).Result == null && second.Snapshots == 0 && second.Copies == 0, "overlapping operations do not copy"); + signal.SetResult(0); Check(pending.Result == "fresh selected text", "first pending capture completes"); + Check(second.Run(true).Result == "fresh selected text", "gate reusable after completion"); + Check(ClipboardBackupException.MessageFor(ClipboardBackupFailure.TooLarge).Contains("上限") && ClipboardBackupException.MessageFor(ClipboardBackupFailure.Busy).Contains("暂时无法打开"), "failure descriptions reflect reason"); + } + private static void Permits() + { + var now = DateTime.UtcNow; var source = new IntPtr(42); + var permit = new ClipboardOverwritePermit(7, source, 100, now); + Check(permit.TryConsume(7, source, 100, true, now) && !permit.TryConsume(7, source, 100, true, now), "one-time permission cannot be replayed"); + Check(!new ClipboardOverwritePermit(7, source, 100, now).TryConsume(8, source, 100, true, now), "new selection/settings generation invalidates offer"); + Check(!new ClipboardOverwritePermit(7, source, 100, now).TryConsume(7, new IntPtr(9), 100, true, now), "wrong foreground invalidates offer"); + Check(!new ClipboardOverwritePermit(7, source, 100, now).TryConsume(7, source, 101, true, now), "user clipboard update invalidates offer"); + Check(!new ClipboardOverwritePermit(7, source, 100, now).TryConsume(7, source, 100, true, now.AddSeconds(15)), "fixed expiry despite hover"); + Check(!new ClipboardOverwritePermit(7, source, 100, now).TryConsume(7, source, 100, false, now), "disabled capture invalidates offer"); + var invalidated = new ClipboardOverwritePermit(7, source, 100, now); + Check(!invalidated.TryConsume(7, source, 101, true, now) && !invalidated.TryConsume(7, source, 100, true, now), "invalidated offer cannot become valid again"); + } + private static void SettingsAndUi() + { + string root = Path.Combine(Program.Folder, "overwrite-settings-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(root); + try + { + string path = Path.Combine(root, "settings.json"); + File.WriteAllText(path, "{\"TranslationProvider\":\"index\",\"IndexModel\":\"Index-Translate-9B\",\"BubbleFontSize\":18}"); + var settings = Settings.Load(path); Check(!settings.AllowClipboardOverwrite, "legacy default off"); + int confirmations = 0; bool approve = false; + Func confirm = delegate { confirmations++; return approve; }; + var window = new SettingsWindow(settings, null, new FakeStartupRegistration(), null, confirm); + window.SetOverwriteForTest(true); Check(!window.OverwriteForTest && confirmations == 1 && !settings.AllowClipboardOverwrite, "declined risk prompt does not enable or save"); + approve = true; window.SetOverwriteForTest(true); + Check(window.OverwriteForTest && !settings.AllowClipboardOverwrite, "accepted confirmation remains staged until save"); + window.Close(); Check(!Settings.Load(path).AllowClipboardOverwrite, "cancel keeps disabled configuration"); + window = new SettingsWindow(settings, null, new FakeStartupRegistration(), null, confirm); window.SetOverwriteForTest(true); + Check(window.Apply(path) && settings.AllowClipboardOverwrite && settings.Clone().AllowClipboardOverwrite, "save and runtime copy roundtrip"); + var loaded = Settings.Load(path); int count = confirmations; + window = new SettingsWindow(loaded, null, new FakeStartupRegistration(), null, confirm); + Check(window.OverwriteForTest && confirmations == count && loaded.IndexModel == "Index-Translate-9B" && loaded.BubbleFontSize == 18, "reopen preserves prior consent and other settings"); + window.RenderPreview(Path.Combine(Program.Folder, "settings-overwrite-enabled-preview.png"), 0); + window.Fill(new Settings()); Check(!window.OverwriteForTest && loaded.AllowClipboardOverwrite, "reset input only"); window.Close(); + var original = new Settings(); window = new SettingsWindow(original, null, new FakeStartupRegistration(), null, confirm); window.SetOverwriteForTest(true); + Check(!window.Apply(Path.Combine(root, "missing", "settings.json")) && !original.AllowClipboardOverwrite, "failed save cannot enable overwrite"); window.Close(); + window = new SettingsWindow(new Settings(), null, new FakeStartupRegistration(), null, delegate { throw new InvalidOperationException("synthetic confirmation failure"); }); + window.SetOverwriteForTest(true); Check(!window.OverwriteForTest && window.ErrorForTest.Contains("保持关闭"), "confirmation failure defaults to refusal"); window.Close(); + window = new SettingsWindow(new Settings(), null, new FakeStartupRegistration(), null, confirm); + window.RenderPreview(Path.Combine(Program.Folder, "settings-overwrite-default-preview.png"), 0); window.Close(); + var dialog = new ClipboardOverwriteConfirmation(); dialog.RenderPreview(Path.Combine(Program.Folder, "overwrite-risk-confirmation-preview.png")); dialog.Close(); + var bubble = new Bubble(); int clicks = 0; + IntPtr bubbleHandle = new System.Windows.Interop.WindowInteropHelper(bubble).EnsureHandle(); + bubble.RenderOverwritePreview(Path.Combine(Program.Folder, "overwrite-bubble-preview.png"), delegate { clicks++; }); + Check(bubble.OverwriteVisibleForTest, "one-time action visible in warning"); + bubble.InvokeOverwriteForTest(); bubble.InvokeOverwriteForTest(); Check(clicks == 1, "double click cannot authorize twice"); + bubble.Dismiss(true); bubble.InvokeOverwriteForTest(); Check(clicks == 1 && !bubble.OverwriteVisibleForTest, "dismiss revokes pending action"); + Check(bubble.OwnsSurface(new SelectionSurface { Root = bubbleHandle }) && !bubble.OwnsSurface(new SelectionSurface { Root = new IntPtr(98765) }), "queued bubble click stays classified as own UI after hiding"); + int cancels = 0; + bubble.RenderOverwritePreview(Path.Combine(Program.Folder, "overwrite-bubble-preview.png"), delegate { clicks++; }, delegate { cancels++; bubble.Dismiss(true); }); + bubble.InvokeOverwriteCancelForTest(); bubble.InvokeOverwriteForTest(); + Check(cancels == 1 && clicks == 1, "cancel button revokes pending authorization"); bubble.Close(); + Check(ClipboardBackupException.Risk.Contains("可能丢失") && ClipboardBackupException.Risk.Contains("不保证"), "risk wording never promises history recovery"); + } + finally { Directory.Delete(root, true); } + } + } +} diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index cd742b4..04f5de4 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -9,7 +9,7 @@ namespace LightTranslate { - internal sealed class SelectionUnavailableException : Exception + internal class SelectionUnavailableException : Exception { internal SelectionUnavailableException(string message = "当前应用暂时无法读取选区,已保留剪贴板原内容。") : base(message) { } } diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index cd69da4..b75b4f6 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -45,6 +45,7 @@ private static int Main(string[] args) if (args.Length > 0 && args[0] == "--self-test-clipboard-native") return ClipboardNativeTests.Run(); if (args.Length > 0 && args[0] == "--self-test-providers") return TranslationProviderTests.RunStandalone(); if (args.Length > 0 && args[0] == "--self-test-index") return IndexTests.RunStandalone(); + if (args.Length > 0 && args[0] == "--self-test-overwrite") return ClipboardOverwriteTests.RunStandalone(); if (args.Length > 0 && args[0] == "--test-index-live") return IndexTests.RunLive(); if (args.Length > 0 && args[0] == "--self-test-tray") return TrayIconRenderer.RunStandalone(); if (args.Length > 0 && args[0] == "--self-test-gestures") return SelectionGestureTests.Run(); @@ -89,6 +90,7 @@ internal sealed class Settings { public bool Enabled = true; public bool ClipboardFallback = true; + public bool AllowClipboardOverwrite = false; public string Target = "zh-Hans"; public string TranslationProvider = "auto"; public string IndexModel = IndexTranslator.DefaultModel; @@ -138,6 +140,7 @@ internal void CopyReadingFrom(Settings other) internal void CopyUserFrom(Settings other) { Enabled = other.Enabled; ClipboardFallback = other.ClipboardFallback; + AllowClipboardOverwrite = other.AllowClipboardOverwrite; Target = other.Target; TranslationProvider = other.TranslationProvider; MaxSelectionLength = other.MaxSelectionLength; IndexModel = other.IndexModel; ExcludedApps = other.ExcludedApps == null ? null : (string[])other.ExcludedApps.Clone(); @@ -186,6 +189,7 @@ internal sealed class Controller : IDisposable private uint lastUpTime; private readonly BubbleLifetime lifetime = new BubbleLifetime(); private SettingsWindow settingsWindow; + private ClipboardOverwritePermit overwriteOffer; private readonly Queue diagnosticQueue = new Queue(); private long mouseEvents, mouseDowns, mouseUps, selections; private DateTime nextHeartbeat, nextHealthLog, nextSettingsCheck; @@ -254,6 +258,10 @@ private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow, // Only ignore input generated by this application, rather than all injected input. if (data.extra != Native.OwnInputMarker) { + // A button can hide the bubble before queued hook events are dispatched. + // Use the captured HWND as well as current geometry, so its click cannot + // cancel the just-authorized capture or become another source selection. + if (bubble.OwnsSurface(surface)) { down = false; return; } if (message == 0x201) { mouseDowns++; @@ -324,12 +332,14 @@ private void HandleKeyboard(int message, Native.KEYBOARD data, IntPtr capturedWi private void Dismiss(bool immediate) { generation++; + overwriteOffer = null; if (pending != null) { pending.Cancel(); pending = null; } if (bubble.IsVisible) bubble.Dismiss(immediate); lifetime.Reset(); } - private async void BeginSelection(IntPtr window, Native.POINT point, SelectionSurface origin = null) + private async void BeginSelection(IntPtr window, Native.POINT point, SelectionSurface origin = null, + bool overwriteOnce = false, uint? requiredClipboardSequence = null) { selections++; Dismiss(true); @@ -353,7 +363,8 @@ private async void BeginSelection(IntPtr window, Native.POINT point, SelectionSu // Inspect text context in the isolated helper before any clipboard access. // The main process never owns UIAutomationClient objects. if (!settings.ClipboardFallback || SelectionReader.IsTerminal(processName)) return; - string text = await SelectionReader.CopySelection(window, ct, Trace, point, origin); + string text = await SelectionReader.CopySelection(window, ct, Trace, point, origin, + settings.AllowClipboardOverwrite || overwriteOnce, requiredClipboardSequence); Trace("selection chars=" + (text == null ? 0 : text.Length)); if (!Valid(version, window) || string.IsNullOrWhiteSpace(text)) { Trace("selection discarded valid=" + Valid(version, window)); return; } text = text.Trim(); @@ -382,6 +393,28 @@ private async void BeginSelection(IntPtr window, Native.POINT point, SelectionSu ShowText(translated, point, ReadingSeconds(translated), true); } catch (OperationCanceledException) { } + catch (ClipboardBackupException ex) + { + Program.Log("clipboard-backup", ex.Reason.ToString()); + if (Valid(version, window)) + { + anchor = point; sourceWindow = window; + if (!ex.CanOffer) ShowText(ex.Message, point, 6); + else + { + var permit = new ClipboardOverwritePermit(version, window, ex.Sequence, DateTime.UtcNow); + overwriteOffer = permit; + lifetime.Start(DateTime.UtcNow, 15); + bubble.PresentOverwrite(ex.Message + "\n\n" + ClipboardBackupException.Risk, + point, delegate { + if (!permit.TryConsume(generation, Native.GetForegroundWindow(), Native.GetClipboardSequenceNumber(), + settings.Enabled && settings.ClipboardFallback && !disposed, DateTime.UtcNow)) + { Dismiss(true); return; } + BeginSelection(window, point, origin, true, permit.Sequence); + }, delegate { Dismiss(true); }); + } + } + } catch (Exception ex) { Program.Log("translate", ex.GetType().Name); @@ -438,6 +471,7 @@ private void FlushDiagnostics() private void CheckDismissal() { if (!bubble.IsVisible) return; + if (overwriteOffer != null && DateTime.UtcNow >= overwriteOffer.Expires) { Dismiss(false); return; } if (Native.GetForegroundWindow() != sourceWindow) { Dismiss(false); return; } Native.POINT point; Native.GetCursorPos(out point); @@ -705,7 +739,8 @@ internal static bool ShouldTranslate(string text, int minimumPercent) } return english > 0 && english * 100L >= letters * (long)minimumPercent; } - public static async Task CopySelection(IntPtr window, CancellationToken ct, Action trace, Native.POINT? point = null, SelectionSurface origin = null) + public static async Task CopySelection(IntPtr window, CancellationToken ct, Action trace, Native.POINT? point = null, SelectionSurface origin = null, + bool allowOverwrite = false, uint? requiredClipboardSequence = null) { if (Native.GetForegroundWindow() != window || Native.ModifierDown()) { trace("copy skipped focus/modifier"); return null; } if (Native.IsPasswordFocus(window)) { trace("password field skipped"); return null; } @@ -716,7 +751,8 @@ async delegate(SelectionReadResult result) { using (var clipboard = new NativeSelectionClipboard()) return await ClipboardCapture.Read(clipboard, window, valid, Native.Copy, trace, - delegate { return Task.Delay(15); }, delegate { return Task.FromResult(result.ForCapture()); }); + delegate { return Task.Delay(15); }, delegate { return Task.FromResult(result.ForCapture()); }, + new ClipboardCapturePolicy { AllowOverwrite = allowOverwrite, RequiredSequence = requiredClipboardSequence }); }, valid); } } @@ -725,6 +761,9 @@ internal sealed class Bubble : Window { private readonly Border card; private readonly TextBlock content; + private readonly StackPanel overwriteActions; + private readonly Button overwriteButton, cancelOverwriteButton; + private Action overwriteAction, cancelOverwriteAction; private int hideVersion; public Bubble() { @@ -752,9 +791,27 @@ public Bubble() VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Focusable = false }; + overwriteButton = new Button { Content = "本次覆盖并取词", Focusable = false, IsTabStop = false, + Padding = new Thickness(12, 6, 12, 6), MinHeight = 32, Margin = new Thickness(0, 10, 8, 0) }; + cancelOverwriteButton = new Button { Content = "取消", Focusable = false, IsTabStop = false, + Padding = new Thickness(12, 6, 12, 6), MinHeight = 32, Margin = new Thickness(0, 10, 0, 0) }; + System.Windows.Automation.AutomationProperties.SetName(overwriteButton, "本次覆盖并取词,原剪贴板内容可能丢失"); + System.Windows.Automation.AutomationProperties.SetHelpText(overwriteButton, "只授权当前选区一次;Windows 剪贴板历史不保证恢复。15 秒内有效。"); + overwriteActions = new StackPanel { Orientation = Orientation.Horizontal, Visibility = Visibility.Collapsed }; + overwriteActions.Children.Add(overwriteButton); overwriteActions.Children.Add(cancelOverwriteButton); + overwriteButton.Click += delegate { + var action = overwriteAction; overwriteAction = null; cancelOverwriteAction = null; + overwriteButton.IsEnabled = false; cancelOverwriteButton.IsEnabled = false; + if (action != null) action(); + }; + cancelOverwriteButton.Click += delegate { + var action = cancelOverwriteAction; overwriteAction = null; cancelOverwriteAction = null; + if (action != null) action(); + }; + var body = new StackPanel(); body.Children.Add(scroller); body.Children.Add(overwriteActions); card = new Border { - Child = scroller, Padding = new Thickness(15, 10, 15, 11), + Child = body, Padding = new Thickness(15, 10, 15, 11), Background = new SolidColorBrush(Color.FromRgb(252, 252, 253)), BorderBrush = new SolidColorBrush(Color.FromArgb(35, 40, 48, 64)), BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(11), @@ -790,7 +847,30 @@ public bool Contains(Native.POINT p) if (!Native.GetWindowRect(new WindowInteropHelper(this).Handle, out bounds)) return false; return p.x >= bounds.left && p.x < bounds.right && p.y >= bounds.top && p.y < bounds.bottom; } + internal bool OwnsSurface(SelectionSurface surface) + { + IntPtr handle = new WindowInteropHelper(this).Handle; + return surface != null && handle != IntPtr.Zero && (surface.Root == handle || surface.Window == handle); + } public void Present(string text, Native.POINT point) + { + ClearOverwrite(); + PresentCore(text, point); + } + private void ClearOverwrite() + { overwriteAction = null; cancelOverwriteAction = null; overwriteActions.Visibility = Visibility.Collapsed; } + internal void PresentOverwrite(string text, Native.POINT point, Action overwrite, Action cancel) + { + SetOverwrite(text, overwrite, cancel); + PresentCore(text, point); + } + private void SetOverwrite(string text, Action overwrite, Action cancel) + { + content.Text = text; overwriteAction = overwrite; cancelOverwriteAction = cancel; + overwriteButton.IsEnabled = true; cancelOverwriteButton.IsEnabled = true; + overwriteActions.Visibility = Visibility.Visible; + } + private void PresentCore(string text, Native.POINT point) { hideVersion++; bool wasVisible = IsVisible; @@ -826,6 +906,7 @@ public void Present(string text, Native.POINT point) } public void Dismiss(bool immediate) { + ClearOverwrite(); if (!IsVisible) return; int version = ++hideVersion; if (immediate) { BeginAnimation(OpacityProperty, null); Hide(); return; } @@ -835,7 +916,20 @@ public void Dismiss(bool immediate) } internal void RenderPreview(string file) { + ClearOverwrite(); content.Text = "选中后直接显示译文。\n继续操作,浮层自动消失。"; + RenderContent(file); + } + internal void RenderOverwritePreview(string file, Action action, Action cancel = null) + { + SetOverwrite(ClipboardBackupException.MessageFor(ClipboardBackupFailure.UnsupportedFormat) + "\n\n" + ClipboardBackupException.Risk, action, cancel); + RenderContent(file); + } + internal void InvokeOverwriteForTest() { overwriteButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); } + internal void InvokeOverwriteCancelForTest() { cancelOverwriteButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); } + internal bool OverwriteVisibleForTest { get { return overwriteActions.Visibility == Visibility.Visible; } } + private void RenderContent(string file) + { var view = (FrameworkElement)Content; view.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); view.Arrange(new Rect(view.DesiredSize)); @@ -1183,6 +1277,7 @@ public static int Run(bool offline) results["dictionaryText"] = word; } ClipboardCaptureTests.Run(results); + ClipboardOverwriteTests.Run(results); if (!SelectionReader.IsTerminal("pwsh") || SelectionReader.IsTerminal("Codex")) throw new Exception("Terminal guard failed"); if (SelectionReader.HasForeignText("这是中文") || !SelectionReader.HasForeignText("Read this text")) throw new Exception("Language guard failed"); results["guards"] = "terminal + language passed"; diff --git a/src/ReadingSettings.cs b/src/ReadingSettings.cs index e3a0c6e..7b23ae5 100644 --- a/src/ReadingSettings.cs +++ b/src/ReadingSettings.cs @@ -104,7 +104,9 @@ internal sealed class SettingsWindow : Window private readonly PasswordBox deepLKey; private readonly TextBlock deepLStatus; private bool clearDeepLKey; - private readonly CheckBox enabled, clipboard, autoStart; + private readonly CheckBox enabled, clipboard, allowOverwrite, autoStart; + private readonly Func confirmOverwrite; + private bool fillingOverwrite; private readonly ComboBox language, provider, indexModel, fontFamily, fontSize, autoHide; private readonly TextBox maxSelection, excludedApps, background, englishPercent; private readonly TextBlock error, previewText, startupStatus; @@ -114,9 +116,11 @@ internal sealed class SettingsWindow : Window private bool refreshingStartup, startupDirty; private bool? observedStartup; - internal SettingsWindow(Settings settings, Action saved, IStartupRegistration startup = null, IDeepLCredentials credentials = null) + internal SettingsWindow(Settings settings, Action saved, IStartupRegistration startup = null, IDeepLCredentials credentials = null, + Func confirmOverwrite = null) { this.settings = settings; this.saved = saved; + this.confirmOverwrite = confirmOverwrite ?? delegate { return new ClipboardOverwriteConfirmation(this).ShowDialog() == true; }; this.startup = startup ?? StartupRegistration.CurrentUser(); this.credentials = credentials ?? DeepLCredentials.Current(); Title = "轻译 · 设置"; @@ -141,7 +145,18 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st enabled = Toggle("自动划词翻译"); clipboard = Toggle("启用选区取词"); translation.Children.Add(enabled); translation.Children.Add(clipboard); - translation.Children.Add(Help("托盘开关立即生效;面板修改在保存后生效。关闭取词后停止划词翻译。通常临时复制选区并恢复剪贴板;若含图片或专用数据,则尝试隔离读取选区,不改剪贴板。无法安全读取时会提示。")); + translation.Children.Add(Help("托盘开关立即生效;面板修改在保存后生效。关闭取词后停止划词翻译。先尝试隔离读取选区;需要临时复制时,能完整备份则恢复原剪贴板。无法备份时按下方覆盖选项处理。")); + allowOverwrite = Toggle("取词优先,允许覆盖(默认关闭)"); + translation.Children.Add(allowOverwrite); + translation.Children.Add(Help("仅在无法完整备份时允许覆盖原剪贴板。" + ClipboardBackupException.Risk + "关闭时,可在失败提示中单次选择“本次覆盖并取词”。")); + AutomationProperties.SetHelpText(allowOverwrite, ClipboardBackupException.Risk); + allowOverwrite.Checked += delegate { + if (fillingOverwrite) return; + bool approved = false; + try { approved = this.confirmOverwrite(); } + catch { if (error != null) Invalid("无法完成覆盖风险确认,选项保持关闭。", allowOverwrite, 0); } + if (!approved) allowOverwrite.IsChecked = false; + }; provider = new ComboBox { ItemsSource = new[] { "自动(微软失败后腾讯)", "仅微软", "仅腾讯(中文)", "仅 DeepL(自备 API 密钥)", "仅哔哩哔哩 Index" }, MinHeight = 32 }; AddField(translation, "在线翻译服务", provider); translation.Children.Add(Help("自动模式先查本地英汉词库,再尝试微软、腾讯;指定服务会跳过词库且不自动切换。DeepL 须在 DeepL 页保存密钥;自动模式不会调用 DeepL。")); @@ -272,6 +287,9 @@ internal void Fill(Settings value) { if (error != null) error.Visibility = Visibility.Collapsed; enabled.IsChecked = value.Enabled; clipboard.IsChecked = value.ClipboardFallback; + fillingOverwrite = true; + try { allowOverwrite.IsChecked = value.AllowClipboardOverwrite; } + finally { fillingOverwrite = false; } provider.SelectedIndex = value.TranslationProvider == "microsoft" ? 1 : value.TranslationProvider == "tencent" ? 2 : value.TranslationProvider == "deepl" ? 3 : value.TranslationProvider == "index" ? 4 : 0; indexModel.SelectedItem = value.IndexModel; indexModel.IsEnabled = provider.SelectedIndex == 4; @@ -345,6 +363,7 @@ internal bool Apply(string path) return Invalid("最低英文占比请输入 0–100 的整数百分比。", englishPercent, 0); var next = settings.Clone(); next.Enabled = enabled.IsChecked == true; next.ClipboardFallback = clipboard.IsChecked == true; + next.AllowClipboardOverwrite = allowOverwrite.IsChecked == true; next.TranslationProvider = provider.SelectedIndex == 1 ? "microsoft" : provider.SelectedIndex == 2 ? "tencent" : provider.SelectedIndex == 3 ? "deepl" : provider.SelectedIndex == 4 ? "index" : "auto"; if (provider.SelectedIndex == 4 && !IndexTranslator.ValidModel(indexModel.SelectedItem as string)) return Invalid("请选择 Index 模型:2B、9B 或 35B。", indexModel, 0); @@ -449,6 +468,8 @@ private void RefreshDeepLStatus() internal string IndexModelForTest { get { return indexModel.SelectedItem as string; } } internal bool IndexModelEnabledForTest { get { return indexModel.IsEnabled; } } internal bool TargetEnabledForTest { get { return language.IsEnabled; } } + internal void SetOverwriteForTest(bool value) { allowOverwrite.IsChecked = value; } + internal bool OverwriteForTest { get { return allowOverwrite.IsChecked == true; } } internal void SetStartupForTest(bool value) { autoStart.IsChecked = value; } internal bool EnabledForTest { get { return enabled.IsChecked == true; } } internal bool? StartupForTest { get { return autoStart.IsChecked; } }