Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ jobs:
- name: Clipboard workflow regression
shell: pwsh
run: ./scripts/test-clipboard.ps1
- name: Clipboard overwrite consent and race regression
shell: pwsh
run: ./scripts/test-overwrite.ps1
- name: Native window gesture boundaries
shell: pwsh
run: ./scripts/test-gestures.ps1
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@ Index 单次翻译总期限为 60 秒,429 最多尝试三次,按 Retry-After
额度和费用以 [DeepL 当前 API 套餐](https://support.deepl.com/hc/en-us/articles/360021200939-DeepL-API-plans) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。
译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。
先由独立的 `LightTranslate.SelectionHost.exe` 判断操作区域并读取 Windows UI Automation 文本选区。空选区、图标列表、树等非文本交互直接结束,不访问剪贴板;不会按应用名全局排除资源管理器,列表内重命名编辑框仍可取词。辅助进程限时退出,主程序不持有 UIA/COM 对象。分发或移动程序时请保留该辅助文件。
仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法安全备份时不复制,并显示读取失败提示;不清空剪贴板,也不退回 OLE 快照。未知区域或尚未确认文本上下文的探测失败会安静结束并保留固定诊断码,不会发送复制命令;已确认文本区域的读取失败以及辅助程序缺失仍有明确提示。系统或剪贴板管理器仍可能保留实际执行过的临时复制记录。
仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法完整备份时,默认不复制,而是准确提示原因,并提供“本次覆盖并取词”。点击即允许这次复制替换原剪贴板,原图片、文字或私有格式可能丢失;Windows 剪贴板历史不保证恢复。单次许可最多保留 15 秒,失焦、新操作、设置变化或原剪贴板更新后失效。
“翻译”设置页另有默认关闭的“取词优先,允许覆盖”。勾选时需确认风险,保存后才生效;取消或保存失败不启用。开启后仅对稳定的、不支持保留/过大/无法完整读取的剪贴板使用覆盖兜底,能完整备份时仍优先恢复原内容。剪贴板暂时无法打开或已经变化时会取消并提示重试,不自动覆盖竞争中的数据。
覆盖兜底不预先清空剪贴板,不恢复旧备份,也不放开未知格式或 OLE 反序列化。只有看到新的剪贴板序列号并确认复制来源为源应用后才读取 Unicode 文本;复制失败、空结果、超时、取消、失焦或可检测的并发变化不会翻译旧内容。用户随后复制的新内容不会被旧备份恢复覆盖。未知区域或尚未确认文本上下文的探测失败仍安静结束,不发送复制命令;已确认文本区域的读取失败以及辅助程序缺失仍有明确提示。系统或剪贴板管理器可能保留实际执行过的临时复制记录。
发出复制后再取消,只能停止后续取词和翻译;原剪贴板可能已经被替换,不会尝试用旧数据回滚覆盖新的剪贴板内容。

## 从源码构建

Expand Down
10 changes: 10 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,3 +362,13 @@ text-unsupported,修复后均返回 non-text;比较不读取文件名、选
仅在明确授权后使用 `-Online`:依次向三档发送同一固定公开短句 `The window closes automatically.`,将请求模型、返回模型、HTTP 状态、尝试次数、耗时、公开句译文和错误写入 `index-live-test.json`。它不读取用户选区、剪贴板或外部文档。文档列出的模型不等同于在线测试成功;以该文件中各档的实际结果为准。

原 `--self-test-offline` 也包含 Index 模拟测试;剪贴板、托盘、手势、外部选区辅助程序和已有翻译源测试继续保留。Index 的等待浮层最多等待至 60 秒请求期限;鼠标移开、切换窗口、开始新操作或保存设置仍会取消旧请求。

## 剪贴板覆盖候选验证

`scripts/test-overwrite.ps1 -OutputDirectory <独立输出目录>` 或 `--self-test-overwrite` 仅使用模拟剪贴板和临时配置,不访问用户真实剪贴板正文。覆盖原因分类、默认关闭、能备份时仍恢复、明确许可后覆盖且永不恢复旧备份、复制失败与空结果、有限次等待、来源/序列号校验、取消/失焦、并发用户复制、重复操作,以及单次许可的上下文、15 秒期限与不可重放检查。

配置用例验证拒绝风险提示、确认后待保存、取消、失败回滚、保存回填、旧配置默认关闭和原 Index 设置保留。实际 WPF 浮层、风险确认框和设置页均可离屏渲染;按钮取消、重复点击和提示收起后不再执行动作。

`--self-test-clipboard-native` 先切换到独立 window station 和 desktop,隔离失败即终止,随后才使用该私有剪贴板内的合成数据验证原生取词和覆盖。新增不支持格式时零复制、明确允许后真实 TextBox.Copy 只保留新文字、复制无变化时不返回旧文字等用例。测试不覆盖用户真实剪贴板,不依赖保存/恢复用户数据实现隔离。

此候选未自动替换或启动本机运行版。真实 Steam 窗口点击、复杂第三方剪贴板管理器、不同 DPI 和持续使用仍需后续授权验收。Windows 延迟渲染等原生调用可能阻塞,轮询次数上限不是对每个原生提供方的绝对执行时限保证。
10 changes: 10 additions & 0 deletions scripts/test-overwrite.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[CmdletBinding()]
param([string]$OutputDirectory = (Join-Path $PSScriptRoot '..\dist\LightTranslate'))
$ErrorActionPreference = 'Stop'
$outputPath = [IO.Path]::GetFullPath($OutputDirectory)
$exe = Join-Path $outputPath 'LightTranslate.exe'
if (-not (Test-Path -LiteralPath $exe)) { throw 'Build the independent candidate first.' }
$test = Start-Process -FilePath $exe -ArgumentList '--self-test-overwrite' -WindowStyle Hidden -PassThru
if (-not $test.WaitForExit(30000)) { throw ('Test still running; inspect PID ' + $test.Id) }
if ($test.ExitCode -ne 0) { throw ('Overwrite test failed; see ' + (Join-Path $outputPath 'status.log')) }
Get-Content -LiteralPath (Join-Path $outputPath 'clipboard-overwrite-test.json') -Raw -Encoding utf8
1 change: 1 addition & 0 deletions settings.example.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"Enabled": true,
"ClipboardFallback": true,
"AllowClipboardOverwrite": false,
"Target": "zh-Hans",
"TranslationProvider": "auto",
"IndexModel": "Index-Translate-35B-A3B",
Expand Down
84 changes: 73 additions & 11 deletions src/ClipboardCapture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,40 @@ internal static class ClipboardCapture
private static readonly SemaphoreSlim gate = new SemaphoreSlim(1, 1);

internal static async Task<string> Read(ISelectionClipboard clipboard, IntPtr source,
Func<bool> valid, Action copy, Action<string> trace, Func<Task> wait, Func<Task<string>> withoutClipboard = null)
Func<bool> valid, Action copy, Action<string> trace, Func<Task> wait, Func<Task<string>> withoutClipboard = null,
ClipboardCapturePolicy policy = null)
{
// Do not queue stale selections or snapshot another capture's temporary clipboard.
if (!gate.Wait(0)) { trace("copy skipped busy"); return null; }
try
{
ClipboardSnapshot saved;
if (!valid()) return null;
uint initial = clipboard.Sequence;
if (policy != null && policy.RequiredSequence.HasValue && policy.RequiredSequence.Value != initial)
throw new ClipboardBackupException(ClipboardBackupFailure.Changed, initial);
if (!clipboard.TrySnapshot(out saved))
{
trace("clipboard snapshot skipped");
if (!valid()) return null;
if (policy != null)
{
var diagnostics = clipboard as IClipboardBackupDiagnostics;
var reason = diagnostics == null ? ClipboardBackupFailure.Unreadable : diagnostics.BackupFailure;
uint current = clipboard.Sequence;
if (initial == 0 || current != initial) reason = ClipboardBackupFailure.Changed;
trace("clipboard backup reason=" + reason);
if (policy.AllowOverwrite && ClipboardBackupException.MayOverwrite(reason))
return await ReadWithoutRestore(clipboard, source, current, valid, copy, trace, wait);
throw new ClipboardBackupException(reason, current);
}
if (withoutClipboard == null || !valid()) return null;
string selected = await withoutClipboard();
return valid() ? selected : null;
}
if (!valid() || clipboard.Sequence != saved.Sequence) return null;
if (policy != null && policy.RequiredSequence.HasValue && saved.Sequence != policy.RequiredSequence.Value)
throw new ClipboardBackupException(ClipboardBackupFailure.Changed, clipboard.Sequence);
copy();
for (int i = 0; i < 12; i++)
{
Expand All @@ -62,6 +80,7 @@ internal static async Task<string> Read(ISelectionClipboard clipboard, IntPtr so
var result = clipboard.Restore(saved, copied, valid);
if (result != RestoreResult.Busy)
{
if (result == RestoreResult.Changed) { trace("clipboard changed before restore; result discarded"); return null; }
if (result == RestoreResult.Failed) trace("clipboard restore failed");
return valid() ? text : null;
}
Expand All @@ -74,17 +93,47 @@ internal static async Task<string> Read(ISelectionClipboard clipboard, IntPtr so
}
finally { gate.Release(); }
}

private static async Task<string> ReadWithoutRestore(ISelectionClipboard clipboard, IntPtr source, uint before,
Func<bool> valid, Action copy, Action<string> trace, Func<Task> wait)
{
if (!valid()) return null;
if (before == 0 || clipboard.Sequence != before)
throw new ClipboardBackupException(ClipboardBackupFailure.Changed, clipboard.Sequence);
// Do not clear the clipboard first. A failed Ctrl+C must never return the old data.
// This path has no backup and must never call Restore, even after cancellation.
trace("clipboard overwrite authorized");
try { copy(); }
catch (OperationCanceledException) { throw; }
catch { if (!valid()) return null; throw new SelectionUnavailableException("未能向源应用发送本次复制,未读取旧剪贴板。原剪贴板可能已改变。"); }
for (int i = 0; i < 32; i++)
{
await wait();
if (!valid()) return null;
uint observed = clipboard.Sequence;
if (observed == before) continue;
uint copied; string text;
if (!clipboard.TryReadText(source, observed, out copied, out text) || copied != observed || clipboard.Sequence != copied)
throw new SelectionUnavailableException("剪贴板已变化或复制来源无法确认,已取消本次取词;未翻译旧内容。");
if (!valid()) return null;
if (string.IsNullOrWhiteSpace(text))
throw new SelectionUnavailableException("这次复制没有产生可读取的新文字,未翻译旧内容。原剪贴板可能已改变。");
return text;
}
throw new SelectionUnavailableException("这次复制超时,没有收到可验证的新文字;未翻译旧内容。原剪贴板可能已改变。");
}
}

// Read only documented HGLOBAL text formats. Never materialize IDataObject/OLE objects.
// Unknown formats reject the entire snapshot before Ctrl+C, rather than losing rich data.
internal sealed class NativeSelectionClipboard : ISelectionClipboard, IDisposable
internal sealed class NativeSelectionClipboard : ISelectionClipboard, IClipboardBackupDiagnostics, IDisposable
{
internal const int MaxFormatBytes = 8 * 1024 * 1024;
private const int MaxSnapshotBytes = 16 * 1024 * 1024;
private readonly Forms.NativeWindow window = new Forms.NativeWindow();
internal IntPtr Handle { get { return window.Handle; } }
public uint Sequence { get { return Native.GetClipboardSequenceNumber(); } }
public ClipboardBackupFailure BackupFailure { get; private set; }

internal NativeSelectionClipboard()
{
Expand All @@ -102,52 +151,65 @@ internal static bool Supported(uint format)
}

internal static bool TryFormats(out List<uint> formats)
{ ClipboardBackupFailure reason; return TryFormats(out formats, out reason); }
private static bool TryFormats(out List<uint> formats, out ClipboardBackupFailure reason)
{
reason = ClipboardBackupFailure.None;
formats = new List<uint>();
uint format = 0;
while (true)
{
ClipboardNative.SetLastError(0);
format = ClipboardNative.EnumClipboardFormats(format);
if (format == 0) return Marshal.GetLastWin32Error() == 0;
if (formats.Count >= 64 || !Supported(format) || formats.Contains(format)) return false;
if (format == 0) { if (Marshal.GetLastWin32Error() != 0) { reason = ClipboardBackupFailure.Unreadable; return false; } return true; }
if (formats.Count >= 64) { reason = ClipboardBackupFailure.TooLarge; return false; }
if (!Supported(format)) { reason = ClipboardBackupFailure.UnsupportedFormat; return false; }
if (formats.Contains(format)) { reason = ClipboardBackupFailure.Unreadable; return false; }
formats.Add(format);
}
}

internal static bool TryBytes(uint format, out byte[] bytes)
{ ClipboardBackupFailure reason; return TryBytes(format, out bytes, out reason); }
private static bool TryBytes(uint format, out byte[] bytes, out ClipboardBackupFailure reason)
{
reason = ClipboardBackupFailure.Unreadable;
bytes = null;
IntPtr handle = ClipboardNative.GetClipboardData(format);
if (handle == IntPtr.Zero) return false;
ulong size = ClipboardNative.GlobalSize(handle).ToUInt64();
if (size == 0 || size > MaxFormatBytes) return false;
if (size > MaxFormatBytes) { reason = ClipboardBackupFailure.TooLarge; return false; }
if (size == 0) return false;
IntPtr pointer = ClipboardNative.GlobalLock(handle);
if (pointer == IntPtr.Zero) return false;
try { bytes = new byte[(int)size]; Marshal.Copy(pointer, bytes, 0, bytes.Length); return true; }
try { bytes = new byte[(int)size]; Marshal.Copy(pointer, bytes, 0, bytes.Length); reason = ClipboardBackupFailure.None; return true; }
finally { ClipboardNative.GlobalUnlock(handle); }
}

public bool TrySnapshot(out ClipboardSnapshot snapshot)
{
snapshot = null;
if (!ClipboardNative.OpenClipboard(Handle)) return false;
BackupFailure = ClipboardBackupFailure.None;
if (!ClipboardNative.OpenClipboard(Handle)) { BackupFailure = ClipboardBackupFailure.Busy; return false; }
try
{
var saved = new ClipboardSnapshot { Sequence = Sequence };
if (saved.Sequence == 0) return false;
if (saved.Sequence == 0) { BackupFailure = ClipboardBackupFailure.Changed; return false; }
List<uint> formats;
if (!TryFormats(out formats)) return false;
ClipboardBackupFailure reason;
if (!TryFormats(out formats, out reason)) { BackupFailure = reason; return false; }
int total = 0;
foreach (uint format in formats)
{
byte[] bytes;
if (!TryBytes(format, out bytes) || (total += bytes.Length) > MaxSnapshotBytes) return false;
if (!TryBytes(format, out bytes, out reason)) { BackupFailure = reason; return false; }
if ((total += bytes.Length) > MaxSnapshotBytes) { BackupFailure = ClipboardBackupFailure.TooLarge; return false; }
saved.Formats.Add(new KeyValuePair<uint, byte[]>(format, bytes));
}
// Rendering a delayed format may change the sequence or advertise more formats.
List<uint> after;
if (saved.Sequence != Sequence || !TryFormats(out after) || !formats.SequenceEqual(after)) return false;
if (saved.Sequence != Sequence || !TryFormats(out after, out reason) || !formats.SequenceEqual(after))
{ BackupFailure = ClipboardBackupFailure.Changed; return false; }
snapshot = saved;
return true;
}
Expand Down
3 changes: 1 addition & 2 deletions src/ClipboardCaptureTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ internal static void Run(Dictionary<string, object> results)
var canceled = new Fake(); canceled.OnSnapshot = delegate { canceled.Valid = false; };
Check(canceled.Run(tick).Result == null && canceled.Copies == 0, "canceled snapshot never copies");
var userCopy = new Fake(); userCopy.OnRestore = delegate { userCopy.Version++; };
userCopy.Run(tick).GetAwaiter().GetResult();
Check(userCopy.Restores == 0, "newer clipboard is not overwritten");
Check(userCopy.Run(tick).GetAwaiter().GetResult() == null && userCopy.Restores == 0, "newer clipboard is not overwritten and stale capture is discarded");
var cancelAfter = new Fake(); cancelAfter.OnRead = delegate { cancelAfter.Valid = false; };
Check(cancelAfter.Run(tick).Result == null && cancelAfter.Restores == 0, "cancellation before restore preserves clipboard");
var wrongOwner = new Fake { ReadWorks = false };
Expand Down
Loading
Loading