diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0effef4..413ebfb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,18 +17,37 @@ jobs: - name: Build application shell: pwsh run: ./build.ps1 + - name: Clipboard workflow regression + shell: pwsh + run: ./scripts/test-clipboard.ps1 + - 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 + - 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 - 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/.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..fd42146 100644 --- a/README.md +++ b/README.md @@ -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,9 +81,12 @@ 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) 为准;不内置任何每月免费额度承诺。认证、额度、限流和超时会显示各自提示,不自动重试计费请求。 译文缓存保存在当前进程内,退出后清空。程序默认不记录选区原文或用户译文。 -取词通过临时复制选区完成,并尝试恢复原剪贴板;系统或剪贴板管理器可能保留复制记录。 +先由独立的 `LightTranslate.SelectionHost.exe` 判断操作区域并读取 Windows UI Automation 文本选区。空选区、图标列表、树等非文本交互直接结束,不访问剪贴板;不会按应用名全局排除资源管理器,列表内重命名编辑框仍可取词。辅助进程限时退出,主程序不持有 UIA/COM 对象。分发或移动程序时请保留该辅助文件。 +仅在确认是文本编辑框或文档、但不支持选区接口时,才尝试安全备份、临时复制和恢复剪贴板。图片或应用专用格式导致无法安全备份时不复制,并显示读取失败提示;不清空剪贴板,也不退回 OLE 快照。未知区域或尚未确认文本上下文的探测失败会安静结束并保留固定诊断码,不会发送复制命令;已确认文本区域的读取失败以及辅助程序缺失仍有明确提示。系统或剪贴板管理器仍可能保留实际执行过的临时复制记录。 ## 从源码构建 diff --git a/build.ps1 b/build.ps1 index 3cddb97..026a016 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\' + $_)) } @@ -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')) ('/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'), (Join-Path $PSScriptRoot 'THIRD_PARTY_NOTICES.md') -Destination $outputPath diff --git a/docs/TESTING.md b/docs/TESTING.md index fef41a0..b56feff 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -56,8 +56,9 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 | 字段 | 默认值 | 作用 | |---|---|---| | `Enabled` | `true` | 自动划词翻译开关,也可通过托盘修改 | -| `ClipboardFallback` | `true` | 剪贴板取词开关,关闭后停止取词 | -| `Target` | `zh-Hans` | 微软接口的目标语言;本地词库和腾讯备用接口输出中文 | +| `ClipboardFallback` | `true` | 选区取词开关,关闭后停止所有取词 | +| `TranslationProvider` | `auto` | `auto` 保留本地词库优先、微软失败后腾讯;`microsoft` / `tencent` / `deepl` 仅调用选定服务并跳过词库 | +| `Target` | `zh-Hans` | 微软 / DeepL 的目标语言;本地词库和腾讯输出中文 | | `MaxSelectionLength` | `2000` | 单次选区字符数上限 | | `ExcludedApps` | `[]` | 排除的进程名称,可带或不带 `.exe` | | `Diagnostics` | `false` | 触发诊断日志开关 | @@ -72,10 +73,10 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 补充平面的字母按 Unicode 标量计一次,全角 Latin / 重音字母计入分母但不计英文分子。 大于 0% 时没有 A–Z/a–z 的文本不触发;0% 时无文字字母或纯中文仍被原有规则跳过。 -`ClipboardFallback` 沿用早期字段名,当前取词路径统一使用剪贴板。 +`ClipboardFallback` 沿用早期字段名,同时控制剪贴板取词和独立进程选区读取。 面板纳入 `Enabled`、`ClipboardFallback`、`Target`、`MaxSelectionLength`、`ExcludedApps` -和五项阅读选项。目标语言只校验修改后输入的语言标签语法,不联网获取语言列表;服务是否支持自定义标签由微软决定。 +和五项阅读选项。目标语言只校验修改后输入的语言标签语法,不联网获取语言列表;服务是否支持自定义标签由所选服务决定。 修改后的选区上限要求正整数,排除应用支持换行及中英文逗号/分号,按进程名校验、去重。 未改动的原有自定义目标、长度和排除数组逐值保留;隐藏的 `Diagnostics` 克隆保留,不因普通设置或恢复默认值而重置。 @@ -96,15 +97,16 @@ GitHub Actions 会执行编译、词库构建和离线自检,并上传构建 ## 取词与数据处理 -程序使用带内部标记的 `Ctrl+C` 获取选区,并尝试保存、恢复原剪贴板的各格式。 +程序先由独立进程判断文本上下文和读取 UIA 选区;空选区及非文本交互不访问剪贴板。仅确认是文本区域但缺少选区接口时,才使用带内部标记的 `Ctrl+C` 回退,快照仅接受支持的文本格式;原剪贴板无法完整安全备份时保留原内容并提示读取失败。 如果用户或其他应用在取词期间更新了剪贴板,程序会避免覆盖新的内容。 系统剪贴板历史和第三方剪贴板管理器仍可能保留临时复制记录。 -命中本地词库的选区不会发送给在线服务。其他文字发送给微软,主服务失败时可能发送给腾讯。 -启动时会预热微软连接,该请求不包含选区文字。在线接口采用兼容协议,当前无需个人 API 密钥; -接口可用性由服务端决定,可能出现限流或协议变更。 +自动模式命中本地词库时不发送选区;未命中发送给微软,失败后可能发送给腾讯。 +自动或微软模式启动时预热微软连接,不包含选区;腾讯和 DeepL 模式不预热。 +明确选择单一服务时跳过词库且不回退;DeepL 需要用户保存密钥,可能计费。 +微软和腾讯内置接口无需个人密钥;接口可用性由服务端决定,可能限流或变更。 -译文缓存最多 256 条,仅保存在当前进程内。程序不记录选区原文或用户译文。 +普通服务和 DeepL 各有最多 256 条译文缓存,仅保存在当前进程内。程序不记录选区原文或用户译文。 诊断日志启用后会记录进程名、进程编号、字符数和触发状态;启动错误日志可能包含本机路径。 ## 兼容性记录 @@ -147,3 +149,208 @@ 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 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 +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. + +## 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. + +## Translation provider regression + +`TranslationProvider` defaults to `auto` for old settings. The panel also offers +`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 target. Automatic mode +retains the existing Chinese dictionary and Tencent fallback behavior even when +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 +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. + + +## 图片或专用格式剪贴板下的选区读取 + +仅允许文本快照的守卫会拒绝图片和应用专用格式。这是保护原剪贴板所需的行为。 +现在首先通过短时独立进程 `LightTranslate.SelectionHost.exe` 判断上下文并请求应用的 +UIA TextPattern 选区;能直接读取的文本无需快照,也不读取或修改剪贴板。 +主程序仍不引用 UIAutomationClient,不持有跨进程 UIA/COM 对象,也不恢复原 OLE 快照路径。 +辅助进程只接受源窗口、焦点窗口句柄、鼠标起止位置、起点原生窗口和长度上限,验证窗口归属并拒绝密码字段; +选区通过匿名标准输出管道返回,不写文件或日志。辅助进程有 3 秒的自身终止期限, +主程序异步等待上限为 3.8 秒,并丢弃已取消或焦点改变后的响应。 +这不是权限沙箱;它隔离 UIA 原生故障,不会终止用户源应用或轻译主进程。 +已确认文本区域无法安全读取或超时,以及辅助程序缺失时,浮层提示取词失败并保留剪贴板;尚未确认文本上下文时只保留固定诊断码。 + +`./scripts/test-selection.ps1` 使用真实 Windows 编辑控件和真实外部辅助进程, +合成选区经过上下文判断、选区读取、英文比例检查,最终命中本地词典。 +它同时验证空选区、密码框、错误源窗口、取消和输出长度上限,不调用在线翻译, +不读取用户剪贴板内容,也不改变用户窗口焦点;只记录剪贴板序列号是否保持不变。 +`./scripts/test-clipboard.ps1 -Native` 在私有 window station 中额外验证真实编辑控件的 +复制命令、原生快照恢复,以及专用格式不会被覆盖;所有数据均为合成数据。 +这些测试不等于已验证每个浏览器、Word、管理员权限窗口或远程桌面的实际兼容性。 + +### Chromium 选区定位 + +鼠标拖选网页文字不一定把键盘焦点移到该文档。辅助进程优先从鼠标释放位置的 +UIA 元素向上查找 TextPattern,随后才尝试原生焦点和 UIA 键盘焦点;每一步验证 +源窗口归属,最多查找 32 层,并保留独立进程的总超时限制。它不扫描其他文档、 +不读整个页面或 ValuePattern 的值(仅检查 IsReadOnly 元数据),也不修改 Chromium 的可访问性设置。 +主程序仅记录固定失败码,例如无 TextPattern、空选区、密码字段、窗口不符、 +深度上限、提供方异常和超时;不记录控件名称、选区原文或页面内容。 +真实控件测试不覆盖网页布局、iframe 与键盘焦点差异,仍须进行实际拖选验收。 + +### 窗口操作与文字拖选的边界 + +鼠标按下、松开时,输入线程只记录窗口句柄、客户区位置、窗口边界和控件类名。 +取词前排除非客户区、原生滚动条、跨窗口拖动,以及期间发生的窗口移动或缩放; +客户区内的自绘标题栏再由带 25 毫秒时限的 WM_NCHITTEST 检查排除。 +命中测试在 UI 调度线程执行,不在全局鼠标钩子中发送跨进程消息。 +不合格的手势不会进入选区读取、剪贴板快照、复制或翻译路径,也不会成为下一次双击的起点。 + +`./scripts/test-gestures.ps1` 使用自有隐藏原生窗口、编辑框和滚动条,结合合成手势端点, +验证普通文字拖选、双击区域、标题栏、边框、独立滚动条、编辑框内滚动条、自绘标题栏、 +客户区发起的移动和缩放,以及移动之后重新选词。测试使用真实窗口几何和命中测试, +不向用户应用注入鼠标事件,不读取剪贴板内容;它不替代实际记事本、浏览器和桌面应用验收。 +完全自绘、未暴露原生滚动条且命中测试始终返回客户区的滚动条仍不在此守卫的覆盖范围内。 + +### 空选区与读取失败 + +辅助进程的结果区分有文本、成功但选区为空、不支持 TextPattern、密码字段、超时与失败。 +成功的空选区直接结束当前取词,不显示失败提示;辅助进程也不再向其他焦点或祖先回退, +避免把另一个控件保留的旧选区作为本次结果。折叠文本范围先检查端点,不读取其相邻文本。 +文本区域缺少选区接口、超时和提供方异常仍保留失败提示。未确认文本上下文的无接口、超时或异常仅记固定诊断,不将一般交互当作取词错误。 + +选区集成测试使用真实 TextBox 和 RichTextBox,分别覆盖文末折叠选区(空拖动后的状态)、 +正文中折叠光标、空文档以及空选区前后的正常选词;经过同一上下文判断和错误转换路径, +验证没有复制、剪贴板读取或旧文本返回。另验证真实不支持 TextPattern 的窗口和固定错误协议。 +这些控件测试不注入实际记事本鼠标动作;实际记事本的文末空拖以及 Chromium 正常选词仍需人工验收。 + +### 非文本交互的提前判断 + +`./scripts/test-selection-context.ps1` 使用自有隐藏 ListView、TreeView 和列表内编辑框, +覆盖空白图标区域、已有项目选中的图标拖动上下文、详细列表和树选择;同时在可备份与 +不可备份的模拟剪贴板下验证快照、复制、读取和恢复调用次数均为零,且不返回旧文本。 +列表内的重命名编辑框仍能返回所选测试词;不是按 Explorer 进程名或桌面标题硬编码禁用。 + +辅助进程按控件角色及 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 系统浮层;没有清除通知、读取通知正文或更改系统设置。 + +### 文件属性单元格与真正的重命名编辑框 + +真实 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 new file mode 100644 index 0000000..a4c863f --- /dev/null +++ b/helpers/SelectionHost.cs @@ -0,0 +1,218 @@ +using System; +using System.Runtime.InteropServices; +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 +{ + 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(textContext ? "text-deadline" : "deadline"); } catch { } TerminateProcess(new IntPtr(-1), 3); }, null, 3000, Timeout.Infinite); + try + { + long rootValue, focusValue; int maximum; + 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; + if (current != null && current.Current.IsPassword) { Console.Error.WriteLine("password"); return 0; } + } + var element = AutomationElement.FromHandle(focus); + 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; + 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. + 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 && status != "text-unsupported" && GetForegroundWindow() == root) + { + var focused = AutomationElement.FocusedElement; + if (focused != null && !focused.Current.IsPassword && BelongsTo(focused, root)) + text = ReadAncestors(focused, root, maximum); + } + if (!string.IsNullOrEmpty(text)) + { + Console.OutputEncoding = new UTF8Encoding(false); + Console.Write(text); + Console.Error.WriteLine("selected"); + } + else Console.Error.WriteLine(status); + return 0; + } + catch { Console.Error.WriteLine(textContext ? "text-provider-error" : "provider-error"); return 2; } + } + 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. + bool itemSurface = false; + for (int i = 0; i < 32 && element != null; i++) + { + if (element.Current.IsPassword) { status = "password"; 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) + { + 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, selection); + 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 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 + || 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++) + { + 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, 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"; + 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(part.Substring(0, Math.Min(part.Length, 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(); + [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/scripts/test-clipboard.ps1 b/scripts/test-clipboard.ps1 new file mode 100644 index 0000000..10c925e --- /dev/null +++ b/scripts/test-clipboard.ps1 @@ -0,0 +1,17 @@ +[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) { + 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/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/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/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/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/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/ClipboardCapture.cs b/src/ClipboardCapture.cs new file mode 100644 index 0000000..00ff1f6 --- /dev/null +++ b/src/ClipboardCapture.cs @@ -0,0 +1,241 @@ +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, 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()) 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++) + { + 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..d614331 --- /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"] = "workflow/race/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..fe9f04d --- /dev/null +++ b/src/ClipboardNativeTests.cs @@ -0,0 +1,192 @@ +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(); + // 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, "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"); + 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; + 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), "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(); } + 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(); } + } + } + + [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, 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); + } +} 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/IsolatedSelectionReader.cs b/src/IsolatedSelectionReader.cs new file mode 100644 index 0000000..cd742b4 --- /dev/null +++ b/src/IsolatedSelectionReader.cs @@ -0,0 +1,114 @@ +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 enum SelectionReadState { Selected, Empty, NonText, Unconfirmed, TextUnsupported, Blocked, ProbeTimeout, ProbeFailed, 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.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; + } + } + 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) + { return (await ReadResult(window, ct, maximum, focus, point)).Text; } + + internal static SelectionReadResult Decode(int exitCode, string status, string text, int maximum) + { + 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" || 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, SelectionSurface origin = null) + { + 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)) }; + // 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)) { 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 + { + 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(3800); }); + ct.ThrowIfCancellationRequested(); + 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 != "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); + return Decode(process.ExitCode, status, text, maximum); + } + } + catch (OperationCanceledException) { throw; } + 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 3b4ee70..6a3e7cd 100644 --- a/src/LightTranslate.cs +++ b/src/LightTranslate.cs @@ -41,6 +41,13 @@ 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-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); bool created; @@ -81,6 +88,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; @@ -107,6 +115,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; @@ -125,7 +134,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(); @@ -182,10 +191,10 @@ public Controller(Application app) settings = Settings.Load(); lexicon = new Lexicon(Program.Folder); translator = new Translator(); - 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(), 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 @@ -210,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() @@ -221,29 +230,17 @@ 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) + private SelectionSurface downSurface; + + private void HandleMouse(int message, Native.MOUSE data, IntPtr capturedWindow, SelectionSurface surface) { if (!disposed) { @@ -262,7 +259,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) @@ -273,18 +271,20 @@ 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; + 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) @@ -302,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; @@ -322,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); @@ -343,11 +345,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); - Trace("clipboard chars=" + (text == null ? 0 : text.Length)); + 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(); if (!SelectionReader.ShouldTranslate(text, settings.MinEnglishPercent)) { Trace("selection language threshold skipped"); return; } @@ -358,13 +360,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; @@ -375,7 +379,12 @@ 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); + 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 { @@ -453,7 +462,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 +485,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 +527,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 +565,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); }); } } } @@ -689,69 +699,19 @@ 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, 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; } - 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++) + Func valid = delegate { return !ct.IsCancellationRequested && Native.GetForegroundWindow() == window && !Native.ModifierDown(); }; + return await SelectionAcquisition.Read( + delegate { return IsolatedSelectionReader.ReadResult(window, ct, point: point, origin: origin); }, + async delegate(SelectionReadResult result) { - 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, valid, Native.Copy, trace, + delegate { return Task.Delay(15); }, delegate { return Task.FromResult(result.ForCapture()); }); + }, valid); } } @@ -970,12 +930,16 @@ 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() + public Translator() : this(null) { } + internal Translator(HttpMessageHandler handler, IDeepLCredentials credentials = null, HttpMessageHandler deepLHandler = null) { - http = new HttpClient { Timeout = TimeSpan.FromSeconds(7) }; + 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)"); http.DefaultRequestHeaders.ExpectContinue = false; } @@ -988,20 +952,37 @@ 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 == "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") + { + // 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)) 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()); @@ -1057,7 +1038,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 @@ -1188,17 +1169,14 @@ 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"; + 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"); @@ -1209,7 +1187,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(); }); @@ -1225,7 +1202,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. @@ -1287,8 +1264,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/ReadingSettings.cs b/src/ReadingSettings.cs index 2f2fb94..cc56172 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,8 +100,12 @@ 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, 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; @@ -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); @@ -134,12 +139,15 @@ 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。")); 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。超过上限只提示分段选择,不发送该选区。")); @@ -192,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); @@ -206,13 +228,14 @@ 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(); }; 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(); } @@ -246,6 +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 : 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); @@ -315,7 +340,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" : provider.SelectedIndex == 3 ? "deepl" : "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); @@ -339,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(); } @@ -377,6 +422,17 @@ 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; } } 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/SelectionContextTests.cs b/src/SelectionContextTests.cs new file mode 100644 index 0000000..d92ba6d --- /dev/null +++ b/src/SelectionContextTests.cs @@ -0,0 +1,163 @@ +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 + { + // 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; + 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); + 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" }) + { + 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); + 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" }, + 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.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 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/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); + } +} diff --git a/src/SelectionIntegrationTests.cs b/src/SelectionIntegrationTests.cs new file mode 100644 index 0000000..221a766 --- /dev/null +++ b/src/SelectionIntegrationTests.cs @@ -0,0 +1,133 @@ +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 Snapshots, Copies, Reads, Restores; + public uint Sequence { get { return 1; } } + 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) + { 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(); + } + private static string Capture(ProtectedClipboard clipboard, IntPtr root, IntPtr focus) + { + 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) + { + 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 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) + { + 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.Snapshots == 0 && clipboard.Copies == 0 && clipboard.Reads == 0 && clipboard.Restores == 0, "empty gestures never snapshot, 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); + 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()) + 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" }) + { + form.Controls.Add(text); + IntPtr root = form.Handle, focus = text.Handle; + text.Select(7, 10); + var clipboard = new ProtectedClipboard(); + 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"); + 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 -> 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"] = "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; + } + } +} diff --git a/src/TranslationProviderTests.cs b/src/TranslationProviderTests.cs new file mode 100644 index 0000000..f8af801 --- /dev/null +++ b/src/TranslationProviderTests.cs @@ -0,0 +1,118 @@ +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) + { + DeepLTests.Run(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"; + } + } +} diff --git a/src/TrayIconRenderer.cs b/src/TrayIconRenderer.cs new file mode 100644 index 0000000..e259f2f --- /dev/null +++ b/src/TrayIconRenderer.cs @@ -0,0 +1,142 @@ +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 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); + 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"); + 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; save/reopen/cancel passed; 100 replacements without USER handle growth"; + } + + [DllImport("user32.dll")] private static extern uint GetGuiResources(IntPtr process, uint flags); + } +}