From db2a2ea4926a2ddc150c1d3980a1d5a5e048af58 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:10:58 +0800 Subject: [PATCH 01/17] Avoid OLE clipboard materialization during selection capture --- .github/workflows/build.yml | 6 + docs/TESTING.md | 28 +++++ scripts/test-clipboard.ps1 | 14 +++ src/ClipboardCapture.cs | 234 +++++++++++++++++++++++++++++++++++ src/ClipboardCaptureTests.cs | 95 ++++++++++++++ src/ClipboardNativeTests.cs | 149 ++++++++++++++++++++++ src/LightTranslate.cs | 73 ++--------- src/ReadingSettings.cs | 2 +- 8 files changed, 534 insertions(+), 67 deletions(-) create mode 100644 scripts/test-clipboard.ps1 create mode 100644 src/ClipboardCapture.cs create mode 100644 src/ClipboardCaptureTests.cs create mode 100644 src/ClipboardNativeTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0effef4..464843b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,6 +17,12 @@ jobs: - name: Build application shell: pwsh run: ./build.ps1 + - name: Clipboard workflow regression + shell: pwsh + run: ./scripts/test-clipboard.ps1 + - name: Isolated native clipboard regression + shell: pwsh + run: ./scripts/test-clipboard.ps1 -Native - name: Fetch and build pinned dictionary shell: pwsh run: ./scripts/download-dictionary.ps1 diff --git a/docs/TESTING.md b/docs/TESTING.md index fef41a0..8a06183 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -147,3 +147,31 @@ OCR、朗读、翻译历史、原位替换、AI 润色、自动更新、安装 13. 输入非法颜色、字号、秒数或比例,确认就地报错且不保存;取消和关闭设置不应用,重启后保留已保存的值且不改动自动翻译开关等其他设置。 14. 打开面板后切换托盘自动翻译,再保存其他选项,确认开关不会被旧值覆盖;目标语言、选区上限、排除应用和取词开关即时应用,取消不应用。 15. 自启验证只在隔离目录或模拟后端完成;打开、勾选、恢复配置默认值和取消均不得写入,只有保存才能修改;覆盖禁用/未知/异目标以及保存和回滚失败状态。真实用户启动项由用户自行选择,不作为自动测试动作。 + +## Clipboard capture regression + +`./scripts/test-clipboard.ps1` tests capture cancellation, concurrent selections, +snapshot/read/restore races and bounded retries without accessing the clipboard. +`./scripts/test-clipboard.ps1 -Native` creates a private window station and desktop +before opening a clipboard. It aborts if isolation is unavailable; it never falls +back to the interactive clipboard. It tests exact byte preservation for Unicode, +HTML and RTF, empty/unsupported/oversized data, busy access, stale restoration and +delayed rendering. Both commands run in CI; neither needs the dictionary. + +Capture now accepts only HGLOBAL text formats (Unicode/ANSI/OEM text, locale, +HTML Format and Rich Text Format), at most 64 formats, 8 MiB per format and +16 MiB total. Unknown or incomplete snapshots skip the selection before Ctrl+C; +images, file lists and application-private formats are not silently discarded. +Delayed rendering may cause a snapshot to be skipped when its version changes. +A slow native clipboard owner can still delay GetClipboardData. Restore checks +the sequence while holding OpenClipboard, and preallocates every buffer before +EmptyClipboard. Windows provides no atomic multi-format replacement; a native +SetClipboardData failure is reported, and newer user data is never deliberately +replaced to retry a failed restore. Cancellation leaves the current clipboard +alone. A copy from the same source with no observable input/version distinction +cannot be attributed with certainty; this is not a proof of clipboard ownership. + +The change bypasses the observed IDataObject/OLE IStream conversion crash path. +The original native crash has not been reproduced, and the faulty format or +provider has not been identified. These tests exercise the replacement behavior, +not the original corrupt COM pointer. diff --git a/scripts/test-clipboard.ps1 b/scripts/test-clipboard.ps1 new file mode 100644 index 0000000..70ee621 --- /dev/null +++ b/scripts/test-clipboard.ps1 @@ -0,0 +1,14 @@ +[CmdletBinding()] +param([switch]$Native) +$ErrorActionPreference = 'Stop' +$exe = Join-Path $PSScriptRoot '..\dist\LightTranslate\LightTranslate.exe' +$argument = if ($Native) { '--self-test-clipboard-native' } else { '--self-test-clipboard' } +$test = Start-Process -FilePath $exe -ArgumentList $argument -WindowStyle Hidden -PassThru +if (-not $test.WaitForExit(30000)) { + Stop-Process -Id $test.Id -Force + throw 'Clipboard test timed out.' +} +$test.Refresh() +if ($test.ExitCode -ne 0) { throw 'Clipboard test failed; see dist/LightTranslate/status.log.' } +$name = if ($Native) { 'clipboard-native-test.json' } else { 'clipboard-test.json' } +Get-Content -LiteralPath (Join-Path (Split-Path $exe) $name) diff --git a/src/ClipboardCapture.cs b/src/ClipboardCapture.cs new file mode 100644 index 0000000..eb80645 --- /dev/null +++ b/src/ClipboardCapture.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + internal sealed class ClipboardSnapshot + { + internal uint Sequence; + internal readonly List> Formats = new List>(); + } + + internal enum RestoreResult { Restored, Changed, Busy, Failed } + + internal interface ISelectionClipboard + { + uint Sequence { get; } + bool TrySnapshot(out ClipboardSnapshot snapshot); + bool TryReadText(IntPtr source, uint expected, out uint sequence, out string text); + RestoreResult Restore(ClipboardSnapshot snapshot, uint expected, Func valid); + } + + 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) + { + // Do not queue stale selections or snapshot another capture's temporary clipboard. + if (!gate.Wait(0)) { trace("copy skipped busy"); return null; } + try + { + ClipboardSnapshot saved; + if (!valid() || !clipboard.TrySnapshot(out saved)) { trace("clipboard snapshot skipped"); return null; } + if (!valid() || clipboard.Sequence != saved.Sequence) return null; + copy(); + for (int i = 0; i < 12; i++) + { + await wait(); + if (!valid()) return null; + uint observed = clipboard.Sequence; + if (observed == saved.Sequence) continue; + uint copied; + string text; + if (!clipboard.TryReadText(source, observed, out copied, out text)) return null; + // Read and restore each check ownership/version while holding the clipboard lock. + for (int retry = 0; retry < 3; retry++) + { + var result = clipboard.Restore(saved, copied, valid); + if (result != RestoreResult.Busy) + { + if (result == RestoreResult.Failed) trace("clipboard restore failed"); + return valid() ? text : null; + } + await wait(); + } + trace("clipboard restore busy"); + return valid() ? text : null; + } + return null; + } + finally { gate.Release(); } + } + } + + // 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 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(); } } + + internal NativeSelectionClipboard() + { + window.CreateHandle(new Forms.CreateParams { Caption = "LightTranslate clipboard", Parent = new IntPtr(-3) }); + } + public void Dispose() { window.DestroyHandle(); } + + internal static bool Supported(uint format) + { + if (format == 1 || format == 7 || format == 13 || format == 16) return true; + if (format < 0xc000) return false; + var name = new StringBuilder(256); + if (ClipboardNative.GetClipboardFormatName(format, name, name.Capacity) == 0) return false; + return name.ToString() == "HTML Format" || name.ToString() == "Rich Text Format"; + } + + internal static bool TryFormats(out List formats) + { + 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; + formats.Add(format); + } + } + + internal static bool TryBytes(uint format, out byte[] bytes) + { + 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; + 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; } + finally { ClipboardNative.GlobalUnlock(handle); } + } + + public bool TrySnapshot(out ClipboardSnapshot snapshot) + { + snapshot = null; + if (!ClipboardNative.OpenClipboard(Handle)) return false; + try + { + var saved = new ClipboardSnapshot { Sequence = Sequence }; + if (saved.Sequence == 0) return false; + List formats; + if (!TryFormats(out formats)) return false; + int total = 0; + foreach (uint format in formats) + { + byte[] bytes; + if (!TryBytes(format, out bytes) || (total += bytes.Length) > MaxSnapshotBytes) 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; + snapshot = saved; + return true; + } + finally { ClipboardNative.CloseClipboard(); } + } + + internal static string DecodeUnicode(byte[] bytes) + { + if (bytes == null || bytes.Length % 2 != 0) return null; + for (int i = 0; i < bytes.Length; i += 2) + if (bytes[i] == 0 && bytes[i + 1] == 0) return Encoding.Unicode.GetString(bytes, 0, i); + return null; + } + + public bool TryReadText(IntPtr source, uint expected, out uint sequence, out string text) + { + sequence = 0; text = null; + if (!ClipboardNative.OpenClipboard(Handle)) return false; + try + { + if (Sequence != expected || !Native.SameApp(Native.GetClipboardOwner(), source)) return false; + byte[] bytes; + // A non-text copy still needs restoration; never fall back to OLE conversion. + if (ClipboardNative.IsClipboardFormatAvailable(13) && TryBytes(13, out bytes)) text = DecodeUnicode(bytes); + sequence = Sequence; + return sequence != 0 && sequence == expected && Native.SameApp(Native.GetClipboardOwner(), source); + } + finally { ClipboardNative.CloseClipboard(); } + } + + internal static IntPtr Allocate(byte[] bytes) + { + IntPtr handle = ClipboardNative.GlobalAlloc(0x42, new UIntPtr((uint)bytes.Length)); + if (handle == IntPtr.Zero) return IntPtr.Zero; + IntPtr pointer = ClipboardNative.GlobalLock(handle); + if (pointer == IntPtr.Zero) { ClipboardNative.GlobalFree(handle); return IntPtr.Zero; } + try { Marshal.Copy(bytes, 0, pointer, bytes.Length); } + finally { ClipboardNative.GlobalUnlock(handle); } + return handle; + } + + public RestoreResult Restore(ClipboardSnapshot snapshot, uint expected, Func valid) + { + // Allocate everything before EmptyClipboard: allocation failure must not clear data. + var handles = new List(); + try + { + foreach (var item in snapshot.Formats) + { + IntPtr handle = Allocate(item.Value); + if (handle == IntPtr.Zero) return RestoreResult.Failed; + handles.Add(handle); + } + if (!ClipboardNative.OpenClipboard(Handle)) return RestoreResult.Busy; + try + { + if (!valid() || expected == 0 || Sequence != expected) return RestoreResult.Changed; + if (!ClipboardNative.EmptyClipboard()) return RestoreResult.Failed; + bool complete = true; + for (int i = 0; i < handles.Count; i++) + { + if (ClipboardNative.SetClipboardData(snapshot.Formats[i].Key, handles[i]) == IntPtr.Zero) complete = false; + else handles[i] = IntPtr.Zero; // Ownership transferred to Windows. + } + return complete ? RestoreResult.Restored : RestoreResult.Failed; + } + finally { ClipboardNative.CloseClipboard(); } + } + finally { foreach (IntPtr handle in handles) if (handle != IntPtr.Zero) ClipboardNative.GlobalFree(handle); } + } + } + + internal static class ClipboardNative + { + [DllImport("user32.dll", SetLastError = true)] internal static extern bool OpenClipboard(IntPtr window); + [DllImport("user32.dll")] internal static extern bool CloseClipboard(); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint EnumClipboardFormats(uint format); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetClipboardFormatName(uint format, StringBuilder name, int count); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern uint RegisterClipboardFormat(string name); + [DllImport("user32.dll")] internal static extern IntPtr GetClipboardData(uint format); + [DllImport("user32.dll")] internal static extern bool IsClipboardFormatAvailable(uint format); + [DllImport("user32.dll")] internal static extern bool EmptyClipboard(); + [DllImport("user32.dll")] internal static extern IntPtr SetClipboardData(uint format, IntPtr data); + [DllImport("kernel32.dll")] internal static extern UIntPtr GlobalSize(IntPtr memory); + [DllImport("kernel32.dll")] internal static extern IntPtr GlobalLock(IntPtr memory); + [DllImport("kernel32.dll")] internal static extern bool GlobalUnlock(IntPtr memory); + [DllImport("kernel32.dll")] internal static extern IntPtr GlobalAlloc(uint flags, UIntPtr bytes); + [DllImport("kernel32.dll")] internal static extern IntPtr GlobalFree(IntPtr memory); + [DllImport("kernel32.dll")] internal static extern void SetLastError(uint error); + } +} diff --git a/src/ClipboardCaptureTests.cs b/src/ClipboardCaptureTests.cs new file mode 100644 index 0000000..73ca524 --- /dev/null +++ b/src/ClipboardCaptureTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using System.Web.Script.Serialization; + +namespace LightTranslate +{ + internal static class ClipboardCaptureTests + { + internal static void Check(bool value, string message) + { if (!value) throw new Exception("Clipboard: " + message); } + + private sealed class Fake : ISelectionClipboard + { + internal uint Version = 10; + internal bool SnapshotWorks = true, ReadWorks = true, Valid = true; + internal int Copies, Restores, RestoreCalls, Snapshots, Busy; + internal Action OnSnapshot, OnRead, OnRestore; + 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) + { + sequence = Version; text = "selected"; + if (OnRead != null) OnRead(); + return ReadWorks && Version == expected; + } + public RestoreResult Restore(ClipboardSnapshot snapshot, uint expected, Func valid) + { + RestoreCalls++; + if (OnRestore != null) OnRestore(); + if (!valid() || expected != Version) return RestoreResult.Changed; + if (Busy-- > 0) return RestoreResult.Busy; + Restores++; Version++; + return RestoreResult.Restored; + } + internal Task Run(Func wait) + { + return ClipboardCapture.Read(this, IntPtr.Zero, delegate { return Valid; }, + delegate { Copies++; Version++; }, delegate { }, wait); + } + } + + internal static void Run(Dictionary results) + { + Func tick = delegate { return Task.FromResult(0); }; + var normal = new Fake(); + Check(normal.Run(tick).GetAwaiter().GetResult() == "selected" && normal.Copies == 1 && normal.Restores == 1, "copy and restore"); + var rejected = new Fake { SnapshotWorks = false }; + Check(rejected.Run(tick).Result == null && rejected.Copies == 0, "failed/unsupported snapshot never copies"); + var stale = new Fake(); stale.OnSnapshot = delegate { stale.Version++; }; + Check(stale.Run(tick).Result == null && stale.Copies == 0, "changed snapshot never copies"); + 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"); + 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 }; + Check(wrongOwner.Run(tick).Result == null && wrongOwner.Restores == 0, "unverified copy never restores"); + var race = new Fake(); race.OnRead = delegate { race.Version++; }; + Check(race.Run(tick).Result == null && race.Restores == 0, "read race never restores"); + var busy = new Fake { Busy = 2 }; + Check(busy.Run(tick).Result == "selected" && busy.Restores == 1 && busy.RestoreCalls == 3, "bounded busy retries"); + var blocked = new Fake { Busy = 10 }; + blocked.Run(tick).GetAwaiter().GetResult(); + Check(blocked.RestoreCalls == 3 && blocked.Restores == 0, "busy retries stop"); + var signal = new TaskCompletionSource(); + var first = new Fake(); var pending = first.Run(delegate { return signal.Task; }); + var second = new Fake(); + Check(second.Run(tick).Result == null && second.Snapshots == 0 && second.Copies == 0, "overlapping capture is skipped"); + signal.SetResult(0); pending.GetAwaiter().GetResult(); + Check(second.Run(tick).Result == "selected", "gate released for next selection"); + Check(NativeSelectionClipboard.DecodeUnicode(Encoding.Unicode.GetBytes("text\0")) == "text", "bounded Unicode decode"); + Check(NativeSelectionClipboard.DecodeUnicode(new byte[] { 65 }) == null, "odd byte count rejected"); + Check(NativeSelectionClipboard.DecodeUnicode(new byte[] { 65, 0 }) == null, "unterminated text rejected"); + results["clipboardCapture"] = "14 workflow/decoding checks passed; no system clipboard access"; + } + + internal static int RunStandalone() + { + var results = new Dictionary(); Run(results); + File.WriteAllText(Path.Combine(Program.Folder, "clipboard-test.json"), new JavaScriptSerializer().Serialize(results)); + return 0; + } + } +} diff --git a/src/ClipboardNativeTests.cs b/src/ClipboardNativeTests.cs new file mode 100644 index 0000000..5ab05be --- /dev/null +++ b/src/ClipboardNativeTests.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Web.Script.Serialization; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + // Opt-in native tests run in a new window station, which owns a separate clipboard. + // Isolation failure aborts before opening any clipboard. Never save/restore the user's data. + internal static class ClipboardNativeTests + { + private static void Check(bool ok, string message) { ClipboardCaptureTests.Check(ok, message); } + private static void Put(IntPtr owner, params KeyValuePair[] formats) + { + Check(ClipboardNative.OpenClipboard(owner), "fixture open"); + try + { + Check(ClipboardNative.EmptyClipboard(), "fixture empty"); + foreach (var item in formats) + { + var handle = NativeSelectionClipboard.Allocate(item.Value); + Check(handle != IntPtr.Zero, "fixture allocation"); + if (ClipboardNative.SetClipboardData(item.Key, handle) == IntPtr.Zero) + { ClipboardNative.GlobalFree(handle); throw new Exception("Fixture set failed"); } + } + } + finally { ClipboardNative.CloseClipboard(); } + } + private static KeyValuePair Text(string value) + { return new KeyValuePair(13, Encoding.Unicode.GetBytes(value + "\0")); } + + private sealed class DelayedWindow : Forms.NativeWindow + { + internal int Renders; + internal DelayedWindow() { CreateHandle(new Forms.CreateParams { Parent = new IntPtr(-3) }); } + protected override void WndProc(ref Forms.Message message) + { + if (message.Msg == 0x305) + { + Renders++; + var handle = NativeSelectionClipboard.Allocate(Text("delayed").Value); + if (ClipboardNative.SetClipboardData(13, handle) == IntPtr.Zero) ClipboardNative.GlobalFree(handle); + return; + } + base.WndProc(ref message); + } + } + + internal static int Run() + { + IntPtr previousStation = GetProcessWindowStation(); + IntPtr previousDesktop = GetThreadDesktop(Native.GetCurrentThreadId()); + // A named station requires administrator membership. A standard user can + // request an automatically named station only if it does not already exist. + IntPtr station = CreateWindowStation("LightTranslate-test-" + Guid.NewGuid().ToString("N"), 1, 0x37f, IntPtr.Zero); + if (station == IntPtr.Zero && Marshal.GetLastWin32Error() == 5) + station = CreateWindowStation(null, 1, 0x37f, IntPtr.Zero); + Check(station != IntPtr.Zero, "create isolated window station: " + Marshal.GetLastWin32Error()); + IntPtr desktop = IntPtr.Zero; + try + { + Check(SetProcessWindowStation(station), "select isolated window station"); + desktop = CreateDesktop("test", IntPtr.Zero, IntPtr.Zero, 0, 0x1ff, IntPtr.Zero); + Check(desktop != IntPtr.Zero && SetThreadDesktop(desktop), "select isolated desktop"); + using (var clipboard = new NativeSelectionClipboard()) + { + uint html = ClipboardNative.RegisterClipboardFormat("HTML Format"); + uint rtf = ClipboardNative.RegisterClipboardFormat("Rich Text Format"); + uint unknown = ClipboardNative.RegisterClipboardFormat("LightTranslate unsupported fixture"); + Put(clipboard.Handle, Text("original"), new KeyValuePair(html, Encoding.UTF8.GetBytes("original\0")), + new KeyValuePair(rtf, Encoding.ASCII.GetBytes("{\\rtf1 original}\0"))); + ClipboardSnapshot original; + Check(clipboard.TrySnapshot(out original), "text/HTML/RTF snapshot"); + Put(clipboard.Handle, Text("selected")); + uint version; string selected; + Check(clipboard.TryReadText(clipboard.Handle, clipboard.Sequence, out version, out selected) && selected == "selected", "native Unicode read"); + Check(clipboard.Restore(original, version, delegate { return true; }) == RestoreResult.Restored, "native restore"); + ClipboardSnapshot restored; + Check(clipboard.TrySnapshot(out restored), "restored snapshot"); + Check(original.Formats.Count == restored.Formats.Count && original.Formats.All(x => restored.Formats.Any(y => x.Key == y.Key && x.Value.SequenceEqual(y.Value))), "all format bytes preserved"); + Put(clipboard.Handle, Text("new user copy")); + Check(clipboard.Restore(original, version, delegate { return true; }) == RestoreResult.Changed, "stale restore rejected"); + Check(clipboard.Restore(original, clipboard.Sequence, delegate { return false; }) == RestoreResult.Changed, "canceled restore rejected"); + 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"); + 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"); + Put(clipboard.Handle, Text("busy")); + using (var opened = new ManualResetEvent(false)) + using (var release = new ManualResetEvent(false)) + { + bool locked = false; + var thread = new Thread(delegate() + { + SetThreadDesktop(desktop); + locked = ClipboardNative.OpenClipboard(IntPtr.Zero); opened.Set(); + release.WaitOne(); if (locked) ClipboardNative.CloseClipboard(); + }); + thread.Start(); opened.WaitOne(); + try { Check(locked && !clipboard.TrySnapshot(out restored), "busy clipboard skips"); } + finally { release.Set(); thread.Join(); } + } + var delayed = new DelayedWindow(); + try + { + Check(ClipboardNative.OpenClipboard(delayed.Handle), "delayed open"); + try { Check(ClipboardNative.EmptyClipboard(), "delayed empty"); ClipboardNative.SetClipboardData(13, IntPtr.Zero); } + finally { ClipboardNative.CloseClipboard(); } + bool captured = clipboard.TrySnapshot(out original); + Check(delayed.Renders == 1, "native delayed rendering invoked"); + // A changed sequence rejects the first snapshot; the next attempt can succeed. + Check(captured || clipboard.TrySnapshot(out original), "delayed rendering safely resolves or skips"); + Check(original.Formats.Any(x => x.Key == 13 && NativeSelectionClipboard.DecodeUnicode(x.Value) == "delayed"), "delayed bytes preserved"); + } + finally { delayed.DestroyHandle(); } + } + 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" })); + return 0; + } + finally + { + SetThreadDesktop(previousDesktop); SetProcessWindowStation(previousStation); + if (desktop != IntPtr.Zero) CloseDesktop(desktop); + CloseWindowStation(station); + } + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr CreateWindowStation(string name, uint flags, uint access, IntPtr security); + [DllImport("user32.dll")] private static extern IntPtr GetProcessWindowStation(); + [DllImport("user32.dll")] private static extern bool SetProcessWindowStation(IntPtr station); + [DllImport("user32.dll")] private static extern bool CloseWindowStation(IntPtr station); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CreateDesktop(string name, IntPtr device, IntPtr mode, uint flags, uint access, IntPtr security); + [DllImport("user32.dll")] private static extern IntPtr GetThreadDesktop(uint thread); + [DllImport("user32.dll")] private static extern bool SetThreadDesktop(IntPtr desktop); + [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr desktop); + } +} diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 3b4ee70..5826e94 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -41,6 +41,8 @@ private static int Main(string[] args) Lexicon.Build(args[1], Folder); return 0; } + if (args.Length > 0 && args[0] == "--self-test-clipboard") return ClipboardCaptureTests.RunStandalone(); + if (args.Length > 0 && args[0] == "--self-test-clipboard-native") return ClipboardNativeTests.Run(); if (args.Length > 0 && args[0] == "--self-test") return SelfTest.Run(false); if (args.Length > 0 && args[0] == "--self-test-offline") return SelfTest.Run(true); bool created; @@ -693,65 +695,10 @@ public static async Task CopySelection(IntPtr window, CancellationToken { if (Native.GetForegroundWindow() != window || Native.ModifierDown()) { trace("copy skipped focus/modifier"); return null; } if (Native.IsPasswordFocus(window)) { trace("password field skipped"); return null; } - uint before = Native.GetClipboardSequenceNumber(), copied = before; - Forms.DataObject saved; - try { saved = Snapshot(Forms.Clipboard.GetDataObject()); } - catch (Exception ex) { trace("clipboard snapshot " + ex.GetType().Name); return null; } - if (Native.GetClipboardSequenceNumber() != before) return null; - string result = null; - try - { - if (Native.GetForegroundWindow() != window || ct.IsCancellationRequested) return null; - Native.Copy(); - for (int i = 0; i < 12; i++) - { - await Task.Delay(15); - uint sequence = Native.GetClipboardSequenceNumber(); - if (sequence != before) - { - bool owned = Native.SameApp(Native.GetClipboardOwner(), window); - trace("copy changed owner-same-app=" + owned + " canceled=" + ct.IsCancellationRequested); - if (!ct.IsCancellationRequested && Native.GetForegroundWindow() == window && owned) - { - copied = sequence; - if (Forms.Clipboard.ContainsText()) result = Forms.Clipboard.GetText(); - } - break; - } - if (ct.IsCancellationRequested) break; - } - return ct.IsCancellationRequested ? null : result; - } - catch { return null; } - finally - { - // Do not overwrite a newer clipboard created by the user or another app. - if (copied != before) - { - for (int i = 0; i < 3; i++) - { - if (Native.GetClipboardSequenceNumber() != copied) break; - try { Forms.Clipboard.SetDataObject(saved, true); break; } - catch { Thread.Sleep(10); } - } - } - } - } - internal static Forms.DataObject Snapshot(Forms.IDataObject source) - { - var copy = new Forms.DataObject(); - if (source == null) return copy; - foreach (string format in source.GetFormats(false)) - { - var value = source.GetData(format, false); - var stream = value as MemoryStream; - var image = value as System.Drawing.Image; - if (stream != null) value = new MemoryStream(stream.ToArray()); - else if (image != null) value = image.Clone(); - else if (value is string[]) value = ((string[])value).Clone(); - if (value != null) copy.SetData(format, false, value); - } - return copy; + using (var clipboard = new NativeSelectionClipboard()) + return await ClipboardCapture.Read(clipboard, window, + delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }, + Native.Copy, trace, delegate { return Task.Delay(15); }); } } @@ -1188,14 +1135,9 @@ public static int Run(bool offline) results["dictionaryLookupMs"] = sw.Elapsed.TotalMilliseconds; results["dictionaryText"] = word; } - var original = new Forms.DataObject(); - original.SetData(Forms.DataFormats.UnicodeText, false, "original clipboard"); - original.SetData(Forms.DataFormats.Html, false, "original"); - var snapshot = SelectionReader.Snapshot(original); - if ((string)snapshot.GetData(Forms.DataFormats.UnicodeText) != "original clipboard" || (string)snapshot.GetData(Forms.DataFormats.Html) != "original") throw new Exception("Clipboard snapshot failed"); + ClipboardCaptureTests.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["clipboardSnapshot"] = "text + HTML preserved"; results["guards"] = "terminal + language passed"; ReadingSettingsTests.Run(results); UnifiedSettingsTests.Run(results); @@ -1209,7 +1151,6 @@ public static int Run(bool offline) } results["capture"] = "clipboard only; no UIAutomationClient dependency"; results["passwordGuard"] = "native password/plain controls passed"; - for (int i = 0; i < 100; i++) SelectionReader.Snapshot(original); Program.Log("self-test", "password guard passed; collecting objects"); // OLE finalizers can marshal back to the STA: pump while awaiting them. var finalizers = Task.Run(delegate { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); }); diff --git a/src/ReadingSettings.cs b/src/ReadingSettings.cs index 2f2fb94..367d441 100644 --- a/src/ReadingSettings.cs +++ b/src/ReadingSettings.cs @@ -136,7 +136,7 @@ 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("托盘开关立即生效并同步到这里;面板修改在保存后生效。当前仅支持剪贴板取词;关闭后停止划词翻译。取词会临时复制选区;剪贴板含不支持的格式时跳过,不覆盖原内容。")); language = new ComboBox { IsEditable = true, ItemsSource = Languages, MinHeight = 32 }; AddField(translation, "目标语言(微软)", language); translation.Children.Add(Help("可直接输入语言代码,如 en、ja。该选项只用于微软在线翻译;本地词库和腾讯备用仍输出中文。")); From 2ee5cb694efe811680243eb7f7d3e1af99190352 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:11:40 +0800 Subject: [PATCH 02/17] Center tray glyph and follow reading appearance settings --- docs/TESTING.md | 10 ++++ src/LightTranslate.cs | 26 ++------- src/TrayIconRenderer.cs | 122 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+), 20 deletions(-) create mode 100644 src/TrayIconRenderer.cs diff --git a/docs/TESTING.md b/docs/TESTING.md index 8a06183..e2e07da 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -175,3 +175,13 @@ The change bypasses the observed IDataObject/OLE IStream conversion crash path. The original native crash has not been reproduced, and the faulty format or provider has not been identified. These tests exercise the replacement behavior, not the original corrupt COM pointer. + +## Tray icon rendering + +The offline self-test renders `tray-icon-preview.png` at 16/20/24/32/48/64 px +with three font/background combinations. Glyph ink bounds are centered inside +the solid circle. The selected reading font and automatic contrast foreground +are reused; font size is fitted to the icon, independently of bubble text size. +The test replaces an invisible NotifyIcon 100 times and checks USER handle growth. +This does not replace a live Explorer tray/DPI test. Saved appearance settings +update the running tray icon and dispose its previous Icon; canceled edits do not. diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 5826e94..e9c8bfe 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -187,7 +187,7 @@ public Controller(Application app) var warming = translator.WarmConnection(); bubble = new Bubble(); bubble.ApplySettings(settings); - tray = new Forms.NotifyIcon { Text = "轻译 · 选中即译", Icon = MakeIcon(), Visible = true }; + tray = new Forms.NotifyIcon { Text = "轻译 · 选中即译", Icon = MakeIcon(settings), Visible = true }; var menu = new Forms.ContextMenuStrip(); enabledItem = new Forms.ToolStripMenuItem("自动划词翻译") { Checked = settings.Enabled, CheckOnClick = true }; enabledItem.Click += delegate @@ -223,27 +223,13 @@ private void OpenSettings() if (settingsWindow.WindowState == WindowState.Minimized) settingsWindow.WindowState = WindowState.Normal; settingsWindow.Activate(); return; } - settingsWindow = new SettingsWindow(settings, delegate { enabledItem.Checked = settings.Enabled; Dismiss(true); bubble.ApplySettings(settings); }); + settingsWindow = new SettingsWindow(settings, delegate { enabledItem.Checked = settings.Enabled; Dismiss(true); bubble.ApplySettings(settings); TrayIconRenderer.Update(tray, settings); }); settingsWindow.Closed += delegate { settingsWindow = null; }; settingsWindow.Show(); } - internal static System.Drawing.Icon MakeIcon() - { - using (var bmp = new System.Drawing.Bitmap(32, 32)) - using (var g = System.Drawing.Graphics.FromImage(bmp)) - using (var brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(56, 112, 210))) - using (var font = new System.Drawing.Font("Microsoft YaHei UI", 16, System.Drawing.FontStyle.Bold)) - { - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; - g.Clear(System.Drawing.Color.Transparent); - g.FillEllipse(brush, 1, 1, 30, 30); - g.DrawString("译", font, System.Drawing.Brushes.White, 1, 1); - IntPtr h = bmp.GetHicon(); - try { return (System.Drawing.Icon)System.Drawing.Icon.FromHandle(h).Clone(); } - finally { Native.DestroyIcon(h); } - } - } + internal static System.Drawing.Icon MakeIcon(Settings value = null) + { return TrayIconRenderer.Create(value ?? new Settings()); } private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow) { @@ -1139,6 +1125,7 @@ public static int Run(bool offline) 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"; + TrayIconRenderer.Test(results); ReadingSettingsTests.Run(results); UnifiedSettingsTests.Run(results); Program.Log("self-test", "dictionary and clipboard snapshot passed"); @@ -1228,8 +1215,7 @@ public static int Run(bool offline) if ((Native.GetWindowLong(handle, -20) & 0x08000000) == 0) throw new Exception("No-activation style missing"); results["noActivation"] = "window style verified"; bubble.RenderPreview(Path.Combine(Program.Folder, "preview.png")); - using (var icon = Controller.MakeIcon()) - using (var file = File.Create(Path.Combine(Program.Folder, "LightTranslate.ico"))) icon.Save(file); + File.WriteAllBytes(Path.Combine(Program.Folder, "LightTranslate.ico"), TrayIconRenderer.Encode(new Settings())); results["bubblePreview"] = "rendered"; File.WriteAllText(Path.Combine(Program.Folder, "self-test.json"), new JavaScriptSerializer().Serialize(results), Encoding.UTF8); Program.Log("self-test", "passed"); diff --git a/src/TrayIconRenderer.cs b/src/TrayIconRenderer.cs new file mode 100644 index 0000000..0f69777 --- /dev/null +++ b/src/TrayIconRenderer.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + internal static class TrayIconRenderer + { + internal static BitmapSource Render(Settings settings, int size) + { + var background = BubbleAppearance.Background(settings.BubbleBackground); + var ink = new SolidColorBrush(BubbleAppearance.Foreground(background)); + var text = new FormattedText("译", CultureInfo.GetCultureInfo("zh-CN"), FlowDirection.LeftToRight, + new Typeface(BubbleAppearance.ResolveFont(settings.BubbleFontFamily), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), + 100, ink, 1.0); + Geometry glyph = text.BuildGeometry(new Point()); + Rect bounds = glyph.Bounds; + double scale = size * 0.64 / Math.Max(bounds.Width, bounds.Height); + // Center the visible ink, not the font's line box or baseline. + glyph.Transform = new MatrixTransform(scale, 0, 0, scale, + size / 2.0 - (bounds.X + bounds.Width / 2) * scale, + size / 2.0 - (bounds.Y + bounds.Height / 2) * scale); + var visual = new DrawingVisual(); + using (var drawing = visual.RenderOpen()) + { + drawing.DrawEllipse(new SolidColorBrush(background), null, new Point(size / 2.0, size / 2.0), size / 2.0 - 0.5, size / 2.0 - 0.5); + drawing.DrawGeometry(ink, null, glyph); + } + var bitmap = new RenderTargetBitmap(size, size, 96, 96, PixelFormats.Pbgra32); + bitmap.Render(visual); bitmap.Freeze(); + return bitmap; + } + + internal static byte[] Encode(Settings settings) + { + int[] sizes = { 16, 20, 24, 32, 48, 64 }; + var frames = new List(); + foreach (int size in sizes) + { + using (var stream = new MemoryStream()) + { + var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(Render(settings, size))); + encoder.Save(stream); frames.Add(stream.ToArray()); + } + } + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + writer.Write((ushort)0); writer.Write((ushort)1); writer.Write((ushort)sizes.Length); + int offset = 6 + 16 * sizes.Length; + for (int i = 0; i < sizes.Length; i++) + { + writer.Write((byte)sizes[i]); writer.Write((byte)sizes[i]); writer.Write((byte)0); writer.Write((byte)0); + writer.Write((ushort)1); writer.Write((ushort)32); writer.Write(frames[i].Length); writer.Write(offset); + offset += frames[i].Length; + } + foreach (var frame in frames) writer.Write(frame); + return stream.ToArray(); + } + } + + internal static System.Drawing.Icon Create(Settings settings) + { + using (var stream = new MemoryStream(Encode(settings))) + using (var icon = new System.Drawing.Icon(stream, Forms.SystemInformation.SmallIconSize)) + return (System.Drawing.Icon)icon.Clone(); + } + + internal static void Update(Forms.NotifyIcon tray, Settings settings) + { + var replacement = Create(settings); + var previous = tray.Icon; + try { tray.Icon = replacement; } + catch { replacement.Dispose(); throw; } + if (previous != null) previous.Dispose(); + } + + internal static void Test(Dictionary results) + { + string[] colors = { "#FFFFFF", "#25282F", "#3870D2" }; + string[] fonts = { "Microsoft YaHei UI", "SimSun", "Segoe UI" }; + var sheet = new DrawingVisual(); + using (var drawing = sheet.RenderOpen()) + { + drawing.DrawRectangle(Brushes.LightGray, null, new Rect(0, 0, 720, 324)); + for (int row = 0; row < 3; row++) + { + var settings = new Settings { BubbleBackground = colors[row], BubbleFontFamily = fonts[row] }; + int x = 12; + foreach (int size in new[] { 16, 20, 24, 32, 48, 64 }) + { + var bitmap = Render(settings, size); + drawing.DrawImage(bitmap, new Rect(x, row * 108 + 10, size, size)); + x += 112; + } + } + } + var preview = new RenderTargetBitmap(720, 324, 96, 96, PixelFormats.Pbgra32); preview.Render(sheet); + var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(preview)); + using (var file = File.Create(Path.Combine(Program.Folder, "tray-icon-preview.png"))) encoder.Save(file); + using (var process = System.Diagnostics.Process.GetCurrentProcess()) + using (var tray = new Forms.NotifyIcon()) // Invisible: never adds a test icon to the user's tray. + { + Update(tray, new Settings()); + uint before = GetGuiResources(process.Handle, 1); + for (int i = 0; i < 100; i++) Update(tray, new Settings { BubbleBackground = colors[i % colors.Length], BubbleFontFamily = fonts[i % fonts.Length] }); + uint after = GetGuiResources(process.Handle, 1); + if (after > before + 2) throw new Exception("Tray icon handle leak"); + tray.Icon.Dispose(); tray.Icon = null; + } + results["trayIcon"] = "six sizes, three fonts/colors rendered; 100 replacements without USER handle growth"; + } + + [DllImport("user32.dll")] private static extern uint GetGuiResources(IntPtr process, uint flags); + } +} From fc6e9e6abc623021e59bbe9428b71e795f8e35e1 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:17:58 +0800 Subject: [PATCH 03/17] Expose existing translation providers with isolated caches --- docs/TESTING.md | 18 +++++ settings.example.json | 1 + src/LightTranslate.cs | 54 ++++++++++----- src/ReadingSettings.cs | 15 +++- src/TranslationProviderTests.cs | 117 ++++++++++++++++++++++++++++++++ 5 files changed, 185 insertions(+), 20 deletions(-) create mode 100644 src/TranslationProviderTests.cs diff --git a/docs/TESTING.md b/docs/TESTING.md index e2e07da..b488c47 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -57,6 +57,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 |---|---|---| | `Enabled` | `true` | 自动划词翻译开关,也可通过托盘修改 | | `ClipboardFallback` | `true` | 剪贴板取词开关,关闭后停止取词 | +| `TranslationProvider` | `auto` | `auto` 保留本地词库优先、微软失败后腾讯;`microsoft` / `tencent` 仅调用选定服务并跳过词库 | | `Target` | `zh-Hans` | 微软接口的目标语言;本地词库和腾讯备用接口输出中文 | | `MaxSelectionLength` | `2000` | 单次选区字符数上限 | | `ExcludedApps` | `[]` | 排除的进程名称,可带或不带 `.exe` | @@ -185,3 +186,20 @@ are reused; font size is fitted to the icon, independently of bubble text size. The test replaces an invisible NotifyIcon 100 times and checks USER handle growth. This does not replace a live Explorer tray/DPI test. Saved appearance settings update the running tray icon and dispose its previous Icon; canceled edits do not. + +## Translation provider regression + +`TranslationProvider` defaults to `auto` for old settings. The panel also offers +`microsoft` and `tencent`; explicit choices bypass the local dictionary and never +fall back to another service. Tencent currently outputs Chinese only. Its target +control is disabled without erasing the last Microsoft target. Automatic mode +retains the existing Chinese dictionary and Tencent fallback behavior even when +Microsoft's target is another language. No new endpoints or credential fields +are introduced. + +The offline self-test uses an injected HTTP handler to verify routing, automatic +fallback, explicit-provider failure, provider/target cache separation, canceled +in-flight responses, and settings save/cancel/reopen/live application. It makes +no network requests. Applying settings uses the existing capture/request +cancellation path before any new translation. Live service availability is not +covered by these fixture tests. diff --git a/settings.example.json b/settings.example.json index 814ec0d..086c2f2 100644 --- a/settings.example.json +++ b/settings.example.json @@ -2,6 +2,7 @@ "Enabled": true, "ClipboardFallback": true, "Target": "zh-Hans", + "TranslationProvider": "auto", "MaxSelectionLength": 2000, "ExcludedApps": [], "Diagnostics": false, diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index e9c8bfe..ab2a570 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -43,6 +43,7 @@ private static int Main(string[] args) } if (args.Length > 0 && args[0] == "--self-test-clipboard") return ClipboardCaptureTests.RunStandalone(); 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") return SelfTest.Run(false); if (args.Length > 0 && args[0] == "--self-test-offline") return SelfTest.Run(true); bool created; @@ -83,6 +84,7 @@ internal sealed class Settings public bool Enabled = true; public bool ClipboardFallback = true; public string Target = "zh-Hans"; + public string TranslationProvider = "auto"; public int MaxSelectionLength = 2000; public string[] ExcludedApps = new string[0]; public bool Diagnostics = false; @@ -109,6 +111,7 @@ internal static Settings Load(string path) } internal void NormalizeReading() { + TranslationProvider = Translator.NormalizeProvider(TranslationProvider); BubbleFontFamily = BubbleAppearance.ResolveFont(BubbleFontFamily).Source; if (double.IsNaN(BubbleFontSize) || double.IsInfinity(BubbleFontSize) || BubbleFontSize < 10 || BubbleFontSize > 48) BubbleFontSize = 14; Color color; @@ -127,7 +130,7 @@ internal void CopyReadingFrom(Settings other) internal void CopyUserFrom(Settings other) { Enabled = other.Enabled; ClipboardFallback = other.ClipboardFallback; - Target = other.Target; MaxSelectionLength = other.MaxSelectionLength; + Target = other.Target; TranslationProvider = other.TranslationProvider; MaxSelectionLength = other.MaxSelectionLength; ExcludedApps = other.ExcludedApps == null ? null : (string[])other.ExcludedApps.Clone(); CopyReadingFrom(other); if (Changed != null) Changed(); @@ -184,7 +187,7 @@ public Controller(Application app) settings = Settings.Load(); lexicon = new Lexicon(Program.Folder); translator = new Translator(); - var warming = translator.WarmConnection(); + if (settings.TranslationProvider != "tencent") { var warming = translator.WarmConnection(); } bubble = new Bubble(); bubble.ApplySettings(settings); tray = new Forms.NotifyIcon { Text = "轻译 · 选中即译", Icon = MakeIcon(settings), Visible = true }; @@ -346,13 +349,15 @@ private async void BeginSelection(IntPtr window, Native.POINT point) ShowText("选中文字较长,请分段选择", point, 5); return; } - string translated = lexicon.Lookup(text); - if (translated != null || translator.TryCached(text, settings.Target, out translated)) + string provider = Translator.NormalizeProvider(settings.TranslationProvider); + string target = settings.Target; + string translated = provider == "auto" ? lexicon.Lookup(text) : null; + if (translated != null || translator.TryCached(text, target, out translated, provider)) { ShowText(translated, point, ReadingSeconds(translated), true); return; } - var request = translator.Translate(text, settings.Target, ct); + var request = translator.Translate(text, target, ct, provider); if (await Task.WhenAny(request, Task.Delay(220, ct)) != request && Valid(version, window)) ShowText("…", point, 8); translated = await request; @@ -906,9 +911,11 @@ internal sealed class Translator : IDisposable private readonly JavaScriptSerializer json = new JavaScriptSerializer(); private readonly Dictionary cache = new Dictionary(); private readonly Queue eviction = new Queue(); - public Translator() + public Translator() : this(null) { } + internal Translator(HttpMessageHandler handler) { - http = new HttpClient { Timeout = TimeSpan.FromSeconds(7) }; + http = handler == null ? new HttpClient() : new HttpClient(handler); + http.Timeout = TimeSpan.FromSeconds(7); http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); http.DefaultRequestHeaders.ExpectContinue = false; } @@ -921,20 +928,32 @@ internal async Task WarmConnection() } catch { } } - public bool TryCached(string text, string target, out string result) { return cache.TryGetValue(target + "\n" + text, out result); } - public async Task Translate(string text, string target, CancellationToken ct) + internal static string NormalizeProvider(string provider) + { return provider == "microsoft" || provider == "tencent" ? provider : "auto"; } + private static string CacheKey(string text, string target, string provider) + { return NormalizeProvider(provider) + "\n" + (provider == "tencent" ? "zh" : target) + "\n" + text; } + public bool TryCached(string text, string target, out string result, string provider = "auto") + { return cache.TryGetValue(CacheKey(text, target, provider), out result); } + public async Task Translate(string text, string target, CancellationToken ct, string provider = "auto") { + ct.ThrowIfCancellationRequested(); + provider = NormalizeProvider(provider); string result; - if (TryCached(text, target, out result)) return result; - bool fallback = false; - result = null; - try { result = await Microsoft(text, target, ct); } - catch (OperationCanceledException) { if (ct.IsCancellationRequested) throw; fallback = true; } - catch { ct.ThrowIfCancellationRequested(); fallback = true; } - if (fallback) result = await Tencent(text, ct); + if (TryCached(text, target, out result, provider)) return result; + if (provider == "tencent") result = await Tencent(text, ct); + else if (provider == "microsoft") result = await Microsoft(text, target, ct); + else + { + bool fallback = false; + result = null; + try { result = await Microsoft(text, target, ct); } + catch (OperationCanceledException) { if (ct.IsCancellationRequested) throw; fallback = true; } + catch { ct.ThrowIfCancellationRequested(); fallback = true; } + if (fallback) result = await Tencent(text, ct); + } if (string.IsNullOrWhiteSpace(result)) throw new InvalidDataException("Empty translation"); ct.ThrowIfCancellationRequested(); - string key = target + "\n" + text; + string key = CacheKey(text, target, provider); if (!cache.ContainsKey(key)) { if (cache.Count >= 256) cache.Remove(eviction.Dequeue()); @@ -1128,6 +1147,7 @@ public static int Run(bool offline) TrayIconRenderer.Test(results); ReadingSettingsTests.Run(results); UnifiedSettingsTests.Run(results); + TranslationProviderTests.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 index 367d441..cc0767a 100644 --- a/src/ReadingSettings.cs +++ b/src/ReadingSettings.cs @@ -101,7 +101,7 @@ internal sealed class SettingsWindow : Window private readonly Action saved; private readonly IStartupRegistration startup; private readonly CheckBox enabled, clipboard, autoStart; - private readonly ComboBox language, fontFamily, fontSize, autoHide; + private readonly ComboBox language, provider, fontFamily, fontSize, autoHide; private readonly TextBox maxSelection, excludedApps, background, englishPercent; private readonly TextBlock error, previewText, startupStatus; private readonly Border preview; @@ -137,9 +137,12 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st clipboard = Toggle("通过剪贴板获取选中文字"); translation.Children.Add(enabled); translation.Children.Add(clipboard); translation.Children.Add(Help("托盘开关立即生效并同步到这里;面板修改在保存后生效。当前仅支持剪贴板取词;关闭后停止划词翻译。取词会临时复制选区;剪贴板含不支持的格式时跳过,不覆盖原内容。")); + provider = new ComboBox { ItemsSource = new[] { "自动(微软失败后腾讯)", "仅微软", "仅腾讯(中文)" }, MinHeight = 32 }; + AddField(translation, "在线翻译服务", provider); + translation.Children.Add(Help("自动模式先查本地英汉词库,再请求在线服务;仅微软或仅腾讯会跳过本地词库,不切换服务。现有内置服务无需填写密钥。")); language = new ComboBox { IsEditable = true, ItemsSource = Languages, MinHeight = 32 }; AddField(translation, "目标语言(微软)", language); - translation.Children.Add(Help("可直接输入语言代码,如 en、ja。该选项只用于微软在线翻译;本地词库和腾讯备用仍输出中文。")); + translation.Children.Add(Help("可直接输入语言代码,如 en、ja。目标语言只对微软有效;自动模式下的本地词库和腾讯回退仍输出中文。仅腾讯固定输出中文。")); maxSelection = Input(); AddField(translation, "选区字符数上限", maxSelection); translation.Children.Add(Help("正整数,默认 2,000。超过上限只提示分段选择,不发送该选区。")); @@ -206,6 +209,7 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st 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); + provider.SelectionChanged += delegate { language.IsEnabled = provider.SelectedIndex != 2; }; fontFamily.SelectionChanged += delegate { UpdatePreview(); }; fontSize.AddHandler(System.Windows.Controls.Primitives.TextBoxBase.TextChangedEvent, new TextChangedEventHandler(delegate { UpdatePreview(); })); background.TextChanged += delegate { UpdatePreview(); }; @@ -246,6 +250,7 @@ internal void Fill(Settings value) { if (error != null) error.Visibility = Visibility.Collapsed; enabled.IsChecked = value.Enabled; clipboard.IsChecked = value.ClipboardFallback; + provider.SelectedIndex = value.TranslationProvider == "microsoft" ? 1 : value.TranslationProvider == "tencent" ? 2 : 0; language.Text = LanguageLabel(value.Target); maxSelection.Text = value.MaxSelectionLength.ToString(CultureInfo.CurrentCulture); excludedApps.Text = AppsText(value.ExcludedApps); @@ -315,7 +320,8 @@ 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; - if (language.Text != LanguageLabel(settings.Target)) + next.TranslationProvider = provider.SelectedIndex == 1 ? "microsoft" : provider.SelectedIndex == 2 ? "tencent" : "auto"; + if (provider.SelectedIndex != 2 && language.Text != LanguageLabel(settings.Target)) { string choice = Languages.FirstOrDefault(x => x == language.Text); string code = choice == null ? language.Text.Trim() : choice.Substring(choice.LastIndexOf(" · ", StringComparison.Ordinal) + 3); @@ -377,6 +383,9 @@ internal void SetInputForTest(string size, string color, string seconds, string { fontSize.Text = size; background.Text = color; autoHide.Text = seconds; englishPercent.Text = percent; } internal void SetBehaviorForTest(bool on, bool capture, string target, string maximum, string apps) { enabled.IsChecked = on; clipboard.IsChecked = capture; language.Text = target; maxSelection.Text = maximum; excludedApps.Text = apps; } + internal void SetProviderForTest(int value) { provider.SelectedIndex = value; } + internal int ProviderForTest { get { return provider.SelectedIndex; } } + internal bool TargetEnabledForTest { get { return language.IsEnabled; } } internal void SetStartupForTest(bool value) { autoStart.IsChecked = value; } internal bool EnabledForTest { get { return enabled.IsChecked == true; } } internal bool? StartupForTest { get { return autoStart.IsChecked; } } diff --git a/src/TranslationProviderTests.cs b/src/TranslationProviderTests.cs new file mode 100644 index 0000000..9fa4b11 --- /dev/null +++ b/src/TranslationProviderTests.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace LightTranslate +{ + internal static class TranslationProviderTests + { + internal static int RunStandalone() + { + var results = new Dictionary(); Run(results); + File.WriteAllText(Path.Combine(Program.Folder, "provider-test.json"), new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(results)); + return 0; + } + private sealed class Handler : HttpMessageHandler + { + internal int MicrosoftCalls, TencentCalls; + internal bool FailMicrosoft; + internal string LastTarget, LastTencentBody; + internal TaskCompletionSource Pending; + internal static HttpResponseMessage Success(string json) + { return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json) }; } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + if (request.RequestUri.Host == "api.cognitive.microsofttranslator.com") + { + MicrosoftCalls++; LastTarget = request.RequestUri.Query; + if (Pending != null) return Pending.Task; + if (FailMicrosoft) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); + return Task.FromResult(Success("[{\"translations\":[{\"text\":\"Microsoft fixture\"}]}]")); + } + if (request.RequestUri.Host != "transmart.qq.com") throw new Exception("Unexpected translation destination"); + TencentCalls++; LastTencentBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + return Task.FromResult(Success("{\"auto_translation\":\"Tencent fixture\"}")); + } + } + private static void Check(bool ok, string message) + { if (!ok) throw new Exception("Translation provider: " + message); } + + internal static void Run(Dictionary results) + { + var handler = new Handler(); + using (var translator = new Translator(handler)) + { + var none = CancellationToken.None; + Check(translator.Translate("sample", "ja", none).Result == "Microsoft fixture", "default Microsoft"); + translator.Translate("sample", "ja", none).GetAwaiter().GetResult(); + Check(handler.MicrosoftCalls == 1 && handler.TencentCalls == 0, "same policy cache"); + translator.Translate("sample", "ja", none, "microsoft").GetAwaiter().GetResult(); + Check(handler.MicrosoftCalls == 2, "explicit provider cache isolation"); + translator.Translate("sample", "fr", none, "microsoft").GetAwaiter().GetResult(); + Check(handler.MicrosoftCalls == 3 && handler.LastTarget.Contains("to=fr"), "target cache isolation"); + Check(translator.Translate("sample", "fr", none, "tencent").Result == "Tencent fixture", "Tencent choice"); + Check(handler.MicrosoftCalls == 3 && handler.TencentCalls == 1 && handler.LastTencentBody.Contains("\"lang\":\"zh\""), "Tencent fixed Chinese"); + handler.FailMicrosoft = true; + Check(translator.Translate("fallback", "ja", none).Result == "Tencent fixture" && handler.TencentCalls == 2, "automatic fallback retained"); + bool failed = false; + try { translator.Translate("failure", "ja", none, "microsoft").GetAwaiter().GetResult(); } + catch (HttpRequestException) { failed = true; } + Check(failed && handler.TencentCalls == 2, "explicit Microsoft never falls back"); + using (var canceled = new CancellationTokenSource()) + { + canceled.Cancel(); bool stopped = false; + try { translator.Translate("sample", "ja", canceled.Token).GetAwaiter().GetResult(); } + catch (OperationCanceledException) { stopped = true; } + Check(stopped, "cancellation precedes cache hit"); + } + handler.FailMicrosoft = false; + handler.Pending = new TaskCompletionSource(); + using (var canceled = new CancellationTokenSource()) + { + var pending = translator.Translate("pending", "en", canceled.Token, "microsoft"); + canceled.Cancel(); + handler.Pending.SetResult(Handler.Success("[{\"translations\":[{\"text\":\"old response\"}]}]")); + bool stopped = false; + try { pending.GetAwaiter().GetResult(); } catch (OperationCanceledException) { stopped = true; } + string cached; + Check(stopped && !translator.TryCached("pending", "en", out cached, "microsoft"), "canceled old response cannot enter cache"); + } + } + + string root = Path.Combine(Program.Folder, "self-test-provider-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + string path = Path.Combine(root, "settings.json"); + File.WriteAllText(path, "{\"Target\":\"ja\"}"); + var settings = Settings.Load(path); + Check(settings.TranslationProvider == "auto", "legacy default"); + settings.TranslationProvider = "unsupported"; settings.NormalizeReading(); + Check(settings.TranslationProvider == "auto", "unknown provider normalization"); + int applied = 0; + var window = new SettingsWindow(settings, delegate { applied++; }, new FakeStartupRegistration()); + window.SetProviderForTest(2); + Check(!window.TargetEnabledForTest && settings.TranslationProvider == "auto", "unsaved Tencent choice is local and disables target"); + Check(window.Apply(path), "save provider"); + Check(settings.TranslationProvider == "tencent" && settings.Target == "ja" && applied == 1, "live apply preserves Microsoft target"); + var reopened = new SettingsWindow(Settings.Load(path), null, new FakeStartupRegistration()); + Check(reopened.ProviderForTest == 2 && !reopened.TargetEnabledForTest, "reopen persisted provider"); + reopened.SetProviderForTest(1); + Check(reopened.TargetEnabledForTest, "Microsoft target reenabled"); + reopened.Close(); + Check(Settings.Load(path).TranslationProvider == "tencent", "cancel preserves saved provider"); + var switching = new SettingsWindow(settings, delegate { applied++; }, new FakeStartupRegistration()); + switching.SetProviderForTest(1); Check(switching.Apply(path), "runtime provider switch"); + Check(settings.TranslationProvider == "microsoft" && applied == 2, "switch callback invoked"); + } + finally { Directory.Delete(root, true); } + results["translationProviders"] = "legacy/default, save/cancel/reopen/live switch, provider/target cache isolation, explicit routing, fallback and cancellation passed with fake HTTP; no network requests"; + } + } +} From 06212d15a9f95f414daae4db7a2b7077639514b6 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:17:58 +0800 Subject: [PATCH 04/17] Assert unsupported snapshots never request delayed data --- src/ClipboardCaptureTests.cs | 2 +- src/ClipboardNativeTests.cs | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/ClipboardCaptureTests.cs b/src/ClipboardCaptureTests.cs index 73ca524..d614331 100644 --- a/src/ClipboardCaptureTests.cs +++ b/src/ClipboardCaptureTests.cs @@ -82,7 +82,7 @@ internal static void Run(Dictionary results) Check(NativeSelectionClipboard.DecodeUnicode(Encoding.Unicode.GetBytes("text\0")) == "text", "bounded Unicode decode"); Check(NativeSelectionClipboard.DecodeUnicode(new byte[] { 65 }) == null, "odd byte count rejected"); Check(NativeSelectionClipboard.DecodeUnicode(new byte[] { 65, 0 }) == null, "unterminated text rejected"); - results["clipboardCapture"] = "14 workflow/decoding checks passed; no system clipboard access"; + results["clipboardCapture"] = "workflow/race/decoding checks passed; no system clipboard access"; } internal static int RunStandalone() diff --git a/src/ClipboardNativeTests.cs b/src/ClipboardNativeTests.cs index 5ab05be..4ca9bff 100644 --- a/src/ClipboardNativeTests.cs +++ b/src/ClipboardNativeTests.cs @@ -114,6 +114,17 @@ internal static int Run() var delayed = new DelayedWindow(); try { + Check(ClipboardNative.OpenClipboard(delayed.Handle), "mixed delayed open"); + try + { + Check(ClipboardNative.EmptyClipboard(), "mixed delayed empty"); + ClipboardNative.SetClipboardData(13, IntPtr.Zero); + var privateData = NativeSelectionClipboard.Allocate(new byte[] { 1, 2, 3 }); + if (ClipboardNative.SetClipboardData(unknown, privateData) == IntPtr.Zero) + { ClipboardNative.GlobalFree(privateData); throw new Exception("Private fixture set failed"); } + } + finally { ClipboardNative.CloseClipboard(); } + Check(!clipboard.TrySnapshot(out restored) && delayed.Renders == 0, "unsupported snapshot never requests delayed data"); Check(ClipboardNative.OpenClipboard(delayed.Handle), "delayed open"); try { Check(ClipboardNative.EmptyClipboard(), "delayed empty"); ClipboardNative.SetClipboardData(13, IntPtr.Zero); } finally { ClipboardNative.CloseClipboard(); } From 9b6b49d5972c0a9adf1a2f20446bd2a132ab2f30 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:19:27 +0800 Subject: [PATCH 05/17] Verify saved tray appearance and canceled edits --- src/TrayIconRenderer.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/TrayIconRenderer.cs b/src/TrayIconRenderer.cs index 0f69777..7e26f00 100644 --- a/src/TrayIconRenderer.cs +++ b/src/TrayIconRenderer.cs @@ -112,9 +112,23 @@ internal static void Test(Dictionary results) for (int i = 0; i < 100; i++) Update(tray, new Settings { BubbleBackground = colors[i % colors.Length], BubbleFontFamily = fonts[i % fonts.Length] }); uint after = GetGuiResources(process.Handle, 1); if (after > before + 2) throw new Exception("Tray icon handle leak"); + string path = Path.Combine(Program.Folder, "self-test-icon-" + Guid.NewGuid().ToString("N") + ".json"); + try + { + var settings = new Settings(); int updates = 0; + var editor = new SettingsWindow(settings, delegate { Update(tray, settings); updates++; }, new FakeStartupRegistration()); + editor.SetInputForTest("14", "#3870D2", "0", "0"); + if (!editor.Apply(path) || updates != 1 || settings.BubbleBackground != "#3870D2") + throw new Exception("Tray appearance save failed"); + var reopened = new SettingsWindow(Settings.Load(path), delegate { updates++; }, new FakeStartupRegistration()); + reopened.SetInputForTest("14", "#FFFFFF", "0", "0"); reopened.Close(); + if (updates != 1 || Settings.Load(path).BubbleBackground != "#3870D2") + throw new Exception("Canceled appearance changed tray settings"); + } + finally { if (File.Exists(path)) File.Delete(path); } tray.Icon.Dispose(); tray.Icon = null; } - results["trayIcon"] = "six sizes, three fonts/colors rendered; 100 replacements without USER handle growth"; + results["trayIcon"] = "six sizes, three fonts/colors rendered; save/reopen/cancel passed; 100 replacements without USER handle growth"; } [DllImport("user32.dll")] private static extern uint GetGuiResources(IntPtr process, uint flags); From 61488adce3bca08c1a7fd777de518966106a92f4 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:22:29 +0800 Subject: [PATCH 06/17] Expose focused tray checks and native test diagnostics --- scripts/test-clipboard.ps1 | 5 ++++- src/LightTranslate.cs | 1 + src/TrayIconRenderer.cs | 6 ++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/scripts/test-clipboard.ps1 b/scripts/test-clipboard.ps1 index 70ee621..10c925e 100644 --- a/scripts/test-clipboard.ps1 +++ b/scripts/test-clipboard.ps1 @@ -9,6 +9,9 @@ if (-not $test.WaitForExit(30000)) { throw 'Clipboard test timed out.' } $test.Refresh() -if ($test.ExitCode -ne 0) { throw 'Clipboard test failed; see dist/LightTranslate/status.log.' } +if ($test.ExitCode -ne 0) { + Get-Content -LiteralPath (Join-Path (Split-Path $exe) 'status.log') -Tail 12 + throw 'Clipboard test failed.' +} $name = if ($Native) { 'clipboard-native-test.json' } else { 'clipboard-test.json' } Get-Content -LiteralPath (Join-Path (Split-Path $exe) $name) diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index ab2a570..a7c852f 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -44,6 +44,7 @@ private static int Main(string[] args) if (args.Length > 0 && args[0] == "--self-test-clipboard") return ClipboardCaptureTests.RunStandalone(); 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-tray") return TrayIconRenderer.RunStandalone(); if (args.Length > 0 && args[0] == "--self-test") return SelfTest.Run(false); if (args.Length > 0 && args[0] == "--self-test-offline") return SelfTest.Run(true); bool created; diff --git a/src/TrayIconRenderer.cs b/src/TrayIconRenderer.cs index 7e26f00..e259f2f 100644 --- a/src/TrayIconRenderer.cs +++ b/src/TrayIconRenderer.cs @@ -12,6 +12,12 @@ namespace LightTranslate { internal static class TrayIconRenderer { + internal static int RunStandalone() + { + var results = new Dictionary(); Test(results); + File.WriteAllText(Path.Combine(Program.Folder, "tray-test.json"), new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(results)); + return 0; + } internal static BitmapSource Render(Settings settings, int size) { var background = BubbleAppearance.Background(settings.BubbleBackground); From 063d229a582ce4f184f9eeea2885403c8b8d34a4 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:24:57 +0800 Subject: [PATCH 07/17] Run native clipboard fixtures on a fresh isolated thread --- src/ClipboardNativeTests.cs | 47 +++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/src/ClipboardNativeTests.cs b/src/ClipboardNativeTests.cs index 4ca9bff..f80e932 100644 --- a/src/ClipboardNativeTests.cs +++ b/src/ClipboardNativeTests.cs @@ -54,7 +54,6 @@ protected override void WndProc(ref Forms.Message message) internal static int Run() { IntPtr previousStation = GetProcessWindowStation(); - IntPtr previousDesktop = GetThreadDesktop(Native.GetCurrentThreadId()); // A named station requires administrator membership. A standard user can // request an automatically named station only if it does not already exist. IntPtr station = CreateWindowStation("LightTranslate-test-" + Guid.NewGuid().ToString("N"), 1, 0x37f, IntPtr.Zero); @@ -66,7 +65,36 @@ internal static int Run() { Check(SetProcessWindowStation(station), "select isolated window station"); desktop = CreateDesktop("test", IntPtr.Zero, IntPtr.Zero, 0, 0x1ff, IntPtr.Zero); - Check(desktop != IntPtr.Zero && SetThreadDesktop(desktop), "select isolated desktop"); + Check(desktop != IntPtr.Zero, "create isolated desktop: " + Marshal.GetLastWin32Error()); + Exception failure = null; + var worker = new Thread(delegate() + { + try + { + // The entry-point STA may already own COM windows. Native clipboard + // APIs need no COM apartment; switch a fresh MTA thread before any UI. + Check(SetThreadDesktop(desktop), "select isolated desktop: " + Marshal.GetLastWin32Error()); + RunCases(desktop); + } + catch (Exception error) { failure = error; } + }); + worker.SetApartmentState(ApartmentState.MTA); + 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" })); + return 0; + } + finally + { + SetProcessWindowStation(previousStation); + if (desktop != IntPtr.Zero) CloseDesktop(desktop); + CloseWindowStation(station); + } + } + + private static void RunCases(IntPtr desktop) + { using (var clipboard = new NativeSelectionClipboard()) { uint html = ClipboardNative.RegisterClipboardFormat("HTML Format"); @@ -136,25 +164,14 @@ internal static int Run() } finally { delayed.DestroyHandle(); } } - 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" })); - return 0; - } - finally - { - SetThreadDesktop(previousDesktop); SetProcessWindowStation(previousStation); - if (desktop != IntPtr.Zero) CloseDesktop(desktop); - CloseWindowStation(station); - } } [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr CreateWindowStation(string name, uint flags, uint access, IntPtr security); [DllImport("user32.dll")] private static extern IntPtr GetProcessWindowStation(); [DllImport("user32.dll")] private static extern bool SetProcessWindowStation(IntPtr station); [DllImport("user32.dll")] private static extern bool CloseWindowStation(IntPtr station); - [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CreateDesktop(string name, IntPtr device, IntPtr mode, uint flags, uint access, IntPtr security); - [DllImport("user32.dll")] private static extern IntPtr GetThreadDesktop(uint thread); - [DllImport("user32.dll")] private static extern bool SetThreadDesktop(IntPtr desktop); + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr CreateDesktop(string name, IntPtr device, IntPtr mode, uint flags, uint access, IntPtr security); + [DllImport("user32.dll", SetLastError = true)] private static extern bool SetThreadDesktop(IntPtr desktop); [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr desktop); } } From 228c071d3bad1da554444dbdd306270f069fe68c Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:47:10 +0800 Subject: [PATCH 08/17] Add optional DeepL API with protected user credentials --- .github/workflows/build.yml | 3 + .gitignore | 2 + README.md | 13 ++- build.ps1 | 2 +- docs/TESTING.md | 62 +++++++++-- scripts/test-providers.ps1 | 12 ++ src/DeepL.cs | 163 +++++++++++++++++++++++++++ src/DeepLTests.cs | 192 ++++++++++++++++++++++++++++++++ src/LightTranslate.cs | 19 +++- src/ReadingSettings.cs | 65 +++++++++-- src/TranslationProviderTests.cs | 1 + 11 files changed, 501 insertions(+), 33 deletions(-) create mode 100644 scripts/test-providers.ps1 create mode 100644 src/DeepL.cs create mode 100644 src/DeepLTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 464843b..811501f 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: Translation providers and DeepL offline regression + shell: pwsh + run: ./scripts/test-providers.ps1 - name: Isolated native clipboard regression shell: pwsh run: ./scripts/test-clipboard.ps1 -Native diff --git a/.gitignore b/.gitignore index 5c6ad56..4363672 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,8 @@ lexicon.idx dictionary-build.txt settings.json status.log +deepl-key.bin +deepl-key.bin.*.tmp self-test.json .vs/ *.user diff --git a/README.md b/README.md index 9a935ba..cd24292 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 轻译 · LightTranslate +# 轻译 · LightTranslate **选中英文,译文自然浮起;继续操作,浮层自然消失。** @@ -12,7 +12,7 @@ - **选中即译**:拖选、双击选词或使用键盘选择文字,自动显示译文。 - **顺手收起**:点击、打字、滚动页面或切换应用时,浮层自动淡出。 - **单词本地快查**:约 76 万条 ECDICT 词库,支持离线查词,并补充常见编程术语。 -- **句子在线翻译**:使用微软翻译接口,腾讯接口作为备用。 +- **句子在线翻译**:默认使用微软翻译接口,腾讯接口作为备用;也可明确选择单一服务或自备密钥使用 DeepL 官方 API。 - **留足阅读时间**:鼠标悬停时保持显示,长译文可在浮层内滚动。 - **融入桌面**:圆角、淡入淡出、明暗主题和托盘开关。 @@ -32,9 +32,10 @@ ## 按自己的习惯设置 -在托盘“译”图标上右键,选择 **设置…**。面板分为“翻译、浮层、启动”三页,保存后生效: +在托盘“译”图标上右键,选择 **设置…**。面板分为“翻译、浮层、启动、DeepL”四页,保存后生效: -- **翻译**:自动划词开关、剪贴板取词开关、微软在线目标语言、单次选区长度上限、排除应用和最低英文占比。托盘开关会立即生效并同步到已打开的面板;面板中的改动在保存后应用。关闭剪贴板取词后不获取选区。目标语言只影响微软在线翻译,本地词库和腾讯备用仍输出中文。 +- **翻译**:自动划词开关、剪贴板取词开关、在线服务及目标语言、单次选区长度上限、排除应用和最低英文占比。托盘开关会立即生效并同步到已打开的面板;面板中的改动在保存后应用。关闭剪贴板取词后不获取选区。目标语言影响微软和 DeepL;本地词库和腾讯仍输出中文。 +- **DeepL**:手动输入 API 密钥,输入遮挡且不回填。留空保留现有密钥,清除需点击“保存”;取消不改变密钥。密钥用 Windows 当前用户 DPAPI 加密,单独存入应用目录的 `deepl-key.bin`,不写入 `settings.json`。换用户或电脑需重新输入。保存设置不联网验证。 - **启动**:读取实际的当前用户启动项,显示当前目录是否开机自启;只有改变选择并保存时才创建或移除启动快捷方式。不写入 `settings.json` 的自启标志,也不默认开启自启。保存失败会显示错误;配置保存失败时会尝试恢复启动项,恢复失败会显示实际状态供检查。 “浮层”页保留以下阅读设置;最低英文占比在“翻译”页: @@ -80,7 +81,9 @@ pwsh -File .\startup.ps1 -Remove ## 文字如何处理 -命中本地词库的文字在电脑上查询;其他文字发送给微软翻译,主服务失败时会尝试腾讯。 +默认自动模式先查询本地词库,未命中时发送给微软翻译,失败后尝试腾讯;自动模式不会调用 DeepL。明确选择微软、腾讯或 DeepL 会跳过词库,只请求所选服务,失败不会自动切换。 +选择 DeepL 并保存密钥后,选中文字将发送给 DeepL,可能按账户套餐计费;未配置密钥时不请求 DeepL。只使用官方 `POST /v2/translate`,按密钥的 `:fx` 标记选择 `api-free.deepl.com`,其余使用 `api.deepl.com`,不接受自定义地址或 HTTP 重定向。简繁中文对应 `ZH-HANS`、`ZH-HANT`。 +额度和费用以 [DeepL 当前 API 套餐](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。 译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。 取词通过临时复制选区完成,并尝试恢复原剪贴板;系统或剪贴板管理器可能保留复制记录。 diff --git a/build.ps1 b/build.ps1 index 3cddb97..2423b5a 100644 --- a/build.ps1 +++ b/build.ps1 @@ -10,7 +10,7 @@ $compiler = Join-Path $framework 'csc.exe' if (-not (Test-Path -LiteralPath $compiler)) { throw '.NET Framework 4.8 and its 64-bit compiler are required.' } $outputPath = [System.IO.Path]::GetFullPath($OutputDirectory) New-Item -ItemType Directory -Path $outputPath -Force | Out-Null -$references = @('System.dll','System.Core.dll','System.Net.Http.dll','System.Drawing.dll','System.Windows.Forms.dll','System.Web.Extensions.dll','System.Xaml.dll','Microsoft.VisualBasic.dll') | +$references = @('System.dll','System.Core.dll','System.Security.dll','System.Net.Http.dll','System.Drawing.dll','System.Windows.Forms.dll','System.Web.Extensions.dll','System.Xaml.dll','Microsoft.VisualBasic.dll') | ForEach-Object { '/r:' + (Join-Path $framework $_) } $references += @('WindowsBase.dll','PresentationCore.dll','PresentationFramework.dll') | ForEach-Object { '/r:' + (Join-Path $framework ('WPF\' + $_)) } diff --git a/docs/TESTING.md b/docs/TESTING.md index b488c47..138a066 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,4 +1,4 @@ -# 开发与测试 +# 开发与测试 ## 构建、自检与打包 @@ -57,8 +57,8 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 |---|---|---| | `Enabled` | `true` | 自动划词翻译开关,也可通过托盘修改 | | `ClipboardFallback` | `true` | 剪贴板取词开关,关闭后停止取词 | -| `TranslationProvider` | `auto` | `auto` 保留本地词库优先、微软失败后腾讯;`microsoft` / `tencent` 仅调用选定服务并跳过词库 | -| `Target` | `zh-Hans` | 微软接口的目标语言;本地词库和腾讯备用接口输出中文 | +| `TranslationProvider` | `auto` | `auto` 保留本地词库优先、微软失败后腾讯;`microsoft` / `tencent` / `deepl` 仅调用选定服务并跳过词库 | +| `Target` | `zh-Hans` | 微软 / DeepL 的目标语言;本地词库和腾讯输出中文 | | `MaxSelectionLength` | `2000` | 单次选区字符数上限 | | `ExcludedApps` | `[]` | 排除的进程名称,可带或不带 `.exe` | | `Diagnostics` | `false` | 触发诊断日志开关 | @@ -76,7 +76,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 `ClipboardFallback` 沿用早期字段名,当前取词路径统一使用剪贴板。 面板纳入 `Enabled`、`ClipboardFallback`、`Target`、`MaxSelectionLength`、`ExcludedApps` -和五项阅读选项。目标语言只校验修改后输入的语言标签语法,不联网获取语言列表;服务是否支持自定义标签由微软决定。 +和五项阅读选项。目标语言只校验修改后输入的语言标签语法,不联网获取语言列表;服务是否支持自定义标签由所选服务决定。 修改后的选区上限要求正整数,排除应用支持换行及中英文逗号/分号,按进程名校验、去重。 未改动的原有自定义目标、长度和排除数组逐值保留;隐藏的 `Diagnostics` 克隆保留,不因普通设置或恢复默认值而重置。 @@ -101,11 +101,12 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 如果用户或其他应用在取词期间更新了剪贴板,程序会避免覆盖新的内容。 系统剪贴板历史和第三方剪贴板管理器仍可能保留临时复制记录。 -命中本地词库的选区不会发送给在线服务。其他文字发送给微软,主服务失败时可能发送给腾讯。 -启动时会预热微软连接,该请求不包含选区文字。在线接口采用兼容协议,当前无需个人 API 密钥; -接口可用性由服务端决定,可能出现限流或协议变更。 +自动模式命中本地词库时不发送选区;未命中发送给微软,失败后可能发送给腾讯。 +自动或微软模式启动时预热微软连接,不包含选区;腾讯和 DeepL 模式不预热。 +明确选择单一服务时跳过词库且不回退;DeepL 需要用户保存密钥,可能计费。 +微软和腾讯内置接口无需个人密钥;接口可用性由服务端决定,可能限流或变更。 -译文缓存最多 256 条,仅保存在当前进程内。程序不记录选区原文或用户译文。 +普通服务和 DeepL 各有最多 256 条译文缓存,仅保存在当前进程内。程序不记录选区原文或用户译文。 诊断日志启用后会记录进程名、进程编号、字符数和触发状态;启动错误日志可能包含本机路径。 ## 兼容性记录 @@ -190,12 +191,11 @@ update the running tray icon and dispose its previous Icon; canceled edits do no ## Translation provider regression `TranslationProvider` defaults to `auto` for old settings. The panel also offers -`microsoft` and `tencent`; explicit choices bypass the local dictionary and never +`microsoft`, `tencent` and `deepl`; explicit choices bypass the local dictionary and never fall back to another service. Tencent currently outputs Chinese only. Its target -control is disabled without erasing the last Microsoft target. Automatic mode +control is disabled without erasing the last target. Automatic mode retains the existing Chinese dictionary and Tencent fallback behavior even when -Microsoft's target is another language. No new endpoints or credential fields -are introduced. +Microsoft's target is another language. DeepL is never part of automatic fallback. The offline self-test uses an injected HTTP handler to verify routing, automatic fallback, explicit-provider failure, provider/target cache separation, canceled @@ -203,3 +203,41 @@ in-flight responses, and settings save/cancel/reopen/live application. It makes no network requests. Applying settings uses the existing capture/request cancellation path before any new translation. Live service availability is not covered by these fixture tests. + + +## Optional DeepL API + +DeepL uses only `POST https://api.deepl.com/v2/translate` or +`POST https://api-free.deepl.com/v2/translate`, with `DeepL-Auth-Key` Authorization. +The key suffix `:fx` selects the latter, following the official +[authentication guide](https://developers.deepl.com/docs/getting-started/auth) and +[SDK endpoint selection](https://github.com/DeepLcom/deepl-dotnet/blob/main/DeepL/Translator.cs). +This does not infer a host from plan marketing names. DeepL says its API documentation +applies to all plans. Its [current plans](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) +include Developer (a total, non-resetting allowance), Growth and Enterprise; +legacy Free/Pro are no longer sold. The app does not promise a recurring free quota. +Region-specific Enterprise endpoints are not included in this implementation. +No custom URL, redirect, automatic retry or automatic switch to/from DeepL is allowed. +`zh-Hans` and `zh-Hant` normalize to `ZH-HANS` and `ZH-HANT`. + +`deepl-key.bin` contains only current-user DPAPI ciphertext. It is excluded from Git +and release artifacts. Plaintext is not serialized into settings, logs, error messages, +previews or test reports. Opening settings checks only file existence and never fills +the PasswordBox with a stored key. Replacement/clear is staged until Save; config-save +failure attempts to restore the previous encrypted file. Rollback failure is reported. +This is not a crash-atomic transaction across config, credentials and startup state. +DPAPI protects storage from other users, not processes already running as that user; +the key necessarily exists briefly in managed memory and the outgoing auth header. +The controller cancels pending translations on settings application. The DeepL client +also rejects a response if credentials changed during its request, checks credentials +before cache access and clears its separate cache when the credential scope changes. + +Run `./scripts/test-providers.ps1` after building, or run the complete offline self-test. +The provider test is also a separate CI step. Only fictitious sentinel credentials, +injected HTTP handlers, a temporary DPAPI file and fake startup registration are used. +Coverage includes zero requests without a key, default/explicit routing, both hosts, +Chinese targets, provider/target/credential cache isolation, authentication failures, +quota exhaustion, 429, invalid targets, request size, malformed responses, timeout, +network failure, cancellation, stale responses, and save/clear/cancel/reopen/rollback. +No live DeepL account, registration, key validation or billed request is exercised. +The generated settings previews show an empty credential field. diff --git a/scripts/test-providers.ps1 b/scripts/test-providers.ps1 new file mode 100644 index 0000000..99daddf --- /dev/null +++ b/scripts/test-providers.ps1 @@ -0,0 +1,12 @@ +[CmdletBinding()] +param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\LightTranslate')) + +$ErrorActionPreference = 'Stop' +$outputPath = [System.IO.Path]::GetFullPath($OutputDirectory) +$testProcess = Start-Process -FilePath (Join-Path $outputPath 'LightTranslate.exe') -ArgumentList '--self-test-providers' -WindowStyle Hidden -PassThru +if (-not $testProcess.WaitForExit(30000)) { + Stop-Process -Id $testProcess.Id -Force + throw 'Provider self-test exceeded 30 seconds.' +} +if ($testProcess.ExitCode -ne 0) { throw 'Provider self-test failed; see status.log in the test output directory.' } +Get-Content -LiteralPath (Join-Path $outputPath 'provider-test.json') diff --git a/src/DeepL.cs b/src/DeepL.cs new file mode 100644 index 0000000..dddc6c1 --- /dev/null +++ b/src/DeepL.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Web.Script.Serialization; + +namespace LightTranslate +{ + // Messages are fixed locally: never include response bodies, keys or inner exceptions. + internal sealed class DeepLException : Exception + { + internal DeepLException(string message) : base(message) { } + } + + internal interface IDeepLCredentials + { + bool Exists { get; } + string Read(); + Action Replace(string key); + } + + internal sealed class DeepLCredentials : IDeepLCredentials + { + private readonly string path; + internal DeepLCredentials(string path) { this.path = path; } + internal static DeepLCredentials Current() + { return new DeepLCredentials(Path.Combine(Program.Folder, "deepl-key.bin")); } + public bool Exists { get { return File.Exists(path); } } + public string Read() + { + if (!Exists) return null; + byte[] plain = null; + try + { + plain = ProtectedData.Unprotect(File.ReadAllBytes(path), null, DataProtectionScope.CurrentUser); + return Encoding.UTF8.GetString(plain); + } + catch { throw new DeepLException("DeepL 密钥无法读取,请在设置中重新保存或清除。"); } + finally { if (plain != null) Array.Clear(plain, 0, plain.Length); } + } + internal static bool ValidKey(string key) + { + if (string.IsNullOrWhiteSpace(key) || key.Length > 1024) return false; + foreach (char c in key) if (c <= 32 || c >= 127) return false; + return true; + } + public Action Replace(string key) + { + if (key != null && !ValidKey(key)) throw new DeepLException("请输入有效的 DeepL API 密钥,不要包含空白或换行。"); + byte[] previous = Exists ? File.ReadAllBytes(path) : null; + byte[] plain = key == null ? null : Encoding.UTF8.GetBytes(key); + try { Write(plain == null ? null : ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser)); } + finally { if (plain != null) Array.Clear(plain, 0, plain.Length); } + return delegate { Write(previous); }; + } + private void Write(byte[] encrypted) + { + if (encrypted == null) { File.Delete(path); return; } + string temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + File.WriteAllBytes(temporary, encrypted); + if (File.Exists(path)) File.Replace(temporary, path, null); + else File.Move(temporary, path); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } + } + + internal sealed class DeepLTranslator : IDisposable + { + private readonly IDeepLCredentials credentials; + private readonly HttpClient http; + private readonly JavaScriptSerializer json = new JavaScriptSerializer(); + private readonly Dictionary cache = new Dictionary(); + private string credentialScope; + internal DeepLTranslator(IDeepLCredentials credentials, HttpMessageHandler handler = null) + { + this.credentials = credentials; + // Never forward a selected text or key through an HTTP redirect. + http = new HttpClient(handler ?? new HttpClientHandler { AllowAutoRedirect = false }); + http.Timeout = TimeSpan.FromSeconds(7); + } + internal static string Target(string target) + { + string value = (target ?? "").Trim().ToUpperInvariant(); + if (value == "ZH" || value == "ZH-CN") value = "ZH-HANS"; + if (value == "ZH-TW") value = "ZH-HANT"; + if (!System.Text.RegularExpressions.Regex.IsMatch(value, "^[A-Z]{2,3}(?:-[A-Z0-9]{1,8})*$")) + throw new DeepLException("DeepL 目标语言代码无效,请检查设置。"); + return value; + } + internal static string Endpoint(string key) + { + // Same key-suffix selection as the official SDK; independent of plan names. + return key.EndsWith(":fx", StringComparison.Ordinal) ? "https://api-free.deepl.com/v2/translate" : "https://api.deepl.com/v2/translate"; + } + private static string Scope(string key) + { + if (key == null) return null; + byte[] bytes = Encoding.UTF8.GetBytes(key); + try { using (var hash = SHA256.Create()) return Convert.ToBase64String(hash.ComputeHash(bytes)); } + finally { Array.Clear(bytes, 0, bytes.Length); } + } + internal async Task Translate(string text, string target, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + string key = credentials.Read(); + string scope = Scope(key); + if (credentialScope != scope) { cache.Clear(); credentialScope = scope; } + if (!DeepLCredentials.ValidKey(key)) throw new DeepLException("请先在设置的 DeepL 页保存 API 密钥。"); + string language = Target(target), cacheKey = language + "\n" + text, result; + if (cache.TryGetValue(cacheKey, out result)) return result; + string body = json.Serialize(new { text = new[] { text }, target_lang = language }); + if (Encoding.UTF8.GetByteCount(body) > 128 * 1024) throw new DeepLException("选中文字超过 DeepL 单次请求上限,请缩短选区。"); + try + { + using (var request = new HttpRequestMessage(HttpMethod.Post, Endpoint(key))) + { + request.Headers.Authorization = new AuthenticationHeaderValue("DeepL-Auth-Key", key); + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + using (var response = await http.SendAsync(request, ct)) + { + ct.ThrowIfCancellationRequested(); + int status = (int)response.StatusCode; + if (status == 401 || status == 403) throw new DeepLException("DeepL 认证失败,请检查 API 密钥及翻译权限。"); + if (status == 456) throw new DeepLException("DeepL 用量或费用已达上限,请检查账户额度。"); + if (status == 429) throw new DeepLException("DeepL 请求过于频繁,请稍后重试。"); + if (status == 400) throw new DeepLException("DeepL 不接受此请求,请检查目标语言是否受支持。"); + if (status == 413) throw new DeepLException("选中文字超过 DeepL 单次请求上限,请缩短选区。"); + if (!response.IsSuccessStatusCode) throw new DeepLException("DeepL 暂时不可用,请稍后重试。"); + try + { + var item = (Dictionary)json.DeserializeObject(await response.Content.ReadAsStringAsync()); + var translations = (object[])item["translations"]; + result = (string)((Dictionary)translations[0])["text"]; + if (string.IsNullOrWhiteSpace(result)) throw new InvalidDataException(); + } + catch { ct.ThrowIfCancellationRequested(); throw new DeepLException("DeepL 返回了无法解析的译文,请稍后重试。"); } + } + } + } + catch (OperationCanceledException) + { + ct.ThrowIfCancellationRequested(); + throw new DeepLException("DeepL 请求超时,请稍后重试。"); + } + catch (HttpRequestException) { throw new DeepLException("无法连接 DeepL,请检查网络后重试。"); } + ct.ThrowIfCancellationRequested(); + // Clearing/replacing credentials while a request is in flight also discards its result. + if (scope != Scope(credentials.Read())) throw new OperationCanceledException(); + if (cache.Count >= 256) cache.Clear(); + cache[cacheKey] = result; + return result; + } + public void Dispose() { http.Dispose(); } + } +} diff --git a/src/DeepLTests.cs b/src/DeepLTests.cs new file mode 100644 index 0000000..614f0af --- /dev/null +++ b/src/DeepLTests.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace LightTranslate +{ + internal static class DeepLTests + { + // Deliberately invalid sentinel. Never use an account key in tests or snapshots. + private const string Sentinel = "test-only-not-a-real-deepl-key"; + private sealed class Credentials : IDeepLCredentials + { + internal string Key; + internal bool FailWrite; + internal int Reads; + public bool Exists { get { return Key != null; } } + public string Read() { Reads++; return Key; } + public Action Replace(string key) + { + if (FailWrite) throw new IOException("Fixture"); + string previous = Key; Key = key; return delegate { Key = previous; }; + } + } + private sealed class Handler : HttpMessageHandler + { + internal int Calls; + internal int Status = 200; + internal bool Timeout, NetworkError, FailMicrosoft; + internal string Host, Body, Auth, Path, Method; + internal string Response = "{\"translations\":[{\"text\":\"DeepL fixture\"}]}"; + internal TaskCompletionSource Pending; + internal HttpResponseMessage Reply() + { return new HttpResponseMessage((HttpStatusCode)Status) { Content = new StringContent(Response) }; } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Calls++; Host = request.RequestUri.Host; Path = request.RequestUri.AbsolutePath; Method = request.Method.Method; + Body = request.Content == null ? "" : request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + Auth = request.Headers.Authorization == null ? "" : request.Headers.Authorization.ToString(); + if (Host == "api.cognitive.microsofttranslator.com" && FailMicrosoft) + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); + if (Host == "transmart.qq.com") + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"auto_translation\":\"Tencent fixture\"}") }); + if (Timeout) throw new TaskCanceledException(); + if (NetworkError) throw new HttpRequestException("Do not expose " + Sentinel); + return Pending == null ? Task.FromResult(Reply()) : Pending.Task; + } + } + private static void Check(bool ok, string message) + { if (!ok) throw new Exception("DeepL fixture: " + message); } + private static void Error(Action action, string expected) + { + try { action(); } + catch (DeepLException ex) + { + Check(ex.Message.Contains(expected) && !ex.ToString().Contains(Sentinel), "safe error category"); return; + } + throw new Exception("DeepL fixture: expected failure"); + } + internal static void Run(Dictionary results) + { + var credentials = new Credentials(); var deepL = new Handler(); var existing = new Handler(); + existing.Response = "[{\"translations\":[{\"text\":\"Microsoft fixture\"}]}]"; + var none = CancellationToken.None; + using (var translator = new Translator(existing, credentials, deepL)) + { + translator.Translate("sample", "zh-Hans", none).GetAwaiter().GetResult(); + Check(deepL.Calls == 0 && credentials.Reads == 0, "default never accesses DeepL"); + existing.FailMicrosoft = true; + Check(translator.Translate("fallback", "ja", none).Result == "Tencent fixture", "default Microsoft/Tencent fallback unchanged"); + Check(deepL.Calls == 0 && credentials.Reads == 0, "automatic fallback never accesses DeepL"); + existing.FailMicrosoft = false; + Error(delegate { translator.Translate("sample", "zh-Hans", none, "deepl").GetAwaiter().GetResult(); }, "先"); + Check(deepL.Calls == 0 && existing.Calls == 3, "unconfigured sends nothing and never falls back"); + credentials.Key = "invalid\r\nfixture"; + Error(delegate { translator.Translate("sample", "ja", none, "deepl").GetAwaiter().GetResult(); }, "先"); + Check(deepL.Calls == 0, "invalid credential never sent"); + credentials.Key = Sentinel; + Check(translator.Translate("sample", "zh-Hans", none, "deepl").Result == "DeepL fixture", "explicit route and provider cache isolation"); + Check(deepL.Host == "api.deepl.com" && deepL.Path == "/v2/translate" && deepL.Method == "POST", "official endpoint"); + Check(deepL.Auth == "DeepL-Auth-Key " + Sentinel && deepL.Body.Contains("ZH-HANS") && !deepL.Body.Contains(Sentinel), "auth header and simplified Chinese"); + translator.Translate("sample", "zh-Hans", none, "deepl").GetAwaiter().GetResult(); + Check(deepL.Calls == 1, "DeepL cache"); + translator.Translate("sample", "zh-Hant", none, "deepl").GetAwaiter().GetResult(); + Check(deepL.Calls == 2 && deepL.Body.Contains("ZH-HANT"), "traditional Chinese target isolation"); + credentials.Key = Sentinel + ":fx"; + translator.Translate("sample", "zh-Hant", none, "deepl").GetAwaiter().GetResult(); + Check(deepL.Calls == 3 && deepL.Host == "api-free.deepl.com", "legacy suffix and credential cache isolation"); + credentials.Key = null; + Error(delegate { translator.Translate("sample", "zh-Hant", none, "deepl").GetAwaiter().GetResult(); }, "先"); + Check(deepL.Calls == 3, "cleared credential disables cached and network result"); + credentials.Key = Sentinel; + int[] statuses = { 401, 403, 456, 429, 400, 413, 500, 307 }; + string[] messages = { "认证", "认证", "上限", "频繁", "目标语言", "上限", "不可用", "不可用" }; + for (int i = 0; i < statuses.Length; i++) + { + deepL.Status = statuses[i]; deepL.Response = Sentinel; + Error(delegate { translator.Translate("error", "ja", none, "deepl").GetAwaiter().GetResult(); }, messages[i]); + } + deepL.Status = 200; deepL.Response = "malformed " + Sentinel; + Error(delegate { translator.Translate("error", "ja", none, "deepl").GetAwaiter().GetResult(); }, "解析"); + deepL.Timeout = true; + Error(delegate { translator.Translate("error", "ja", none, "deepl").GetAwaiter().GetResult(); }, "超时"); + deepL.Timeout = false; deepL.NetworkError = true; + Error(delegate { translator.Translate("error", "ja", none, "deepl").GetAwaiter().GetResult(); }, "网络"); + deepL.NetworkError = false; + int before = deepL.Calls; + Error(delegate { translator.Translate("error", "invalid target", none, "deepl").GetAwaiter().GetResult(); }, "代码"); + Error(delegate { translator.Translate(new string('a', 132000), "ja", none, "deepl").GetAwaiter().GetResult(); }, "上限"); + Check(deepL.Calls == before && existing.Calls == 3, "invalid input never sent, DeepL errors never fall back"); + deepL.Response = "{\"translations\":[{\"text\":\"DeepL fixture\"}]}"; + for (int mode = 0; mode < 2; mode++) + { + deepL.Pending = new TaskCompletionSource(); + using (var cancellation = new CancellationTokenSource()) + { + var task = translator.Translate("pending", "ja", cancellation.Token, "deepl"); + if (mode == 0) cancellation.Cancel(); else credentials.Key = Sentinel + ":fx"; + deepL.Pending.SetResult(deepL.Reply()); + bool stopped = false; + try { task.GetAwaiter().GetResult(); } catch (OperationCanceledException) { stopped = true; } + Check(stopped, "canceled/credential-replaced response discarded"); + } + deepL.Pending = null; credentials.Key = Sentinel; + } + before = deepL.Calls; + translator.Translate("pending", "ja", none, "deepl").GetAwaiter().GetResult(); + Check(deepL.Calls == before + 1, "discarded result not cached"); + using (var cancellation = new CancellationTokenSource()) + { + cancellation.Cancel(); bool stopped = false; + try { translator.Translate("pending", "ja", cancellation.Token, "deepl").GetAwaiter().GetResult(); } + catch (OperationCanceledException) { stopped = true; } + Check(stopped && deepL.Calls == before + 1, "cancellation precedes cache"); + } + } + TestStorageAndSettings(); + results["deepL"] = "mock HTTP only: official endpoints/auth, Chinese targets, no-key/no-fallback, errors, quota, rate limit, timeout, cancellation, isolated caches; DPAPI and settings save/clear/cancel/rollback passed"; + } + private static void TestStorageAndSettings() + { + string root = Path.Combine(Program.Folder, "self-test-deepl-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + string keyPath = Path.Combine(root, "deepl-key.bin"), settingsPath = Path.Combine(root, "settings.json"); + var store = new DeepLCredentials(keyPath); + var undo = store.Replace(Sentinel); + Check(store.Read() == Sentinel && !Encoding.UTF8.GetString(File.ReadAllBytes(keyPath)).Contains(Sentinel), "current-user encrypted roundtrip"); + undo(); Check(!store.Exists, "encrypted store rollback"); + store.Replace(Sentinel); var restore = store.Replace(null); Check(!store.Exists, "delete encrypted key"); + restore(); Check(store.Read() == Sentinel, "clear rollback"); + File.WriteAllText(keyPath, "corrupted fixture"); + Error(delegate { store.Read(); }, "重新保存"); + store.Replace(null); + var settings = new Settings(); int applied = 0; + var window = new SettingsWindow(settings, delegate { applied++; }, new FakeStartupRegistration(), store); + window.SetProviderForTest(3); window.SetDeepLKeyForTest(Sentinel); + Check(window.TargetEnabledForTest && !store.Exists, "credential edits are staged"); + Check(window.Apply(settingsPath) && store.Read() == Sentinel && applied == 1, "save credential and runtime provider callback"); + Check(settings.TranslationProvider == "deepl" && !File.ReadAllText(settingsPath).Contains(Sentinel), "config contains provider only"); + var reopened = new SettingsWindow(Settings.Load(settingsPath), null, new FakeStartupRegistration(), store); + Check(reopened.ProviderForTest == 3 && reopened.DeepLInputEmptyForTest, "reopen without key refill"); + reopened.ClearDeepLKeyForTest(); reopened.Close(); + Check(store.Read() == Sentinel, "cancel pending clear"); + var canceled = new SettingsWindow(settings, null, new FakeStartupRegistration(), store); + canceled.SetDeepLKeyForTest(Sentinel + ":fx"); canceled.Close(); + Check(store.Read() == Sentinel, "cancel pending replacement"); + var failure = new SettingsWindow(settings, null, new FakeStartupRegistration(), store); + failure.SetDeepLKeyForTest(Sentinel + ":fx"); + Check(!failure.Apply(root) && store.Read() == Sentinel, "config failure restores previous encrypted key"); failure.Close(); + var failedClear = new SettingsWindow(settings, null, new FakeStartupRegistration(), store); + failedClear.ClearDeepLKeyForTest(); + Check(!failedClear.Apply(root) && store.Read() == Sentinel, "config failure restores cleared key"); failedClear.Close(); + var badStore = new Credentials { FailWrite = true }; + var failedKey = new SettingsWindow(settings, null, new FakeStartupRegistration(), badStore); + failedKey.SetProviderForTest(1); failedKey.SetDeepLKeyForTest(Sentinel); + Check(!failedKey.Apply(settingsPath) && Settings.Load(settingsPath).TranslationProvider == "deepl", "credential failure preserves config"); failedKey.Close(); + var clear = new SettingsWindow(settings, null, new FakeStartupRegistration(), store); + clear.ClearDeepLKeyForTest(); Check(clear.Apply(settingsPath) && !store.Exists, "saved clear"); + var preview = new SettingsWindow(settings, null, new FakeStartupRegistration(), store); + preview.RenderPreview(Path.Combine(Program.Folder, "settings-deepl-preview.png"), 3); + preview.RenderPreview(Path.Combine(Program.Folder, "settings-deepl-provider-preview.png"), 0); preview.Close(); + } + finally { Directory.Delete(root, true); } + } + } +} diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index a7c852f..7fd17e7 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -188,7 +188,7 @@ public Controller(Application app) settings = Settings.Load(); lexicon = new Lexicon(Program.Folder); translator = new Translator(); - if (settings.TranslationProvider != "tencent") { var warming = translator.WarmConnection(); } + if (settings.TranslationProvider == "auto" || settings.TranslationProvider == "microsoft") { var warming = translator.WarmConnection(); } bubble = new Bubble(); bubble.ApplySettings(settings); tray = new Forms.NotifyIcon { Text = "轻译 · 选中即译", Icon = MakeIcon(settings), Visible = true }; @@ -369,7 +369,7 @@ private async void BeginSelection(IntPtr window, Native.POINT point) catch (Exception ex) { Program.Log("translate", ex.GetType().Name); - if (Valid(version, window)) ShowText("暂时无法连接翻译服务", point, 3); + if (Valid(version, window)) ShowText(ex is DeepLException ? ex.Message : "暂时无法连接翻译服务", point, ex is DeepLException ? 6 : 3); } finally { @@ -909,12 +909,14 @@ public static void Build(string csv, string folder) internal sealed class Translator : IDisposable { private readonly HttpClient http; + private readonly DeepLTranslator deepl; private readonly JavaScriptSerializer json = new JavaScriptSerializer(); private readonly Dictionary cache = new Dictionary(); private readonly Queue eviction = new Queue(); public Translator() : this(null) { } - internal Translator(HttpMessageHandler handler) + internal Translator(HttpMessageHandler handler, IDeepLCredentials credentials = null, HttpMessageHandler deepLHandler = null) { + deepl = new DeepLTranslator(credentials ?? DeepLCredentials.Current(), deepLHandler); http = handler == null ? new HttpClient() : new HttpClient(handler); http.Timeout = TimeSpan.FromSeconds(7); http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); @@ -930,15 +932,20 @@ internal async Task WarmConnection() catch { } } internal static string NormalizeProvider(string provider) - { return provider == "microsoft" || provider == "tencent" ? provider : "auto"; } + { return provider == "microsoft" || provider == "tencent" || provider == "deepl" ? provider : "auto"; } private static string CacheKey(string text, string target, string provider) { return NormalizeProvider(provider) + "\n" + (provider == "tencent" ? "zh" : target) + "\n" + text; } public bool TryCached(string text, string target, out string result, string provider = "auto") - { return cache.TryGetValue(CacheKey(text, target, provider), out result); } + { + // DeepL validates the current credential before consulting its separate cache. + if (provider == "deepl") { result = null; return false; } + return cache.TryGetValue(CacheKey(text, target, provider), out result); + } public async Task Translate(string text, string target, CancellationToken ct, string provider = "auto") { ct.ThrowIfCancellationRequested(); provider = NormalizeProvider(provider); + if (provider == "deepl") return await deepl.Translate(text, target, ct); string result; if (TryCached(text, target, out result, provider)) return result; if (provider == "tencent") result = await Tencent(text, ct); @@ -1010,7 +1017,7 @@ private static string Signature(string path) using (var hmac = new HMACSHA256(key)) return "MSTranslatorAndroidApp::" + Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(value))) + "::" + date + "::" + guid; } - public void Dispose() { http.Dispose(); } + public void Dispose() { http.Dispose(); deepl.Dispose(); } } internal static class Native diff --git a/src/ReadingSettings.cs b/src/ReadingSettings.cs index cc0767a..c0ef9cf 100644 --- a/src/ReadingSettings.cs +++ b/src/ReadingSettings.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.IO; using System.Linq; @@ -100,6 +100,10 @@ internal sealed class SettingsWindow : Window private readonly Settings settings; private readonly Action saved; private readonly IStartupRegistration startup; + private readonly IDeepLCredentials credentials; + private readonly PasswordBox deepLKey; + private readonly TextBlock deepLStatus; + private bool clearDeepLKey; private readonly CheckBox enabled, clipboard, autoStart; private readonly ComboBox language, provider, fontFamily, fontSize, autoHide; private readonly TextBox maxSelection, excludedApps, background, englishPercent; @@ -110,10 +114,11 @@ internal sealed class SettingsWindow : Window private bool refreshingStartup, startupDirty; private bool? observedStartup; - internal SettingsWindow(Settings settings, Action saved, IStartupRegistration startup = null) + internal SettingsWindow(Settings settings, Action saved, IStartupRegistration startup = null, IDeepLCredentials credentials = null) { this.settings = settings; this.saved = saved; this.startup = startup ?? StartupRegistration.CurrentUser(); + this.credentials = credentials ?? DeepLCredentials.Current(); Title = "轻译 · 设置"; Width = 620; Height = 790; MinWidth = 480; MinHeight = 450; MaxHeight = Math.Max(450, SystemParameters.WorkArea.Height - 40); @@ -137,12 +142,12 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st clipboard = Toggle("通过剪贴板获取选中文字"); translation.Children.Add(enabled); translation.Children.Add(clipboard); translation.Children.Add(Help("托盘开关立即生效并同步到这里;面板修改在保存后生效。当前仅支持剪贴板取词;关闭后停止划词翻译。取词会临时复制选区;剪贴板含不支持的格式时跳过,不覆盖原内容。")); - provider = new ComboBox { ItemsSource = new[] { "自动(微软失败后腾讯)", "仅微软", "仅腾讯(中文)" }, MinHeight = 32 }; + provider = new ComboBox { ItemsSource = new[] { "自动(微软失败后腾讯)", "仅微软", "仅腾讯(中文)", "仅 DeepL(自备 API 密钥)" }, MinHeight = 32 }; AddField(translation, "在线翻译服务", provider); - translation.Children.Add(Help("自动模式先查本地英汉词库,再请求在线服务;仅微软或仅腾讯会跳过本地词库,不切换服务。现有内置服务无需填写密钥。")); + translation.Children.Add(Help("自动模式先查本地英汉词库,再尝试微软、腾讯;指定服务会跳过词库且不自动切换。DeepL 须在 DeepL 页保存密钥;自动模式不会调用 DeepL。")); language = new ComboBox { IsEditable = true, ItemsSource = Languages, MinHeight = 32 }; - AddField(translation, "目标语言(微软)", language); - translation.Children.Add(Help("可直接输入语言代码,如 en、ja。目标语言只对微软有效;自动模式下的本地词库和腾讯回退仍输出中文。仅腾讯固定输出中文。")); + AddField(translation, "目标语言", language); + translation.Children.Add(Help("可直接输入服务支持的语言代码,如 en、ja。DeepL 简繁中文分别使用 ZH-HANS、ZH-HANT。词库和腾讯固定输出中文。")); maxSelection = Input(); AddField(translation, "选区字符数上限", maxSelection); translation.Children.Add(Help("正整数,默认 2,000。超过上限只提示分段选择,不发送该选区。")); @@ -195,6 +200,20 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st AutomationProperties.SetHelpText(autoHide, "自动,或 1 到 120 秒;鼠标悬停保留浮层"); AutomationProperties.SetHelpText(englishPercent, "范围 0 到 100,分母为全部 Unicode 字母,不含空白、数字和标点"); + var deepL = NewTab("DeepL"); + deepL.Children.Add(Heading("DeepL 官方 API(可选)")); + deepL.Children.Add(Help("选择“仅 DeepL”并保存密钥后,选中文字将发送给 DeepL,可能按账户套餐计费。不会自动回退到其他服务,也不会在自动模式中调用 DeepL。")); + deepLStatus = Help(""); deepL.Children.Add(deepLStatus); + deepLKey = new PasswordBox { MinHeight = 32, MaxLength = 1024, VerticalContentAlignment = VerticalAlignment.Center }; + AddField(deepL, "API 密钥", deepLKey); + deepL.Children.Add(Help("留空保留已保存密钥;密钥不会回填。保存时使用 Windows 当前用户加密,单独存放,不写入普通配置。其他用户或电脑需重新输入。")); + var clearKey = Button("清除已保存密钥"); clearKey.HorizontalAlignment = HorizontalAlignment.Left; + clearKey.Click += delegate { StageDeepLClear(); }; deepL.Children.Add(clearKey); + deepL.Children.Add(Help("新增、替换和清除都在点击“保存”后生效;取消不改变密钥。保存不会发起联网验证。")); + deepL.Children.Add(Help("按官方密钥标记选择 api.deepl.com 或 api-free.deepl.com,不支持自定义地址。可用额度和费用请以 DeepL 账户为准。")); + deepLKey.PasswordChanged += delegate { if (deepLKey.Password.Length != 0) clearDeepLKey = false; RefreshDeepLStatus(); }; + RefreshDeepLStatus(); + 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); @@ -216,7 +235,7 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st autoStart.Checked += delegate { StartupChoiceChanged(); }; autoStart.Unchecked += delegate { StartupChoiceChanged(); }; PreviewKeyDown += delegate(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { e.Handled = true; Close(); } }; settings.Changed += SyncEnabled; - Closed += delegate { settings.Changed -= SyncEnabled; }; + Closed += delegate { settings.Changed -= SyncEnabled; deepLKey.Clear(); }; Activated += delegate { RefreshStartup(); }; Fill(settings); RefreshStartup(); } @@ -250,7 +269,8 @@ internal void Fill(Settings value) { if (error != null) error.Visibility = Visibility.Collapsed; enabled.IsChecked = value.Enabled; clipboard.IsChecked = value.ClipboardFallback; - provider.SelectedIndex = value.TranslationProvider == "microsoft" ? 1 : value.TranslationProvider == "tencent" ? 2 : 0; + provider.SelectedIndex = value.TranslationProvider == "microsoft" ? 1 : value.TranslationProvider == "tencent" ? 2 : value.TranslationProvider == "deepl" ? 3 : 0; + deepLKey.Clear(); clearDeepLKey = false; RefreshDeepLStatus(); language.Text = LanguageLabel(value.Target); maxSelection.Text = value.MaxSelectionLength.ToString(CultureInfo.CurrentCulture); excludedApps.Text = AppsText(value.ExcludedApps); @@ -320,7 +340,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.TranslationProvider = provider.SelectedIndex == 1 ? "microsoft" : provider.SelectedIndex == 2 ? "tencent" : "auto"; + next.TranslationProvider = provider.SelectedIndex == 1 ? "microsoft" : provider.SelectedIndex == 2 ? "tencent" : provider.SelectedIndex == 3 ? "deepl" : "auto"; if (provider.SelectedIndex != 2 && language.Text != LanguageLabel(settings.Target)) { string choice = Languages.FirstOrDefault(x => x == language.Text); @@ -345,14 +365,33 @@ internal bool Apply(string path) next.BubbleFontFamily = BubbleAppearance.ResolveFont(fontFamily.SelectedItem as string).Source; next.BubbleFontSize = size; next.BubbleBackground = background.Text.Trim().ToUpperInvariant(); next.AutoHideSeconds = seconds; next.MinEnglishPercent = percent; + string newKey = deepLKey.Password.Trim(); + if (newKey.Length != 0 && !DeepLCredentials.ValidKey(newKey)) + return Invalid("API 密钥不能包含空白、换行或非 ASCII 字符。", deepLKey, 3); + Action credentialRollback = null; Action rollback = null; string startupError; if (startupDirty && !startup.TrySet(autoStart.IsChecked == true, out rollback, out startupError)) { RefreshAfterFailure(); return Invalid(startupError, autoStart, 2); } + try + { + if (clearDeepLKey || newKey.Length != 0) credentialRollback = credentials.Replace(clearDeepLKey ? null : newKey); + } + catch + { + string message = "无法保存 DeepL 密钥,请检查应用目录权限;设置未保存。"; + if (rollback != null) { try { rollback(); } catch { message += " 启动项恢复失败,请检查启动页。"; } } + RefreshAfterFailure(); return Invalid(message, deepLKey, 3); + } if (!next.TrySave(path)) { string message = "无法保存设置。请检查应用目录是否可写;当前配置未改变。"; + if (credentialRollback != null) + { + try { credentialRollback(); } + catch { message += " DeepL 密钥恢复失败,请检查 DeepL 页并重新保存或清除。"; } + } if (rollback != null) { try { rollback(); } @@ -383,6 +422,14 @@ internal void SetInputForTest(string size, string color, string seconds, string { fontSize.Text = size; background.Text = color; autoHide.Text = seconds; englishPercent.Text = percent; } internal void SetBehaviorForTest(bool on, bool capture, string target, string maximum, string apps) { enabled.IsChecked = on; clipboard.IsChecked = capture; language.Text = target; maxSelection.Text = maximum; excludedApps.Text = apps; } + private void RefreshDeepLStatus() + { + deepLStatus.Text = clearDeepLKey ? "待保存:清除密钥。" : deepLKey.Password.Length != 0 ? "待保存:替换密钥。" : credentials.Exists ? "已保存加密密钥(未验证)。" : "尚未配置密钥;DeepL 不会发起请求。"; + } + private void StageDeepLClear() { deepLKey.Clear(); clearDeepLKey = true; RefreshDeepLStatus(); } + internal void SetDeepLKeyForTest(string key) { deepLKey.Password = key; } + internal void ClearDeepLKeyForTest() { StageDeepLClear(); } + internal bool DeepLInputEmptyForTest { get { return deepLKey.Password.Length == 0; } } internal void SetProviderForTest(int value) { provider.SelectedIndex = value; } internal int ProviderForTest { get { return provider.SelectedIndex; } } internal bool TargetEnabledForTest { get { return language.IsEnabled; } } diff --git a/src/TranslationProviderTests.cs b/src/TranslationProviderTests.cs index 9fa4b11..f8af801 100644 --- a/src/TranslationProviderTests.cs +++ b/src/TranslationProviderTests.cs @@ -44,6 +44,7 @@ private static void Check(bool ok, string message) internal static void Run(Dictionary results) { + DeepLTests.Run(results); var handler = new Handler(); using (var translator = new Translator(handler)) { From 3c6a8626d6ada76bd1d7d3cf6fe5ed76bce63230 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:25:56 +0800 Subject: [PATCH 09/17] Read protected-clipboard selections in an isolated helper --- .github/workflows/build.yml | 4 ++ README.md | 5 +- build.ps1 | 4 ++ docs/TESTING.md | 31 ++++++++++-- helpers/SelectionHost.cs | 84 ++++++++++++++++++++++++++++++++ scripts/test-selection.ps1 | 14 ++++++ src/ClipboardCapture.cs | 11 ++++- src/ClipboardNativeTests.cs | 15 ++++++ src/IsolatedSelectionReader.cs | 50 +++++++++++++++++++ src/LightTranslate.cs | 18 ++++++- src/ReadingSettings.cs | 4 +- src/SelectionIntegrationTests.cs | 72 +++++++++++++++++++++++++++ 12 files changed, 299 insertions(+), 13 deletions(-) create mode 100644 helpers/SelectionHost.cs create mode 100644 scripts/test-selection.ps1 create mode 100644 src/IsolatedSelectionReader.cs create mode 100644 src/SelectionIntegrationTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 811501f..a5e298f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,12 +32,16 @@ jobs: - name: Run offline self-test shell: pwsh run: ./scripts/test.ps1 + - name: Real selection helper integration + shell: pwsh + run: ./scripts/test-selection.ps1 - name: Upload build uses: actions/upload-artifact@v4 with: name: LightTranslate-windows-x64 path: | dist/LightTranslate/LightTranslate.exe + dist/LightTranslate/LightTranslate.SelectionHost.exe dist/LightTranslate/LightTranslate.exe.config dist/LightTranslate/LightTranslate.ico dist/LightTranslate/lexicon.dat diff --git a/README.md b/README.md index cd24292..97fe263 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ 在托盘“译”图标上右键,选择 **设置…**。面板分为“翻译、浮层、启动、DeepL”四页,保存后生效: -- **翻译**:自动划词开关、剪贴板取词开关、在线服务及目标语言、单次选区长度上限、排除应用和最低英文占比。托盘开关会立即生效并同步到已打开的面板;面板中的改动在保存后应用。关闭剪贴板取词后不获取选区。目标语言影响微软和 DeepL;本地词库和腾讯仍输出中文。 +- **翻译**:自动划词开关、选区取词开关、在线服务及目标语言、单次选区长度上限、排除应用和最低英文占比。托盘开关会立即生效并同步到已打开的面板;面板中的改动在保存后应用。关闭选区取词后不获取选区。目标语言影响微软和 DeepL;本地词库和腾讯仍输出中文。 - **DeepL**:手动输入 API 密钥,输入遮挡且不回填。留空保留现有密钥,清除需点击“保存”;取消不改变密钥。密钥用 Windows 当前用户 DPAPI 加密,单独存入应用目录的 `deepl-key.bin`,不写入 `settings.json`。换用户或电脑需重新输入。保存设置不联网验证。 - **启动**:读取实际的当前用户启动项,显示当前目录是否开机自启;只有改变选择并保存时才创建或移除启动快捷方式。不写入 `settings.json` 的自启标志,也不默认开启自启。保存失败会显示错误;配置保存失败时会尝试恢复启动项,恢复失败会显示实际状态供检查。 @@ -85,7 +85,8 @@ pwsh -File .\startup.ps1 -Remove 选择 DeepL 并保存密钥后,选中文字将发送给 DeepL,可能按账户套餐计费;未配置密钥时不请求 DeepL。只使用官方 `POST /v2/translate`,按密钥的 `:fx` 标记选择 `api-free.deepl.com`,其余使用 `api.deepl.com`,不接受自定义地址或 HTTP 重定向。简繁中文对应 `ZH-HANS`、`ZH-HANT`。 额度和费用以 [DeepL 当前 API 套餐](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。 译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。 -取词通过临时复制选区完成,并尝试恢复原剪贴板;系统或剪贴板管理器可能保留复制记录。 +通常通过临时复制选区取词,并尝试恢复原剪贴板;系统或剪贴板管理器可能保留复制记录。 +剪贴板含图片或应用专用格式、无法安全备份时,改由独立的 `LightTranslate.SelectionHost.exe` 读取应用通过 Windows UI Automation 提供的选区,不复制、不改剪贴板。辅助进程限时退出,主程序不持有 UIA/COM 对象。应用不支持这种读取时显示明确提示,不清空剪贴板,也不退回 OLE 快照。分发或移动程序时请保留该辅助文件。 ## 从源码构建 diff --git a/build.ps1 b/build.ps1 index 2423b5a..8243907 100644 --- a/build.ps1 +++ b/build.ps1 @@ -21,6 +21,10 @@ $sourceFiles = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'src') -Fil ('/win32icon:' + (Join-Path $PSScriptRoot 'assets\LightTranslate.ico')) ` @references @sourceFiles if ($LASTEXITCODE -ne 0) { throw 'Compilation failed.' } +$helperReferences = @('System.dll','System.Core.dll') | ForEach-Object { '/r:' + (Join-Path $framework $_) } +$helperReferences += @('WindowsBase.dll','UIAutomationClient.dll','UIAutomationTypes.dll') | ForEach-Object { '/r:' + (Join-Path $framework ('WPF\' + $_)) } +& $compiler /nologo /target:exe /platform:x64 /optimize+ ('/out:' + (Join-Path $outputPath 'LightTranslate.SelectionHost.exe')) @helperReferences (Join-Path $PSScriptRoot 'helpers\SelectionHost.cs') +if ($LASTEXITCODE -ne 0) { throw 'Selection helper compilation failed.' } Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'src\LightTranslate.exe.config'), (Join-Path $PSScriptRoot 'LICENSE'), (Join-Path $PSScriptRoot 'README.md'), (Join-Path $PSScriptRoot 'THIRD_PARTY_NOTICES.md') -Destination $outputPath diff --git a/docs/TESTING.md b/docs/TESTING.md index 138a066..5505ca1 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,4 +1,4 @@ -# 开发与测试 +# 开发与测试 ## 构建、自检与打包 @@ -56,7 +56,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 | 字段 | 默认值 | 作用 | |---|---|---| | `Enabled` | `true` | 自动划词翻译开关,也可通过托盘修改 | -| `ClipboardFallback` | `true` | 剪贴板取词开关,关闭后停止取词 | +| `ClipboardFallback` | `true` | 选区取词开关,关闭后停止所有取词 | | `TranslationProvider` | `auto` | `auto` 保留本地词库优先、微软失败后腾讯;`microsoft` / `tencent` / `deepl` 仅调用选定服务并跳过词库 | | `Target` | `zh-Hans` | 微软 / DeepL 的目标语言;本地词库和腾讯输出中文 | | `MaxSelectionLength` | `2000` | 单次选区字符数上限 | @@ -73,7 +73,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 补充平面的字母按 Unicode 标量计一次,全角 Latin / 重音字母计入分母但不计英文分子。 大于 0% 时没有 A–Z/a–z 的文本不触发;0% 时无文字字母或纯中文仍被原有规则跳过。 -`ClipboardFallback` 沿用早期字段名,当前取词路径统一使用剪贴板。 +`ClipboardFallback` 沿用早期字段名,同时控制剪贴板取词和独立进程选区读取。 面板纳入 `Enabled`、`ClipboardFallback`、`Target`、`MaxSelectionLength`、`ExcludedApps` 和五项阅读选项。目标语言只校验修改后输入的语言标签语法,不联网获取语言列表;服务是否支持自定义标签由所选服务决定。 @@ -97,7 +97,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 ## 取词与数据处理 -程序使用带内部标记的 `Ctrl+C` 获取选区,并尝试保存、恢复原剪贴板的各格式。 +程序优先使用带内部标记的 `Ctrl+C` 获取选区,快照仅接受支持的文本格式。原剪贴板无法完整安全备份时,改由独立进程读取 UIA 选区,保留剪贴板原内容。 如果用户或其他应用在取词期间更新了剪贴板,程序会避免覆盖新的内容。 系统剪贴板历史和第三方剪贴板管理器仍可能保留临时复制记录。 @@ -162,7 +162,7 @@ delayed rendering. Both commands run in CI; neither needs the dictionary. Capture now accepts only HGLOBAL text formats (Unicode/ANSI/OEM text, locale, HTML Format and Rich Text Format), at most 64 formats, 8 MiB per format and -16 MiB total. Unknown or incomplete snapshots skip the selection before Ctrl+C; +16 MiB total. Unknown or incomplete snapshots bypass Ctrl+C and try the isolated selection helper; images, file lists and application-private formats are not silently discarded. Delayed rendering may cause a snapshot to be skipped when its version changes. A slow native clipboard owner can still delay GetClipboardData. Restore checks @@ -241,3 +241,24 @@ quota exhaustion, 429, invalid targets, request size, malformed responses, timeo network failure, cancellation, stale responses, and save/clear/cancel/reopen/rollback. No live DeepL account, registration, key validation or billed request is exercised. The generated settings previews show an empty credential field. + + +## 图片或专用格式剪贴板下的选区读取 + +仅允许文本快照的守卫会拒绝图片和应用专用格式。这是保护原剪贴板所需的行为, +但不能因此让划词静默失效。快照失败时,现在通过短时独立进程 +`LightTranslate.SelectionHost.exe` 请求应用的 UIA TextPattern 选区,不读取或修改剪贴板。 +主程序仍不引用 UIAutomationClient,不持有跨进程 UIA/COM 对象,也不恢复原 OLE 快照路径。 +辅助进程只接受源窗口、焦点窗口句柄和长度上限,验证窗口归属并拒绝密码字段; +选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 1.5 秒的自身终止期限, +主程序异步等待上限为 2.2 秒,并丢弃已取消或焦点改变后的响应。 +这不是权限沙箱;它隔离 UIA 原生故障,不会终止用户源应用或轻译主进程。 +无法安全读取、辅助程序缺失或超时时,浮层提示取词失败并保留剪贴板。 + +`./scripts/test-selection.ps1` 使用真实 Windows 编辑控件和真实外部辅助进程, +合成选区经过拒绝备份分支、选区读取、英文比例检查,最终命中本地词典。 +它同时验证空选区、密码框、错误源窗口、取消和输出长度上限,不调用在线翻译, +不读取用户剪贴板内容,也不改变用户窗口焦点;只记录剪贴板序列号是否保持不变。 +`./scripts/test-clipboard.ps1 -Native` 在私有 window station 中额外验证真实编辑控件的 +复制命令、原生快照恢复,以及专用格式不会被覆盖;所有数据均为合成数据。 +这些测试不等于已验证每个浏览器、Word、管理员权限窗口或远程桌面的实际兼容性。 diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs new file mode 100644 index 0000000..e5b1c0e --- /dev/null +++ b/helpers/SelectionHost.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Windows.Automation; + +// A short-lived process owns every UIA/COM object. No clipboard API, file output or network. +internal static class SelectionHost +{ + private static Timer deadline; + [MTAThread] + private static int Main(string[] args) + { + // Keep the deadline alive through COM finalization; it may only end this helper. + deadline = new Timer(delegate { TerminateProcess(new IntPtr(-1), 3); }, null, 1500, Timeout.Infinite); + try + { + long rootValue, focusValue; int maximum; + if (args.Length != 3 || !long.TryParse(args[0], out rootValue) || !long.TryParse(args[1], out focusValue) + || !int.TryParse(args[2], out maximum) || maximum < 1 || maximum > 65537) return 2; + IntPtr root = new IntPtr(rootValue), focus = new IntPtr(focusValue); + if (root == IntPtr.Zero || focus == IntPtr.Zero || GetAncestor(focus, 2) != root) return 2; + if (GetForegroundWindow() == root) + { + var current = AutomationElement.FocusedElement; + if (current != null && current.Current.IsPassword) return 0; + } + var element = AutomationElement.FromHandle(focus); + if (element == null || element.Current.IsPassword) return 0; + string text = Read(element, maximum); + // Browsers can expose their actual focused document below the native HWND. + if (string.IsNullOrEmpty(text) && GetForegroundWindow() == root) + { + var focused = AutomationElement.FocusedElement; + if (focused != null && !focused.Current.IsPassword && BelongsTo(focused, root)) + { + for (int i = 0; i < 8 && focused != null; i++) + { + if (focused.Current.IsPassword || !BelongsTo(focused, root)) break; + text = Read(focused, maximum); + if (!string.IsNullOrEmpty(text)) break; + focused = TreeWalker.ControlViewWalker.GetParent(focused); + } + } + } + if (!string.IsNullOrEmpty(text)) + { + Console.OutputEncoding = new UTF8Encoding(false); + Console.Write(text); + } + return 0; + } + catch { return 2; } + } + private static bool BelongsTo(AutomationElement element, IntPtr root) + { + for (int i = 0; i < 32 && element != null; i++) + { + int handle = element.Current.NativeWindowHandle; + if (handle != 0) return GetAncestor(new IntPtr(handle), 2) == root; + element = TreeWalker.ControlViewWalker.GetParent(element); + } + return false; + } + private static string Read(AutomationElement element, int maximum) + { + if (element.Current.IsPassword) return null; + object value; + if (!element.TryGetCurrentPattern(TextPattern.Pattern, out value)) return null; + var ranges = ((TextPattern)value).GetSelection(); + if (ranges == null || ranges.Length == 0 || ranges.Length > 8) return null; + var text = new StringBuilder(); + foreach (var range in ranges) + { + if (text.Length != 0) text.Append('\n'); + if (text.Length >= maximum) break; + text.Append(range.GetText(maximum - text.Length)); + } + return text.ToString(); + } + [DllImport("kernel32.dll")] private static extern bool TerminateProcess(IntPtr process, uint code); + [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr window, uint flags); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); +} diff --git a/scripts/test-selection.ps1 b/scripts/test-selection.ps1 new file mode 100644 index 0000000..b11a799 --- /dev/null +++ b/scripts/test-selection.ps1 @@ -0,0 +1,14 @@ +[CmdletBinding()] +param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\LightTranslate')) +$ErrorActionPreference = 'Stop' +$outputPath = [System.IO.Path]::GetFullPath($OutputDirectory) +$test = Start-Process -FilePath (Join-Path $outputPath 'LightTranslate.exe') -ArgumentList '--self-test-selection' -WindowStyle Hidden -PassThru +if (-not $test.WaitForExit(30000)) { + Stop-Process -Id $test.Id -Force + throw 'Selection integration test timed out.' +} +if ($test.ExitCode -ne 0) { + Get-Content -LiteralPath (Join-Path $outputPath 'status.log') -Tail 10 + throw 'Selection integration test failed.' +} +Get-Content -LiteralPath (Join-Path $outputPath 'selection-integration-test.json') diff --git a/src/ClipboardCapture.cs b/src/ClipboardCapture.cs index eb80645..00ff1f6 100644 --- a/src/ClipboardCapture.cs +++ b/src/ClipboardCapture.cs @@ -30,14 +30,21 @@ 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 valid, Action copy, Action trace, Func wait, Func> withoutClipboard = null) { // Do not queue stale selections or snapshot another capture's temporary clipboard. if (!gate.Wait(0)) { trace("copy skipped busy"); return null; } try { ClipboardSnapshot saved; - if (!valid() || !clipboard.TrySnapshot(out saved)) { trace("clipboard snapshot skipped"); return null; } + if (!valid()) return null; + if (!clipboard.TrySnapshot(out saved)) + { + trace("clipboard snapshot skipped"); + if (withoutClipboard == null || !valid()) return null; + string selected = await withoutClipboard(); + return valid() ? selected : null; + } if (!valid() || clipboard.Sequence != saved.Sequence) return null; copy(); for (int i = 0; i < 12; i++) diff --git a/src/ClipboardNativeTests.cs b/src/ClipboardNativeTests.cs index f80e932..fe9f04d 100644 --- a/src/ClipboardNativeTests.cs +++ b/src/ClipboardNativeTests.cs @@ -100,6 +100,21 @@ private static void RunCases(IntPtr desktop) uint html = ClipboardNative.RegisterClipboardFormat("HTML Format"); uint rtf = ClipboardNative.RegisterClipboardFormat("Rich Text Format"); uint unknown = ClipboardNative.RegisterClipboardFormat("LightTranslate unsupported fixture"); + // Exercise real edit-control copy on the private clipboard. + // UIA integration runs separately without any clipboard payload access. + using (var form = new Forms.Form()) + using (var edit = new Forms.TextBox { Multiline = true, Text = "prefix reversible suffix" }) + { + form.Controls.Add(edit); + IntPtr root = form.Handle, focus = edit.Handle; + edit.Select(7, 10); + Put(clipboard.Handle, Text("original fixture")); + string capturedText = SelectionIntegrationTests.Pump(ClipboardCapture.Read(clipboard, root, + delegate { return true; }, edit.Copy, delegate { }, delegate { return System.Threading.Tasks.Task.Delay(15); })); + Check(capturedText == "reversible", "real edit copy -> native capture -> restore"); + ClipboardSnapshot checkOriginal; + Check(clipboard.TrySnapshot(out checkOriginal) && checkOriginal.Formats.Any(x => x.Key == 13 && NativeSelectionClipboard.DecodeUnicode(x.Value) == "original fixture"), "real edit copy restores original"); + } Put(clipboard.Handle, Text("original"), new KeyValuePair(html, Encoding.UTF8.GetBytes("original\0")), new KeyValuePair(rtf, Encoding.ASCII.GetBytes("{\\rtf1 original}\0"))); ClipboardSnapshot original; diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs new file mode 100644 index 0000000..d43418d --- /dev/null +++ b/src/IsolatedSelectionReader.cs @@ -0,0 +1,50 @@ +using System; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace LightTranslate +{ + internal sealed class SelectionUnavailableException : Exception + { + internal SelectionUnavailableException(string message = "剪贴板无法安全备份,已保留原内容;当前应用暂时无法读取选区。") : base(message) { } + } + internal static class IsolatedSelectionReader + { + internal static async Task Read(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr)) + { + ct.ThrowIfCancellationRequested(); + if (focus == IntPtr.Zero) + { + uint pid; + uint thread = Native.GetWindowThreadProcessId(window, out pid); + var info = new Native.GUITHREADINFO { size = (uint)Marshal.SizeOf(typeof(Native.GUITHREADINFO)) }; + if (!Native.GetGUIThreadInfo(thread, ref info)) return null; + focus = info.focus; + } + string path = Path.Combine(Program.Folder, "LightTranslate.SelectionHost.exe"); + if (focus == IntPtr.Zero || !File.Exists(path)) return null; + var start = new ProcessStartInfo(path, window.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + focus.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + maximum.ToString(CultureInfo.InvariantCulture)) + { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, StandardOutputEncoding = Encoding.UTF8 }; + try + { + using (var process = Process.Start(start)) + { + var output = process.StandardOutput.ReadToEndAsync(); + // The helper self-exits on timeout; never terminate the user's application. + bool exited = await Task.Run(delegate { return process.WaitForExit(2200); }); + ct.ThrowIfCancellationRequested(); + if (!exited || process.ExitCode != 0) return null; + string text = await output; + return text.Length <= maximum ? text : null; + } + } + catch (OperationCanceledException) { throw; } + catch { return null; } + } + } +} diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 7fd17e7..7dc8815 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-tray") return TrayIconRenderer.RunStandalone(); + if (args.Length > 0 && args[0] == "--self-test-selection") return SelectionIntegrationTests.Run(); if (args.Length > 0 && args[0] == "--self-test") return SelfTest.Run(false); if (args.Length > 0 && args[0] == "--self-test-offline") return SelfTest.Run(true); bool created; @@ -369,7 +370,12 @@ private async void BeginSelection(IntPtr window, Native.POINT point) catch (Exception ex) { Program.Log("translate", ex.GetType().Name); - if (Valid(version, window)) ShowText(ex is DeepLException ? ex.Message : "暂时无法连接翻译服务", point, ex is DeepLException ? 6 : 3); + bool explained = ex is DeepLException || ex is SelectionUnavailableException; + if (Valid(version, window)) + { + anchor = point; sourceWindow = window; + ShowText(explained ? ex.Message : "暂时无法连接翻译服务", point, explained ? 6 : 3); + } } finally { @@ -690,7 +696,15 @@ public static async Task CopySelection(IntPtr window, CancellationToken using (var clipboard = new NativeSelectionClipboard()) return await ClipboardCapture.Read(clipboard, window, delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }, - Native.Copy, trace, delegate { return Task.Delay(15); }); + Native.Copy, trace, delegate { return Task.Delay(15); }, async delegate + { + string text = await IsolatedSelectionReader.Read(window, ct); + if (text != null && text.Length >= 65537) throw new SelectionUnavailableException("选中文字较长,请分段选择"); + if (!ct.IsCancellationRequested && Native.GetForegroundWindow() == window && string.IsNullOrEmpty(text)) + throw new SelectionUnavailableException(); + trace("selection helper chars=" + (text == null ? 0 : text.Length)); + return text; + }); } } diff --git a/src/ReadingSettings.cs b/src/ReadingSettings.cs index c0ef9cf..cc56172 100644 --- a/src/ReadingSettings.cs +++ b/src/ReadingSettings.cs @@ -139,9 +139,9 @@ internal SettingsWindow(Settings settings, Action saved, IStartupRegistration st var translation = NewTab("翻译"); enabled = Toggle("自动划词翻译"); - clipboard = Toggle("通过剪贴板获取选中文字"); + clipboard = Toggle("启用选区取词"); translation.Children.Add(enabled); translation.Children.Add(clipboard); - translation.Children.Add(Help("托盘开关立即生效并同步到这里;面板修改在保存后生效。当前仅支持剪贴板取词;关闭后停止划词翻译。取词会临时复制选区;剪贴板含不支持的格式时跳过,不覆盖原内容。")); + translation.Children.Add(Help("托盘开关立即生效;面板修改在保存后生效。关闭取词后停止划词翻译。通常临时复制选区并恢复剪贴板;若含图片或专用数据,则尝试隔离读取选区,不改剪贴板。无法安全读取时会提示。")); provider = new ComboBox { ItemsSource = new[] { "自动(微软失败后腾讯)", "仅微软", "仅腾讯(中文)", "仅 DeepL(自备 API 密钥)" }, MinHeight = 32 }; AddField(translation, "在线翻译服务", provider); translation.Children.Add(Help("自动模式先查本地英汉词库,再尝试微软、腾讯;指定服务会跳过词库且不自动切换。DeepL 须在 DeepL 页保存密钥;自动模式不会调用 DeepL。")); diff --git a/src/SelectionIntegrationTests.cs b/src/SelectionIntegrationTests.cs new file mode 100644 index 0000000..5b53fd3 --- /dev/null +++ b/src/SelectionIntegrationTests.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + internal static class SelectionIntegrationTests + { + // Real native edit controls and the real external UIA process; no user clipboard payload. + private sealed class ProtectedClipboard : ISelectionClipboard + { + internal int Copies, Reads, Restores; + public uint Sequence { get { return 1; } } + public bool TrySnapshot(out ClipboardSnapshot snapshot) { snapshot = null; return false; } + public bool TryReadText(IntPtr source, uint expected, out uint sequence, out string text) + { Reads++; sequence = 0; text = null; throw new Exception("Protected clipboard must not be read"); } + public RestoreResult Restore(ClipboardSnapshot snapshot, uint expected, Func valid) + { Restores++; throw new Exception("Protected clipboard must not be restored"); } + } + internal static T Pump(Task task) + { + DateTime until = DateTime.UtcNow.AddSeconds(5); + while (!task.IsCompleted && DateTime.UtcNow < until) { Forms.Application.DoEvents(); Thread.Sleep(5); } + if (!task.IsCompleted) throw new Exception("Selection integration timed out"); + return task.GetAwaiter().GetResult(); + } + internal static int Run() + { + uint before = Native.GetClipboardSequenceNumber(); + var results = new Dictionary(); + using (var form = new Forms.Form()) + using (var text = new Forms.TextBox { Multiline = true, Text = "prefix reversible suffix" }) + { + form.Controls.Add(text); + IntPtr root = form.Handle, focus = text.Handle; + text.Select(7, 10); + var clipboard = new ProtectedClipboard(); + string selected = Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, + delegate { clipboard.Copies++; }, delegate { }, delegate { return Task.Delay(15); }, + delegate { return IsolatedSelectionReader.Read(root, CancellationToken.None, 2001, focus); })); + ClipboardCaptureTests.Check(selected == "reversible", "real edit selection through protected clipboard fallback"); + ClipboardCaptureTests.Check(clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0, "protected clipboard untouched"); + ClipboardCaptureTests.Check(SelectionReader.ShouldTranslate(selected, 25), "selected English passes real language gate"); + using (var lexicon = new Lexicon(Program.Folder)) + ClipboardCaptureTests.Check((lexicon.Lookup(selected) ?? "").Contains("逆"), "selected text reaches local dictionary without network"); + text.Select(0, 0); + ClipboardCaptureTests.Check(string.IsNullOrEmpty(Pump(IsolatedSelectionReader.Read(root, CancellationToken.None, 2001, focus))), "empty selection stays empty"); + text.Select(0, text.TextLength); + ClipboardCaptureTests.Check(Pump(IsolatedSelectionReader.Read(root, CancellationToken.None, 8, focus)).Length == 8, "bounded selection output"); + text.UseSystemPasswordChar = true; + ClipboardCaptureTests.Check(string.IsNullOrEmpty(Pump(IsolatedSelectionReader.Read(root, CancellationToken.None, 2001, text.Handle))), "password selection rejected"); + using (var other = new Forms.Form()) + ClipboardCaptureTests.Check(string.IsNullOrEmpty(Pump(IsolatedSelectionReader.Read(other.Handle, CancellationToken.None, 2001, text.Handle))), "wrong root rejected"); + using (var canceled = new CancellationTokenSource()) + { + canceled.Cancel(); bool stopped = false; + try { Pump(IsolatedSelectionReader.Read(root, canceled.Token, 2001, text.Handle)); } + catch (OperationCanceledException) { stopped = true; } + ClipboardCaptureTests.Check(stopped, "canceled selection rejected"); + } + } + results["selectionIntegration"] = "real Windows edit selection -> external UIA helper -> protected clipboard fallback -> language gate -> local dictionary; empty/password/wrong-root/canceled/length cases passed; no network or clipboard contents accessed"; + results["clipboardSequenceUnchanged"] = before == Native.GetClipboardSequenceNumber(); + File.WriteAllText(Path.Combine(Program.Folder, "selection-integration-test.json"), new JavaScriptSerializer().Serialize(results)); + return 0; + } + } +} From 1bdf9d39db7ba2dd8a37502e1dd310a0f63091a6 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:58:42 +0800 Subject: [PATCH 10/17] Follow the pointer target when web selection differs from keyboard focus --- build.ps1 | 2 +- docs/TESTING.md | 10 +++++++ helpers/SelectionHost.cs | 53 ++++++++++++++++++++++++---------- src/IsolatedSelectionReader.cs | 25 +++++++++++----- src/LightTranslate.cs | 6 ++-- 5 files changed, 68 insertions(+), 28 deletions(-) diff --git a/build.ps1 b/build.ps1 index 8243907..026a016 100644 --- a/build.ps1 +++ b/build.ps1 @@ -23,7 +23,7 @@ $sourceFiles = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'src') -Fil if ($LASTEXITCODE -ne 0) { throw 'Compilation failed.' } $helperReferences = @('System.dll','System.Core.dll') | ForEach-Object { '/r:' + (Join-Path $framework $_) } $helperReferences += @('WindowsBase.dll','UIAutomationClient.dll','UIAutomationTypes.dll') | ForEach-Object { '/r:' + (Join-Path $framework ('WPF\' + $_)) } -& $compiler /nologo /target:exe /platform:x64 /optimize+ ('/out:' + (Join-Path $outputPath 'LightTranslate.SelectionHost.exe')) @helperReferences (Join-Path $PSScriptRoot 'helpers\SelectionHost.cs') +& $compiler /nologo /target:exe /platform:x64 /optimize+ ('/out:' + (Join-Path $outputPath 'LightTranslate.SelectionHost.exe')) ('/win32manifest:' + (Join-Path $PSScriptRoot 'src\LightTranslate.manifest')) @helperReferences (Join-Path $PSScriptRoot 'helpers\SelectionHost.cs') if ($LASTEXITCODE -ne 0) { throw 'Selection helper 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 5505ca1..48d5975 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -262,3 +262,13 @@ The generated settings previews show an empty credential field. `./scripts/test-clipboard.ps1 -Native` 在私有 window station 中额外验证真实编辑控件的 复制命令、原生快照恢复,以及专用格式不会被覆盖;所有数据均为合成数据。 这些测试不等于已验证每个浏览器、Word、管理员权限窗口或远程桌面的实际兼容性。 + +### Chromium 选区定位 + +鼠标拖选网页文字不一定把键盘焦点移到该文档。辅助进程优先从鼠标释放位置的 +UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘焦点;每一步验证 +源窗口归属,最多查找 32 层,并保留独立进程的总超时限制。它不扫描其他文档、 +不读整个页面或 ValuePattern,也不修改 Chromium 的可访问性设置。 +主程序仅记录固定失败码,例如无 TextPattern、空选区、密码字段、窗口不符、 +深度上限、提供方异常和超时;不记录控件名称、选区原文或页面内容。 +真实控件测试不覆盖网页布局、iframe 与键盘焦点差异,仍须进行实际拖选验收。 \ No newline at end of file diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs index e5b1c0e..d4dcc23 100644 --- a/helpers/SelectionHost.cs +++ b/helpers/SelectionHost.cs @@ -8,49 +8,69 @@ internal static class SelectionHost { private static Timer deadline; + private static string status = "no-text-pattern"; [MTAThread] private static int Main(string[] args) { // Keep the deadline alive through COM finalization; it may only end this helper. - deadline = new Timer(delegate { TerminateProcess(new IntPtr(-1), 3); }, null, 1500, Timeout.Infinite); + deadline = new Timer(delegate { try { Console.Error.WriteLine("deadline"); } catch { } TerminateProcess(new IntPtr(-1), 3); }, null, 1500, Timeout.Infinite); try { long rootValue, focusValue; int maximum; - if (args.Length != 3 || !long.TryParse(args[0], out rootValue) || !long.TryParse(args[1], out focusValue) + if ((args.Length != 3 && args.Length != 5) || !long.TryParse(args[0], out rootValue) || !long.TryParse(args[1], out focusValue) || !int.TryParse(args[2], out maximum) || maximum < 1 || maximum > 65537) return 2; IntPtr root = new IntPtr(rootValue), focus = new IntPtr(focusValue); - if (root == IntPtr.Zero || focus == IntPtr.Zero || GetAncestor(focus, 2) != root) return 2; + if (root == IntPtr.Zero || focus == IntPtr.Zero || GetAncestor(focus, 2) != root) { Console.Error.WriteLine("wrong-root"); return 2; } if (GetForegroundWindow() == root) { var current = AutomationElement.FocusedElement; - if (current != null && current.Current.IsPassword) return 0; + if (current != null && current.Current.IsPassword) { Console.Error.WriteLine("password"); return 0; } } var element = AutomationElement.FromHandle(focus); - if (element == null || element.Current.IsPassword) return 0; - string text = Read(element, maximum); + if (element == null || element.Current.IsPassword) { Console.Error.WriteLine("password"); return 0; } + string text = null; + // Selecting web text need not move keyboard focus into that document/iframe. + // The release point identifies the selected surface without scanning other documents. + if (args.Length == 5 && GetForegroundWindow() == root) + { + int x, y; + if (!int.TryParse(args[3], out x) || !int.TryParse(args[4], out y)) return 2; + text = ReadAncestors(AutomationElement.FromPoint(new System.Windows.Point(x, y)), root, maximum); + if (status == "password") { Console.Error.WriteLine("password"); return 0; } + } + if (string.IsNullOrEmpty(text)) text = Read(element, maximum); // Browsers can expose their actual focused document below the native HWND. if (string.IsNullOrEmpty(text) && GetForegroundWindow() == root) { var focused = AutomationElement.FocusedElement; if (focused != null && !focused.Current.IsPassword && BelongsTo(focused, root)) - { - for (int i = 0; i < 8 && focused != null; i++) - { - if (focused.Current.IsPassword || !BelongsTo(focused, root)) break; - text = Read(focused, maximum); - if (!string.IsNullOrEmpty(text)) break; - focused = TreeWalker.ControlViewWalker.GetParent(focused); - } - } + text = ReadAncestors(focused, root, maximum); } if (!string.IsNullOrEmpty(text)) { Console.OutputEncoding = new UTF8Encoding(false); Console.Write(text); } + else Console.Error.WriteLine(status); return 0; } - catch { return 2; } + catch { Console.Error.WriteLine("provider-error"); return 2; } + } + private static string ReadAncestors(AutomationElement element, IntPtr root, int maximum) + { + // Chromium can put many layout groups between focus and its Document. + // Stay within the source window, with a depth bound and process deadline. + for (int i = 0; i < 32 && element != null; i++) + { + if (element.Current.IsPassword) { status = "password"; return null; } + if (!BelongsTo(element, root)) return null; + string text = Read(element, maximum); + if (!string.IsNullOrEmpty(text)) return text; + if (element.Current.NativeWindowHandle == root.ToInt64()) return null; + element = TreeWalker.ControlViewWalker.GetParent(element); + } + if (element != null) status = "depth-limit"; + return null; } private static bool BelongsTo(AutomationElement element, IntPtr root) { @@ -67,6 +87,7 @@ private static string Read(AutomationElement element, int maximum) if (element.Current.IsPassword) return null; object value; if (!element.TryGetCurrentPattern(TextPattern.Pattern, out value)) return null; + status = "empty-selection"; var ranges = ((TextPattern)value).GetSelection(); if (ranges == null || ranges.Length == 0 || ranges.Length > 8) return null; var text = new StringBuilder(); diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index d43418d..acfbd32 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -15,7 +15,7 @@ internal SelectionUnavailableException(string message = "剪贴板无法安全 } internal static class IsolatedSelectionReader { - internal static async Task Read(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr)) + internal static async Task Read(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null) { ct.ThrowIfCancellationRequested(); if (focus == IntPtr.Zero) @@ -23,28 +23,37 @@ internal static class IsolatedSelectionReader uint pid; uint thread = Native.GetWindowThreadProcessId(window, out pid); var info = new Native.GUITHREADINFO { size = (uint)Marshal.SizeOf(typeof(Native.GUITHREADINFO)) }; - if (!Native.GetGUIThreadInfo(thread, ref info)) return null; - focus = info.focus; + // Missing native focus does not mean the foreground document has no UIA selection. + focus = Native.GetGUIThreadInfo(thread, ref info) && info.focus != IntPtr.Zero ? info.focus : window; } string path = Path.Combine(Program.Folder, "LightTranslate.SelectionHost.exe"); - if (focus == IntPtr.Zero || !File.Exists(path)) return null; - var start = new ProcessStartInfo(path, window.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + focus.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + maximum.ToString(CultureInfo.InvariantCulture)) - { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, StandardOutputEncoding = Encoding.UTF8 }; + if (focus == IntPtr.Zero || !File.Exists(path)) { Program.Log("selection-helper", "missing-helper-or-window"); return null; } + string arguments = window.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + focus.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + maximum.ToString(CultureInfo.InvariantCulture); + if (point.HasValue) arguments += " " + point.Value.x.ToString(CultureInfo.InvariantCulture) + " " + point.Value.y.ToString(CultureInfo.InvariantCulture); + var start = new ProcessStartInfo(path, arguments) + { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8 }; try { using (var process = Process.Start(start)) { var output = process.StandardOutput.ReadToEndAsync(); + var diagnostic = process.StandardError.ReadToEndAsync(); // The helper self-exits on timeout; never terminate the user's application. bool exited = await Task.Run(delegate { return process.WaitForExit(2200); }); ct.ThrowIfCancellationRequested(); - if (!exited || process.ExitCode != 0) return null; + if (!exited) { Program.Log("selection-helper", "wait-timeout"); return null; } + string status = (await diagnostic).Trim(); + // Only fixed status codes enter logs, never provider text or selected content. + if (status != "no-text-pattern" && status != "empty-selection" && status != "password" + && status != "wrong-root" && status != "deadline" && status != "provider-error" && status != "depth-limit") status = "unknown"; + if (process.ExitCode != 0) { Program.Log("selection-helper", "exit=" + process.ExitCode + " status=" + status); return null; } string text = await output; + if (string.IsNullOrEmpty(text)) Program.Log("selection-helper", "status=" + status); return text.Length <= maximum ? text : null; } } catch (OperationCanceledException) { throw; } - catch { return null; } + catch { Program.Log("selection-helper", "launch-or-pipe-error"); return null; } } } } diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 7dc8815..bef4e71 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -339,7 +339,7 @@ private async void BeginSelection(IntPtr window, Native.POINT point) // Capture through the clipboard without UIAutomationClient handles. // Native UIA pattern finalizers caused an access violation during testing. if (!settings.ClipboardFallback || SelectionReader.IsTerminal(processName)) return; - string text = await SelectionReader.CopySelection(window, ct, Trace); + string text = await SelectionReader.CopySelection(window, ct, Trace, 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(); @@ -689,7 +689,7 @@ 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) + public static async Task CopySelection(IntPtr window, CancellationToken ct, Action trace, Native.POINT? point = null) { if (Native.GetForegroundWindow() != window || Native.ModifierDown()) { trace("copy skipped focus/modifier"); return null; } if (Native.IsPasswordFocus(window)) { trace("password field skipped"); return null; } @@ -698,7 +698,7 @@ public static async Task CopySelection(IntPtr window, CancellationToken delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }, Native.Copy, trace, delegate { return Task.Delay(15); }, async delegate { - string text = await IsolatedSelectionReader.Read(window, ct); + string text = await IsolatedSelectionReader.Read(window, ct, point: point); if (text != null && text.Length >= 65537) throw new SelectionUnavailableException("选中文字较长,请分段选择"); if (!ct.IsCancellationRequested && Native.GetForegroundWindow() == window && string.IsNullOrEmpty(text)) throw new SelectionUnavailableException(); From de5c17994280e4fd05880a9756b5e914a6e226ca Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:59:53 +0800 Subject: [PATCH 11/17] Clarify pointer coordinates in selection helper documentation --- docs/TESTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 48d5975..9da83f7 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -249,7 +249,7 @@ The generated settings previews show an empty credential field. 但不能因此让划词静默失效。快照失败时,现在通过短时独立进程 `LightTranslate.SelectionHost.exe` 请求应用的 UIA TextPattern 选区,不读取或修改剪贴板。 主程序仍不引用 UIAutomationClient,不持有跨进程 UIA/COM 对象,也不恢复原 OLE 快照路径。 -辅助进程只接受源窗口、焦点窗口句柄和长度上限,验证窗口归属并拒绝密码字段; +辅助进程只接受源窗口、焦点窗口句柄、鼠标释放位置和长度上限,验证窗口归属并拒绝密码字段; 选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 1.5 秒的自身终止期限, 主程序异步等待上限为 2.2 秒,并丢弃已取消或焦点改变后的响应。 这不是权限沙箱;它隔离 UIA 原生故障,不会终止用户源应用或轻译主进程。 @@ -271,4 +271,4 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 不读整个页面或 ValuePattern,也不修改 Chromium 的可访问性设置。 主程序仅记录固定失败码,例如无 TextPattern、空选区、密码字段、窗口不符、 深度上限、提供方异常和超时;不记录控件名称、选区原文或页面内容。 -真实控件测试不覆盖网页布局、iframe 与键盘焦点差异,仍须进行实际拖选验收。 \ No newline at end of file +真实控件测试不覆盖网页布局、iframe 与键盘焦点差异,仍须进行实际拖选验收。 From 92d79ab8c18a128da011cd1abf69fb9292fda0a6 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:02:44 +0800 Subject: [PATCH 12/17] Allow bounded time for cold UIA provider initialization --- docs/TESTING.md | 4 ++-- helpers/SelectionHost.cs | 2 +- src/IsolatedSelectionReader.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 9da83f7..62155a9 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -250,8 +250,8 @@ The generated settings previews show an empty credential field. `LightTranslate.SelectionHost.exe` 请求应用的 UIA TextPattern 选区,不读取或修改剪贴板。 主程序仍不引用 UIAutomationClient,不持有跨进程 UIA/COM 对象,也不恢复原 OLE 快照路径。 辅助进程只接受源窗口、焦点窗口句柄、鼠标释放位置和长度上限,验证窗口归属并拒绝密码字段; -选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 1.5 秒的自身终止期限, -主程序异步等待上限为 2.2 秒,并丢弃已取消或焦点改变后的响应。 +选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 3 秒的自身终止期限, +主程序异步等待上限为 3.8 秒,并丢弃已取消或焦点改变后的响应。 这不是权限沙箱;它隔离 UIA 原生故障,不会终止用户源应用或轻译主进程。 无法安全读取、辅助程序缺失或超时时,浮层提示取词失败并保留剪贴板。 diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs index d4dcc23..1d76c6b 100644 --- a/helpers/SelectionHost.cs +++ b/helpers/SelectionHost.cs @@ -13,7 +13,7 @@ internal static class SelectionHost private static int Main(string[] args) { // Keep the deadline alive through COM finalization; it may only end this helper. - deadline = new Timer(delegate { try { Console.Error.WriteLine("deadline"); } catch { } TerminateProcess(new IntPtr(-1), 3); }, null, 1500, Timeout.Infinite); + deadline = new Timer(delegate { try { Console.Error.WriteLine("deadline"); } catch { } TerminateProcess(new IntPtr(-1), 3); }, null, 3000, Timeout.Infinite); try { long rootValue, focusValue; int maximum; diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index acfbd32..3dbc78d 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -39,7 +39,7 @@ internal static class IsolatedSelectionReader var output = process.StandardOutput.ReadToEndAsync(); var diagnostic = process.StandardError.ReadToEndAsync(); // The helper self-exits on timeout; never terminate the user's application. - bool exited = await Task.Run(delegate { return process.WaitForExit(2200); }); + bool exited = await Task.Run(delegate { return process.WaitForExit(3800); }); ct.ThrowIfCancellationRequested(); if (!exited) { Program.Log("selection-helper", "wait-timeout"); return null; } string status = (await diagnostic).Trim(); From 90d5dc2a3fe9c81255aec827978fbe1b94d9d9a8 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:27:09 +0800 Subject: [PATCH 13/17] Reject window manipulation before selection capture --- .github/workflows/build.yml | 3 ++ docs/TESTING.md | 14 ++++++ scripts/test-gestures.ps1 | 14 ++++++ src/LightTranslate.cs | 28 ++++++----- src/SelectionGesture.cs | 69 +++++++++++++++++++++++++++ src/SelectionGestureTests.cs | 90 ++++++++++++++++++++++++++++++++++++ 6 files changed, 207 insertions(+), 11 deletions(-) create mode 100644 scripts/test-gestures.ps1 create mode 100644 src/SelectionGesture.cs create mode 100644 src/SelectionGestureTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a5e298f..61689d9 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: Native window gesture boundaries + shell: pwsh + run: ./scripts/test-gestures.ps1 - name: Translation providers and DeepL offline regression shell: pwsh run: ./scripts/test-providers.ps1 diff --git a/docs/TESTING.md b/docs/TESTING.md index 62155a9..d64f1d0 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -272,3 +272,17 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 主程序仅记录固定失败码,例如无 TextPattern、空选区、密码字段、窗口不符、 深度上限、提供方异常和超时;不记录控件名称、选区原文或页面内容。 真实控件测试不覆盖网页布局、iframe 与键盘焦点差异,仍须进行实际拖选验收。 + +### 窗口操作与文字拖选的边界 + +鼠标按下、松开时,输入线程只记录窗口句柄、客户区位置、窗口边界和控件类名。 +取词前排除非客户区、原生滚动条、跨窗口拖动,以及期间发生的窗口移动或缩放; +客户区内的自绘标题栏再由带 25 毫秒时限的 WM_NCHITTEST 检查排除。 +命中测试在 UI 调度线程执行,不在全局鼠标钩子中发送跨进程消息。 +不合格的手势不会进入选区读取、剪贴板快照、复制或翻译路径,也不会成为下一次双击的起点。 + +`./scripts/test-gestures.ps1` 使用自有隐藏原生窗口、编辑框和滚动条,结合合成手势端点, +验证普通文字拖选、双击区域、标题栏、边框、独立滚动条、编辑框内滚动条、自绘标题栏、 +客户区发起的移动和缩放,以及移动之后重新选词。测试使用真实窗口几何和命中测试, +不向用户应用注入鼠标事件,不读取剪贴板内容;它不替代实际记事本、浏览器和桌面应用验收。 +完全自绘、未暴露原生滚动条且命中测试始终返回客户区的滚动条仍不在此守卫的覆盖范围内。 diff --git a/scripts/test-gestures.ps1 b/scripts/test-gestures.ps1 new file mode 100644 index 0000000..5f21432 --- /dev/null +++ b/scripts/test-gestures.ps1 @@ -0,0 +1,14 @@ +[CmdletBinding()] +param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\LightTranslate')) +$ErrorActionPreference = 'Stop' +$outputPath = [System.IO.Path]::GetFullPath($OutputDirectory) +$test = Start-Process -FilePath (Join-Path $outputPath 'LightTranslate.exe') -ArgumentList '--self-test-gestures' -WindowStyle Hidden -PassThru +if (-not $test.WaitForExit(30000)) { + Stop-Process -Id $test.Id -Force + throw 'Gesture integration test timed out.' +} +if ($test.ExitCode -ne 0) { + Get-Content -LiteralPath (Join-Path $outputPath 'status.log') -Tail 10 + throw 'Gesture integration test failed.' +} +Get-Content -LiteralPath (Join-Path $outputPath 'gesture-integration-test.json') diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index bef4e71..5737f0f 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-tray") return TrayIconRenderer.RunStandalone(); + if (args.Length > 0 && args[0] == "--self-test-gestures") return SelectionGestureTests.Run(); if (args.Length > 0 && args[0] == "--self-test-selection") return SelectionIntegrationTests.Run(); if (args.Length > 0 && args[0] == "--self-test") return SelfTest.Run(false); if (args.Length > 0 && args[0] == "--self-test-offline") return SelfTest.Run(true); @@ -236,7 +237,9 @@ private void OpenSettings() internal static System.Drawing.Icon MakeIcon(Settings value = null) { return TrayIconRenderer.Create(value ?? new Settings()); } - private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow) + private SelectionSurface downSurface; + + private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow, SelectionSurface surface) { if (!disposed) { @@ -255,7 +258,8 @@ private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow) down = settings.Enabled; dragged = false; downPoint = data.pt; - downWindow = Native.GetAncestor(Native.WindowFromPoint(data.pt), 2); + downSurface = surface; + downWindow = surface == null ? IntPtr.Zero : surface.Root; } } else if (message == 0x200 && down) @@ -266,14 +270,15 @@ private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow) { mouseUps++; down = false; - bool twice = unchecked(data.time - lastUpTime) <= Native.GetDoubleClickTime() + bool eligible = SelectionSurface.AllowsSelection(downSurface, surface); + bool twice = eligible && lastUpTime != 0 && unchecked(data.time - lastUpTime) <= Native.GetDoubleClickTime() && Math.Abs(data.pt.x - previousUp.x) <= Native.GetSystemMetrics(36) && Math.Abs(data.pt.y - previousUp.y) <= Native.GetSystemMetrics(37); previousUp = data.pt; - lastUpTime = data.time; + lastUpTime = eligible ? data.time : 0; IntPtr window = capturedWindow; - Trace("mouse-up drag=" + dragged + " double=" + twice + " same-window=" + (window == downWindow) + " same-app=" + Native.SameApp(window, downWindow) + " injected=" + ((data.flags & 1) != 0)); - if (settings.Enabled && (dragged || twice) && (window == downWindow || Native.SameApp(window, downWindow)) && !bubble.Contains(data.pt)) + Trace("mouse-up eligible=" + eligible + " drag=" + dragged + " double=" + twice + " same-window=" + (window == downWindow) + " same-app=" + Native.SameApp(window, downWindow) + " injected=" + ((data.flags & 1) != 0)); + if (settings.Enabled && eligible && (dragged || twice) && (window == downWindow || Native.SameApp(window, downWindow)) && !bubble.Contains(data.pt)) { var point = data.pt; int queuedVersion = generation; @@ -453,7 +458,7 @@ internal sealed class InputHooks : IDisposable { private const uint ProbeMessage = 0x84c0, DropTestMessage = 0x84c1; private readonly Dispatcher dispatcher; - private readonly Action onMouse; + private readonly Action onMouse; private readonly Action onKeyboard; private readonly Native.Hook mouseCallback, keyboardCallback; private readonly Thread thread; @@ -476,7 +481,7 @@ internal sealed class InputHooks : IDisposable public int InstallationVersion { get { return Interlocked.CompareExchange(ref installationVersion, 0, 0); } } internal int Probes { get { return Interlocked.CompareExchange(ref probes, 0, 0); } } - public InputHooks(Dispatcher dispatcher, Action onMouse, + public InputHooks(Dispatcher dispatcher, Action onMouse, Action onKeyboard, bool testMode = false) { this.dispatcher = dispatcher; @@ -518,7 +523,7 @@ private void Run() else if (message.message == ProbeMessage && testMode) { Interlocked.Increment(ref probes); - Queue(delegate { onMouse(0, new Native.MOUSE(), IntPtr.Zero); }); + Queue(delegate { onMouse(0, new Native.MOUSE(), IntPtr.Zero, null); }); } else if (message.message == DropTestMessage && testMode) RemoveHooks(); } @@ -556,7 +561,8 @@ private IntPtr MouseCallback(int code, IntPtr wParam, IntPtr lParam) if (forward) { IntPtr window = Native.GetForegroundWindow(); - Queue(delegate { onMouse(message, data, window); }); + SelectionSurface surface = (message == 0x201 || message == 0x202) ? SelectionSurface.Capture(data.pt) : null; + Queue(delegate { onMouse(message, data, window, surface); }); } } } @@ -1195,7 +1201,7 @@ public static int Run(bool offline) int forwarded = 0; var dispatcher = Dispatcher.CurrentDispatcher; using (var hooks = new InputHooks(dispatcher, - delegate(int message, Native.MOUSE data, IntPtr window) { if (message == 0) forwarded++; }, + delegate(int message, Native.MOUSE data, IntPtr window, SelectionSurface surface) { if (message == 0) forwarded++; }, delegate(int message, Native.KEYBOARD data, IntPtr window) { }, true)) { // Keep the WPF/clipboard STA blocked while probing the real input thread. diff --git a/src/SelectionGesture.cs b/src/SelectionGesture.cs new file mode 100644 index 0000000..80cd2e4 --- /dev/null +++ b/src/SelectionGesture.cs @@ -0,0 +1,69 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace LightTranslate +{ + // Captured on the input thread, before Windows processes the button event. + // Only local window metadata APIs are used here: never send messages from a hook. + internal sealed class SelectionSurface + { + internal IntPtr Window, Root; + internal Native.POINT Point; + internal Native.RECT Bounds; + internal bool Client; + + internal static SelectionSurface Capture(Native.POINT point) + { return Capture(Native.WindowFromPoint(point), point); } + + internal static SelectionSurface Capture(IntPtr window, Native.POINT point) + { + var value = new SelectionSurface { Window = window, Point = point, Root = Native.GetAncestor(window, 2) }; + Native.RECT client; + var local = point; + var name = new StringBuilder(64); + Native.GetClassName(window, name, name.Capacity); + value.Client = window != IntPtr.Zero && value.Root != IntPtr.Zero + && Native.GetWindowRect(value.Root, out value.Bounds) + && GetClientRect(window, out client) && ScreenToClient(window, ref local) + && local.x >= client.left && local.x < client.right && local.y >= client.top && local.y < client.bottom + && !string.Equals(name.ToString(), "ScrollBar", StringComparison.OrdinalIgnoreCase) + && !name.ToString().StartsWith("WindowsForms10.SCROLLBAR.", StringComparison.OrdinalIgnoreCase); + return value; + } + + // Run on the dispatcher only after a potential selection gesture. A hung source + // must not hold up the input hook or cause us to copy arbitrary focused text. + internal static bool AllowsSelection(SelectionSurface start, SelectionSurface end) + { + if (start == null || end == null || !start.Client || !end.Client + || start.Root != end.Root || !Equal(start.Bounds, end.Bounds)) return false; + Native.RECT current; + if (!Native.GetWindowRect(start.Root, out current) || !Equal(start.Bounds, current)) return false; + return ClientHit(start) && ClientHit(end); + } + + private static bool ClientHit(SelectionSurface surface) + { + // Custom title bars can lie inside the client rectangle but report HTCAPTION. + if (!Hit(surface.Root, surface.Point, false)) return false; + return surface.Window == surface.Root || Hit(surface.Window, surface.Point, true); + } + + private static bool Hit(IntPtr window, Native.POINT point, bool child) + { + IntPtr result; + var position = new IntPtr(unchecked((int)(((uint)point.y & 0xffff) << 16 | ((uint)point.x & 0xffff)))); + if (SendMessageTimeout(window, 0x84, IntPtr.Zero, position, 0x22, 25, out result) == IntPtr.Zero) return false; + return result.ToInt64() == 1 || (child && result.ToInt64() == -1); // HTCLIENT / transparent child + } + + internal static bool Equal(Native.RECT a, Native.RECT b) + { return a.left == b.left && a.top == b.top && a.right == b.right && a.bottom == b.bottom; } + + [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Native.RECT rect); + [DllImport("user32.dll")] private static extern bool ScreenToClient(IntPtr window, ref Native.POINT point); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr SendMessageTimeout( + IntPtr window, uint message, IntPtr wParam, IntPtr lParam, uint flags, uint timeout, out IntPtr result); + } +} diff --git a/src/SelectionGestureTests.cs b/src/SelectionGestureTests.cs new file mode 100644 index 0000000..821a655 --- /dev/null +++ b/src/SelectionGestureTests.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Runtime.InteropServices; +using System.Web.Script.Serialization; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + internal static class SelectionGestureTests + { + private sealed class CaptionForm : Forms.Form + { + internal bool CustomCaption; + protected override void WndProc(ref Forms.Message m) + { + if (CustomCaption && m.Msg == 0x84) + { + long packed = m.LParam.ToInt64(); + var point = PointToClient(new Point(unchecked((short)(packed & 0xffff)), unchecked((short)((packed >> 16) & 0xffff)))); + if (point.Y >= 0 && point.Y < 35) { m.Result = new IntPtr(2); return; } + } + base.WndProc(ref m); + } + } + + internal static int Run() + { + uint clipboardBefore = Native.GetClipboardSequenceNumber(); + var passed = new List(); + using (var form = new CaptionForm { Size = new Size(500, 350), StartPosition = Forms.FormStartPosition.Manual, Location = new Point(100, 100) }) + using (var edit = new Forms.TextBox { Multiline = true, Bounds = new Rectangle(10, 50, 350, 170), Text = "prefix reversible suffix" }) + using (var scroll = new Forms.VScrollBar { Bounds = new Rectangle(370, 50, 20, 170) }) + { + // Own hidden real HWNDs only. No global mouse injection, user text or clipboard payload. + form.Controls.Add(edit); form.Controls.Add(scroll); + IntPtr root = form.Handle, editHandle = edit.Handle, scrollHandle = scroll.Handle; + Func at = delegate(Forms.Control control, int x, int y) + { + Point point = control.PointToScreen(new Point(x, y)); + return SelectionSurface.Capture(control.Handle, new Native.POINT { x = point.X, y = point.Y }); + }; + Action check = delegate(string name, bool value) { ClipboardCaptureTests.Check(value, name); passed.Add(name); }; + var textStart = at(edit, 10, 10); var textEnd = at(edit, 100, 10); + check("real edit drag accepted", SelectionSurface.AllowsSelection(textStart, textEnd)); + check("real edit double click surface accepted", SelectionSurface.AllowsSelection(textStart, textStart)); + Native.RECT bounds; Native.GetWindowRect(root, out bounds); + Point origin = form.PointToScreen(Point.Empty); + var titlePoint = new Native.POINT { x = bounds.left + 100, y = bounds.top + (origin.Y - bounds.top) / 2 }; + var title = SelectionSurface.Capture(root, titlePoint); + // Reproduce the old classifier: a >5 px same-window drag was sufficient. + check("old classifier accepts title drag", Math.Abs(titlePoint.x + 20 - titlePoint.x) >= 5 && title.Root == root); + check("title drag rejected before capture", !SelectionSurface.AllowsSelection(title, textEnd)); + check("title double click rejected", !SelectionSurface.AllowsSelection(title, title)); + var border = SelectionSurface.Capture(root, new Native.POINT { x = bounds.right - 1, y = bounds.top + 150 }); + check("resize border rejected before capture", !SelectionSurface.AllowsSelection(border, textEnd)); + check("scrollbar drag rejected before capture", !SelectionSurface.AllowsSelection(at(scroll, 5, 10), at(scroll, 5, 80))); + ShowScrollBar(editHandle, 3, true); + Native.RECT editBounds; Native.GetWindowRect(editHandle, out editBounds); + var vertical = SelectionSurface.Capture(editHandle, new Native.POINT { x = editBounds.right - 5, y = editBounds.top + 60 }); + var horizontal = SelectionSurface.Capture(editHandle, new Native.POINT { x = editBounds.left + 60, y = editBounds.bottom - 5 }); + check("edit nonclient vertical scrollbar rejected", !SelectionSurface.AllowsSelection(vertical, vertical)); + check("edit nonclient horizontal scrollbar rejected", !SelectionSurface.AllowsSelection(horizontal, horizontal)); + check("drag ending in title rejected", !SelectionSurface.AllowsSelection(textStart, title)); + form.CustomCaption = true; + var caption = at(form, 100, 15); + check("custom caption inside client rejected", caption.Client && !SelectionSurface.AllowsSelection(caption, textEnd)); + check("custom title bar leaves edit selection working", SelectionSurface.AllowsSelection(textStart, textEnd)); + form.CustomCaption = false; + form.Location = new Point(150, 150); + check("client initiated window move rejected", !SelectionSurface.AllowsSelection(textStart, at(edit, 100, 10))); + var beforeResize = at(edit, 10, 10); + form.Size = new Size(550, 400); + check("client initiated resize rejected", !SelectionSurface.AllowsSelection(beforeResize, at(edit, 100, 10))); + check("fresh selection after move and resize accepted", SelectionSurface.AllowsSelection(at(edit, 10, 10), at(edit, 100, 10))); + using (var other = new Forms.Form()) + check("cross window gesture rejected", !SelectionSurface.AllowsSelection(at(edit, 10, 10), at(other, 20, 20))); + check("missing geometry rejected", !SelectionSurface.AllowsSelection(null, textEnd)); + } + File.WriteAllText(Path.Combine(Program.Folder, "gesture-integration-test.json"), new JavaScriptSerializer().Serialize(new { + passed, clipboardSequenceUnchanged = clipboardBefore == Native.GetClipboardSequenceNumber(), + scope = "Owned hidden native controls and real window metadata/hit tests; synthetic gesture endpoints; no physical user-app drag automated" + })); + return 0; + } + + [DllImport("user32.dll")] private static extern bool ShowScrollBar(IntPtr window, int bar, bool show); + } +} From ed5c63fc75372c9dd1f27888b8037083669683b5 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:53:20 +0800 Subject: [PATCH 14/17] Treat successful empty selections as a quiet result --- docs/TESTING.md | 12 +++++++ helpers/SelectionHost.cs | 24 ++++++++++---- src/IsolatedSelectionReader.cs | 40 ++++++++++++++++++---- src/LightTranslate.cs | 7 ++-- src/SelectionIntegrationTests.cs | 57 ++++++++++++++++++++++++++++++-- 5 files changed, 120 insertions(+), 20 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index d64f1d0..d136f3c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -286,3 +286,15 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 客户区发起的移动和缩放,以及移动之后重新选词。测试使用真实窗口几何和命中测试, 不向用户应用注入鼠标事件,不读取剪贴板内容;它不替代实际记事本、浏览器和桌面应用验收。 完全自绘、未暴露原生滚动条且命中测试始终返回客户区的滚动条仍不在此守卫的覆盖范围内。 + +### 空选区与读取失败 + +辅助进程的结果区分有文本、成功但选区为空、不支持 TextPattern、密码字段、超时与失败。 +成功的空选区直接结束当前取词,不显示失败提示;辅助进程也不再向其他焦点或祖先回退, +避免把另一个控件保留的旧选区作为本次结果。折叠文本范围先检查端点,不读取其相邻文本。 +不支持、超时、提供方异常和未知响应仍保留失败提示,不通过统一隐藏错误来处理空拖动。 + +选区集成测试使用真实 TextBox 和 RichTextBox,分别覆盖文末折叠选区(空拖动后的状态)、 +正文中折叠光标、空文档以及空选区前后的正常选词;经过同一受保护剪贴板分支和错误转换路径, +验证没有复制、剪贴板读取或旧文本返回。另验证真实不支持 TextPattern 的窗口和固定错误协议。 +这些控件测试不注入实际记事本鼠标动作;实际记事本的文末空拖以及 Chromium 正常选词仍需人工验收。 diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs index 1d76c6b..8da7131 100644 --- a/helpers/SelectionHost.cs +++ b/helpers/SelectionHost.cs @@ -3,6 +3,7 @@ using System.Text; using System.Threading; using System.Windows.Automation; +using System.Windows.Automation.Text; // A short-lived process owns every UIA/COM object. No clipboard API, file output or network. internal static class SelectionHost @@ -38,9 +39,11 @@ private static int Main(string[] args) text = ReadAncestors(AutomationElement.FromPoint(new System.Windows.Point(x, y)), root, maximum); if (status == "password") { Console.Error.WriteLine("password"); return 0; } } - if (string.IsNullOrEmpty(text)) text = Read(element, maximum); + // null means unsupported/unresolved; empty means a successful, authoritative + // empty selection. Do not replace an empty pointer selection with stale focus text. + if (text == null) text = Read(element, maximum); // Browsers can expose their actual focused document below the native HWND. - if (string.IsNullOrEmpty(text) && GetForegroundWindow() == root) + if (text == null && GetForegroundWindow() == root) { var focused = AutomationElement.FocusedElement; if (focused != null && !focused.Current.IsPassword && BelongsTo(focused, root)) @@ -50,6 +53,7 @@ private static int Main(string[] args) { Console.OutputEncoding = new UTF8Encoding(false); Console.Write(text); + Console.Error.WriteLine("selected"); } else Console.Error.WriteLine(status); return 0; @@ -65,7 +69,7 @@ private static string ReadAncestors(AutomationElement element, IntPtr root, int if (element.Current.IsPassword) { status = "password"; return null; } if (!BelongsTo(element, root)) return null; string text = Read(element, maximum); - if (!string.IsNullOrEmpty(text)) return text; + if (text != null) return text; if (element.Current.NativeWindowHandle == root.ToInt64()) return null; element = TreeWalker.ControlViewWalker.GetParent(element); } @@ -84,18 +88,24 @@ private static bool BelongsTo(AutomationElement element, IntPtr root) } private static string Read(AutomationElement element, int maximum) { - if (element.Current.IsPassword) return null; + if (element.Current.IsPassword) { status = "password"; return string.Empty; } object value; if (!element.TryGetCurrentPattern(TextPattern.Pattern, out value)) return null; - status = "empty-selection"; var ranges = ((TextPattern)value).GetSelection(); - if (ranges == null || ranges.Length == 0 || ranges.Length > 8) return null; + if (ranges == null || ranges.Length > 8) throw new InvalidOperationException(); + status = "empty-selection"; + if (ranges.Length == 0) return string.Empty; var text = new StringBuilder(); foreach (var range in ranges) { + // A caret range is not a selection, even if a provider's GetText returns + // an adjacent character. Multiple collapsed ranges must not create newlines. + if (range.CompareEndpoints(TextPatternRangeEndpoint.Start, range, TextPatternRangeEndpoint.End) == 0) continue; + string part = range.GetText(maximum - text.Length); + if (string.IsNullOrEmpty(part)) continue; if (text.Length != 0) text.Append('\n'); if (text.Length >= maximum) break; - text.Append(range.GetText(maximum - text.Length)); + text.Append(part.Substring(0, Math.Min(part.Length, maximum - text.Length))); } return text.ToString(); } diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index 3dbc78d..4470ad7 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -13,9 +13,37 @@ internal sealed class SelectionUnavailableException : Exception { internal SelectionUnavailableException(string message = "剪贴板无法安全备份,已保留原内容;当前应用暂时无法读取选区。") : base(message) { } } + internal enum SelectionReadState { Selected, Empty, Unsupported, Blocked, Timeout, Failed } + internal sealed class SelectionReadResult + { + internal SelectionReadState State; + internal string Text; + internal SelectionReadResult(SelectionReadState state, string text = null) { State = state; Text = text; } + internal string ForCapture() + { + if (State == SelectionReadState.Empty || State == SelectionReadState.Blocked) return string.Empty; + if (State != SelectionReadState.Selected) throw new SelectionUnavailableException(); + if (Text.Length >= 65537) throw new SelectionUnavailableException("选中文字较长,请分段选择"); + return Text; + } + } internal static class IsolatedSelectionReader { internal static async Task Read(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null) + { return (await ReadResult(window, ct, maximum, focus, point)).Text; } + + internal static SelectionReadResult Decode(int exitCode, string status, string text, int maximum) + { + if (status == "deadline") return new SelectionReadResult(SelectionReadState.Timeout); + if (exitCode != 0 || text.Length > maximum) return new SelectionReadResult(SelectionReadState.Failed); + if (status == "password") return new SelectionReadResult(SelectionReadState.Blocked, string.Empty); + if (text.Length != 0 && status == "selected") return new SelectionReadResult(SelectionReadState.Selected, text); + if (text.Length == 0 && status == "empty-selection") return new SelectionReadResult(SelectionReadState.Empty, string.Empty); + if (status == "no-text-pattern") return new SelectionReadResult(SelectionReadState.Unsupported); + return new SelectionReadResult(SelectionReadState.Failed); + } + + internal static async Task ReadResult(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null) { ct.ThrowIfCancellationRequested(); if (focus == IntPtr.Zero) @@ -27,7 +55,7 @@ internal static class IsolatedSelectionReader focus = Native.GetGUIThreadInfo(thread, ref info) && info.focus != IntPtr.Zero ? info.focus : window; } string path = Path.Combine(Program.Folder, "LightTranslate.SelectionHost.exe"); - if (focus == IntPtr.Zero || !File.Exists(path)) { Program.Log("selection-helper", "missing-helper-or-window"); return null; } + if (focus == IntPtr.Zero || !File.Exists(path)) { Program.Log("selection-helper", "missing-helper-or-window"); return new SelectionReadResult(SelectionReadState.Failed); } string arguments = window.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + focus.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + maximum.ToString(CultureInfo.InvariantCulture); if (point.HasValue) arguments += " " + point.Value.x.ToString(CultureInfo.InvariantCulture) + " " + point.Value.y.ToString(CultureInfo.InvariantCulture); var start = new ProcessStartInfo(path, arguments) @@ -41,19 +69,19 @@ internal static class IsolatedSelectionReader // The helper self-exits on timeout; never terminate the user's application. bool exited = await Task.Run(delegate { return process.WaitForExit(3800); }); ct.ThrowIfCancellationRequested(); - if (!exited) { Program.Log("selection-helper", "wait-timeout"); return null; } + if (!exited) { Program.Log("selection-helper", "wait-timeout"); return new SelectionReadResult(SelectionReadState.Timeout); } string status = (await diagnostic).Trim(); // Only fixed status codes enter logs, never provider text or selected content. - if (status != "no-text-pattern" && status != "empty-selection" && status != "password" + if (status != "selected" && status != "no-text-pattern" && status != "empty-selection" && status != "password" && status != "wrong-root" && status != "deadline" && status != "provider-error" && status != "depth-limit") status = "unknown"; - if (process.ExitCode != 0) { Program.Log("selection-helper", "exit=" + process.ExitCode + " status=" + status); return null; } + if (process.ExitCode != 0) Program.Log("selection-helper", "exit=" + process.ExitCode + " status=" + status); string text = await output; if (string.IsNullOrEmpty(text)) Program.Log("selection-helper", "status=" + status); - return text.Length <= maximum ? text : null; + return Decode(process.ExitCode, status, text, maximum); } } catch (OperationCanceledException) { throw; } - catch { Program.Log("selection-helper", "launch-or-pipe-error"); return null; } + catch { Program.Log("selection-helper", "launch-or-pipe-error"); return new SelectionReadResult(SelectionReadState.Failed); } } } } diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 5737f0f..3ecdf64 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -704,10 +704,9 @@ public static async Task CopySelection(IntPtr window, CancellationToken delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }, Native.Copy, trace, delegate { return Task.Delay(15); }, async delegate { - string text = await IsolatedSelectionReader.Read(window, ct, point: point); - if (text != null && text.Length >= 65537) throw new SelectionUnavailableException("选中文字较长,请分段选择"); - if (!ct.IsCancellationRequested && Native.GetForegroundWindow() == window && string.IsNullOrEmpty(text)) - throw new SelectionUnavailableException(); + SelectionReadResult result = await IsolatedSelectionReader.ReadResult(window, ct, point: point); + if (ct.IsCancellationRequested || Native.GetForegroundWindow() != window) return null; + string text = result.ForCapture(); trace("selection helper chars=" + (text == null ? 0 : text.Length)); return text; }); diff --git a/src/SelectionIntegrationTests.cs b/src/SelectionIntegrationTests.cs index 5b53fd3..8e9ddc4 100644 --- a/src/SelectionIntegrationTests.cs +++ b/src/SelectionIntegrationTests.cs @@ -28,10 +28,61 @@ internal static T Pump(Task task) if (!task.IsCompleted) throw new Exception("Selection integration timed out"); return task.GetAwaiter().GetResult(); } + private static string Capture(ProtectedClipboard clipboard, IntPtr root, IntPtr focus) + { + return Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, + delegate { clipboard.Copies++; }, delegate { }, delegate { return Task.Delay(15); }, + async delegate { return (await IsolatedSelectionReader.ReadResult(root, CancellationToken.None, 2001, focus)).ForCapture(); })); + } + + private static void ExpectFailure(SelectionReadResult result, SelectionReadState state) + { + ClipboardCaptureTests.Check(result.State == state, "fixed helper failure classification " + state); + bool explained = false; + try { result.ForCapture(); } catch (SelectionUnavailableException) { explained = true; } + ClipboardCaptureTests.Check(explained, "real failures retain error prompt " + state); + } + + private static void EmptySelectionCases(Forms.TextBoxBase edit, List passed) + { + using (var form = new Forms.Form()) + using (edit) + { + edit.Text = "prefix reversible suffix"; + form.Controls.Add(edit); + IntPtr root = form.Handle, focus = edit.Handle; + var clipboard = new ProtectedClipboard(); + edit.Select(7, 10); + ClipboardCaptureTests.Check(Capture(clipboard, root, focus) == "reversible", "selected word before collapse"); + foreach (string scenario in new[] { "end-of-document empty drag result", "middle collapsed caret", "empty document" }) + { + if (scenario == "empty document") edit.Text = string.Empty; + edit.Select(scenario == "middle collapsed caret" ? 5 : edit.TextLength, 0); + SelectionReadResult result = Pump(IsolatedSelectionReader.ReadResult(root, CancellationToken.None, 2001, focus)); + ClipboardCaptureTests.Check(result.State == SelectionReadState.Empty, "successful empty selection classified " + scenario); + string selected = Capture(clipboard, root, focus); + ClipboardCaptureTests.Check(selected == string.Empty && !SelectionReader.ShouldTranslate(selected, 25), "empty selection silently ends without stale text " + scenario); + passed.Add(edit.GetType().Name + ": " + scenario); + } + edit.Text = "prefix reversible suffix"; edit.Select(7, 10); + ClipboardCaptureTests.Check(Capture(clipboard, root, focus) == "reversible", "normal selection still works after empty gestures"); + ClipboardCaptureTests.Check(clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0, "empty gestures never copy or read stale clipboard"); + } + } internal static int Run() { uint before = Native.GetClipboardSequenceNumber(); var results = new Dictionary(); + var emptyCases = new List(); + EmptySelectionCases(new Forms.TextBox { Multiline = true }, emptyCases); + EmptySelectionCases(new Forms.RichTextBox(), emptyCases); + ExpectFailure(IsolatedSelectionReader.Decode(0, "no-text-pattern", "", 20), SelectionReadState.Unsupported); + ExpectFailure(IsolatedSelectionReader.Decode(3, "deadline", "", 20), SelectionReadState.Timeout); + ExpectFailure(IsolatedSelectionReader.Decode(2, "provider-error", "", 20), SelectionReadState.Failed); + ExpectFailure(IsolatedSelectionReader.Decode(2, "empty-selection", "", 20), SelectionReadState.Failed); + ExpectFailure(IsolatedSelectionReader.Decode(0, "unknown", "", 20), SelectionReadState.Failed); + using (var unsupported = new Forms.Form()) + ExpectFailure(Pump(IsolatedSelectionReader.ReadResult(unsupported.Handle, CancellationToken.None, 2001, unsupported.Handle)), SelectionReadState.Unsupported); using (var form = new Forms.Form()) using (var text = new Forms.TextBox { Multiline = true, Text = "prefix reversible suffix" }) { @@ -39,9 +90,7 @@ internal static int Run() IntPtr root = form.Handle, focus = text.Handle; text.Select(7, 10); var clipboard = new ProtectedClipboard(); - string selected = Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, - delegate { clipboard.Copies++; }, delegate { }, delegate { return Task.Delay(15); }, - delegate { return IsolatedSelectionReader.Read(root, CancellationToken.None, 2001, focus); })); + string selected = Capture(clipboard, root, focus); ClipboardCaptureTests.Check(selected == "reversible", "real edit selection through protected clipboard fallback"); ClipboardCaptureTests.Check(clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0, "protected clipboard untouched"); ClipboardCaptureTests.Check(SelectionReader.ShouldTranslate(selected, 25), "selected English passes real language gate"); @@ -64,6 +113,8 @@ internal static int Run() } } results["selectionIntegration"] = "real Windows edit selection -> external UIA helper -> protected clipboard fallback -> language gate -> local dictionary; empty/password/wrong-root/canceled/length cases passed; no network or clipboard contents accessed"; + results["emptySelectionCases"] = emptyCases; + results["failureClassification"] = "unsupported, deadline, provider error, nonzero exit with empty status, unknown status retain errors; successful empty selections are silent"; results["clipboardSequenceUnchanged"] = before == Native.GetClipboardSequenceNumber(); File.WriteAllText(Path.Combine(Program.Folder, "selection-integration-test.json"), new JavaScriptSerializer().Serialize(results)); return 0; From 432552e0b82aa528f2ba40766e2abe0893098463 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:27:22 +0800 Subject: [PATCH 15/17] Classify selection context before clipboard access --- .github/workflows/build.yml | 3 + README.md | 4 +- docs/TESTING.md | 29 ++++++-- helpers/SelectionHost.cs | 49 +++++++++++-- scripts/test-selection-context.ps1 | 14 ++++ src/IsolatedSelectionReader.cs | 30 ++++++-- src/LightTranslate.cs | 29 ++++---- src/SelectionContextTests.cs | 107 +++++++++++++++++++++++++++++ src/SelectionIntegrationTests.cs | 16 +++-- 9 files changed, 241 insertions(+), 40 deletions(-) create mode 100644 scripts/test-selection-context.ps1 create mode 100644 src/SelectionContextTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 61689d9..413ebfb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,6 +23,9 @@ jobs: - name: Native window gesture boundaries shell: pwsh run: ./scripts/test-gestures.ps1 + - name: Non-text selection contexts + shell: pwsh + run: ./scripts/test-selection-context.ps1 - name: Translation providers and DeepL offline regression shell: pwsh run: ./scripts/test-providers.ps1 diff --git a/README.md b/README.md index 97fe263..d8b9ccd 100644 --- a/README.md +++ b/README.md @@ -85,8 +85,8 @@ pwsh -File .\startup.ps1 -Remove 选择 DeepL 并保存密钥后,选中文字将发送给 DeepL,可能按账户套餐计费;未配置密钥时不请求 DeepL。只使用官方 `POST /v2/translate`,按密钥的 `:fx` 标记选择 `api-free.deepl.com`,其余使用 `api.deepl.com`,不接受自定义地址或 HTTP 重定向。简繁中文对应 `ZH-HANS`、`ZH-HANT`。 额度和费用以 [DeepL 当前 API 套餐](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。 译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。 -通常通过临时复制选区取词,并尝试恢复原剪贴板;系统或剪贴板管理器可能保留复制记录。 -剪贴板含图片或应用专用格式、无法安全备份时,改由独立的 `LightTranslate.SelectionHost.exe` 读取应用通过 Windows UI Automation 提供的选区,不复制、不改剪贴板。辅助进程限时退出,主程序不持有 UIA/COM 对象。应用不支持这种读取时显示明确提示,不清空剪贴板,也不退回 OLE 快照。分发或移动程序时请保留该辅助文件。 +先由独立的 `LightTranslate.SelectionHost.exe` 判断操作区域并读取 Windows UI Automation 文本选区。空选区、图标列表、树等非文本交互直接结束,不访问剪贴板;不会按应用名全局排除资源管理器,列表内重命名编辑框仍可取词。辅助进程限时退出,主程序不持有 UIA/COM 对象。分发或移动程序时请保留该辅助文件。 +仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法安全备份时不复制,并显示读取失败提示;不清空剪贴板,也不退回 OLE 快照。未知区域、辅助程序缺失或读取失败不会盲目发送复制命令。系统或剪贴板管理器仍可能保留实际执行过的临时复制记录。 ## 从源码构建 diff --git a/docs/TESTING.md b/docs/TESTING.md index d136f3c..4ea1a67 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -97,7 +97,7 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 ## 取词与数据处理 -程序优先使用带内部标记的 `Ctrl+C` 获取选区,快照仅接受支持的文本格式。原剪贴板无法完整安全备份时,改由独立进程读取 UIA 选区,保留剪贴板原内容。 +程序先由独立进程判断文本上下文和读取 UIA 选区;空选区及非文本交互不访问剪贴板。仅确认是文本区域但缺少选区接口时,才使用带内部标记的 `Ctrl+C` 回退,快照仅接受支持的文本格式;原剪贴板无法完整安全备份时保留原内容并提示读取失败。 如果用户或其他应用在取词期间更新了剪贴板,程序会避免覆盖新的内容。 系统剪贴板历史和第三方剪贴板管理器仍可能保留临时复制记录。 @@ -245,9 +245,9 @@ The generated settings previews show an empty credential field. ## 图片或专用格式剪贴板下的选区读取 -仅允许文本快照的守卫会拒绝图片和应用专用格式。这是保护原剪贴板所需的行为, -但不能因此让划词静默失效。快照失败时,现在通过短时独立进程 -`LightTranslate.SelectionHost.exe` 请求应用的 UIA TextPattern 选区,不读取或修改剪贴板。 +仅允许文本快照的守卫会拒绝图片和应用专用格式。这是保护原剪贴板所需的行为。 +现在首先通过短时独立进程 `LightTranslate.SelectionHost.exe` 判断上下文并请求应用的 +UIA TextPattern 选区;能直接读取的文本无需快照,也不读取或修改剪贴板。 主程序仍不引用 UIAutomationClient,不持有跨进程 UIA/COM 对象,也不恢复原 OLE 快照路径。 辅助进程只接受源窗口、焦点窗口句柄、鼠标释放位置和长度上限,验证窗口归属并拒绝密码字段; 选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 3 秒的自身终止期限, @@ -256,7 +256,7 @@ The generated settings previews show an empty credential field. 无法安全读取、辅助程序缺失或超时时,浮层提示取词失败并保留剪贴板。 `./scripts/test-selection.ps1` 使用真实 Windows 编辑控件和真实外部辅助进程, -合成选区经过拒绝备份分支、选区读取、英文比例检查,最终命中本地词典。 +合成选区经过上下文判断、选区读取、英文比例检查,最终命中本地词典。 它同时验证空选区、密码框、错误源窗口、取消和输出长度上限,不调用在线翻译, 不读取用户剪贴板内容,也不改变用户窗口焦点;只记录剪贴板序列号是否保持不变。 `./scripts/test-clipboard.ps1 -Native` 在私有 window station 中额外验证真实编辑控件的 @@ -295,6 +295,23 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 不支持、超时、提供方异常和未知响应仍保留失败提示,不通过统一隐藏错误来处理空拖动。 选区集成测试使用真实 TextBox 和 RichTextBox,分别覆盖文末折叠选区(空拖动后的状态)、 -正文中折叠光标、空文档以及空选区前后的正常选词;经过同一受保护剪贴板分支和错误转换路径, +正文中折叠光标、空文档以及空选区前后的正常选词;经过同一上下文判断和错误转换路径, 验证没有复制、剪贴板读取或旧文本返回。另验证真实不支持 TextPattern 的窗口和固定错误协议。 这些控件测试不注入实际记事本鼠标动作;实际记事本的文末空拖以及 Chromium 正常选词仍需人工验收。 + +### 非文本交互的提前判断 + +`./scripts/test-selection-context.ps1` 使用自有隐藏 ListView、TreeView 和列表内编辑框, +覆盖空白图标区域、已有项目选中的图标拖动上下文、详细列表和树选择;同时在可备份与 +不可备份的模拟剪贴板下验证快照、复制、读取和恢复调用次数均为零,且不返回旧文本。 +列表内的重命名编辑框仍能返回所选测试词;不是按 Explorer 进程名或桌面标题硬编码禁用。 + +辅助进程按控件角色及 Selection/SelectionItem 模式识别项目交互,区分 Edit/Document +文本区域;网页列表仍可向所属 Document 查找文本选区。Shell 的 UIA 层级若跳过原生 +根窗口,到达源窗口边界时保留已确认的非文本结果,不查询其他窗口或回退旧焦点。 +只有已确认的文本区域缺少文本选区接口时才允许剪贴板回退;未知区域、超时和真实错误 +继续报告失败,且不尝试复制。辅助进程成为取词前置依赖,须与主程序一起分发。 + +测试不移动用户图标或文件,也不执行真实 Shell 拖放。实际桌面另做只读控件分类验证; +桌面框选、资源管理器列表交互及文件重命名的实际手势仍需人工验收。剪贴板序列号是 +只读观察项,其他程序在测试期间可能改变它;不接触剪贴板的断言以调用计数为准。 diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs index 8da7131..62ea593 100644 --- a/helpers/SelectionHost.cs +++ b/helpers/SelectionHost.cs @@ -41,9 +41,9 @@ private static int Main(string[] args) } // null means unsupported/unresolved; empty means a successful, authoritative // empty selection. Do not replace an empty pointer selection with stale focus text. - if (text == null) text = Read(element, maximum); + if (text == null && status != "text-unsupported") text = ReadAncestors(element, root, maximum); // Browsers can expose their actual focused document below the native HWND. - if (text == null && GetForegroundWindow() == root) + if (text == null && status != "text-unsupported" && GetForegroundWindow() == root) { var focused = AutomationElement.FocusedElement; if (focused != null && !focused.Current.IsPassword && BelongsTo(focused, root)) @@ -64,18 +64,55 @@ private static string ReadAncestors(AutomationElement element, IntPtr root, int { // Chromium can put many layout groups between focus and its Document. // Stay within the source window, with a depth bound and process deadline. + bool itemSurface = false; for (int i = 0; i < 32 && element != null; i++) { if (element.Current.IsPassword) { status = "password"; return null; } - if (!BelongsTo(element, root)) return null; - string text = Read(element, maximum); - if (text != null) return text; - if (element.Current.NativeWindowHandle == root.ToInt64()) return null; + if (!BelongsTo(element, root)) + { + // Shell UIA trees may skip the native WorkerW root. Once traversal + // leaves our source window, an already identified item surface is final. + if (itemSurface) { status = "non-text"; return string.Empty; } + return null; + } + ControlType type = element.Current.ControlType; + // An inline rename Edit remains text even when its parent is an icon list. + // A web list can belong to a selectable Document: do not blacklist its app. + if (type == ControlType.Edit || type == ControlType.Document) + { + string text = Read(element, maximum); + if (text == null) status = "text-unsupported"; + return text; + } + itemSurface |= IsItemSurface(element, type); + if (!itemSurface) + { + string text = Read(element, maximum); + if (text != null) return text; + } + if (element.Current.NativeWindowHandle == root.ToInt64()) + { + if (itemSurface) { status = "non-text"; return string.Empty; } + return null; + } element = TreeWalker.ControlViewWalker.GetParent(element); } if (element != null) status = "depth-limit"; + else if (itemSurface) { status = "non-text"; return string.Empty; } return null; } + private static bool IsItemSurface(AutomationElement element, ControlType type) + { + if (type == ControlType.List || type == ControlType.ListItem || type == ControlType.Tree || type == ControlType.TreeItem + || type == ControlType.DataGrid || type == ControlType.DataItem || type == ControlType.Header || type == ControlType.HeaderItem + || type == ControlType.Button || type == ControlType.CheckBox || type == ControlType.RadioButton || type == ControlType.ComboBox + || type == ControlType.ScrollBar || type == ControlType.Slider || type == ControlType.Menu || type == ControlType.MenuItem + || type == ControlType.Tab || type == ControlType.TabItem || type == ControlType.ToolBar || type == ControlType.Image + || type == ControlType.Separator || type == ControlType.ProgressBar) return true; + object pattern; + return element.TryGetCurrentPattern(SelectionPattern.Pattern, out pattern) + || element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern); + } private static bool BelongsTo(AutomationElement element, IntPtr root) { for (int i = 0; i < 32 && element != null; i++) diff --git a/scripts/test-selection-context.ps1 b/scripts/test-selection-context.ps1 new file mode 100644 index 0000000..970eaaa --- /dev/null +++ b/scripts/test-selection-context.ps1 @@ -0,0 +1,14 @@ +[CmdletBinding()] +param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\LightTranslate')) +$ErrorActionPreference = 'Stop' +$outputPath = [System.IO.Path]::GetFullPath($OutputDirectory) +$test = Start-Process -FilePath (Join-Path $outputPath 'LightTranslate.exe') -ArgumentList '--self-test-selection-context' -WindowStyle Hidden -PassThru +if (-not $test.WaitForExit(30000)) { + Stop-Process -Id $test.Id -Force + throw 'Selection context test timed out.' +} +if ($test.ExitCode -ne 0) { + Get-Content -LiteralPath (Join-Path $outputPath 'status.log') -Tail 10 + throw 'Selection context test failed.' +} +Get-Content -LiteralPath (Join-Path $outputPath 'selection-context-test.json') diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index 4470ad7..d567510 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -11,9 +11,9 @@ namespace LightTranslate { internal sealed class SelectionUnavailableException : Exception { - internal SelectionUnavailableException(string message = "剪贴板无法安全备份,已保留原内容;当前应用暂时无法读取选区。") : base(message) { } + internal SelectionUnavailableException(string message = "当前应用暂时无法读取选区,已保留剪贴板原内容。") : base(message) { } } - internal enum SelectionReadState { Selected, Empty, Unsupported, Blocked, Timeout, Failed } + internal enum SelectionReadState { Selected, Empty, NonText, Unsupported, TextUnsupported, Blocked, Timeout, Failed } internal sealed class SelectionReadResult { internal SelectionReadState State; @@ -21,12 +21,32 @@ internal sealed class SelectionReadResult internal SelectionReadResult(SelectionReadState state, string text = null) { State = state; Text = text; } internal string ForCapture() { - if (State == SelectionReadState.Empty || State == SelectionReadState.Blocked) return string.Empty; + if (State == SelectionReadState.Empty || State == SelectionReadState.NonText || State == SelectionReadState.Blocked) return string.Empty; if (State != SelectionReadState.Selected) throw new SelectionUnavailableException(); if (Text.Length >= 65537) throw new SelectionUnavailableException("选中文字较长,请分段选择"); return Text; } } + internal static class SelectionAcquisition + { + private static readonly SemaphoreSlim gate = new SemaphoreSlim(1, 1); + internal static async Task Read(Func> inspect, + Func> textFallback, Func valid) + { + if (!gate.Wait(0)) return null; + try + { + if (!valid()) return null; + SelectionReadResult result = await inspect(); + if (!valid()) return null; + // Clipboard access requires positive evidence of a text context. UIA failures + // and item selection must never send Ctrl+C to a list or stale focused control. + if (result.State == SelectionReadState.TextUnsupported) return await textFallback(result); + return result.ForCapture(); + } + finally { gate.Release(); } + } + } internal static class IsolatedSelectionReader { internal static async Task Read(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null) @@ -39,6 +59,8 @@ internal static SelectionReadResult Decode(int exitCode, string status, string t if (status == "password") return new SelectionReadResult(SelectionReadState.Blocked, string.Empty); if (text.Length != 0 && status == "selected") return new SelectionReadResult(SelectionReadState.Selected, text); if (text.Length == 0 && status == "empty-selection") return new SelectionReadResult(SelectionReadState.Empty, string.Empty); + if (text.Length == 0 && status == "non-text") return new SelectionReadResult(SelectionReadState.NonText, string.Empty); + if (status == "text-unsupported") return new SelectionReadResult(SelectionReadState.TextUnsupported); if (status == "no-text-pattern") return new SelectionReadResult(SelectionReadState.Unsupported); return new SelectionReadResult(SelectionReadState.Failed); } @@ -72,7 +94,7 @@ internal static SelectionReadResult Decode(int exitCode, string status, string t if (!exited) { Program.Log("selection-helper", "wait-timeout"); return new SelectionReadResult(SelectionReadState.Timeout); } string status = (await diagnostic).Trim(); // Only fixed status codes enter logs, never provider text or selected content. - if (status != "selected" && status != "no-text-pattern" && status != "empty-selection" && status != "password" + if (status != "selected" && status != "no-text-pattern" && status != "text-unsupported" && status != "non-text" && status != "empty-selection" && status != "password" && status != "wrong-root" && status != "deadline" && status != "provider-error" && status != "depth-limit") status = "unknown"; if (process.ExitCode != 0) Program.Log("selection-helper", "exit=" + process.ExitCode + " status=" + status); string text = await output; diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 3ecdf64..0164939 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -46,6 +46,7 @@ private static int Main(string[] args) if (args.Length > 0 && args[0] == "--self-test-providers") return TranslationProviderTests.RunStandalone(); if (args.Length > 0 && args[0] == "--self-test-tray") return TrayIconRenderer.RunStandalone(); if (args.Length > 0 && args[0] == "--self-test-gestures") return SelectionGestureTests.Run(); + if (args.Length > 0 && args[0] == "--self-test-selection-context") return SelectionContextTests.Run(); if (args.Length > 0 && args[0] == "--self-test-selection") return SelectionIntegrationTests.Run(); if (args.Length > 0 && args[0] == "--self-test") return SelfTest.Run(false); if (args.Length > 0 && args[0] == "--self-test-offline") return SelfTest.Run(true); @@ -218,7 +219,7 @@ public Controller(Application app) timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) }; timer.Tick += delegate { CheckDismissal(); FlushDiagnostics(); }; timer.Start(); - Program.Log("started", "hooks=dedicated-thread recovery=enabled capture=clipboard dictionary=" + lexicon.Count); + Program.Log("started", "hooks=dedicated-thread recovery=enabled capture=isolated-context clipboard=text-fallback dictionary=" + lexicon.Count); } private void OpenSettings() @@ -341,11 +342,11 @@ private async void BeginSelection(IntPtr window, Native.POINT point) { await Task.Delay(25, ct); if (!Valid(version, window)) return; - // Capture through the clipboard without UIAutomationClient handles. - // Native UIA pattern finalizers caused an access violation during testing. + // 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); - Trace("clipboard chars=" + (text == null ? 0 : text.Length)); + 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(); if (!SelectionReader.ShouldTranslate(text, settings.MinEnglishPercent)) { Trace("selection language threshold skipped"); return; } @@ -699,17 +700,15 @@ public static async Task CopySelection(IntPtr window, CancellationToken { if (Native.GetForegroundWindow() != window || Native.ModifierDown()) { trace("copy skipped focus/modifier"); return null; } if (Native.IsPasswordFocus(window)) { trace("password field skipped"); return null; } - using (var clipboard = new NativeSelectionClipboard()) - return await ClipboardCapture.Read(clipboard, window, - delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }, - Native.Copy, trace, delegate { return Task.Delay(15); }, async delegate - { - SelectionReadResult result = await IsolatedSelectionReader.ReadResult(window, ct, point: point); - if (ct.IsCancellationRequested || Native.GetForegroundWindow() != window) return null; - string text = result.ForCapture(); - trace("selection helper chars=" + (text == null ? 0 : text.Length)); - return text; - }); + Func valid = delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }; + return await SelectionAcquisition.Read( + delegate { return IsolatedSelectionReader.ReadResult(window, ct, point: point); }, + 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()); }); + }, valid); } } diff --git a/src/SelectionContextTests.cs b/src/SelectionContextTests.cs new file mode 100644 index 0000000..a613e7b --- /dev/null +++ b/src/SelectionContextTests.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using Forms = System.Windows.Forms; + +namespace LightTranslate +{ + internal static class SelectionContextTests + { + private sealed class Clipboard : ISelectionClipboard + { + internal int Snapshots, Copies, Reads, Restores; + internal bool CanSnapshot = true; + private uint sequence = 10; + public uint Sequence { get { return sequence; } } + public bool TrySnapshot(out ClipboardSnapshot saved) + { Snapshots++; saved = new ClipboardSnapshot { Sequence = sequence }; return CanSnapshot; } + internal void Copy() { Copies++; sequence++; } + public bool TryReadText(IntPtr source, uint expected, out uint version, out string text) + { Reads++; version = sequence; text = "reversible"; return true; } + public RestoreResult Restore(ClipboardSnapshot saved, uint expected, Func valid) + { Restores++; return RestoreResult.Restored; } + } + + private static string Acquire(SelectionReadResult result, Clipboard clipboard) + { + return SelectionIntegrationTests.Pump(SelectionAcquisition.Read(delegate { return Task.FromResult(result); }, + delegate(SelectionReadResult inspected) { return ClipboardCapture.Read(clipboard, IntPtr.Zero, delegate { return true; }, + clipboard.Copy, delegate { }, delegate { return Task.FromResult(0); }, delegate { return Task.FromResult(inspected.ForCapture()); }); }, + delegate { return true; })); + } + + internal static int Run() + { + var passed = new List(); + Action check = delegate(string name, bool value) { ClipboardCaptureTests.Check(value, name); passed.Add(name); }; + uint before = Native.GetClipboardSequenceNumber(); + using (var form = new Forms.Form()) + using (var list = new Forms.ListView { View = Forms.View.LargeIcon, MultiSelect = true, LabelEdit = true }) + using (var tree = new Forms.TreeView()) + using (var stale = new Forms.TextBox { Text = "stale fixture" }) + { + form.Controls.Add(list); form.Controls.Add(tree); form.Controls.Add(stale); + IntPtr root = form.Handle, listHandle = list.Handle, treeHandle = tree.Handle, staleHandle = stale.Handle; + stale.SelectAll(); + Func probe = delegate(Forms.Control control) + { return SelectionIntegrationTests.Pump(IsolatedSelectionReader.ReadResult(root, CancellationToken.None, 2001, control.Handle)); }; + Action nonText = delegate(string label, Forms.Control control) + { + SelectionReadResult result = probe(control); + check(label + " classified as non-text", result.State == SelectionReadState.NonText); + foreach (bool snapshotAllowed in new[] { true, false }) + { + var clipboard = new Clipboard { CanSnapshot = snapshotAllowed }; + check(label + " returns no stale text", Acquire(result, clipboard) == string.Empty); + check(label + " never accesses clipboard", clipboard.Snapshots == 0 && clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0); + } + }; + nonText("desktop-style empty icon canvas", list); + list.Items.Add("synthetic icon").Selected = true; + nonText("selected icon drag context", list); + list.View = Forms.View.Details; list.Columns.Add("synthetic column", 120); + nonText("explorer-style item list", list); + tree.Nodes.Add("synthetic tree item"); tree.SelectedNode = tree.Nodes[0]; + nonText("tree selection context", tree); + using (var rename = new Forms.TextBox { Text = "reversible.txt" }) + { + list.Controls.Add(rename); IntPtr renameHandle = rename.Handle; rename.Select(0, 10); + var clipboard = new Clipboard(); + check("inline edit inside item list remains selectable text", Acquire(probe(rename), clipboard) == "reversible"); + check("inline edit selection avoids clipboard", clipboard.Snapshots == 0 && clipboard.Copies == 0); + } + } + foreach (SelectionReadState state in new[] { SelectionReadState.Unsupported, SelectionReadState.Timeout, SelectionReadState.Failed }) + { + var clipboard = new Clipboard(); bool error = false; + try { Acquire(new SelectionReadResult(state), clipboard); } catch (SelectionUnavailableException) { error = true; } + check(state + " remains an error before clipboard access", error && clipboard.Snapshots == 0 && clipboard.Copies == 0); + } + var supportedFallback = new Clipboard(); + check("confirmed text context can use safe clipboard fallback", Acquire(new SelectionReadResult(SelectionReadState.TextUnsupported), supportedFallback) == "reversible" + && supportedFallback.Snapshots == 1 && supportedFallback.Copies == 1 && supportedFallback.Restores == 1); + var protectedFallback = new Clipboard { CanSnapshot = false }; bool protectedError = false; + try { Acquire(new SelectionReadResult(SelectionReadState.TextUnsupported), protectedFallback); } catch (SelectionUnavailableException) { protectedError = true; } + check("unsupported text preserves unsafe clipboard and reports error", protectedError && protectedFallback.Copies == 0 && protectedFallback.Reads == 0); + bool valid = true; int fallbackCalls = 0; + string canceled = SelectionIntegrationTests.Pump(SelectionAcquisition.Read( + delegate { valid = false; return Task.FromResult(new SelectionReadResult(SelectionReadState.Selected, "stale fixture")); }, + delegate { fallbackCalls++; return Task.FromResult("stale fallback"); }, delegate { return valid; })); + check("changed source discards selection before fallback or translation", canceled == null && fallbackCalls == 0); + var waiting = new TaskCompletionSource(); int probes = 0; + Func> noFallback = delegate { throw new Exception("Unexpected clipboard fallback"); }; + Task first = SelectionAcquisition.Read(delegate { probes++; return waiting.Task; }, noFallback, delegate { return true; }); + string second = SelectionIntegrationTests.Pump(SelectionAcquisition.Read(delegate { probes++; return waiting.Task; }, noFallback, delegate { return true; })); + waiting.SetResult(new SelectionReadResult(SelectionReadState.NonText, string.Empty)); + check("overlapping gestures do not launch another helper", second == null && SelectionIntegrationTests.Pump(first) == string.Empty && probes == 1); + File.WriteAllText(Path.Combine(Program.Folder, "selection-context-test.json"), new JavaScriptSerializer().Serialize(new { + passed, clipboardSequenceUnchanged = before == Native.GetClipboardSequenceNumber(), + scope = "Owned hidden ListView, TreeView and inline Edit; real external UIA; synthetic gesture contexts, no user icons or files moved" + })); + return 0; + } + } +} diff --git a/src/SelectionIntegrationTests.cs b/src/SelectionIntegrationTests.cs index 8e9ddc4..2ccbdb1 100644 --- a/src/SelectionIntegrationTests.cs +++ b/src/SelectionIntegrationTests.cs @@ -13,9 +13,9 @@ internal static class SelectionIntegrationTests // Real native edit controls and the real external UIA process; no user clipboard payload. private sealed class ProtectedClipboard : ISelectionClipboard { - internal int Copies, Reads, Restores; + internal int Snapshots, Copies, Reads, Restores; public uint Sequence { get { return 1; } } - public bool TrySnapshot(out ClipboardSnapshot snapshot) { snapshot = null; return false; } + public bool TrySnapshot(out ClipboardSnapshot snapshot) { Snapshots++; snapshot = null; return false; } public bool TryReadText(IntPtr source, uint expected, out uint sequence, out string text) { Reads++; sequence = 0; text = null; throw new Exception("Protected clipboard must not be read"); } public RestoreResult Restore(ClipboardSnapshot snapshot, uint expected, Func valid) @@ -30,9 +30,11 @@ internal static T Pump(Task task) } private static string Capture(ProtectedClipboard clipboard, IntPtr root, IntPtr focus) { - return Pump(ClipboardCapture.Read(clipboard, root, delegate { return true; }, - delegate { clipboard.Copies++; }, delegate { }, delegate { return Task.Delay(15); }, - async delegate { return (await IsolatedSelectionReader.ReadResult(root, CancellationToken.None, 2001, focus)).ForCapture(); })); + return Pump(SelectionAcquisition.Read( + delegate { return IsolatedSelectionReader.ReadResult(root, CancellationToken.None, 2001, focus); }, + delegate(SelectionReadResult result) { return ClipboardCapture.Read(clipboard, root, delegate { return true; }, + delegate { clipboard.Copies++; }, delegate { }, delegate { return Task.Delay(15); }, + delegate { return Task.FromResult(result.ForCapture()); }); }, delegate { return true; })); } private static void ExpectFailure(SelectionReadResult result, SelectionReadState state) @@ -66,7 +68,7 @@ private static void EmptySelectionCases(Forms.TextBoxBase edit, List pas } edit.Text = "prefix reversible suffix"; edit.Select(7, 10); ClipboardCaptureTests.Check(Capture(clipboard, root, focus) == "reversible", "normal selection still works after empty gestures"); - ClipboardCaptureTests.Check(clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0, "empty gestures never copy or read stale clipboard"); + ClipboardCaptureTests.Check(clipboard.Snapshots == 0 && clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0, "empty gestures never snapshot, copy or read stale clipboard"); } } internal static int Run() @@ -112,7 +114,7 @@ internal static int Run() ClipboardCaptureTests.Check(stopped, "canceled selection rejected"); } } - results["selectionIntegration"] = "real Windows edit selection -> external UIA helper -> protected clipboard fallback -> language gate -> local dictionary; empty/password/wrong-root/canceled/length cases passed; no network or clipboard contents accessed"; + results["selectionIntegration"] = "real Windows edit selection -> external UIA helper -> context gate -> language gate -> local dictionary; empty/password/wrong-root/canceled/length cases passed; no network or clipboard contents accessed"; results["emptySelectionCases"] = emptyCases; results["failureClassification"] = "unsupported, deadline, provider error, nonzero exit with empty status, unknown status retain errors; successful empty selections are silent"; results["clipboardSequenceUnchanged"] = before == Native.GetClipboardSequenceNumber(); From 71b8d606a2df0fb3e16250a9da5ad00db7bda531 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:47:09 +0800 Subject: [PATCH 16/17] Require text context before surfacing selection errors --- README.md | 4 ++-- docs/TESTING.md | 25 +++++++++++++++++++++---- helpers/SelectionHost.cs | 14 +++++++++++--- src/IsolatedSelectionReader.cs | 19 +++++++++++-------- src/SelectionContextTests.cs | 29 +++++++++++++++++++++++++++-- src/SelectionIntegrationTests.cs | 22 +++++++++++++++------- 6 files changed, 87 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index d8b9ccd..fd42146 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 轻译 · LightTranslate +# 轻译 · LightTranslate **选中英文,译文自然浮起;继续操作,浮层自然消失。** @@ -86,7 +86,7 @@ pwsh -File .\startup.ps1 -Remove 额度和费用以 [DeepL 当前 API 套餐](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。 译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。 先由独立的 `LightTranslate.SelectionHost.exe` 判断操作区域并读取 Windows UI Automation 文本选区。空选区、图标列表、树等非文本交互直接结束,不访问剪贴板;不会按应用名全局排除资源管理器,列表内重命名编辑框仍可取词。辅助进程限时退出,主程序不持有 UIA/COM 对象。分发或移动程序时请保留该辅助文件。 -仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法安全备份时不复制,并显示读取失败提示;不清空剪贴板,也不退回 OLE 快照。未知区域、辅助程序缺失或读取失败不会盲目发送复制命令。系统或剪贴板管理器仍可能保留实际执行过的临时复制记录。 +仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法安全备份时不复制,并显示读取失败提示;不清空剪贴板,也不退回 OLE 快照。未知区域或尚未确认文本上下文的探测失败会安静结束并保留固定诊断码,不会发送复制命令;已确认文本区域的读取失败以及辅助程序缺失仍有明确提示。系统或剪贴板管理器仍可能保留实际执行过的临时复制记录。 ## 从源码构建 diff --git a/docs/TESTING.md b/docs/TESTING.md index 4ea1a67..ea4dbdd 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -253,7 +253,7 @@ UIA TextPattern 选区;能直接读取的文本无需快照,也不读取或 选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 3 秒的自身终止期限, 主程序异步等待上限为 3.8 秒,并丢弃已取消或焦点改变后的响应。 这不是权限沙箱;它隔离 UIA 原生故障,不会终止用户源应用或轻译主进程。 -无法安全读取、辅助程序缺失或超时时,浮层提示取词失败并保留剪贴板。 +已确认文本区域无法安全读取或超时,以及辅助程序缺失时,浮层提示取词失败并保留剪贴板;尚未确认文本上下文时只保留固定诊断码。 `./scripts/test-selection.ps1` 使用真实 Windows 编辑控件和真实外部辅助进程, 合成选区经过上下文判断、选区读取、英文比例检查,最终命中本地词典。 @@ -292,7 +292,7 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 辅助进程的结果区分有文本、成功但选区为空、不支持 TextPattern、密码字段、超时与失败。 成功的空选区直接结束当前取词,不显示失败提示;辅助进程也不再向其他焦点或祖先回退, 避免把另一个控件保留的旧选区作为本次结果。折叠文本范围先检查端点,不读取其相邻文本。 -不支持、超时、提供方异常和未知响应仍保留失败提示,不通过统一隐藏错误来处理空拖动。 +文本区域缺少选区接口、超时和提供方异常仍保留失败提示。未确认文本上下文的无接口、超时或异常仅记固定诊断,不将一般交互当作取词错误。 选区集成测试使用真实 TextBox 和 RichTextBox,分别覆盖文末折叠选区(空拖动后的状态)、 正文中折叠光标、空文档以及空选区前后的正常选词;经过同一上下文判断和错误转换路径, @@ -309,9 +309,26 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 辅助进程按控件角色及 Selection/SelectionItem 模式识别项目交互,区分 Edit/Document 文本区域;网页列表仍可向所属 Document 查找文本选区。Shell 的 UIA 层级若跳过原生 根窗口,到达源窗口边界时保留已确认的非文本结果,不查询其他窗口或回退旧焦点。 -只有已确认的文本区域缺少文本选区接口时才允许剪贴板回退;未知区域、超时和真实错误 -继续报告失败,且不尝试复制。辅助进程成为取词前置依赖,须与主程序一起分发。 +只有已确认的文本区域缺少文本选区接口时才允许剪贴板回退;未知区域安静结束, +探测失败保留固定诊断码,已确认文本区域的读取失败仍提示,且不会盲目复制。 +辅助进程成为取词前置依赖,须与主程序一起分发。 测试不移动用户图标或文件,也不执行真实 Shell 拖放。实际桌面另做只读控件分类验证; 桌面框选、资源管理器列表交互及文件重命名的实际手势仍需人工验收。剪贴板序列号是 只读观察项,其他程序在测试期间可能改变它;不接触剪贴板的断言以调用计数为准。 + +### 未确认文本上下文的系统浮层交互 + +窗口不提供 TextPattern 只能说明没有确认可读取的文本选区,不足以认定用户正在选词。 +因此通用 Pane/Group 等区域以及尚未确认文本上下文的探测失败会安静结束,仍记录固定 +`no-text-pattern`、`provider-error`、`deadline` 等诊断码;不启动剪贴板回退。鼠标所在区域 +已成功检查但没有文本证据时,不再转向另一个控件的旧键盘选区。 + +辅助进程确认 Edit/Document 或取得 TextPattern 后,错误与超时分别使用 +`text-provider-error`、`text-deadline`,仍显示读取失败提示。文本框、网页文档和重命名 +编辑框无需按宿主进程豁免;没有通知中心、日历或系统进程的黑名单。 + +上下文测试增加真实 Panel、GroupBox、Button、Label、MonthCalendar、TrackBar、 +CheckBox,以及通用面板内 TextBox 的选词,断言无文本区域既不报错也不读写剪贴板, +已确认文本失败仍提示。它们覆盖通知、日历、快速设置常见控件语义,不等于自动操作 +或完整复现 Windows 系统浮层;没有清除通知、读取通知正文或更改系统设置。 diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs index 62ea593..4e94989 100644 --- a/helpers/SelectionHost.cs +++ b/helpers/SelectionHost.cs @@ -10,11 +10,12 @@ internal static class SelectionHost { private static Timer deadline; private static string status = "no-text-pattern"; + private static volatile bool textContext; [MTAThread] private static int Main(string[] args) { // Keep the deadline alive through COM finalization; it may only end this helper. - deadline = new Timer(delegate { try { Console.Error.WriteLine("deadline"); } catch { } TerminateProcess(new IntPtr(-1), 3); }, null, 3000, Timeout.Infinite); + deadline = new Timer(delegate { try { Console.Error.WriteLine(textContext ? "text-deadline" : "deadline"); } catch { } TerminateProcess(new IntPtr(-1), 3); }, null, 3000, Timeout.Infinite); try { long rootValue, focusValue; int maximum; @@ -36,8 +37,13 @@ private static int Main(string[] args) { int x, y; if (!int.TryParse(args[3], out x) || !int.TryParse(args[4], out y)) return 2; - text = ReadAncestors(AutomationElement.FromPoint(new System.Windows.Point(x, y)), root, maximum); + var hit = AutomationElement.FromPoint(new System.Windows.Point(x, y)); + bool inSource = hit != null && BelongsTo(hit, root); + text = ReadAncestors(hit, root, maximum); if (status == "password") { Console.Error.WriteLine("password"); return 0; } + // A successfully inspected pointer surface with no text evidence is not + // permission to read a different control's stale keyboard selection. + if (inSource && text == null && status != "text-unsupported") text = string.Empty; } // null means unsupported/unresolved; empty means a successful, authoritative // empty selection. Do not replace an empty pointer selection with stale focus text. @@ -58,7 +64,7 @@ private static int Main(string[] args) else Console.Error.WriteLine(status); return 0; } - catch { Console.Error.WriteLine("provider-error"); return 2; } + catch { Console.Error.WriteLine(textContext ? "text-provider-error" : "provider-error"); return 2; } } private static string ReadAncestors(AutomationElement element, IntPtr root, int maximum) { @@ -80,6 +86,7 @@ private static string ReadAncestors(AutomationElement element, IntPtr root, int // A web list can belong to a selectable Document: do not blacklist its app. if (type == ControlType.Edit || type == ControlType.Document) { + textContext = true; string text = Read(element, maximum); if (text == null) status = "text-unsupported"; return text; @@ -128,6 +135,7 @@ private static string Read(AutomationElement element, int maximum) if (element.Current.IsPassword) { status = "password"; return string.Empty; } object value; if (!element.TryGetCurrentPattern(TextPattern.Pattern, out value)) return null; + textContext = true; var ranges = ((TextPattern)value).GetSelection(); if (ranges == null || ranges.Length > 8) throw new InvalidOperationException(); status = "empty-selection"; diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index d567510..ee93bf2 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -13,7 +13,7 @@ internal sealed class SelectionUnavailableException : Exception { internal SelectionUnavailableException(string message = "当前应用暂时无法读取选区,已保留剪贴板原内容。") : base(message) { } } - internal enum SelectionReadState { Selected, Empty, NonText, Unsupported, TextUnsupported, Blocked, Timeout, Failed } + internal enum SelectionReadState { Selected, Empty, NonText, Unconfirmed, TextUnsupported, Blocked, ProbeTimeout, ProbeFailed, Timeout, Failed } internal sealed class SelectionReadResult { internal SelectionReadState State; @@ -21,7 +21,8 @@ internal sealed class SelectionReadResult internal SelectionReadResult(SelectionReadState state, string text = null) { State = state; Text = text; } internal string ForCapture() { - if (State == SelectionReadState.Empty || State == SelectionReadState.NonText || State == SelectionReadState.Blocked) return string.Empty; + if (State == SelectionReadState.Empty || State == SelectionReadState.NonText || State == SelectionReadState.Blocked + || State == SelectionReadState.Unconfirmed || State == SelectionReadState.ProbeTimeout || State == SelectionReadState.ProbeFailed) return string.Empty; if (State != SelectionReadState.Selected) throw new SelectionUnavailableException(); if (Text.Length >= 65537) throw new SelectionUnavailableException("选中文字较长,请分段选择"); return Text; @@ -54,15 +55,17 @@ internal static class IsolatedSelectionReader internal static SelectionReadResult Decode(int exitCode, string status, string text, int maximum) { - if (status == "deadline") return new SelectionReadResult(SelectionReadState.Timeout); - if (exitCode != 0 || text.Length > maximum) return new SelectionReadResult(SelectionReadState.Failed); + if (status == "text-deadline") return new SelectionReadResult(SelectionReadState.Timeout); + if (status == "text-provider-error" || text.Length > maximum) return new SelectionReadResult(SelectionReadState.Failed); + if (status == "deadline") return new SelectionReadResult(SelectionReadState.ProbeTimeout); + if (exitCode != 0) return new SelectionReadResult(SelectionReadState.ProbeFailed); if (status == "password") return new SelectionReadResult(SelectionReadState.Blocked, string.Empty); if (text.Length != 0 && status == "selected") return new SelectionReadResult(SelectionReadState.Selected, text); if (text.Length == 0 && status == "empty-selection") return new SelectionReadResult(SelectionReadState.Empty, string.Empty); if (text.Length == 0 && status == "non-text") return new SelectionReadResult(SelectionReadState.NonText, string.Empty); if (status == "text-unsupported") return new SelectionReadResult(SelectionReadState.TextUnsupported); - if (status == "no-text-pattern") return new SelectionReadResult(SelectionReadState.Unsupported); - return new SelectionReadResult(SelectionReadState.Failed); + if (status == "no-text-pattern" || status == "depth-limit") return new SelectionReadResult(SelectionReadState.Unconfirmed); + return new SelectionReadResult(SelectionReadState.ProbeFailed); } internal static async Task ReadResult(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null) @@ -91,11 +94,11 @@ internal static SelectionReadResult Decode(int exitCode, string status, string t // The helper self-exits on timeout; never terminate the user's application. bool exited = await Task.Run(delegate { return process.WaitForExit(3800); }); ct.ThrowIfCancellationRequested(); - if (!exited) { Program.Log("selection-helper", "wait-timeout"); return new SelectionReadResult(SelectionReadState.Timeout); } + if (!exited) { Program.Log("selection-helper", "wait-timeout"); return new SelectionReadResult(SelectionReadState.ProbeTimeout); } string status = (await diagnostic).Trim(); // Only fixed status codes enter logs, never provider text or selected content. if (status != "selected" && status != "no-text-pattern" && status != "text-unsupported" && status != "non-text" && status != "empty-selection" && status != "password" - && status != "wrong-root" && status != "deadline" && status != "provider-error" && status != "depth-limit") status = "unknown"; + && status != "wrong-root" && status != "deadline" && status != "text-deadline" && status != "provider-error" && status != "text-provider-error" && status != "depth-limit") status = "unknown"; if (process.ExitCode != 0) Program.Log("selection-helper", "exit=" + process.ExitCode + " status=" + status); string text = await output; if (string.IsNullOrEmpty(text)) Program.Log("selection-helper", "status=" + status); diff --git a/src/SelectionContextTests.cs b/src/SelectionContextTests.cs index a613e7b..5c46515 100644 --- a/src/SelectionContextTests.cs +++ b/src/SelectionContextTests.cs @@ -73,8 +73,33 @@ internal static int Run() check("inline edit inside item list remains selectable text", Acquire(probe(rename), clipboard) == "reversible"); check("inline edit selection avoids clipboard", clipboard.Snapshots == 0 && clipboard.Copies == 0); } + foreach (Forms.Control surface in new Forms.Control[] { + new Forms.Panel(), new Forms.GroupBox(), new Forms.Button { Text = "synthetic action" }, + new Forms.Label { Text = "synthetic notification" }, new Forms.MonthCalendar(), + new Forms.TrackBar(), new Forms.CheckBox { Text = "synthetic setting" } }) + using (surface) + { + form.Controls.Add(surface); IntPtr handle = surface.Handle; + SelectionReadResult result = probe(surface); + check(surface.GetType().Name + " has no confirmed selectable text", result.State == SelectionReadState.NonText || result.State == SelectionReadState.Unconfirmed); + var clipboard = new Clipboard(); + check(surface.GetType().Name + " gesture quietly ends without stale text", Acquire(result, clipboard) == string.Empty); + check(surface.GetType().Name + " never touches clipboard", clipboard.Snapshots == 0 && clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0); + } + using (var panel = new Forms.Panel()) + using (var edit = new Forms.TextBox { Text = "reversible" }) + { + form.Controls.Add(panel); panel.Controls.Add(edit); IntPtr panelHandle = panel.Handle, editHandle = edit.Handle; + edit.SelectAll(); var clipboard = new Clipboard(); + check("text edit inside generic flyout panel remains usable", Acquire(probe(edit), clipboard) == "reversible" && clipboard.Snapshots == 0); + } + } + foreach (SelectionReadState state in new[] { SelectionReadState.Unconfirmed, SelectionReadState.ProbeTimeout, SelectionReadState.ProbeFailed }) + { + var clipboard = new Clipboard(); + check(state + " quietly ends before clipboard access", Acquire(new SelectionReadResult(state), clipboard) == string.Empty && clipboard.Snapshots == 0 && clipboard.Copies == 0); } - foreach (SelectionReadState state in new[] { SelectionReadState.Unsupported, SelectionReadState.Timeout, SelectionReadState.Failed }) + foreach (SelectionReadState state in new[] { SelectionReadState.Timeout, SelectionReadState.Failed }) { var clipboard = new Clipboard(); bool error = false; try { Acquire(new SelectionReadResult(state), clipboard); } catch (SelectionUnavailableException) { error = true; } @@ -99,7 +124,7 @@ internal static int Run() check("overlapping gestures do not launch another helper", second == null && SelectionIntegrationTests.Pump(first) == string.Empty && probes == 1); File.WriteAllText(Path.Combine(Program.Folder, "selection-context-test.json"), new JavaScriptSerializer().Serialize(new { passed, clipboardSequenceUnchanged = before == Native.GetClipboardSequenceNumber(), - scope = "Owned hidden ListView, TreeView and inline Edit; real external UIA; synthetic gesture contexts, no user icons or files moved" + scope = "Owned hidden lists, tree, edit, panel, group, button, static label, calendar, slider and checkbox; real external UIA; no actual shell actions, notifications or settings touched" })); return 0; } diff --git a/src/SelectionIntegrationTests.cs b/src/SelectionIntegrationTests.cs index 2ccbdb1..221a766 100644 --- a/src/SelectionIntegrationTests.cs +++ b/src/SelectionIntegrationTests.cs @@ -44,6 +44,11 @@ private static void ExpectFailure(SelectionReadResult result, SelectionReadState try { result.ForCapture(); } catch (SelectionUnavailableException) { explained = true; } ClipboardCaptureTests.Check(explained, "real failures retain error prompt " + state); } + private static void ExpectUnconfirmed(SelectionReadResult result, SelectionReadState state) + { + ClipboardCaptureTests.Check(result.State == state && result.ForCapture() == string.Empty, + "unconfirmed text context stays quiet with diagnostic state " + state); + } private static void EmptySelectionCases(Forms.TextBoxBase edit, List passed) { @@ -78,13 +83,16 @@ internal static int Run() var emptyCases = new List(); EmptySelectionCases(new Forms.TextBox { Multiline = true }, emptyCases); EmptySelectionCases(new Forms.RichTextBox(), emptyCases); - ExpectFailure(IsolatedSelectionReader.Decode(0, "no-text-pattern", "", 20), SelectionReadState.Unsupported); - ExpectFailure(IsolatedSelectionReader.Decode(3, "deadline", "", 20), SelectionReadState.Timeout); - ExpectFailure(IsolatedSelectionReader.Decode(2, "provider-error", "", 20), SelectionReadState.Failed); - ExpectFailure(IsolatedSelectionReader.Decode(2, "empty-selection", "", 20), SelectionReadState.Failed); - ExpectFailure(IsolatedSelectionReader.Decode(0, "unknown", "", 20), SelectionReadState.Failed); + ExpectUnconfirmed(IsolatedSelectionReader.Decode(0, "no-text-pattern", "", 20), SelectionReadState.Unconfirmed); + ExpectUnconfirmed(IsolatedSelectionReader.Decode(3, "deadline", "", 20), SelectionReadState.ProbeTimeout); + ExpectUnconfirmed(IsolatedSelectionReader.Decode(2, "provider-error", "", 20), SelectionReadState.ProbeFailed); + ExpectUnconfirmed(IsolatedSelectionReader.Decode(2, "empty-selection", "", 20), SelectionReadState.ProbeFailed); + ExpectUnconfirmed(IsolatedSelectionReader.Decode(0, "unknown", "", 20), SelectionReadState.ProbeFailed); + ExpectFailure(IsolatedSelectionReader.Decode(3, "text-deadline", "", 20), SelectionReadState.Timeout); + ExpectFailure(IsolatedSelectionReader.Decode(2, "text-provider-error", "", 20), SelectionReadState.Failed); + ExpectFailure(IsolatedSelectionReader.Decode(0, "text-unsupported", "", 20), SelectionReadState.TextUnsupported); using (var unsupported = new Forms.Form()) - ExpectFailure(Pump(IsolatedSelectionReader.ReadResult(unsupported.Handle, CancellationToken.None, 2001, unsupported.Handle)), SelectionReadState.Unsupported); + ExpectUnconfirmed(Pump(IsolatedSelectionReader.ReadResult(unsupported.Handle, CancellationToken.None, 2001, unsupported.Handle)), SelectionReadState.Unconfirmed); using (var form = new Forms.Form()) using (var text = new Forms.TextBox { Multiline = true, Text = "prefix reversible suffix" }) { @@ -116,7 +124,7 @@ internal static int Run() } results["selectionIntegration"] = "real Windows edit selection -> external UIA helper -> context gate -> language gate -> local dictionary; empty/password/wrong-root/canceled/length cases passed; no network or clipboard contents accessed"; results["emptySelectionCases"] = emptyCases; - results["failureClassification"] = "unsupported, deadline, provider error, nonzero exit with empty status, unknown status retain errors; successful empty selections are silent"; + results["failureClassification"] = "unconfirmed context and probe failures stay quiet with fixed diagnostics; confirmed text deadline, provider error and unsupported text retain errors; successful empty selections are silent"; results["clipboardSequenceUnchanged"] = before == Native.GetClipboardSequenceNumber(); File.WriteAllText(Path.Combine(Program.Folder, "selection-integration-test.json"), new JavaScriptSerializer().Serialize(results)); return 0; From e51b6484e705bccaf01303d4cf9c261de814aeb6 Mon Sep 17 00:00:00 2001 From: Stellar-He <166851263+Stellar-He@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:29:09 +0800 Subject: [PATCH 17/17] Distinguish Explorer item properties from text selections --- docs/TESTING.md | 26 +++++++++++- helpers/SelectionHost.cs | 74 ++++++++++++++++++++++++++++++---- src/IsolatedSelectionReader.cs | 4 +- src/LightTranslate.cs | 13 +++--- src/SelectionContextTests.cs | 31 ++++++++++++++ 5 files changed, 132 insertions(+), 16 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index ea4dbdd..b56feff 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -249,7 +249,7 @@ The generated settings previews show an empty credential field. 现在首先通过短时独立进程 `LightTranslate.SelectionHost.exe` 判断上下文并请求应用的 UIA TextPattern 选区;能直接读取的文本无需快照,也不读取或修改剪贴板。 主程序仍不引用 UIAutomationClient,不持有跨进程 UIA/COM 对象,也不恢复原 OLE 快照路径。 -辅助进程只接受源窗口、焦点窗口句柄、鼠标释放位置和长度上限,验证窗口归属并拒绝密码字段; +辅助进程只接受源窗口、焦点窗口句柄、鼠标起止位置、起点原生窗口和长度上限,验证窗口归属并拒绝密码字段; 选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 3 秒的自身终止期限, 主程序异步等待上限为 3.8 秒,并丢弃已取消或焦点改变后的响应。 这不是权限沙箱;它隔离 UIA 原生故障,不会终止用户源应用或轻译主进程。 @@ -268,7 +268,7 @@ UIA TextPattern 选区;能直接读取的文本无需快照,也不读取或 鼠标拖选网页文字不一定把键盘焦点移到该文档。辅助进程优先从鼠标释放位置的 UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘焦点;每一步验证 源窗口归属,最多查找 32 层,并保留独立进程的总超时限制。它不扫描其他文档、 -不读整个页面或 ValuePattern,也不修改 Chromium 的可访问性设置。 +不读整个页面或 ValuePattern 的值(仅检查 IsReadOnly 元数据),也不修改 Chromium 的可访问性设置。 主程序仅记录固定失败码,例如无 TextPattern、空选区、密码字段、窗口不符、 深度上限、提供方异常和超时;不记录控件名称、选区原文或页面内容。 真实控件测试不覆盖网页布局、iframe 与键盘焦点差异,仍须进行实际拖选验收。 @@ -332,3 +332,25 @@ UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘 CheckBox,以及通用面板内 TextBox 的选词,断言无文本区域既不报错也不读写剪贴板, 已确认文本失败仍提示。它们覆盖通知、日历、快速设置常见控件语义,不等于自动操作 或完整复现 Windows 系统浮层;没有清除通知、读取通知正文或更改系统设置。 + +### 文件属性单元格与真正的重命名编辑框 + +真实 Explorer 复现表明,文件列表的属性单元格可能暴露为 Edit + ValuePattern,却没有 +TextPattern;鼠标释放在这种单元格时,键盘焦点仍在 ListItem。仅凭 Edit 角色允许剪贴板 +回退会将文件拖动当成选词失败。现在会检查 Selection/SelectionItem 祖先、焦点和只读 +元数据:列表内未活动或只读的属性若没有 TextPattern,按项目交互结束,不发复制命令。 +提供 TextPattern 的重命名编辑框及只读可选文本仍可读取;活动的可编辑控件缺少该接口时 +仍可走原有安全回退,普通文本提供方异常与超时仍提示。不使用进程名或控件类名黑名单。 + +鼠标手势还将按下时记录的原生窗口和位置传给辅助进程,在读取释放位置之前检查起点; +起点没有文本证据时,不因终点碰到另一个编辑框或焦点改变而读取其旧选区。该检查不在 +鼠标钩子中运行,也不读取起点选中文字;按 Esc 取消的拖动不再排队取词。UIA 起点语义 +在释放后的隔离进程中检查,因此源界面在手势期间完全重建的情况仍需按实际应用验收。 + +上下文测试增加真实隐藏控件的 MSAA Edit 属性角色、单选/多选列表、只读与未活动属性、 +列表内真正的编辑框和只读文本选区,并确认列表之外的无接口 Edit 不被全局屏蔽。 +另对同一真实 Explorer 的 12 个属性单元格比较旧、新辅助程序:旧版均返回 +text-unsupported,修复后均返回 non-text;比较不读取文件名、选区或剪贴板。 +该分类比较不替代完整交互验收。人工测试只在专用目录的合成文件上进行,分别检查单选 +及多选后横拖释放、框选、Esc 取消拖动、F2 后选取文件名文字并取消重命名;不拖动、 +移动或覆盖用户真实文件。当前候选的最终鼠标交互结果需在部署后单独记录。 diff --git a/helpers/SelectionHost.cs b/helpers/SelectionHost.cs index 4e94989..a4c863f 100644 --- a/helpers/SelectionHost.cs +++ b/helpers/SelectionHost.cs @@ -19,10 +19,32 @@ private static int Main(string[] args) try { long rootValue, focusValue; int maximum; - if ((args.Length != 3 && args.Length != 5) || !long.TryParse(args[0], out rootValue) || !long.TryParse(args[1], out focusValue) + if ((args.Length != 3 && args.Length != 5 && args.Length != 8) || !long.TryParse(args[0], out rootValue) || !long.TryParse(args[1], out focusValue) || !int.TryParse(args[2], out maximum) || maximum < 1 || maximum > 65537) return 2; IntPtr root = new IntPtr(rootValue), focus = new IntPtr(focusValue); if (root == IntPtr.Zero || focus == IntPtr.Zero || GetAncestor(focus, 2) != root) { Console.Error.WriteLine("wrong-root"); return 2; } + // A file drag may end over an unrelated Edit or Document. Validate the + // captured origin before inspecting the release point or keyboard focus. + if (args.Length == 8) + { + long originHandle; int originX, originY; + if (!long.TryParse(args[5], out originHandle) || !int.TryParse(args[6], out originX) || !int.TryParse(args[7], out originY)) return 2; + IntPtr origin = new IntPtr(originHandle); + if (GetForegroundWindow() != root || origin == IntPtr.Zero || GetAncestor(origin, 2) != root) + { Console.Error.WriteLine("no-text-pattern"); return 0; } + var hit = AutomationElement.FromPoint(new System.Windows.Point(originX, originY)); + // If layout/focus changed after down, the endpoint cannot authorize text + // capture. Keep the native origin as a boundary, not an application list. + IntPtr currentOrigin = WindowFromPoint(new POINT { x = originX, y = originY }); + // Browser UIA trees may omit a native child HWND. Use the native hit + // boundary rather than requiring that HWND to appear in the UIA tree. + if (hit == null || (currentOrigin != origin && !IsChild(origin, currentOrigin))) + hit = AutomationElement.FromHandle(origin); + ReadAncestors(hit, root, maximum, false); + if (!textContext) + { Console.Error.WriteLine(status); return 0; } + status = "no-text-pattern"; + } if (GetForegroundWindow() == root) { var current = AutomationElement.FocusedElement; @@ -33,7 +55,7 @@ private static int Main(string[] args) string text = null; // Selecting web text need not move keyboard focus into that document/iframe. // The release point identifies the selected surface without scanning other documents. - if (args.Length == 5 && GetForegroundWindow() == root) + if (args.Length >= 5 && GetForegroundWindow() == root) { int x, y; if (!int.TryParse(args[3], out x) || !int.TryParse(args[4], out y)) return 2; @@ -66,7 +88,7 @@ private static int Main(string[] args) } catch { Console.Error.WriteLine(textContext ? "text-provider-error" : "provider-error"); return 2; } } - private static string ReadAncestors(AutomationElement element, IntPtr root, int maximum) + private static string ReadAncestors(AutomationElement element, IntPtr root, int maximum, bool selection = true) { // Chromium can put many layout groups between focus and its Document. // Stay within the source window, with a depth bound and process deadline. @@ -86,15 +108,24 @@ private static string ReadAncestors(AutomationElement element, IntPtr root, int // A web list can belong to a selectable Document: do not blacklist its app. if (type == ControlType.Edit || type == ControlType.Document) { - textContext = true; - string text = Read(element, maximum); - if (text == null) status = "text-unsupported"; + bool inactiveProperty = type == ControlType.Edit && IsInactiveItemProperty(element, root); + if (!inactiveProperty) textContext = true; + string text = Read(element, maximum, selection); + if (text == null) + { + // Shell/property grids can expose display cells as Edit + ValuePattern. + // That role alone does not mean a text selection or an active editor. + if (inactiveProperty) + { status = "non-text"; return string.Empty; } + textContext = true; + status = "text-unsupported"; + } return text; } itemSurface |= IsItemSurface(element, type); if (!itemSurface) { - string text = Read(element, maximum); + string text = Read(element, maximum, selection); if (text != null) return text; } if (element.Current.NativeWindowHandle == root.ToInt64()) @@ -108,6 +139,29 @@ private static string ReadAncestors(AutomationElement element, IntPtr root, int else if (itemSurface) { status = "non-text"; return string.Empty; } return null; } + private static bool IsInactiveItemProperty(AutomationElement element, IntPtr root) + { + // A real active editor without TextPattern may still need the guarded clipboard + // fallback. Read-only cells and inactive item properties must never trigger it. + object value; + var parent = TreeWalker.ControlViewWalker.GetParent(element); + for (int i = 0; i < 32 && parent != null && BelongsTo(parent, root); i++) + { + ControlType type = parent.Current.ControlType; + if (type == ControlType.Document || type == ControlType.Edit) return false; + if (type == ControlType.List || type == ControlType.ListItem || type == ControlType.Tree || type == ControlType.TreeItem + || type == ControlType.DataGrid || type == ControlType.DataItem + || parent.TryGetCurrentPattern(SelectionPattern.Pattern, out value) + || parent.TryGetCurrentPattern(SelectionItemPattern.Pattern, out value)) + { + bool readOnly = element.TryGetCurrentPattern(ValuePattern.Pattern, out value) && ((ValuePattern)value).Current.IsReadOnly; + return readOnly || !element.Current.HasKeyboardFocus || !element.Current.IsKeyboardFocusable; + } + if (parent.Current.NativeWindowHandle == root.ToInt64()) break; + parent = TreeWalker.ControlViewWalker.GetParent(parent); + } + return false; + } private static bool IsItemSurface(AutomationElement element, ControlType type) { if (type == ControlType.List || type == ControlType.ListItem || type == ControlType.Tree || type == ControlType.TreeItem @@ -130,12 +184,13 @@ private static bool BelongsTo(AutomationElement element, IntPtr root) } return false; } - private static string Read(AutomationElement element, int maximum) + private static string Read(AutomationElement element, int maximum, bool selection) { if (element.Current.IsPassword) { status = "password"; return string.Empty; } object value; if (!element.TryGetCurrentPattern(TextPattern.Pattern, out value)) return null; textContext = true; + if (!selection) return string.Empty; // Origin inspection never fetches selected text. var ranges = ((TextPattern)value).GetSelection(); if (ranges == null || ranges.Length > 8) throw new InvalidOperationException(); status = "empty-selection"; @@ -157,4 +212,7 @@ private static string Read(AutomationElement element, int maximum) [DllImport("kernel32.dll")] private static extern bool TerminateProcess(IntPtr process, uint code); [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr window, uint flags); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [StructLayout(LayoutKind.Sequential)] private struct POINT { internal int x, y; } + [DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(POINT point); + [DllImport("user32.dll")] private static extern bool IsChild(IntPtr parent, IntPtr child); } diff --git a/src/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs index ee93bf2..cd742b4 100644 --- a/src/IsolatedSelectionReader.cs +++ b/src/IsolatedSelectionReader.cs @@ -68,7 +68,7 @@ internal static SelectionReadResult Decode(int exitCode, string status, string t return new SelectionReadResult(SelectionReadState.ProbeFailed); } - internal static async Task ReadResult(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null) + internal static async Task ReadResult(IntPtr window, CancellationToken ct, int maximum = 65537, IntPtr focus = default(IntPtr), Native.POINT? point = null, SelectionSurface origin = null) { ct.ThrowIfCancellationRequested(); if (focus == IntPtr.Zero) @@ -83,6 +83,8 @@ internal static SelectionReadResult Decode(int exitCode, string status, string t if (focus == IntPtr.Zero || !File.Exists(path)) { Program.Log("selection-helper", "missing-helper-or-window"); return new SelectionReadResult(SelectionReadState.Failed); } string arguments = window.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + focus.ToInt64().ToString(CultureInfo.InvariantCulture) + " " + maximum.ToString(CultureInfo.InvariantCulture); if (point.HasValue) arguments += " " + point.Value.x.ToString(CultureInfo.InvariantCulture) + " " + point.Value.y.ToString(CultureInfo.InvariantCulture); + if (point.HasValue && origin != null) arguments += " " + origin.Window.ToInt64().ToString(CultureInfo.InvariantCulture) + + " " + origin.Point.x.ToString(CultureInfo.InvariantCulture) + " " + origin.Point.y.ToString(CultureInfo.InvariantCulture); var start = new ProcessStartInfo(path, arguments) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8 }; try diff --git a/src/LightTranslate.cs b/src/LightTranslate.cs index 0164939..6a3e7cd 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -282,8 +282,9 @@ private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow, if (settings.Enabled && eligible && (dragged || twice) && (window == downWindow || Native.SameApp(window, downWindow)) && !bubble.Contains(data.pt)) { var point = data.pt; + var origin = downSurface; int queuedVersion = generation; - app.Dispatcher.BeginInvoke(new Action(delegate { if (queuedVersion == generation) BeginSelection(window, point); })); + app.Dispatcher.BeginInvoke(new Action(delegate { if (queuedVersion == generation) BeginSelection(window, point, origin); })); } } else if (message == 0x20A || message == 0x20E || message == 0x204 || message == 0x207) @@ -301,6 +302,8 @@ private void HandleKeyboard(int message, Native.KEYBOARD data, IntPtr capturedWi if (data.extra != Native.OwnInputMarker) { if (message == 0x100 || message == 0x104) Dismiss(false); + if ((message == 0x100 || message == 0x104) && data.vkCode == 0x1B) + { down = false; lastUpTime = 0; } // Escape cancels an in-progress drag. if ((message == 0x101 || message == 0x105) && (data.vkCode == 0xA0 || data.vkCode == 0xA1) && settings.Enabled) { Native.POINT point; @@ -321,7 +324,7 @@ private void Dismiss(bool immediate) lifetime.Reset(); } - private async void BeginSelection(IntPtr window, Native.POINT point) + private async void BeginSelection(IntPtr window, Native.POINT point, SelectionSurface origin = null) { selections++; Dismiss(true); @@ -345,7 +348,7 @@ private async void BeginSelection(IntPtr window, Native.POINT point) // 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); + string text = await SelectionReader.CopySelection(window, ct, Trace, point, origin); 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(); @@ -696,13 +699,13 @@ 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) + public static async Task CopySelection(IntPtr window, CancellationToken ct, Action trace, Native.POINT? point = null, SelectionSurface origin = null) { if (Native.GetForegroundWindow() != window || Native.ModifierDown()) { trace("copy skipped focus/modifier"); return null; } if (Native.IsPasswordFocus(window)) { trace("password field skipped"); return null; } Func valid = delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }; return await SelectionAcquisition.Read( - delegate { return IsolatedSelectionReader.ReadResult(window, ct, point: point); }, + delegate { return IsolatedSelectionReader.ReadResult(window, ct, point: point, origin: origin); }, async delegate(SelectionReadResult result) { using (var clipboard = new NativeSelectionClipboard()) diff --git a/src/SelectionContextTests.cs b/src/SelectionContextTests.cs index 5c46515..d92ba6d 100644 --- a/src/SelectionContextTests.cs +++ b/src/SelectionContextTests.cs @@ -10,6 +10,21 @@ namespace LightTranslate { internal static class SelectionContextTests { + // Reproduce the metadata contract observed on real Explorer property cells: + // MSAA text/Edit role, no TextPattern, nested under an item-selection surface. + private sealed class PropertyCell : Forms.Control + { + internal bool ReadOnlyCell; + protected override Forms.AccessibleObject CreateAccessibilityInstance() { return new PropertyAccessibility(this); } + private sealed class PropertyAccessibility : Forms.Control.ControlAccessibleObject + { + private readonly PropertyCell cell; + internal PropertyAccessibility(PropertyCell cell) : base(cell) { this.cell = cell; } + public override Forms.AccessibleRole Role { get { return Forms.AccessibleRole.Text; } } + public override Forms.AccessibleStates State { get { return cell.ReadOnlyCell ? Forms.AccessibleStates.ReadOnly | Forms.AccessibleStates.Focusable : Forms.AccessibleStates.None; } } + public override string Value { get { return "synthetic property"; } set { } } + } + } private sealed class Clipboard : ISelectionClipboard { internal int Snapshots, Copies, Reads, Restores; @@ -64,6 +79,20 @@ internal static int Run() nonText("selected icon drag context", list); list.View = Forms.View.Details; list.Columns.Add("synthetic column", 120); nonText("explorer-style item list", list); + list.Items.Add("second synthetic item").Selected = true; + nonText("multiple selected items", list); + using (var property = new PropertyCell()) + { + list.Controls.Add(property); IntPtr propertyHandle = property.Handle; + nonText("inactive editable property inside item list", property); + property.ReadOnlyCell = true; + nonText("read-only property inside item list", property); + } + using (var unsupportedEdit = new PropertyCell()) + { + form.Controls.Add(unsupportedEdit); IntPtr unsupportedHandle = unsupportedEdit.Handle; + check("unsupported Edit outside item surface is not globally suppressed", probe(unsupportedEdit).State == SelectionReadState.TextUnsupported); + } tree.Nodes.Add("synthetic tree item"); tree.SelectedNode = tree.Nodes[0]; nonText("tree selection context", tree); using (var rename = new Forms.TextBox { Text = "reversible.txt" }) @@ -72,6 +101,8 @@ internal static int Run() var clipboard = new Clipboard(); check("inline edit inside item list remains selectable text", Acquire(probe(rename), clipboard) == "reversible"); check("inline edit selection avoids clipboard", clipboard.Snapshots == 0 && clipboard.Copies == 0); + rename.ReadOnly = true; + check("read-only text with TextPattern remains selectable inside list", Acquire(probe(rename), clipboard) == "reversible"); } foreach (Forms.Control surface in new Forms.Control[] { new Forms.Panel(), new Forms.GroupBox(), new Forms.Button { Text = "synthetic action" },