From 44098bfd9614e1b8a4466230139f7371d6497e3a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 24 Nov 2026 22:24:26 +0800 Subject: [PATCH] =?UTF-8?q?fix(file-associations):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E9=BB=98=E8=AE=A4=E5=BA=94=E7=94=A8=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E4=B8=8E=E7=B3=BB=E7=BB=9F=E7=8A=B6=E6=80=81=E5=9B=9E?= =?UTF-8?q?=E8=AF=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-24-file-association-consent-completion.md | 40 ++++ .../2026-11-23-system-file-associations.md | 27 ++- .../internal/fileassociations/registration.go | 19 +- .../fileassociations/registration_darwin.go | 221 ++++++++++++++---- .../registration_darwin_test.go | 52 +++++ .../fileassociations/registration_windows.go | 26 ++- desktop/internal/i18n/shared.generated.go | 34 ++- .../settingswindow/file_associations_test.go | 31 +++ .../settingswindow/file_associations_view.go | 105 +++++++-- .../file_associations_visual_test.go | 37 ++- desktop/internal/settingswindow/window.go | 1 + shared/i18n/features/file-associations.json | 80 ++++++- .../features/system-file-associations.json | 9 +- 13 files changed, 590 insertions(+), 92 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-24-file-association-consent-completion.md create mode 100644 desktop/internal/fileassociations/registration_darwin_test.go create mode 100644 desktop/internal/settingswindow/file_associations_test.go diff --git a/.agents/notes/implemented/bug-fix/2026-11-24-file-association-consent-completion.md b/.agents/notes/implemented/bug-fix/2026-11-24-file-association-consent-completion.md new file mode 100644 index 000000000..e60462a10 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-24-file-association-consent-completion.md @@ -0,0 +1,40 @@ +# Agent 笔记:文件关联必须等待系统确认完成 + +状态:已实现 + +## 先说结论 + +macOS 设置默认应用时,必须等待公开异步接口的完成回调,再读取实际默认应用。一次选择多个格式应处理整批,普通单项失败不能阻止其余格式;系统是否逐项要求确认仍由系统决定。返回设置窗口后只读刷新,保留勾选和上一轮失败反馈。 + +## 问题 + +初版文件关联(`c086a0b1b`,#2361)在同步设置返回成功后立即检查默认应用,把尚未观察到的新值转换成“找不到应用”(-10814),并在首项失败时终止整批。用户日志中的快速失败和下一轮基线冲突与此路径一致;日志没有证明系统确实找不到已安装的 Lithe。Windows 的候选注册也在单项写入失败后直接结束,返回系统设置后没有自动读取结果。 + +## 决策 + +macOS 通过 `NSWorkspace.setDefaultApplication` 等待完成,按统一内容类型(UTType,系统识别文件格式的标识)合并后缀别名。默认查询与候选注册的修订依据系统事实,不使用同应用标识的启发式安装路径。Windows 保持当前用户注册表与系统默认应用设置流程,不写受保护的 UserChoice。 + +普通单项错误保留原生原因和失败后缀后继续。取消、超时或未结束的系统确认停止后续提交;迟到回调只使用自己持有的原生内存,同一进程最多保留一个未结束的系统请求。操作结束后的回读独立限时,窗口激活也只触发读取。 + +正确示例:`.java` 和 `.jav` 共用一个系统类型,只发一次请求,完成后读取实际默认应用。不要在提交接口返回后立即合成 -10814,也不要因用户取消一次等待而释放系统回调仍会访问的内存。完整行为约束见[系统文件关联](../feature/2026-11-23-system-file-associations.md)。 + +## 考虑过的备选方案 + +- 保留同步设置并增加固定等待:无法知道系统确认何时结束,也无法可靠处理用户拒绝。 +- 强制所有格式只显示一次系统授权:公开接口没有整组授权参数,不能作此承诺。 +- 通过修改 Windows UserChoice 直接设置默认:绕过系统保护,不能作为可靠注册流程。 + +## 后果 + +整批不会因一个普通失败而提前结束,界面也能区分“候选已注册”和“默认已生效”。代价是必须管理异步确认生命周期;系统已显示的确认无法撤回,宿主超时后仍可能生效,因此回读和重试提示必须说明这一点。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test -race -tags 'vivahead lithevisual' ./internal/fileassociations ./internal/core ./internal/settingswindow -run '^Test(FileAssociations|VisualFileAssociations$)' -count=1 -timeout=60s`:定向通过;自动回读测试临时移除 `OnActivate` 时失败、恢复后通过。 +- 原生只读与内容类型别名测试不修改默认应用;幂等探针只对已经生效的同一默认应用重复提交一次,完成回调成功且默认值不变。它们不代表批量写入或授权已经验收。 +- 签名发布包的 macOS 批量写入、拒绝与超时后回读,以及 Windows Go 原生构建、注册、系统确认和卸载仍待目标系统验收,功能矩阵保持 `pending`。 +- `scripts/agent-notes/verify-agent-notes.sh`:校验 Note 格式、路径与链接。 + +## 适用范围 + +适用于 `desktop/internal/fileassociations/`、`desktop/internal/settingswindow/file_associations_view.go` 和设置窗口的激活回调。不改变 Core 的格式目录与冲突计划,也不改变既有单文件编辑入口。 diff --git a/.agents/notes/implemented/feature/2026-11-23-system-file-associations.md b/.agents/notes/implemented/feature/2026-11-23-system-file-associations.md index 4c951ee3d..ba38ccf81 100644 --- a/.agents/notes/implemented/feature/2026-11-23-system-file-associations.md +++ b/.agents/notes/implemented/feature/2026-11-23-system-file-associations.md @@ -4,21 +4,25 @@ ## 先说结论 -“通用”设置中的文件关联表格直接显示系统当前的默认应用,用户勾选后明确应用才改变关联。可选格式来自编辑器实际打包的文本高亮扩展名及纯文本,不接受正则或“所有文件”。macOS 使用 Finder 的“打开方式”和默认应用;Windows 注册“打开方式”候选并交给系统设置确认默认应用。 +“通用”设置中的文件关联表格直接显示系统当前的默认应用,并区分“已注册候选”和“已是默认”;用户勾选后点击一次应用,提交整批格式。可选格式来自编辑器实际打包的文本高亮扩展名及纯文本,不接受正则或“所有文件”。macOS 等待系统完成所选内容类型的默认应用请求,Windows 注册全部所选候选后进入系统设置确认;两端返回设置窗口都会自动回读,但不承诺系统只显示一次授权弹窗。 ## 问题 操作系统按扩展名或内容类型注册文件处理程序,不能表达编辑器中的任意正则。单独维护一张扩展名表会与高亮支持和打包声明发生漂移;只保存一个“使用 Lithe 打开”的应用偏好,也无法说明系统真正使用哪个程序。系统打开文件时还必须保留用户已打开的项目,避免为了临时编辑一个文件而索引整个父目录。 +最初实现(`c086a0b1b`,#2361)在 macOS 的同步设置接口返回成功后立即读取默认应用;尚未观察到新值时,宿主自行返回 `kLSApplicationNotFoundErr`(-10814),随后停止整批。用户日志中约 100 毫秒即结束的 -10814 与下一次提交的关联冲突交替出现,不能据此认定系统找不到 Lithe。关联修订还包含按应用标识启发式查出的路径,多份同标识应用可能造成无意义的基线变化。Windows 同样遇首个注册失败就停止,返回系统设置后也没有自动读取最终默认应用。 + ## 决策 - 编辑器只导出内置元数据,不加载语法,也不混入插件贡献。Core(共享 Rust 规则层)筛出实际有语法的语言和纯文本,排除编译/压缩容器、文件名匹配和复合后缀,排序去重。简单后缀与 Viva 原生打包清单的字符和长度限制一致,保留 `.c++`、`.h++`。设置和打包生成器使用同一个结果;增加高亮后须重新生成 `desktop/viva.toml`,打包前检查是否一致。 - 设置只在内存保存勾选草稿。读取来自系统真实默认处理程序,应用前重读默认标识与自有注册信息,再由 Core 拒绝过期基线。成功或部分失败后均重新读取,不把草稿当成生效值。取消勾选只清除本次选择,不还原历史默认应用;复杂后果通过标题的 ⓘ 说明。 -- macOS 在构建期声明备用文本编辑器,运行期只向 Launch Services(系统维护的文件类型与应用关联服务)注册当前 bundle,并显式设置所选类型。macOS 按内容类型关联,共用一种内容类型的多个扩展名可能同时变化,不能承诺每个后缀独立生效。开发二进制只读默认应用,不注册临时测试程序。 -- Windows 只写当前用户的 Classes、Capabilities 和 RegisteredApplications。每个格式使用与 Viva 安装器相同的 ProgID(系统中的文件处理程序标识),显式注册时同时写入自己的“用 Lithe 打开”动作;只有已关联到该 ProgID 的文件有该独立动作,其他文件可从“打开方式”进入。Windows 11 的传统动作可能在“显示更多选项”下。受保护的 UserChoice(用户默认应用选择)只读,最后由 Windows 设置确认;刷新后回显系统结果。 +- 同一格式可以同时注册多个候选应用,已有其他应用不构成注册冲突;访达或文件资源管理器双击使用的是当前默认应用。帮助文案明确说明用户选择会替换所选格式的原默认应用,以及生效后直接进入单文件模式;仅注册候选不能视为已满足双击编辑的目标。 +- macOS 在构建期声明备用文本编辑器,运行期只向 Launch Services(系统维护的文件类型与应用关联服务)注册当前 bundle。所选后缀先解析为统一内容类型(UTType),相同类型只提交一次,已经是默认时跳过;普通类型失败后继续其他类型,并保留所有失败后缀。使用 `NSWorkspace.setDefaultApplication` 的异步完成回调等待系统确认,之后再核对实际默认应用;不在提交后立即合成“找不到应用”错误。查询也使用 `NSWorkspace` 的内容类型接口,注册修订只观察是否为候选,不把按应用标识猜出的安装路径当成版本。开发二进制只读默认应用,不注册临时测试程序。 +- macOS 的主线程只提交原生异步请求,默认查询与包信息读取在后台进行。一次批量应用允许等待五分钟,读取允许三十秒;结束后的独立回读最多五秒,即使提交已超时,也尽量显示真实的部分结果。系统没有撤销已显示授权的接口,因此取消只阻止后续类型,迟到回调只访问自己持有的原生内存;同一进程最多保留一个未完成的系统确认,确认未结束时拒绝新请求,避免反复点击堆积弹窗。 +- Windows 只写当前用户的 Classes、Capabilities 和 RegisteredApplications。每个格式使用与 Viva 安装器相同的 ProgID(系统中的文件处理程序标识),显式注册时同时写入自己的“用 Lithe 打开”动作;一个格式写入失败仍继续其余格式,并回报具体失败后缀。至少一个格式完整注册成功后,只打开一次系统默认应用页。只有已关联到该 ProgID 的文件有独立右键动作,其他文件可从“打开方式”进入;Windows 11 的传统动作可能在“显示更多选项”下。受保护的 UserChoice(用户默认应用选择)只读,最后由 Windows 设置确认。 - Windows 的右键动作放在 Lithe 自己的 ProgID 下,随 Viva 安装器卸载该格式一起移除,不在全局 `SystemFileAssociations` 或所有文件类写额外项。运行期仅允许名为 `lithe.exe` 的产品程序注册,避免测试二进制写入无法由卸载器移除的 Applications 项。 - Finder 事件只接受真实普通文件,复用独立编辑会话;已有项目保留,通过原有项目标签返回。Windows 从启动参数进入既有单文件模式。文档服务的隔离沿用[可选 CLI 注册与单文件编辑](2026-11-20-cli-and-standalone-editor.md),不创建插件、目录索引或项目服务。 -- 表格复用 Viva 的虚拟列表和共享滚动条,只创建可见行;勾选以扩展名保存,不依赖离屏控件是否存在。系统查询和写入在可取消、有期限的后台任务中完成。 +- 表格复用 Viva 的虚拟列表和共享滚动条,只创建可见行;勾选以扩展名保存,不依赖离屏控件是否存在。状态来自系统回读,不能把候选注册成功说成默认应用已生效;无打包身份时显示“需安装包”。窗口重新激活只读取系统,不写入、不清空草稿,也不覆盖上一次提交的失败反馈;激活发生在操作期间时,完成后补读一次。 正确做法:新增内置高亮后运行生成器,把格式同时带到设置、macOS 声明和 Windows 安装器;打开设置只查系统,勾选后点击应用才发布。不要在界面手写另一份格式名单,也不要通过改写安装包里的清单来补运行期关联。 @@ -27,25 +31,30 @@ - 正则输入和所有文本文件总开关:系统不理解正则,也无法仅凭文件内容在 Explorer/Finder 注册默认应用。最终采用真实内置高亮扩展名的全选操作,避免抢占二进制或压缩文件。 - macOS 添加固定 Finder 右键动作:需要额外的系统扩展和生命周期;系统已有“打开方式”可表达同一入口,本次使用它。 - Windows 直接写 UserChoice:绕过系统保护且不能可靠生效,保留系统确认流程。 +- macOS 继续使用同步设置接口并立即检查:无法表达异步系统授权的完成时间,会把尚未观察到的结果误判为失败。等待原生异步回调再核对结果,代价是需要管理取消后仍可能完成的系统请求。 +- 把所有类型一次提交给一个系统授权:公开接口每次接受一个内容类型,没有整组授权参数。宿主负责一次发起整批、按系统类型去重和继续处理普通失败,弹窗策略仍由系统决定,不使用私有接口强改。 - 全局右键项配扩展名过滤:Viva 当前卸载器不会清理额外全局项。把动作放进自有 ProgID 可以复用现有安装和卸载边界,代价是它只出现在已关联文件上。 - 所有平台各写一份筛选和冲突判断:行为会漂移,共享规则在 Core,平台只负责原生查询和写入。 ## 后果 -格式目录、高亮支持和安装声明可以相互核对,打开设置不改变系统,也没有虚假的“已注册”偏好。代价是仅文件名匹配的 Makefile 等不在系统关联列表中;设置默认应用需要安装后的程序,macOS 的类型别名和 Windows 的用户确认由系统决定。平台外部进程在重读与写入之间仍可竞争,原生接口不提供跨进程事务,批量部分失败会显示错误并回读。 +格式目录、高亮支持和安装声明可以相互核对,打开设置不改变系统,也没有虚假的“已注册”偏好。代价是仅文件名匹配的 Makefile 等不在系统关联列表中;设置默认应用需要安装后的程序,macOS 的类型别名和 Windows 的用户确认由系统决定。例如 `.java/.jav` 共用同一内容类型,一次设置会联动,不能承诺每个后缀独立生效。平台外部进程在重读与写入之间仍可竞争,原生接口不提供跨进程事务,批量部分失败会显示错误并回读;超时后用户仍可能完成已经打开的系统确认。 清单是构建输入,由仓库维护,不是缓存。运行期注册数据由系统管理,macOS bundle 和 Windows 安装目录始终只读,不产生新下载或资源路径,不改变代码签名和增量更新基线。截图和计时报告只属于当前检出的 `.artifacts/`,不跨工作树复制。 ## 验证 -- `scripts/desktop/desktop-go.sh test ./internal/core ./internal/fileassociations ./internal/workbench -run '^Test(FileAssociations|SystemDocuments)' -count=1 -timeout=60s`:链接修改后的 Core,核对共享 fixture、真实高亮解析、Viva 原生清单,以及真实文件的独立打开与项目保留。 -- `scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow -run '^TestVisualFileAssociations$' -count=1 -timeout=60s`:使用 `LITHE_VISUAL_OUTPUT_DIR` 输出中英、明暗截图;系统默认应用只读,验证全选、清空、刷新、鼠标滚轮到末尾、虚拟化和选择保留。 +- `scripts/desktop/desktop-go.sh test ./internal/core ./internal/fileassociations ./internal/workbench -run '^Test(FileAssociations|SystemDocuments)' -count=1 -timeout=60s`:链接固定的 Core,核对共享 fixture、真实高亮解析、Viva 原生清单,以及真实文件的独立打开与项目保留。 +- `scripts/desktop/desktop-go.sh test -tags vivahead ./internal/workbench -run '^Test(SystemDocumentsPreserveProjectAndReuseIsolatedSession|StandaloneEditsWithBundledSyntaxWithoutProjectServices)$' -count=1 -timeout=60s`:定向通过系统文件入口复用独立会话、保留原项目、不启动项目服务,以及真实临时文件的编辑和保存;不替代 Finder 的原生事件投递验收。 +- `scripts/desktop/desktop-go.sh test -race -tags 'vivahead lithevisual' ./internal/fileassociations ./internal/core ./internal/settingswindow -run '^Test(FileAssociations|VisualFileAssociations$)' -count=1 -timeout=60s`:使用 `LITHE_VISUAL_OUTPUT_DIR` 输出中英、明暗的表格和默认应用替换说明截图;验证真实系统类型别名、只读观察、预取消不注册、取消不吞掉真实失败,以及全选、清空、刷新、滚动到末尾、虚拟化、返回窗口自动回读和勾选保留。逐项计时由 `run-go-tests-with-timing.mjs` 生成 HTML 与 JUnit 报告。 - `scripts/desktop/generate-file-associations.sh --check`、`node --test --test-timeout=60000 scripts/desktop/package-desktop.test.mjs`:核对打包目录和生成器在构建主机执行、最终辅助程序保持目标架构。 -- `scripts/desktop/desktop-go.sh build -o ../.artifacts/desktop/bin/lithe-file-associations ./cmd/lithe`:macOS arm64 最终消费者构建通过。宿主固定到配套 Core PR 的确切提交,包含同功能分支与当时最新的 Core main;宿主合并前先合入 Core,合并方式改变提交哈希时同步更新固定修订。 +- `scripts/desktop/desktop-go.sh build -o ../.artifacts/desktop/bin/lithe-file-associations ./cmd/lithe`:检查 macOS arm64 最终消费者;Core 使用桌面构建脚本固定的修订,本次批量提交修复不改变共享契约。 - `scripts/desktop/perf/editor-bench.sh run --bench '^BenchmarkEditorSyntaxViewportWarm' --count 6`:同机改动前后各测六次,六个场景均在预算内,保持 0 B/op、0 allocs/op;对比没有回归。元数据导出不改变分词或视口读取路径。 - Core 的 `cargo clippy --manifest-path rust/Cargo.toml -p lithe-core --all-targets --target x86_64-pc-windows-msvc -- -D warnings`(设置 `LIBSQLITE3_SYS_USE_PKG_CONFIG=1`)通过。它不验证 Windows 的 Go 原生适配器,也不替代来宾运行。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:检查发行目录只读边界。 -- 发布包的 macOS 注册和 Finder 打开、Windows 注册表与默认应用确认、卸载清理需要在目标系统单独验收,功能矩阵保持 pending。无头测试不修改开发机默认应用。 +- 自动回读回归已通过临时移除 `OnActivate` 验证修复前失败、恢复后通过。macOS 即时校验与首错停止的修复依据是用户日志和原生代码,尚未通过签名发布包重放写入与授权,不能把只读测试当成完整回归证据。 +- 使用生产原生桥接的临时探针,对 `.java` 已生效的同一默认应用重复提交一次:新旧查询先确认当前为 Lithe,异步完成回调无错误,未完成标记归零,默认应用 URL 与旧接口结果前后相同。该探针不注册新应用,只证明一次幂等请求的回调和内存生命周期可完成,不覆盖批量改变默认值或授权弹窗。 +- 发布包验收:macOS 选择多个不同类型及一组别名,核对实际写入、系统确认次数、拒绝某项后继续其余项,以及超时后结束弹窗再返回回读;从 Finder 打开文件验证独立会话。Windows 核对整批注册、系统确认后返回自动回读、部分失败提示及卸载清理。本机没有 Windows 来宾,Windows Go 原生编译和上述流程未验证;两端功能矩阵保持 pending。无头测试不修改开发机默认应用。 ## 适用范围 diff --git a/desktop/internal/fileassociations/registration.go b/desktop/internal/fileassociations/registration.go index cb439417e..4beb4b049 100644 --- a/desktop/internal/fileassociations/registration.go +++ b/desktop/internal/fileassociations/registration.go @@ -7,7 +7,9 @@ package fileassociations import ( "context" "errors" + "strings" "sync" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" @@ -16,6 +18,17 @@ import ( var ErrConflict = errors.New("system file associations changed; refresh before applying") var ErrNotPackaged = errors.New("file association registration requires an installed application") var ErrUnsupported = errors.New("file association registration is not supported on this platform") +var ErrConfirmationPending = errors.New("a previous macOS default-application confirmation is still pending") + +// FormatError preserves the exact suffixes and native failures in a partial batch. +// The settings view localizes the message; the operation log retains the cause. +type FormatError struct { + Extensions []string + Err error +} + +func (e *FormatError) Error() string { return strings.Join(e.Extensions, ", ") + ": " + e.Err.Error() } +func (e *FormatError) Unwrap() error { return e.Err } // Handler is an OS observation, rather than a stored Lithe preference. type Handler struct { @@ -101,7 +114,11 @@ func (m *Manager) Apply(ctx context.Context, baseline State, selected []string, return current, ErrConflict } err = applyNative(ctx, current.native, plan.Extensions, menuLabel) - after, readErr := readNative(ctx, formats) + // A consent timeout can follow successful writes. Keep the readback bounded + // independently so cancellation cannot make the pre-write snapshot look current. + readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + after, readErr := readNative(readCtx, formats) if readErr != nil { return current, errors.Join(err, readErr) } diff --git a/desktop/internal/fileassociations/registration_darwin.go b/desktop/internal/fileassociations/registration_darwin.go index fe0df04fe..61c3f1976 100644 --- a/desktop/internal/fileassociations/registration_darwin.go +++ b/desktop/internal/fileassociations/registration_darwin.go @@ -8,6 +8,8 @@ package fileassociations #import #include #include +#include +#include static NSString *lithe_association_identity(const char *path) { NSBundle *bundle = [NSBundle bundleWithPath:[NSString stringWithUTF8String:path]]; @@ -21,35 +23,37 @@ static char *lithe_association_bundle_id(const char *path) { } } -static CFStringRef lithe_association_type(const char *extension) { +static UTType *lithe_association_type(const char *extension) { NSString *suffix = [[NSString stringWithUTF8String:extension] substringFromIndex:1]; - UTType *type = [UTType typeWithFilenameExtension:suffix]; - return type == nil ? NULL : (CFStringRef)CFRetain((__bridge CFTypeRef)type.identifier); + return [UTType typeWithFilenameExtension:suffix]; } -// Each field is NUL-terminated: default bundle ID, display name, offered flag, -// and the registered path for our bundle ID. The caller frees the buffer. +static char *lithe_association_type_id(const char *extension) { + @autoreleasepool { + UTType *type = lithe_association_type(extension); + return type == nil ? NULL : strdup(type.identifier.UTF8String); + } +} + +// Each field is NUL-terminated: default bundle ID, display name, offered flag. +// The caller frees the buffer. static char *lithe_association_read(const char *extension, const char *identity, size_t *size) { @autoreleasepool { - CFStringRef type = lithe_association_type(extension); - NSString *preferred = type == NULL ? nil : CFBridgingRelease( - LSCopyDefaultRoleHandlerForContentType(type, kLSRolesAll)); - NSArray *handlers = type == NULL ? @[] : CFBridgingRelease( - LSCopyAllRoleHandlersForContentType(type, kLSRolesAll)); - if (type != NULL) CFRelease(type); + UTType *type = lithe_association_type(extension); + NSWorkspace *workspace = [NSWorkspace sharedWorkspace]; + NSURL *preferredURL = type == nil ? nil : [workspace URLForApplicationToOpenContentType:type]; + NSString *preferred = preferredURL == nil ? nil : [NSBundle bundleWithURL:preferredURL].bundleIdentifier; + NSArray *handlers = type == nil ? @[] : [workspace URLsForApplicationsToOpenContentType:type]; NSString *ours = [NSString stringWithUTF8String:identity]; - NSURL *preferredURL = preferred.length == 0 ? nil : - [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:preferred]; NSString *name = preferredURL == nil ? @"" : [[NSFileManager defaultManager] displayNameAtPath:preferredURL.path]; - NSURL *ourURL = ours.length == 0 ? nil : - [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:ours]; BOOL offered = NO; - for (NSString *handler in handlers) { - if ([handler caseInsensitiveCompare:ours] == NSOrderedSame) offered = YES; + for (NSURL *handler in handlers) { + NSString *bundleID = [NSBundle bundleWithURL:handler].bundleIdentifier; + if (bundleID != nil && [bundleID caseInsensitiveCompare:ours] == NSOrderedSame) offered = YES; } NSMutableData *data = [NSMutableData data]; - for (NSString *field in @[preferred ?: @"", name ?: @"", offered ? @"1" : @"0", ourURL.path ?: @""]) { + for (NSString *field in @[preferred ?: @"", name ?: @"", offered ? @"1" : @"0"]) { const char *value = field.UTF8String; [data appendBytes:value length:strlen(value)+1]; } @@ -67,21 +71,77 @@ static int lithe_association_register(const char *path) { } } -static int lithe_association_default(const char *extension, const char *identity) { +// The caller and completion block each own a reference. Cancellation releases +// the caller without freeing memory a later system-consent callback still uses. +typedef struct { + atomic_int references; + atomic_bool done; + atomic_bool cancelled; + bool failed; + long code; + char domain[256]; +} lithe_association_request; + +// NSWorkspace cannot revoke consent already presented by the OS. Keep at most +// one such request, including after the Go caller's deadline has expired. +static atomic_bool lithe_association_pending = false; + +static void lithe_association_release(lithe_association_request *request) { + if (atomic_fetch_sub(&request->references, 1) == 1) { + free(request); + } +} + +static lithe_association_request *lithe_association_default(const char *path, const char *identifier, int *pending) { @autoreleasepool { - CFStringRef type = lithe_association_type(extension); - if (type == NULL) return (int)kLSUnknownTypeErr; - NSString *bundleID = [NSString stringWithUTF8String:identity]; - OSStatus result = LSSetDefaultRoleHandlerForContentType(type, kLSRolesAll, - (__bridge CFStringRef)bundleID); - if (result == noErr) { - NSString *actual = CFBridgingRelease(LSCopyDefaultRoleHandlerForContentType(type, kLSRolesAll)); - if (actual == nil || [actual caseInsensitiveCompare:bundleID] != NSOrderedSame) { - result = kLSApplicationNotFoundErr; - } + *pending = atomic_exchange(&lithe_association_pending, true); + if (*pending) return NULL; + lithe_association_request *request = calloc(1, sizeof(*request)); + if (request == NULL) { + atomic_store(&lithe_association_pending, false); + return NULL; } - CFRelease(type); - return (int)result; + atomic_init(&request->references, 2); + atomic_init(&request->done, false); + atomic_init(&request->cancelled, false); + NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]]; + UTType *type = [UTType typeWithIdentifier:[NSString stringWithUTF8String:identifier]]; + dispatch_async(dispatch_get_main_queue(), ^{ + if (atomic_load(&request->cancelled)) { + atomic_store(&lithe_association_pending, false); + lithe_association_release(request); + return; + } + [[NSWorkspace sharedWorkspace] setDefaultApplicationAtURL:url toOpenContentType:type completionHandler:^(NSError *error) { + if (error != nil) { + request->failed = true; + request->code = error.code; + snprintf(request->domain, sizeof(request->domain), "%s", error.domain.UTF8String); + } + atomic_store(&lithe_association_pending, false); + atomic_store(&request->done, true); + lithe_association_release(request); + }]; + }); + return request; + } +} + +static int lithe_association_done(lithe_association_request *request) { + return atomic_load(&request->done); +} + +static void lithe_association_cancel(lithe_association_request *request) { + atomic_store(&request->cancelled, true); +} + +static int lithe_association_matches(const char *path, const char *identifier) { + @autoreleasepool { + UTType *type = [UTType typeWithIdentifier:[NSString stringWithUTF8String:identifier]]; + NSURL *preferred = [[NSWorkspace sharedWorkspace] URLForApplicationToOpenContentType:type]; + NSString *actual = preferred == nil ? nil : [NSBundle bundleWithURL:preferred].bundleIdentifier; + NSString *ours = lithe_association_identity(path); + return actual != nil && ours != nil && [actual caseInsensitiveCompare:ours] == NSOrderedSame; } } */ @@ -91,8 +151,10 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "strings" + "time" "unsafe" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -132,10 +194,12 @@ func readNative(ctx context.Context, formats []core.FileAssociationFormat) (Stat data := C.GoStringN(raw, C.int(size)) C.free(unsafe.Pointer(raw)) fields := strings.Split(data, "\x00") - if len(fields) != 5 { + if len(fields) != 4 { return State{}, fmt.Errorf("file associations: invalid native handler response") } - revision := sha256.Sum256([]byte(fields[2] + "\x00" + fields[3])) + // Launch Services chooses an application URL heuristically when several + // copies share a bundle ID. That lookup is not a registration revision. + revision := sha256.Sum256([]byte(fields[2])) state.Handlers = append(state.Handlers, Handler{ Extension: format.Extension, DefaultID: fields[0], DefaultName: fields[1], IsDefault: state.Available && strings.EqualFold(fields[0], state.native.identity), @@ -149,22 +213,97 @@ func applyNative(ctx context.Context, state nativeState, extensions []string, _ if err := ctx.Err(); err != nil { return err } - path, identity := C.CString(state.bundle), C.CString(state.identity) + path := C.CString(state.bundle) defer C.free(unsafe.Pointer(path)) - defer C.free(unsafe.Pointer(identity)) if status := C.lithe_association_register(path); status != 0 { return fmt.Errorf("file associations: LSRegisterURL status %d", int(status)) } + var failures []error + var failed []string + seen := make(map[string]error, len(extensions)) for _, extension := range extensions { if err := ctx.Err(); err != nil { - return err + if len(failures) == 0 { + return err + } + return errors.Join(&FormatError{Extensions: failed, Err: errors.Join(failures...)}, err) } - value := C.CString(extension) - status := C.lithe_association_default(value, identity) - C.free(unsafe.Pointer(value)) - if status != 0 { - return fmt.Errorf("file associations: LSSetDefaultRoleHandlerForContentType status %d", int(status)) + identifier, err := contentType(extension) + if err == nil { + var submitted bool + err, submitted = seen[identifier] + if !submitted { + err = setDefaultContentType(ctx, state.bundle, identifier) + seen[identifier] = err + } + } + if err != nil { + if errors.Is(err, ErrConfirmationPending) || (ctx.Err() != nil && errors.Is(err, ctx.Err())) { + if len(failures) == 0 { + return err + } + return errors.Join(&FormatError{Extensions: failed, Err: errors.Join(failures...)}, err) + } + failed = append(failed, extension) + failures = append(failures, fmt.Errorf("%s: %w", extension, err)) } } + if len(failures) != 0 { + return &FormatError{Extensions: failed, Err: errors.Join(failures...)} + } return nil } + +func contentType(extension string) (string, error) { + value := C.CString(extension) + defer C.free(unsafe.Pointer(value)) + identifier := C.lithe_association_type_id(value) + if identifier == nil { + return "", fmt.Errorf("file associations: no macOS content type for %s", extension) + } + defer C.free(unsafe.Pointer(identifier)) + return C.GoString(identifier), nil +} + +func setDefaultContentType(ctx context.Context, bundle, identifier string) error { + if err := ctx.Err(); err != nil { + return err + } + path, kind := C.CString(bundle), C.CString(identifier) + defer C.free(unsafe.Pointer(path)) + defer C.free(unsafe.Pointer(kind)) + if C.lithe_association_matches(path, kind) != 0 { + return nil + } + var pending C.int + request := C.lithe_association_default(path, kind, &pending) + if request == nil { + if pending != 0 { + return ErrConfirmationPending + } + return fmt.Errorf("file associations: native request allocation failed") + } + defer C.lithe_association_release(request) + // NSWorkspace owns the asynchronous consent UI and exposes no cancellation + // handle. Only the active request can finish after cancellation; no further + // content types are submitted. The bounded wait never blocks the UI thread. + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + if C.lithe_association_done(request) != 0 { + if request.failed { + return fmt.Errorf("file associations: NSWorkspace.setDefaultApplication type %s: %s code %d", identifier, C.GoString(&request.domain[0]), int(request.code)) + } + if C.lithe_association_matches(path, kind) == 0 { + return fmt.Errorf("file associations: macOS did not confirm the requested default for type %s", identifier) + } + return nil + } + select { + case <-ctx.Done(): + C.lithe_association_cancel(request) + return ctx.Err() + case <-ticker.C: + } + } +} diff --git a/desktop/internal/fileassociations/registration_darwin_test.go b/desktop/internal/fileassociations/registration_darwin_test.go new file mode 100644 index 000000000..20ba73159 --- /dev/null +++ b/desktop/internal/fileassociations/registration_darwin_test.go @@ -0,0 +1,52 @@ +package fileassociations + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestFileAssociationsMacContentTypeAliases(t *testing.T) { + // Resolve actual macOS types without publishing any default handlers. + java, err := contentType(".java") + if err != nil { + t.Fatal(err) + } + alias, err := contentType(".jav") + if err != nil { + t.Fatal(err) + } + if java == "" || java != alias { + t.Fatalf("macOS Java content types differ: %q, %q", java, alias) + } +} + +func TestFileAssociationsMacReadIsStable(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + formats := []core.FileAssociationFormat{{Extension: ".java", Language: "java"}, {Extension: ".js", Language: "javascript"}} + before, err := readNative(ctx, formats) + if err != nil { + t.Fatal(err) + } + after, err := readNative(ctx, formats) + if err != nil { + t.Fatal(err) + } + for i, handler := range before.Handlers { + if handler != after.Handlers[i] { + t.Fatalf("read-only native observations changed: %+v, %+v", handler, after.Handlers[i]) + } + } +} + +func TestFileAssociationsMacCanceledApplyDoesNotRegister(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := applyNative(ctx, nativeState{}, []string{".txt"}, ""); !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled apply: %v", err) + } +} diff --git a/desktop/internal/fileassociations/registration_windows.go b/desktop/internal/fileassociations/registration_windows.go index 4ccec8e20..15cdd0028 100644 --- a/desktop/internal/fileassociations/registration_windows.go +++ b/desktop/internal/fileassociations/registration_windows.go @@ -176,21 +176,39 @@ func writeRegistryValue(value registryValue) (err error) { } func applyNative(ctx context.Context, state nativeState, extensions []string, menuLabel string) error { + var failures []error + var failed []string + registered := false for _, extension := range extensions { + complete := true for _, value := range registrationValues(state.executable, extension, menuLabel) { if err := ctx.Err(); err != nil { - return err + if len(failures) == 0 { + return err + } + return errors.Join(&FormatError{Extensions: failed, Err: errors.Join(failures...)}, err) } if err := writeRegistryValue(value); err != nil { - return err + failed = append(failed, extension) + failures = append(failures, fmt.Errorf("%s registry %s: %w", extension, value.path, err)) + complete = false + break } } + registered = registered || complete } // SHCNE_ASSOCCHANGED + SHCNF_IDLIST refreshes Explorer after all selected formats. associationChanged.Call(0x08000000, 0, 0, 0) - if err := ctx.Err(); err != nil { + var err error + if len(failures) != 0 { + err = &FormatError{Extensions: failed, Err: errors.Join(failures...)} + } + if cancel := ctx.Err(); cancel != nil { + return errors.Join(err, cancel) + } + if !registered { return err } // UserChoice is protected by Windows. Its own UI owns the final consent. - return app.OpenURL("ms-settings:defaultapps?registeredAppUser=" + url.QueryEscape(applicationID)) + return errors.Join(err, app.OpenURL("ms-settings:defaultapps?registeredAppUser="+url.QueryEscape(applicationID))) } diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index a7268b929..6bcde6a4e 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -33,27 +33,36 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.aiCommit.timeout": "The AI provider did not answer within 45 seconds.", "desktop.app.devBadge": "Dev", "desktop.app.previewVersion": "{version} Preview", - "desktop.associations.appliedMac": "Default applications refreshed from the system.", - "desktop.associations.appliedWindows": "Formats registered. Confirm your choices in Windows Settings, then refresh this list.", + "desktop.associations.appliedMac": "Batch finished. Current defaults have been read back from macOS.", + "desktop.associations.appliedWindows": "Selected formats registered. Confirm defaults in Windows Settings; returning here refreshes the result automatically.", "desktop.associations.applyMac": "Set selected defaults", "desktop.associations.applyWindows": "Register and choose defaults…", + "desktop.associations.applying": "Applying selected formats…", + "desktop.associations.candidateRegistered": "Candidate registered", "desktop.associations.clearSelection": "Clear selection", + "desktop.associations.confirmationPending": "A previous macOS confirmation is still open. Finish or dismiss it, then refresh to check current defaults before retrying.", "desktop.associations.conflict": "System associations changed while this page was open. Review the refreshed defaults and apply again.", "desktop.associations.currentDefault": "Current default application", + "desktop.associations.defaultConfirmed": "Default confirmed", "desktop.associations.failed": "Could not read or update file associations. Some formats may have changed. Refresh to check the current defaults and try again.", + "desktop.associations.failedFormats": "Failed formats: {formats}. Review the current defaults before retrying these formats.", "desktop.associations.format": "Format", "desktop.associations.formats": "Supported text formats", - "desktop.associations.helpMac": "Lists the extensions supported by built-in highlighting, plus plain text. Select formats and apply to use Lithe as their default editor. Finder also offers Lithe under Open With. macOS associates content types, so extensions sharing one type may change together. Filename-only rules, compressed files and binary files are excluded; compound suffixes use the final extension. Clearing a checkbox changes only this draft.", - "desktop.associations.helpWindows": "Lists the extensions supported by built-in highlighting, plus plain text. Register selected formats to offer Lithe in Open With, then confirm defaults in Windows Settings. Associated files also have an Open with Lithe context action (under Show more options on Windows 11). Filename-only rules, compressed files and binary files are excluded. Clearing a checkbox changes only this draft.", + "desktop.associations.helpMac": "Select the text formats you want Lithe to edit by default, then apply. This replaces their current default applications. Once confirmed, double-clicking a file in Finder opens it in Single File Mode and keeps your open projects. macOS may ask for confirmation for each content type; extensions sharing a type change together. Returning here refreshes the actual defaults. Clearing a checkbox does not restore a previous default.", + "desktop.associations.helpWindows": "Register the selected text formats, then choose Lithe as their default on Lithe’s page in Windows Settings. This replaces their current default applications. Once confirmed, double-clicking a file in File Explorer opens it in Single File Mode. Registered candidates are not yet defaults. Returning here refreshes the actual defaults. You can also use Open with Lithe (under Show more options on Windows 11). Clearing a checkbox does not restore a previous default.", "desktop.associations.language": "Highlighting", "desktop.associations.litheDefault": "Lithe (default)", "desktop.associations.noDefault": "No default application", "desktop.associations.openWith": "Open with Lithe", + "desktop.associations.packageRequired": "Package required", "desktop.associations.refresh": "Refresh", "desktop.associations.requiresInstalled": "Install and open the packaged Lithe application to register file associations.", "desktop.associations.selectAll": "Select all", "desktop.associations.selected": "{count} selected", + "desktop.associations.status": "Lithe status", + "desktop.associations.timedOut": "System confirmation timed out and remaining requests stopped. An open system dialog may still complete. Finish or dismiss it, then refresh to check current defaults before retrying.", "desktop.associations.title": "File associations", + "desktop.associations.unregistered": "Not registered", "desktop.branch.alreadyOn": "Already on '{name}'", "desktop.branch.branchName": "Branch name", "desktop.branch.checkedOut": "Checked out '{name}'", @@ -4058,27 +4067,36 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.aiCommit.timeout": "AI 服务商在 45 秒内没有响应。", "desktop.app.devBadge": "Dev", "desktop.app.previewVersion": "{version} 预览版", - "desktop.associations.appliedMac": "已从系统重新读取默认应用。", - "desktop.associations.appliedWindows": "所选格式已注册。请在 Windows 设置中确认默认应用,再刷新此列表。", + "desktop.associations.appliedMac": "批量处理结束,已从 macOS 重新读取当前默认应用。", + "desktop.associations.appliedWindows": "所选格式已注册。请在 Windows 设置中确认默认应用,返回此窗口后将自动刷新结果。", "desktop.associations.applyMac": "将所选格式设为默认", "desktop.associations.applyWindows": "注册并选择默认应用…", + "desktop.associations.applying": "正在批量应用所选格式…", + "desktop.associations.candidateRegistered": "已注册候选", "desktop.associations.clearSelection": "清空选择", + "desktop.associations.confirmationPending": "上一轮 macOS 系统确认尚未结束。请先完成或关闭系统弹窗,再刷新核对默认应用后重试。", "desktop.associations.conflict": "打开此页后系统关联发生了变化。请确认刷新后的默认应用,再重新应用。", "desktop.associations.currentDefault": "当前默认应用", + "desktop.associations.defaultConfirmed": "已是默认", "desktop.associations.failed": "无法读取或更新文件关联,部分格式可能已生效。请刷新确认当前状态后重试。", + "desktop.associations.failedFormats": "失败格式:{formats}。请核对当前默认应用后重试这些格式。", "desktop.associations.format": "格式", "desktop.associations.formats": "支持的文本格式", - "desktop.associations.helpMac": "列出内置高亮支持的扩展名及纯文本。勾选格式并应用后,将 Lithe 设为默认编辑器;Finder 也会在“打开方式”中显示 Lithe。macOS 按内容类型关联,共用同一类型的扩展名可能同时生效。仅匹配文件名的规则、压缩文件和二进制文件不在此列,复合后缀使用最后一段扩展名。取消勾选只修改本次草稿。", - "desktop.associations.helpWindows": "列出内置高亮支持的扩展名及纯文本。注册所选格式后,Lithe 会显示在“打开方式”中,再到 Windows 设置确认默认应用。已关联的文件也会有“用 Lithe 打开”右键项(Windows 11 位于“显示更多选项”)。仅匹配文件名的规则、压缩文件和二进制文件不在此列。取消勾选只修改本次草稿。", + "desktop.associations.helpMac": "勾选希望由 Lithe 默认编辑的文本格式后应用,会替换这些格式原来的默认应用。生效后,在访达双击文件会直接进入单文件模式,保留已经打开的项目。macOS 可能按内容类型分别要求确认;共用同一类型的后缀会一同更改。返回此窗口会自动读取实际默认应用。取消勾选不会恢复原来的默认应用。", + "desktop.associations.helpWindows": "注册勾选的文本格式,再到 Windows 设置中的 Lithe 页面将其设为默认,会替换这些格式原来的默认应用。生效后,在文件资源管理器双击文件会直接进入单文件模式。“已注册候选”表示尚未成为默认应用。返回此窗口会自动读取实际结果。也可使用“用 Lithe 打开”右键项(Windows 11 位于“显示更多选项”)。取消勾选不会恢复原来的默认应用。", "desktop.associations.language": "高亮语言", "desktop.associations.litheDefault": "Lithe(默认)", "desktop.associations.noDefault": "未设置默认应用", "desktop.associations.openWith": "用 Lithe 打开", + "desktop.associations.packageRequired": "需安装包", "desktop.associations.refresh": "刷新", "desktop.associations.requiresInstalled": "请安装并运行打包后的 Lithe 应用以注册文件关联。", "desktop.associations.selectAll": "全选", "desktop.associations.selected": "已选 {count} 项", + "desktop.associations.status": "Lithe 状态", + "desktop.associations.timedOut": "系统确认超时,已停止提交剩余请求。已经打开的系统弹窗仍可能生效,请先完成或关闭弹窗,再刷新核对默认应用后重试。", "desktop.associations.title": "文件关联", + "desktop.associations.unregistered": "未注册", "desktop.branch.alreadyOn": "已在“{name}”上", "desktop.branch.branchName": "分支名称", "desktop.branch.checkedOut": "已检出“{name}”", diff --git a/desktop/internal/settingswindow/file_associations_test.go b/desktop/internal/settingswindow/file_associations_test.go new file mode 100644 index 000000000..eb88b2b44 --- /dev/null +++ b/desktop/internal/settingswindow/file_associations_test.go @@ -0,0 +1,31 @@ +package settingswindow + +import ( + "context" + "errors" + "fmt" + "os" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" +) + +func TestFileAssociationsCancellationKeepsFailures(t *testing.T) { + for _, test := range []struct { + name string + err error + want bool + }{ + {"cancelled", context.Canceled, true}, + {"wrapped cancellation", fmt.Errorf("read: %w", context.Canceled), true}, + {"cancelled causes", errors.Join(context.Canceled, context.Canceled), true}, + {"consent timeout", context.DeadlineExceeded, false}, + {"partial native failure", errors.Join(&fileassociations.FormatError{Extensions: []string{".txt"}, Err: os.ErrPermission}, context.Canceled), false}, + } { + t.Run(test.name, func(t *testing.T) { + if got := associationCanceled(test.err); got != test.want { + t.Fatalf("cancellation-only = %t, want %t for %v", got, test.want, test.err) + } + }) + } +} diff --git a/desktop/internal/settingswindow/file_associations_view.go b/desktop/internal/settingswindow/file_associations_view.go index 767249d1d..802bb92d5 100644 --- a/desktop/internal/settingswindow/file_associations_view.go +++ b/desktop/internal/settingswindow/file_associations_view.go @@ -5,6 +5,7 @@ import ( "errors" "runtime" "strconv" + "strings" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" @@ -26,14 +27,15 @@ type associationResult struct { } type associationRegistration struct { - effect *ui.EffectState[associationResult, *associationRequest] - request *associationRequest - state fileassociations.State - list ui.ListState - picked map[string]bool - err error - loaded bool - applied bool + effect *ui.EffectState[associationResult, *associationRequest] + request *associationRequest + state fileassociations.State + list ui.ListState + picked map[string]bool + err error + loaded bool + applied bool + refreshWhenIdle bool } func (w *window) declareAssociations(c ui.C) { @@ -54,6 +56,39 @@ func (w *window) requestAssociations(action string, selected []string) { label: i18n.Shared(w.marketLanguage(), "desktop.associations.openWith"), } s.applied = false + s.err = nil +} + +// Returning from Default Apps or Finder rereads actual defaults without polling +// or losing the draft. Activation can never start a registration. +func (w *window) refreshAssociations() { + s := &w.associations + if !s.loaded { + return + } + if s.request != nil { + s.refreshWhenIdle = true + return + } + s.request = &associationRequest{action: "activate", ctx: context.Background()} + w.inv.Invalidate() +} + +// A cancelled window can still leave a real native or readback failure in the +// joined result. Suppress a log only when every cause is cancellation. +func associationCanceled(err error) bool { + if joined, ok := err.(interface{ Unwrap() []error }); ok { + for _, cause := range joined.Unwrap() { + if !associationCanceled(cause) { + return false + } + } + return true + } + if wrapped, ok := err.(interface{ Unwrap() error }); ok { + return associationCanceled(wrapped.Unwrap()) + } + return errors.Is(err, context.Canceled) } func (w *window) associationsCard(c ui.C) { @@ -67,7 +102,13 @@ func (w *window) associationsCard(c ui.C) { s.picked = make(map[string]bool) s.effect = ui.NewEffectKeyed[associationResult, *associationRequest](func(parent context.Context, request *associationRequest) (associationResult, error) { // Effect cancellation owns the job lifetime; the operation context carries logs. - ctx, cancel := context.WithTimeout(request.ctx, 30*time.Second) + timeout := 30 * time.Second + if request.action == "apply" { + // Native consent is interactive; the read timeout was too short + // for a batch while a person was answering the system dialog. + timeout = 5 * time.Minute + } + ctx, cancel := context.WithTimeout(request.ctx, timeout) stop := context.AfterFunc(parent, cancel) defer stop() defer cancel() @@ -77,7 +118,7 @@ func (w *window) associationsCard(c ui.C) { } else { result.state, result.err = manager.Read(ctx) } - if result.err != nil && !errors.Is(result.err, context.Canceled) && w.ctrl.opts.AssociationError != nil { + if result.err != nil && !associationCanceled(result.err) && w.ctrl.opts.AssociationError != nil { w.ctrl.opts.AssociationError(ctx, result.err) } // log-exempt: 用户取消:设置窗口关闭时 Effect 撤销尚未结束的工作。 @@ -86,12 +127,20 @@ func (w *window) associationsCard(c ui.C) { s.request = &associationRequest{action: "read", ctx: context.Background()} } if result, effectErr, ok := s.effect.Take(); ok { - s.err = errors.Join(result.err, effectErr) - s.applied = s.request.action == "apply" && s.err == nil + // An activation read updates OS facts but retains the last explicit + // operation's feedback, including formats rejected by native consent. + if s.request.action != "activate" || result.err != nil || effectErr != nil { + s.err = errors.Join(result.err, effectErr) + s.applied = s.request.action == "apply" && s.err == nil + } s.request = nil if result.state.Formats != nil { s.state, s.loaded = result.state, true } + if s.refreshWhenIdle { + s.refreshWhenIdle = false + w.refreshAssociations() + } } busy := s.request != nil help := i18n.Shared(language, "desktop.associations.helpMac") @@ -113,29 +162,34 @@ func (w *window) associationsCard(c ui.C) { } ui.Spacer(c) if busy { - ui.Text(c, i18n.Shared(language, "native.loading")).FontSize(12).Color(w.pal.muted) + message := i18n.Shared(language, "native.loading") + if s.request.action == "apply" { + message = i18n.Shared(language, "desktop.associations.applying") + } + ui.Text(c, message).FontSize(12).Color(w.pal.muted) } if ui.Button(c.Part("association-refresh"), i18n.Shared(language, "desktop.associations.refresh")).Ghost().Disabled(busy).Clicked() { c.After(func() { w.requestAssociations("refresh", nil) }) } }) ui.Row(c).FillWidth().Height(24).Items(ui.Center).Gap(8).Children(func() { - ui.Text(c, i18n.Shared(language, "desktop.associations.format")).WidthPercent(30).Ellipsis().Color(w.pal.muted).FontSize(11) - ui.Text(c, i18n.Shared(language, "desktop.associations.language")).WidthPercent(22).Ellipsis().Color(w.pal.muted).FontSize(11) + ui.Text(c, i18n.Shared(language, "desktop.associations.format")).WidthPercent(24).Ellipsis().Color(w.pal.muted).FontSize(11) + ui.Text(c, i18n.Shared(language, "desktop.associations.language")).WidthPercent(19).Ellipsis().Color(w.pal.muted).FontSize(11) ui.Text(c, i18n.Shared(language, "desktop.associations.currentDefault")).Grow(1).Ellipsis().Color(w.pal.muted).FontSize(11) + ui.Text(c, i18n.Shared(language, "desktop.associations.status")).WidthPercent(22).Ellipsis().Color(w.pal.muted).FontSize(11) }) ui.List(c.Part("association-formats"), &s.list, len(s.state.Formats), func(row ui.ListRow) { format := s.state.Formats[row.Index] handler := s.state.Handlers[row.Index] row.Element.FillWidth().Children(func() { ui.Row(row.C).FillWidth().Height(28).Items(ui.Center).Gap(8).Children(func() { - ui.Row(row.C).WidthPercent(30).Shrink(0).Children(func() { + ui.Row(row.C).WidthPercent(24).Shrink(0).Children(func() { picked := s.picked[format.Extension] if ui.Checkbox(row.C.Key(format.Extension), &picked, format.Extension).Disabled(busy).Changed() { s.picked[format.Extension] = picked } }) - ui.Text(row.C, format.Language).WidthPercent(22).Ellipsis().FontSize(12).Color(w.pal.muted) + ui.Text(row.C, format.Language).WidthPercent(19).Ellipsis().FontSize(12).Color(w.pal.muted) name := handler.DefaultName if name == "" { name = handler.DefaultID @@ -150,6 +204,15 @@ func (w *window) associationsCard(c ui.C) { ui.Row(cell).Hit(ui.ID(cell), name).Grow(1).MinWidth(0).Tooltip(name).Children(func() { ui.Text(row.C, name).Ellipsis().FontSize(12).Color(w.pal.text) }) + status := i18n.Shared(language, "desktop.associations.unregistered") + if !s.state.Available { + status = i18n.Shared(language, "desktop.associations.packageRequired") + } else if handler.IsDefault { + status = i18n.Shared(language, "desktop.associations.defaultConfirmed") + } else if handler.Registered { + status = i18n.Shared(language, "desktop.associations.candidateRegistered") + } + ui.Text(row.C, status).WidthPercent(22).Ellipsis().FontSize(11).Color(w.pal.muted) }) }) }).Scrollbars().FillWidth().Height(224).Label(i18n.Shared(language, "desktop.associations.formats")) @@ -179,8 +242,16 @@ func (w *window) associationsCard(c ui.C) { message := i18n.Shared(language, "desktop.associations.failed") if errors.Is(s.err, fileassociations.ErrConflict) { message = i18n.Shared(language, "desktop.associations.conflict") + } else if errors.Is(s.err, fileassociations.ErrConfirmationPending) { + message = i18n.Shared(language, "desktop.associations.confirmationPending") + } else if errors.Is(s.err, context.DeadlineExceeded) { + message = i18n.Shared(language, "desktop.associations.timedOut") } ui.Wrap(c, message).FontSize(12).Color(w.pal.danger) + var formats *fileassociations.FormatError + if errors.As(s.err, &formats) { + ui.Wrap(c, i18n.SharedFormat(language, "desktop.associations.failedFormats", map[string]string{"formats": strings.Join(formats.Extensions, ", ")})).FontSize(12).Color(w.pal.danger) + } } }) } diff --git a/desktop/internal/settingswindow/file_associations_visual_test.go b/desktop/internal/settingswindow/file_associations_visual_test.go index d6cec8f46..c5643a743 100644 --- a/desktop/internal/settingswindow/file_associations_visual_test.go +++ b/desktop/internal/settingswindow/file_associations_visual_test.go @@ -5,6 +5,7 @@ package settingswindow import ( "os" "path/filepath" + "runtime" "testing" "time" @@ -104,7 +105,41 @@ func TestVisualFileAssociations(t *testing.T) { if len(s.picked) != len(s.state.Formats) { t.Fatal("select all omitted virtualized formats") } - if err := session.Screenshot(filepath.Join(out, "file-associations-"+language.Code()+"-"+theme+".png")); err != nil { + // Use the real activation callback, as when returning from system + // Default Apps. Only a read may start; the draft must survive it. + if config.OnActivate == nil { + t.Fatal("settings has no activation refresh callback") + } + config.OnActivate() + if s.request == nil || s.request.action != "activate" { + t.Fatal("returning to settings did not reread system defaults") + } + pending := s.request + config.OnActivate() + if s.request != pending || !s.refreshWhenIdle { + t.Fatal("activation during an operation did not defer its readback") + } + d.pump() + await() + if len(s.picked) != len(s.state.Formats) { + t.Fatal("activation refresh discarded the selection") + } + helpKey := "desktop.associations.helpMac" + if runtime.GOOS == "windows" { + helpKey = "desktop.associations.helpWindows" + } + help := i18n.Shared(language, helpKey) + info := d.hintHit(help).Bounds + if err := d.driver.Move(info.X+info.Width/2, info.Y+info.Height/2); err != nil { + t.Fatal(err) + } + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + if !d.showsHelp(help) { + t.Fatal("file association help did not appear") + } + if err := session.Screenshot(filepath.Join(out, "file-associations-help-"+language.Code()+"-"+theme+".png")); err != nil { t.Fatal(err) } d.click(i18n.Shared(language, "desktop.associations.clearSelection")) diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index 1d40d5125..6d4ad2546 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -339,6 +339,7 @@ func (w *window) config() app.Config { OnWake: w.wake, OnFrameChange: w.framed, OnClosed: w.closed, + OnActivate: w.refreshAssociations, // Chords of printable keys reach the window as shortcuts, not as keys of the // control that has the focus; the one the Keymap page records arrives here. OnShortcut: w.recordShortcut, diff --git a/shared/i18n/features/file-associations.json b/shared/i18n/features/file-associations.json index ceae74e7e..af078d6d5 100644 --- a/shared/i18n/features/file-associations.json +++ b/shared/i18n/features/file-associations.json @@ -144,6 +144,52 @@ "desktop" ] }, + { + "id": "desktop.associations.status", + "description": "Lithe registration and confirmed default status column", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.unregistered", + "description": "Lithe is not registered for this format", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.candidateRegistered", + "description": "Lithe is an Open With candidate but not the default", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.packageRequired", + "description": "A development executable has no packaged identity to compare against OS registrations", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.defaultConfirmed", + "description": "OS readback confirms Lithe is the default", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.applying", + "description": "Batch association operation waiting for native completion", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.timedOut", + "description": "Batch consent exceeded its interactive deadline", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.confirmationPending", + "description": "A previous native confirmation has not completed, so no new batch can start", + "platforms": ["desktop"] + }, + { + "id": "desktop.associations.failedFormats", + "description": "Extensions whose native registration or default request failed", + "platforms": ["desktop"], + "parameters": {"formats": "string"} + }, { "id": "desktop.associations.openWith", "description": "System file associations: openWith", @@ -155,8 +201,8 @@ "locales": { "en-US": { "desktop.associations.title": "File associations", - "desktop.associations.helpMac": "Lists the extensions supported by built-in highlighting, plus plain text. Select formats and apply to use Lithe as their default editor. Finder also offers Lithe under Open With. macOS associates content types, so extensions sharing one type may change together. Filename-only rules, compressed files and binary files are excluded; compound suffixes use the final extension. Clearing a checkbox changes only this draft.", - "desktop.associations.helpWindows": "Lists the extensions supported by built-in highlighting, plus plain text. Register selected formats to offer Lithe in Open With, then confirm defaults in Windows Settings. Associated files also have an Open with Lithe context action (under Show more options on Windows 11). Filename-only rules, compressed files and binary files are excluded. Clearing a checkbox changes only this draft.", + "desktop.associations.helpMac": "Select the text formats you want Lithe to edit by default, then apply. This replaces their current default applications. Once confirmed, double-clicking a file in Finder opens it in Single File Mode and keeps your open projects. macOS may ask for confirmation for each content type; extensions sharing a type change together. Returning here refreshes the actual defaults. Clearing a checkbox does not restore a previous default.", + "desktop.associations.helpWindows": "Register the selected text formats, then choose Lithe as their default on Lithe’s page in Windows Settings. This replaces their current default applications. Once confirmed, double-clicking a file in File Explorer opens it in Single File Mode. Registered candidates are not yet defaults. Returning here refreshes the actual defaults. You can also use Open with Lithe (under Show more options on Windows 11). Clearing a checkbox does not restore a previous default.", "desktop.associations.selectAll": "Select all", "desktop.associations.clearSelection": "Clear selection", "desktop.associations.refresh": "Refresh", @@ -170,16 +216,25 @@ "desktop.associations.applyMac": "Set selected defaults", "desktop.associations.applyWindows": "Register and choose defaults…", "desktop.associations.requiresInstalled": "Install and open the packaged Lithe application to register file associations.", - "desktop.associations.appliedMac": "Default applications refreshed from the system.", - "desktop.associations.appliedWindows": "Formats registered. Confirm your choices in Windows Settings, then refresh this list.", + "desktop.associations.appliedMac": "Batch finished. Current defaults have been read back from macOS.", + "desktop.associations.appliedWindows": "Selected formats registered. Confirm defaults in Windows Settings; returning here refreshes the result automatically.", "desktop.associations.failed": "Could not read or update file associations. Some formats may have changed. Refresh to check the current defaults and try again.", "desktop.associations.conflict": "System associations changed while this page was open. Review the refreshed defaults and apply again.", + "desktop.associations.status": "Lithe status", + "desktop.associations.unregistered": "Not registered", + "desktop.associations.candidateRegistered": "Candidate registered", + "desktop.associations.packageRequired": "Package required", + "desktop.associations.defaultConfirmed": "Default confirmed", + "desktop.associations.applying": "Applying selected formats…", + "desktop.associations.timedOut": "System confirmation timed out and remaining requests stopped. An open system dialog may still complete. Finish or dismiss it, then refresh to check current defaults before retrying.", + "desktop.associations.confirmationPending": "A previous macOS confirmation is still open. Finish or dismiss it, then refresh to check current defaults before retrying.", + "desktop.associations.failedFormats": "Failed formats: {formats}. Review the current defaults before retrying these formats.", "desktop.associations.openWith": "Open with Lithe" }, "zh-CN": { "desktop.associations.title": "文件关联", - "desktop.associations.helpMac": "列出内置高亮支持的扩展名及纯文本。勾选格式并应用后,将 Lithe 设为默认编辑器;Finder 也会在“打开方式”中显示 Lithe。macOS 按内容类型关联,共用同一类型的扩展名可能同时生效。仅匹配文件名的规则、压缩文件和二进制文件不在此列,复合后缀使用最后一段扩展名。取消勾选只修改本次草稿。", - "desktop.associations.helpWindows": "列出内置高亮支持的扩展名及纯文本。注册所选格式后,Lithe 会显示在“打开方式”中,再到 Windows 设置确认默认应用。已关联的文件也会有“用 Lithe 打开”右键项(Windows 11 位于“显示更多选项”)。仅匹配文件名的规则、压缩文件和二进制文件不在此列。取消勾选只修改本次草稿。", + "desktop.associations.helpMac": "勾选希望由 Lithe 默认编辑的文本格式后应用,会替换这些格式原来的默认应用。生效后,在访达双击文件会直接进入单文件模式,保留已经打开的项目。macOS 可能按内容类型分别要求确认;共用同一类型的后缀会一同更改。返回此窗口会自动读取实际默认应用。取消勾选不会恢复原来的默认应用。", + "desktop.associations.helpWindows": "注册勾选的文本格式,再到 Windows 设置中的 Lithe 页面将其设为默认,会替换这些格式原来的默认应用。生效后,在文件资源管理器双击文件会直接进入单文件模式。“已注册候选”表示尚未成为默认应用。返回此窗口会自动读取实际结果。也可使用“用 Lithe 打开”右键项(Windows 11 位于“显示更多选项”)。取消勾选不会恢复原来的默认应用。", "desktop.associations.selectAll": "全选", "desktop.associations.clearSelection": "清空选择", "desktop.associations.refresh": "刷新", @@ -193,10 +248,19 @@ "desktop.associations.applyMac": "将所选格式设为默认", "desktop.associations.applyWindows": "注册并选择默认应用…", "desktop.associations.requiresInstalled": "请安装并运行打包后的 Lithe 应用以注册文件关联。", - "desktop.associations.appliedMac": "已从系统重新读取默认应用。", - "desktop.associations.appliedWindows": "所选格式已注册。请在 Windows 设置中确认默认应用,再刷新此列表。", + "desktop.associations.appliedMac": "批量处理结束,已从 macOS 重新读取当前默认应用。", + "desktop.associations.appliedWindows": "所选格式已注册。请在 Windows 设置中确认默认应用,返回此窗口后将自动刷新结果。", "desktop.associations.failed": "无法读取或更新文件关联,部分格式可能已生效。请刷新确认当前状态后重试。", "desktop.associations.conflict": "打开此页后系统关联发生了变化。请确认刷新后的默认应用,再重新应用。", + "desktop.associations.status": "Lithe 状态", + "desktop.associations.unregistered": "未注册", + "desktop.associations.candidateRegistered": "已注册候选", + "desktop.associations.packageRequired": "需安装包", + "desktop.associations.defaultConfirmed": "已是默认", + "desktop.associations.applying": "正在批量应用所选格式…", + "desktop.associations.timedOut": "系统确认超时,已停止提交剩余请求。已经打开的系统弹窗仍可能生效,请先完成或关闭弹窗,再刷新核对默认应用后重试。", + "desktop.associations.confirmationPending": "上一轮 macOS 系统确认尚未结束。请先完成或关闭系统弹窗,再刷新核对默认应用后重试。", + "desktop.associations.failedFormats": "失败格式:{formats}。请核对当前默认应用后重试这些格式。", "desktop.associations.openWith": "用 Lithe 打开" } } diff --git a/shared/platform-feature-matrix/features/system-file-associations.json b/shared/platform-feature-matrix/features/system-file-associations.json index d72779860..b9601ebdb 100644 --- a/shared/platform-feature-matrix/features/system-file-associations.json +++ b/shared/platform-feature-matrix/features/system-file-associations.json @@ -2,10 +2,10 @@ "id": "system-file-associations", "area": "应用与设置", "group": "通用", - "capability": "按内置文本高亮目录勾选系统文件关联,回显真实默认应用并独立打开文件", + "capability": "按内置文本高亮目录批量申请系统文件关联,区分候选与默认、返回自动回读并独立打开文件", "owner": "Desktop", - "verification": "macOS:从签名发布包打开通用设置,核对表格与 Finder 默认应用一致;选择少量格式设为默认,验证同内容类型扩展名的系统联动、外部修改冲突、刷新和部分失败;从 Finder 打开包含中文/空格的文件,项目保留且文档进入独立会话,关闭后无残留。Windows:使用本机 Windows 来宾安装 amd64 包,核对 HKCU 的 Applications、OpenWithProgids、Capabilities 和 RegisteredApplications,不写 UserChoice;注册所选格式后在系统设置确认默认应用,核对右键打开(Windows 11 显示更多选项)、参数引用、开发二进制不可注册及卸载清理。两端检查中英明暗表格、全选/清空、滚轮/滚动条到末尾和勾选保留,运行前后安装目录清单不变。", - "notes": "Core fixture 与 C ABI、真实高亮解析和 Viva 清单一致性、独立文件打开及定向竞态测试在 macOS 通过;四种无头界面使用真实系统默认应用,未执行默认应用写入。macOS arm64 最终应用构建及 Core 的 Windows MSVC clippy 通过,Windows Go 原生适配器尚未编译验收。宿主固定到配套 Core PR 的确切提交,合并前须先合入 Core。macOS 按内容类型关联,扩展名别名可能同时变化。Windows 的独立右键动作位于自有 ProgID 下,只有关联后的文件显示;其他文件从打开方式进入。Windows 本机未配置来宾,Windows 原生流程与两端发布包验收未完成。", + "verification": "macOS:从签名发布包打开通用设置,核对表格与 Finder 默认应用一致;一次选择多个不同内容类型和一组后缀别名,核对实际写入及系统确认次数,相同类型只提交一次,拒绝某项后继续其余格式并显示失败后缀;验证外部修改冲突、超时后不堆积确认,以及结束系统弹窗再返回自动回读。Finder 打开中文/空格路径文件时项目保留,文档进入独立会话,关闭后无残留。Windows:使用本机 Windows 来宾安装 amd64 包,核对 HKCU 的 Applications、OpenWithProgids、Capabilities 和 RegisteredApplications,不写 UserChoice;一次注册全部勾选格式,部分失败继续其余格式,只打开一次默认应用页;系统确认后返回自动回读。核对右键打开(Windows 11 显示更多选项)、参数引用、开发二进制不可注册及卸载清理。两端检查中英明暗表格、候选与默认状态、全选/清空、滚轮/滚动条到末尾和激活后勾选保留,运行前后安装目录清单不变。", + "notes": "共享目录、冲突计划和 Core 契约保持不变。macOS 修复同步提交后立即合成 -10814 并停止整批的问题,改用 NSWorkspace 异步完成回调和按系统内容类型去重;普通失败继续,取消或超时停止后续提交,同一进程最多保留一个未完成系统确认。注册修订不再包含启发式应用路径。Windows 批量候选注册继续处理单格式失败;两端激活窗口自动回读,保留草稿与上次失败反馈。说明明确替换所选格式原默认应用,生效后双击进入单文件模式。原生只读、类型别名、预取消、错误保留、共享 fixture 和四种无头界面交互在 macOS 定向竞态测试通过,最终应用构建通过;系统文件入口复用独立会话、保留项目和真实文件编辑保存的定向测试通过,无头测试不修改默认应用。原生幂等探针对 .java 已生效的同一默认应用提交后回调成功,默认值未改变;不覆盖新默认值写入或授权。自动回读有修复前失败证据,macOS 批量写入修复依据日志与代码推理。Windows 本机未配置来宾,Go 原生适配器尚未编译验收,两端签名发布包的实际批量写入、授权和卸载流程未完成,状态保持 pending。公开接口不保证整组只出现一次系统确认。", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -13,7 +13,9 @@ "desktop/internal/fileassociations/registration.go", "desktop/internal/fileassociations/registration_darwin.go", "desktop/internal/fileassociations/registration_test.go", + "desktop/internal/fileassociations/registration_darwin_test.go", "desktop/internal/settingswindow/file_associations_view.go", + "desktop/internal/settingswindow/file_associations_test.go", "desktop/internal/settingswindow/file_associations_visual_test.go", "desktop/internal/core/file_associations_test.go", "desktop/internal/workbench/system_document.go", @@ -30,6 +32,7 @@ "desktop/internal/fileassociations/registration_windows.go", "desktop/internal/fileassociations/registration_test.go", "desktop/internal/settingswindow/file_associations_view.go", + "desktop/internal/settingswindow/file_associations_test.go", "desktop/internal/settingswindow/file_associations_visual_test.go", "desktop/internal/core/file_associations_test.go", "desktop/cmd/lithe/main.go",