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 new file mode 100644 index 000000000..4c951ee3d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-23-system-file-associations.md @@ -0,0 +1,59 @@ +# Agent 笔记:按内置文本高亮目录注册系统文件关联 + +状态:已实现 + +## 先说结论 + +“通用”设置中的文件关联表格直接显示系统当前的默认应用,用户勾选后明确应用才改变关联。可选格式来自编辑器实际打包的文本高亮扩展名及纯文本,不接受正则或“所有文件”。macOS 使用 Finder 的“打开方式”和默认应用;Windows 注册“打开方式”候选并交给系统设置确认默认应用。 + +## 问题 + +操作系统按扩展名或内容类型注册文件处理程序,不能表达编辑器中的任意正则。单独维护一张扩展名表会与高亮支持和打包声明发生漂移;只保存一个“使用 Lithe 打开”的应用偏好,也无法说明系统真正使用哪个程序。系统打开文件时还必须保留用户已打开的项目,避免为了临时编辑一个文件而索引整个父目录。 + +## 决策 + +- 编辑器只导出内置元数据,不加载语法,也不混入插件贡献。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 设置确认;刷新后回显系统结果。 +- Windows 的右键动作放在 Lithe 自己的 ProgID 下,随 Viva 安装器卸载该格式一起移除,不在全局 `SystemFileAssociations` 或所有文件类写额外项。运行期仅允许名为 `lithe.exe` 的产品程序注册,避免测试二进制写入无法由卸载器移除的 Applications 项。 +- Finder 事件只接受真实普通文件,复用独立编辑会话;已有项目保留,通过原有项目标签返回。Windows 从启动参数进入既有单文件模式。文档服务的隔离沿用[可选 CLI 注册与单文件编辑](2026-11-20-cli-and-standalone-editor.md),不创建插件、目录索引或项目服务。 +- 表格复用 Viva 的虚拟列表和共享滚动条,只创建可见行;勾选以扩展名保存,不依赖离屏控件是否存在。系统查询和写入在可取消、有期限的后台任务中完成。 + +正确做法:新增内置高亮后运行生成器,把格式同时带到设置、macOS 声明和 Windows 安装器;打开设置只查系统,勾选后点击应用才发布。不要在界面手写另一份格式名单,也不要通过改写安装包里的清单来补运行期关联。 + +## 考虑过的备选方案 + +- 正则输入和所有文本文件总开关:系统不理解正则,也无法仅凭文件内容在 Explorer/Finder 注册默认应用。最终采用真实内置高亮扩展名的全选操作,避免抢占二进制或压缩文件。 +- macOS 添加固定 Finder 右键动作:需要额外的系统扩展和生命周期;系统已有“打开方式”可表达同一入口,本次使用它。 +- Windows 直接写 UserChoice:绕过系统保护且不能可靠生效,保留系统确认流程。 +- 全局右键项配扩展名过滤:Viva 当前卸载器不会清理额外全局项。把动作放进自有 ProgID 可以复用现有安装和卸载边界,代价是它只出现在已关联文件上。 +- 所有平台各写一份筛选和冲突判断:行为会漂移,共享规则在 Core,平台只负责原生查询和写入。 + +## 后果 + +格式目录、高亮支持和安装声明可以相互核对,打开设置不改变系统,也没有虚假的“已注册”偏好。代价是仅文件名匹配的 Makefile 等不在系统关联列表中;设置默认应用需要安装后的程序,macOS 的类型别名和 Windows 的用户确认由系统决定。平台外部进程在重读与写入之间仍可竞争,原生接口不提供跨进程事务,批量部分失败会显示错误并回读。 + +清单是构建输入,由仓库维护,不是缓存。运行期注册数据由系统管理,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/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/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。无头测试不修改开发机默认应用。 + +## 适用范围 + +- `desktop/internal/fileassociations/` +- `desktop/internal/core/file_associations.go` +- `desktop/internal/editor/syntax/catalog.go` +- `desktop/internal/settingswindow/file_associations_view.go` +- `desktop/internal/workbench/system_document.go` +- `desktop/cmd/file-associations-manifest/` +- `desktop/viva.toml` +- `shared/platform-feature-matrix/features/system-file-associations.json` diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 59a1cb781..b2e98244a 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -72,6 +72,7 @@ jobs: bash -n scripts/desktop/build-remote-server.sh bash -n scripts/desktop/desktop-go.sh bash -n scripts/desktop/package-desktop.sh + bash -n scripts/desktop/generate-file-associations.sh bash -n scripts/desktop/build-viva-tool.sh bash -n scripts/desktop/perf/editor-bench.sh bash -n scripts/ci/desktop-release/package-release.sh @@ -90,6 +91,7 @@ jobs: scripts/desktop/build-remote-server.sh \ scripts/desktop/desktop-go.sh \ scripts/desktop/package-desktop.sh \ + scripts/desktop/generate-file-associations.sh \ scripts/desktop/build-viva-tool.sh \ scripts/desktop/perf/editor-bench.sh \ scripts/ci/desktop-release/package-release.sh \ diff --git a/desktop/cmd/file-associations-manifest/main.go b/desktop/cmd/file-associations-manifest/main.go new file mode 100644 index 000000000..14f71be32 --- /dev/null +++ b/desktop/cmd/file-associations-manifest/main.go @@ -0,0 +1,62 @@ +// Command file-associations-manifest projects the editor's actual bundled syntax +// catalog through Core into Viva's native package declarations. +package main + +import ( + "bytes" + "context" + "flag" + "fmt" + "os" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" +) + +const begin = "# BEGIN generated file associations\n" +const end = "# END generated file associations\n" + +func main() { + check := flag.Bool("check", false, "fail if viva.toml differs from the built-in text catalog") + flag.Parse() + if err := generate(*check); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func generate(check bool) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + formats, err := fileassociations.Catalog(ctx, core.NewClient()) + if err != nil { + return err + } + source, err := os.ReadFile("viva.toml") + if err != nil { + return err + } + start := bytes.Index(source, []byte(begin)) + finish := bytes.Index(source, []byte(end)) + if start < 0 || finish < start { + return fmt.Errorf("viva.toml: missing generated file-association markers") + } + var block bytes.Buffer + block.WriteString(begin) + block.WriteString("# Generated by scripts/desktop/generate-file-associations.sh; do not edit.\n") + for _, format := range formats { + fmt.Fprintf(&block, "[[app.file_types]]\nname = %q\nextensions = [%q]\n\n", "Lithe Desktop "+format.Extension, strings.TrimPrefix(format.Extension, ".")) + } + block.WriteString(end) + result := append(bytes.Clone(source[:start]), block.Bytes()...) + result = append(result, source[finish+len(end):]...) + if bytes.Equal(result, source) { + return nil + } + if check { + return fmt.Errorf("viva.toml: file associations are stale; run scripts/desktop/generate-file-associations.sh") + } + return os.WriteFile("viva.toml", result, 0644) +} diff --git a/desktop/go.mod b/desktop/go.mod index ed3ee783c..fecc5bea0 100644 --- a/desktop/go.mod +++ b/desktop/go.mod @@ -18,6 +18,7 @@ require ( github.com/danieljoos/wincred v1.2.3 // indirect github.com/ebitengine/purego v0.11.1 // indirect github.com/godbus/dbus/v5 v5.2.2 // indirect + github.com/pelletier/go-toml/v2 v2.4.3 // indirect ) replace github.com/vivaui/viva => github.com/Lithe-IDEA/viva v0.6.7-0.20261123062230-3c6c46081fe6 diff --git a/desktop/internal/core/file_associations.go b/desktop/internal/core/file_associations.go new file mode 100644 index 000000000..601db95dc --- /dev/null +++ b/desktop/internal/core/file_associations.go @@ -0,0 +1,49 @@ +package core + +import "context" + +// FileAssociationLanguage is observed metadata from the bundled syntax registry. +type FileAssociationLanguage struct { + ID string `json:"id"` + Highlighted bool `json:"highlighted"` + Extensions []string `json:"extensions"` +} + +// FileAssociationFormat is a registrable text suffix selected by Core. +type FileAssociationFormat struct { + Extension string `json:"extension"` + Language string `json:"language"` +} + +func (c *Client) FileAssociationCatalog(ctx context.Context, languages []FileAssociationLanguage) ([]FileAssociationFormat, error) { + var result struct { + Formats []FileAssociationFormat `json:"formats"` + } + err := c.Execute(ctx, "application.fileAssociations.catalog", struct { + Languages []FileAssociationLanguage `json:"languages"` + }{nonNil(languages)}, &result) + return result.Formats, err +} + +// FileAssociationObservation contains native identities, excluding display labels. +type FileAssociationObservation struct { + Extension string `json:"extension"` + DefaultID string `json:"defaultId"` + Registration string `json:"registration"` +} + +type FileAssociationPlan struct { + Conflict bool `json:"conflict"` + Extensions []string `json:"extensions"` +} + +func (c *Client) PlanFileAssociations(ctx context.Context, formats []FileAssociationFormat, selected []string, baseline, current []FileAssociationObservation) (FileAssociationPlan, error) { + var result FileAssociationPlan + err := c.Execute(ctx, "application.fileAssociations.plan", struct { + Formats []FileAssociationFormat `json:"formats"` + Selected []string `json:"selected"` + Baseline []FileAssociationObservation `json:"baseline"` + Current []FileAssociationObservation `json:"current"` + }{nonNil(formats), nonNil(selected), nonNil(baseline), nonNil(current)}, &result) + return result, err +} diff --git a/desktop/internal/core/file_associations_test.go b/desktop/internal/core/file_associations_test.go new file mode 100644 index 000000000..053ae1aed --- /dev/null +++ b/desktop/internal/core/file_associations_test.go @@ -0,0 +1,57 @@ +package core + +import ( + "context" + "encoding/json" + "os" + "reflect" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +func TestFileAssociationsSharedFixture(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + data, err := os.ReadFile(contractfixture.CoreFixture("application/file-associations-v1.json")) + if err != nil { + t.Fatal(err) + } + type fixtureCase struct { + Name, Command string + Payload, Expected json.RawMessage + } + var fixture struct{ Catalog, Plans, Errors []fixtureCase } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + client := NewClient() + for section, cases := range map[string][]fixtureCase{ + "application.fileAssociations.catalog": fixture.Catalog, + "application.fileAssociations.plan": fixture.Plans, + } { + for _, test := range cases { + t.Run(test.Name, func(t *testing.T) { + var actual, expected any + if err := client.Execute(ctx, section, test.Payload, &actual); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(test.Expected, &expected); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(actual, expected) { + t.Fatalf("got %+v, want %+v", actual, expected) + } + }) + } + } + for _, test := range fixture.Errors { + t.Run(test.Name, func(t *testing.T) { + var result any + if err := client.Execute(ctx, test.Command, test.Payload, &result); err == nil { + t.Fatal("invalid association plan accepted") + } + }) + } +} diff --git a/desktop/internal/editor/syntax/catalog.go b/desktop/internal/editor/syntax/catalog.go new file mode 100644 index 000000000..12976aa05 --- /dev/null +++ b/desktop/internal/editor/syntax/catalog.go @@ -0,0 +1,24 @@ +package syntax + +import "slices" + +// BundledFileType is metadata observed from the editor's built-in catalog. It +// does not include plugin contributions and does not load or tokenize grammars. +type BundledFileType struct { + ID string + Highlighted bool + Extensions []string +} + +// BundledFileTypes returns independent metadata for settings and packaging. Core +// decides which suffixes can safely be registered with the operating system. +func BundledFileTypes() []BundledFileType { + result := make([]BundledFileType, len(bundledLanguages)) + for i, language := range bundledLanguages { + result[i] = BundledFileType{ + ID: language.ID, Highlighted: hasBundledGrammar(language.Scope), + Extensions: slices.Clone(language.Extensions), + } + } + return result +} diff --git a/desktop/internal/fileassociations/registration.go b/desktop/internal/fileassociations/registration.go new file mode 100644 index 000000000..cb439417e --- /dev/null +++ b/desktop/internal/fileassociations/registration.go @@ -0,0 +1,109 @@ +// Package fileassociations reads the system's actual text-file handlers and +// publishes explicit registrations. It never writes into the installed package. +package fileassociations + +// Note: 系统默认应用与只读包边界见 .agents/notes/implemented/feature/2026-11-23-system-file-associations.md + +import ( + "context" + "errors" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" +) + +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") + +// Handler is an OS observation, rather than a stored Lithe preference. +type Handler struct { + Extension, DefaultID, DefaultName string + IsDefault, Registered bool + registration string +} + +// State retains an optimistic baseline for the explicit apply action. +type State struct { + Formats []core.FileAssociationFormat + Handlers []Handler + Available bool + native nativeState +} + +// Manager serializes this controller's reads and writes. Opening settings and +// changing draft checkboxes never create files or publish OS registrations. +type Manager struct { + mu sync.Mutex + Kernel *core.Client +} + +func New() *Manager { return &Manager{Kernel: core.NewClient()} } + +// Catalog uses the exact metadata of the built-in editor, including whether a +// grammar is actually bundled. Core owns filtering, deduplication and ordering. +func Catalog(ctx context.Context, kernel *core.Client) ([]core.FileAssociationFormat, error) { + observed := syntax.BundledFileTypes() + languages := make([]core.FileAssociationLanguage, len(observed)) + for i, language := range observed { + languages[i] = core.FileAssociationLanguage{ + ID: language.ID, Highlighted: language.Highlighted, + Extensions: language.Extensions, + } + } + return kernel.FileAssociationCatalog(ctx, languages) +} + +func (m *Manager) Read(ctx context.Context) (State, error) { + m.mu.Lock() + defer m.mu.Unlock() + formats, err := Catalog(ctx, m.Kernel) + if err != nil { + return State{}, err + } + return readNative(ctx, formats) +} + +func observations(state State) []core.FileAssociationObservation { + result := make([]core.FileAssociationObservation, len(state.Handlers)) + for i, handler := range state.Handlers { + result[i] = core.FileAssociationObservation{ + Extension: handler.Extension, DefaultID: handler.DefaultID, + Registration: handler.registration, + } + } + return result +} + +// Apply requests changes for explicitly selected formats; macOS content-type +// aliases may share the resulting default. Native failures are followed by +// readback too, so a partially applied batch is never displayed as success. +func (m *Manager) Apply(ctx context.Context, baseline State, selected []string, menuLabel string) (State, error) { + m.mu.Lock() + defer m.mu.Unlock() + formats, err := Catalog(ctx, m.Kernel) + if err != nil { + return State{}, err + } + current, err := readNative(ctx, formats) + if err != nil { + return State{}, err + } + if !current.Available { + return current, ErrNotPackaged + } + plan, err := m.Kernel.PlanFileAssociations(ctx, formats, selected, observations(baseline), observations(current)) + if err != nil { + return current, err + } + if plan.Conflict { + return current, ErrConflict + } + err = applyNative(ctx, current.native, plan.Extensions, menuLabel) + after, readErr := readNative(ctx, formats) + if readErr != nil { + return current, errors.Join(err, readErr) + } + return after, err +} diff --git a/desktop/internal/fileassociations/registration_darwin.go b/desktop/internal/fileassociations/registration_darwin.go new file mode 100644 index 000000000..fe0df04fe --- /dev/null +++ b/desktop/internal/fileassociations/registration_darwin.go @@ -0,0 +1,170 @@ +package fileassociations + +/* +#cgo CFLAGS: -x objective-c -fobjc-arc +#cgo LDFLAGS: -framework Foundation -framework AppKit -framework CoreServices -framework UniformTypeIdentifiers +#import +#import +#import +#include +#include + +static NSString *lithe_association_identity(const char *path) { + NSBundle *bundle = [NSBundle bundleWithPath:[NSString stringWithUTF8String:path]]; + return bundle.bundleIdentifier; +} + +static char *lithe_association_bundle_id(const char *path) { + @autoreleasepool { + NSString *identity = lithe_association_identity(path); + return identity == nil ? NULL : strdup(identity.UTF8String); + } +} + +static CFStringRef 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); +} + +// 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_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); + 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; + } + NSMutableData *data = [NSMutableData data]; + for (NSString *field in @[preferred ?: @"", name ?: @"", offered ? @"1" : @"0", ourURL.path ?: @""]) { + const char *value = field.UTF8String; + [data appendBytes:value length:strlen(value)+1]; + } + *size = data.length; + void *result = malloc(data.length); + if (result != NULL) memcpy(result, data.bytes, data.length); + return result; + } +} + +static int lithe_association_register(const char *path) { + @autoreleasepool { + NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]]; + return (int)LSRegisterURL((__bridge CFURLRef)url, true); + } +} + +static int lithe_association_default(const char *extension, const char *identity) { + @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; + } + } + CFRelease(type); + return (int)result; + } +} +*/ +import "C" + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "strings" + "unsafe" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackage" +) + +type nativeState struct{ bundle, identity string } + +func readNative(ctx context.Context, formats []core.FileAssociationFormat) (State, error) { + bundle, err := installedpackage.Root() + if err != nil { + return State{}, err + } + path := C.CString(bundle) + defer C.free(unsafe.Pointer(path)) + identity := C.lithe_association_bundle_id(path) + state := State{Formats: formats, native: nativeState{bundle: bundle}} + if identity != nil { + defer C.free(unsafe.Pointer(identity)) + state.native.identity, state.Available = C.GoString(identity), true + } else { + // Development executables can read real defaults, but cannot register a bundle. + identity = C.CString("") + defer C.free(unsafe.Pointer(identity)) + } + for _, format := range formats { + if err := ctx.Err(); err != nil { + return State{}, err + } + extension := C.CString(format.Extension) + var size C.size_t + raw := C.lithe_association_read(extension, identity, &size) + C.free(unsafe.Pointer(extension)) + if raw == nil { + return State{}, fmt.Errorf("file associations: native handler allocation failed") + } + data := C.GoStringN(raw, C.int(size)) + C.free(unsafe.Pointer(raw)) + fields := strings.Split(data, "\x00") + if len(fields) != 5 { + return State{}, fmt.Errorf("file associations: invalid native handler response") + } + revision := sha256.Sum256([]byte(fields[2] + "\x00" + fields[3])) + 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), + Registered: fields[2] == "1", registration: hex.EncodeToString(revision[:]), + }) + } + return state, nil +} + +func applyNative(ctx context.Context, state nativeState, extensions []string, _ string) error { + if err := ctx.Err(); err != nil { + return err + } + path, identity := C.CString(state.bundle), C.CString(state.identity) + 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)) + } + for _, extension := range extensions { + if err := ctx.Err(); err != nil { + return 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)) + } + } + return nil +} diff --git a/desktop/internal/fileassociations/registration_other.go b/desktop/internal/fileassociations/registration_other.go new file mode 100644 index 000000000..458930de6 --- /dev/null +++ b/desktop/internal/fileassociations/registration_other.go @@ -0,0 +1,21 @@ +//go:build !darwin && !windows + +package fileassociations + +import ( + "context" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +type nativeState struct{} + +func readNative(ctx context.Context, formats []core.FileAssociationFormat) (State, error) { + state := State{Formats: formats} + for _, format := range formats { + state.Handlers = append(state.Handlers, Handler{Extension: format.Extension}) + } + return state, ctx.Err() +} + +func applyNative(context.Context, nativeState, []string, string) error { return ErrUnsupported } diff --git a/desktop/internal/fileassociations/registration_test.go b/desktop/internal/fileassociations/registration_test.go new file mode 100644 index 000000000..99948cfbc --- /dev/null +++ b/desktop/internal/fileassociations/registration_test.go @@ -0,0 +1,43 @@ +package fileassociations + +import ( + "context" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" + "github.com/vivaui/viva/tools/manifest" +) + +func TestFileAssociationsMatchBundledSyntaxAndNativePackages(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + formats, err := Catalog(ctx, core.NewClient()) + if err != nil { + t.Fatal(err) + } + packaged, err := manifest.Load(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + if len(formats) != len(packaged.App.FileTypes) || len(formats) < 2 { + t.Fatalf("catalog=%d, native package=%d", len(formats), len(packaged.App.FileTypes)) + } + registry := syntax.NewRegistry() + for index, format := range formats { + kind := packaged.App.FileTypes[index] + if len(kind.Extensions) != 1 || kind.Extensions[0] != strings.TrimPrefix(format.Extension, ".") { + t.Fatalf("native package type %+v differs from settings %+v", kind, format) + } + language, ok := registry.ForPath("sample" + format.Extension) + if !ok || language.ID != format.Language || (format.Language != "plaintext" && language.Scope == "") { + t.Fatalf("catalog entry %+v does not resolve to bundled highlighting: %+v", format, language) + } + if format.Extension == ".rlib" || format.Extension == ".svgz" { + t.Fatalf("non-text container included: %s", format.Extension) + } + } +} diff --git a/desktop/internal/fileassociations/registration_windows.go b/desktop/internal/fileassociations/registration_windows.go new file mode 100644 index 000000000..4ccec8e20 --- /dev/null +++ b/desktop/internal/fileassociations/registration_windows.go @@ -0,0 +1,196 @@ +package fileassociations + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "syscall" + "unsafe" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/installedpackage" + "github.com/vivaui/viva/app" + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" +) + +const applicationID = "app.lithe.viva" +const capabilitiesKey = `Software\` + applicationID + `\Capabilities` +const registeredApplicationsKey = `Software\RegisteredApplications` + +var assocQuery = windows.NewLazySystemDLL("shlwapi.dll").NewProc("AssocQueryStringW") +var associationChanged = windows.NewLazySystemDLL("shell32.dll").NewProc("SHChangeNotify") + +type nativeState struct{ executable string } + +type registryValue struct{ path, name, text string } + +func progID(extension string) string { return applicationID + extension } + +// The owned verb lives under our per-format ProgID, which Viva's installer removes +// on uninstall. Before choosing Lithe as default, Explorer offers Open With through +// OpenWithProgids. No global catch-all or orphaned SystemFileAssociations key is needed. +func registrationValues(executable, extension, menuLabel string) []registryValue { + application := `Software\Classes\Applications\` + filepath.Base(executable) + class := `Software\Classes\` + progID(extension) + command := `"` + executable + `" -- "%1"` + icon := `"` + executable + `",0` + return []registryValue{ + {registeredApplicationsKey, applicationID, capabilitiesKey}, + {capabilitiesKey, "ApplicationName", "Lithe Desktop"}, + {capabilitiesKey, "ApplicationDescription", "Lithe Desktop"}, + {capabilitiesKey, "ApplicationIcon", icon}, + {application, "FriendlyAppName", "Lithe Desktop"}, + {application + `\DefaultIcon`, "", icon}, + {application + `\shell\open\command`, "", command}, + {application + `\SupportedTypes`, extension, ""}, + {class, "", "Lithe Desktop " + extension}, + {class + `\DefaultIcon`, "", icon}, + {class + `\shell\open\command`, "", command}, + {`Software\Classes\` + extension + `\OpenWithProgids`, progID(extension), ""}, + {capabilitiesKey + `\FileAssociations`, extension, progID(extension)}, + {class + `\shell\Lithe`, "", menuLabel}, + {class + `\shell\Lithe`, "Icon", icon}, + {class + `\shell\Lithe\command`, "", command}, + } +} + +func readRegistryValue(path, name string) (text string, exists bool, kind uint32, err error) { + key, err := registry.OpenKey(registry.CURRENT_USER, path, registry.QUERY_VALUE) + if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { + // log-exempt: 预期的缺失:尚未注册的格式没有 Lithe 注册表项。 + return "", false, 0, nil + } + if err != nil { + return "", false, 0, err + } + defer func() { err = errors.Join(err, key.Close()) }() + value, kind, err := key.GetValue(name, nil) + if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { + // log-exempt: 预期的缺失:已存在的键可以尚未包含 Lithe 的值。 + return "", false, 0, nil + } + if err != nil { + return "", false, 0, err + } + if value > 65536 { + return "", false, 0, fmt.Errorf("file associations: registry value exceeds bounds") + } + data := make([]byte, value) + _, kind, err = key.GetValue(name, data) + if err != nil { + return "", false, 0, err + } + // The hash observes even a changed value type; it never overwrites UserChoice. + return string(data), true, kind, nil +} + +func queryDefault(extension string, what uintptr) (string, error) { + value, err := windows.UTF16PtrFromString(extension) + if err != nil { + return "", err + } + buffer := make([]uint16, windows.MAX_LONG_PATH) + size := uint32(len(buffer)) + hr, _, _ := assocQuery.Call(0x20, what, uintptr(unsafe.Pointer(value)), 0, + uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(&size))) + if int32(uint32(hr)) < 0 { + // HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION), ERROR_FILE_NOT_FOUND, E_FAIL: + // AssocQueryString returns these when no effective default is installed. + if uint32(hr) == 0x80070483 || uint32(hr) == 0x80070002 || uint32(hr) == 0x80004005 { + // log-exempt: 预期的缺失:系统尚未为该扩展名选择默认应用。 + return "", nil + } + return "", fmt.Errorf("file associations: AssocQueryString: %w", syscall.Errno(uint32(hr))) + } + return windows.UTF16ToString(buffer), nil +} + +func readNative(ctx context.Context, formats []core.FileAssociationFormat) (State, error) { + executable, err := installedpackage.Executable() + if err != nil { + return State{}, err + } + info, err := os.Stat(executable) + if err != nil { + return State{}, err + } + state := State{Formats: formats, Available: info.Mode().IsRegular() && strings.EqualFold(filepath.Base(executable), "lithe.exe"), native: nativeState{executable: executable}} + for _, format := range formats { + if err := ctx.Err(); err != nil { + return State{}, err + } + // ASSOCSTR_PROGID observes the actual UserChoice result without opening it for write. + identity, err := queryDefault(format.Extension, 20) + if err != nil { + return State{}, err + } + name, err := queryDefault(format.Extension, 4) + if err != nil { + return State{}, err + } + values := registrationValues(executable, format.Extension, "") + hash := sha256.New() + registered := false + for _, value := range values { + text, exists, kind, err := readRegistryValue(value.path, value.name) + if err != nil { + return State{}, err + } + fmt.Fprintf(hash, "%s\x00%s\x00%t:%d:%d:%s\x00", value.path, value.name, exists, kind, len(text), text) + if value.path == capabilitiesKey+`\FileAssociations` && exists && kind == registry.SZ { + // The capability value is UTF-16LE; read its string through the native API. + key, err := registry.OpenKey(registry.CURRENT_USER, value.path, registry.QUERY_VALUE) + if err != nil { + return State{}, err + } + actual, _, readErr := key.GetStringValue(value.name) + if err := errors.Join(readErr, key.Close()); err != nil { + return State{}, err + } + registered = actual == progID(format.Extension) + } + } + state.Handlers = append(state.Handlers, Handler{ + Extension: format.Extension, DefaultID: identity, DefaultName: name, + IsDefault: strings.EqualFold(identity, progID(format.Extension)), + Registered: registered, registration: hex.EncodeToString(hash.Sum(nil)), + }) + } + return state, nil +} + +func writeRegistryValue(value registryValue) (err error) { + key, _, err := registry.CreateKey(registry.CURRENT_USER, value.path, registry.SET_VALUE) + if err != nil { + return err + } + defer func() { err = errors.Join(err, key.Close()) }() + return key.SetStringValue(value.name, value.text) +} + +func applyNative(ctx context.Context, state nativeState, extensions []string, menuLabel string) error { + for _, extension := range extensions { + for _, value := range registrationValues(state.executable, extension, menuLabel) { + if err := ctx.Err(); err != nil { + return err + } + if err := writeRegistryValue(value); err != nil { + return err + } + } + } + // SHCNE_ASSOCCHANGED + SHCNF_IDLIST refreshes Explorer after all selected formats. + associationChanged.Call(0x08000000, 0, 0, 0) + if err := ctx.Err(); err != nil { + return err + } + // UserChoice is protected by Windows. Its own UI owns the final consent. + return 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 babbe9c5a..fe059779e 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -33,6 +33,27 @@ 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.applyMac": "Set selected defaults", + "desktop.associations.applyWindows": "Register and choose defaults…", + "desktop.associations.clearSelection": "Clear selection", + "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.failed": "Could not read or update file associations. Some formats may have changed. Refresh to check the current defaults and try again.", + "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.language": "Highlighting", + "desktop.associations.litheDefault": "Lithe (default)", + "desktop.associations.noDefault": "No default application", + "desktop.associations.openWith": "Open with Lithe", + "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.title": "File associations", "desktop.branch.alreadyOn": "Already on '{name}'", "desktop.branch.branchName": "Branch name", "desktop.branch.checkedOut": "Checked out '{name}'", @@ -4021,6 +4042,27 @@ 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.applyMac": "将所选格式设为默认", + "desktop.associations.applyWindows": "注册并选择默认应用…", + "desktop.associations.clearSelection": "清空选择", + "desktop.associations.conflict": "打开此页后系统关联发生了变化。请确认刷新后的默认应用,再重新应用。", + "desktop.associations.currentDefault": "当前默认应用", + "desktop.associations.failed": "无法读取或更新文件关联,部分格式可能已生效。请刷新确认当前状态后重试。", + "desktop.associations.format": "格式", + "desktop.associations.formats": "支持的文本格式", + "desktop.associations.helpMac": "列出内置高亮支持的扩展名及纯文本。勾选格式并应用后,将 Lithe 设为默认编辑器;Finder 也会在“打开方式”中显示 Lithe。macOS 按内容类型关联,共用同一类型的扩展名可能同时生效。仅匹配文件名的规则、压缩文件和二进制文件不在此列,复合后缀使用最后一段扩展名。取消勾选只修改本次草稿。", + "desktop.associations.helpWindows": "列出内置高亮支持的扩展名及纯文本。注册所选格式后,Lithe 会显示在“打开方式”中,再到 Windows 设置确认默认应用。已关联的文件也会有“用 Lithe 打开”右键项(Windows 11 位于“显示更多选项”)。仅匹配文件名的规则、压缩文件和二进制文件不在此列。取消勾选只修改本次草稿。", + "desktop.associations.language": "高亮语言", + "desktop.associations.litheDefault": "Lithe(默认)", + "desktop.associations.noDefault": "未设置默认应用", + "desktop.associations.openWith": "用 Lithe 打开", + "desktop.associations.refresh": "刷新", + "desktop.associations.requiresInstalled": "请安装并运行打包后的 Lithe 应用以注册文件关联。", + "desktop.associations.selectAll": "全选", + "desktop.associations.selected": "已选 {count} 项", + "desktop.associations.title": "文件关联", "desktop.branch.alreadyOn": "已在“{name}”上", "desktop.branch.branchName": "分支名称", "desktop.branch.checkedOut": "已检出“{name}”", diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 8b14ca913..94588ff71 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -17,6 +17,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/cli" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" "github.com/1lck/Lithe-IDEA/desktop/internal/fontprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/localshell" @@ -385,8 +386,12 @@ type SearchPreferencesSource interface { // Options configure the settings window. type Options struct { - CLI *cli.Manager - CLIAction func(string) + CLI *cli.Manager + CLIAction func(string) + FileAssociations *fileassociations.Manager + // AssociationAction and AssociationError retain the originating settings operation. + AssociationAction func(context.Context, string) context.Context + AssociationError func(context.Context, error) SearchPreferences SearchPreferencesSource // PluginInstallsClosed releases downloads retained by the settings session. PluginInstallsClosed func() diff --git a/desktop/internal/settingswindow/file_associations_view.go b/desktop/internal/settingswindow/file_associations_view.go new file mode 100644 index 000000000..767249d1d --- /dev/null +++ b/desktop/internal/settingswindow/file_associations_view.go @@ -0,0 +1,186 @@ +package settingswindow + +import ( + "context" + "errors" + "runtime" + "strconv" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" +) + +type associationRequest struct { + action string + baseline fileassociations.State + selected []string + label string + ctx context.Context +} + +type associationResult struct { + state fileassociations.State + err error +} + +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 +} + +func (w *window) declareAssociations(c ui.C) { + s := &w.associations + if s.effect != nil && s.request != nil { + ui.Effect(c, s.effect, s.request) + } +} + +func (w *window) requestAssociations(action string, selected []string) { + ctx := context.Background() + if w.ctrl.opts.AssociationAction != nil { + ctx = w.ctrl.opts.AssociationAction(ctx, action) + } + s := &w.associations + s.request = &associationRequest{ + action: action, baseline: s.state, selected: selected, ctx: ctx, + label: i18n.Shared(w.marketLanguage(), "desktop.associations.openWith"), + } + s.applied = false +} + +func (w *window) associationsCard(c ui.C) { + manager := w.ctrl.opts.FileAssociations + if manager == nil { + return + } + s := &w.associations + language := w.marketLanguage() + if s.effect == nil { + 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) + stop := context.AfterFunc(parent, cancel) + defer stop() + defer cancel() + var result associationResult + if request.action == "apply" { + result.state, result.err = manager.Apply(ctx, request.baseline, request.selected, request.label) + } else { + result.state, result.err = manager.Read(ctx) + } + if result.err != nil && !errors.Is(result.err, context.Canceled) && w.ctrl.opts.AssociationError != nil { + w.ctrl.opts.AssociationError(ctx, result.err) + } + // log-exempt: 用户取消:设置窗口关闭时 Effect 撤销尚未结束的工作。 + return result, nil + }) + 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 + s.request = nil + if result.state.Formats != nil { + s.state, s.loaded = result.state, true + } + } + busy := s.request != nil + help := i18n.Shared(language, "desktop.associations.helpMac") + apply := i18n.Shared(language, "desktop.associations.applyMac") + if runtime.GOOS == "windows" { + help, apply = i18n.Shared(language, "desktop.associations.helpWindows"), i18n.Shared(language, "desktop.associations.applyWindows") + } + w.card(c, i18n.Shared(language, "desktop.associations.title"), help, func() { + ui.Row(c).FillWidth().Height(30).Items(ui.Center).Gap(8).Children(func() { + if ui.Button(c.Part("association-all"), i18n.Shared(language, "desktop.associations.selectAll")).Ghost().Disabled(busy || !s.loaded).Clicked() { + c.After(func() { + for _, format := range s.state.Formats { + s.picked[format.Extension] = true + } + }) + } + if ui.Button(c.Part("association-none"), i18n.Shared(language, "desktop.associations.clearSelection")).Ghost().Disabled(busy || !s.loaded).Clicked() { + c.After(func() { clear(s.picked) }) + } + ui.Spacer(c) + if busy { + ui.Text(c, i18n.Shared(language, "native.loading")).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.currentDefault")).Grow(1).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() { + 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) + name := handler.DefaultName + if name == "" { + name = handler.DefaultID + } + if name == "" { + name = i18n.Shared(language, "desktop.associations.noDefault") + } + if handler.IsDefault { + name = i18n.Shared(language, "desktop.associations.litheDefault") + } + cell := row.C.Part("default-application") + 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) + }) + }) + }) + }).Scrollbars().FillWidth().Height(224).Label(i18n.Shared(language, "desktop.associations.formats")) + var selected []string + for _, format := range s.state.Formats { + if s.picked[format.Extension] { + selected = append(selected, format.Extension) + } + } + ui.Row(c).FillWidth().Height(34).Items(ui.Center).Gap(8).Children(func() { + ui.Text(c, i18n.SharedFormat(language, "desktop.associations.selected", map[string]string{"count": strconv.Itoa(len(selected))})).FontSize(12).Color(w.pal.muted).Grow(1) + if ui.Button(c.Part("association-apply"), apply).Outline().Disabled(busy || !s.loaded || !s.state.Available || len(selected) == 0).Clicked() { + c.After(func() { w.requestAssociations("apply", selected) }) + } + }) + if s.loaded && !s.state.Available { + ui.Wrap(c, i18n.Shared(language, "desktop.associations.requiresInstalled")).FontSize(12).Color(w.pal.muted) + } + if s.applied { + message := i18n.Shared(language, "desktop.associations.appliedMac") + if runtime.GOOS == "windows" { + message = i18n.Shared(language, "desktop.associations.appliedWindows") + } + ui.Wrap(c, message).FontSize(12).Color(w.pal.muted) + } + if s.err != nil { + message := i18n.Shared(language, "desktop.associations.failed") + if errors.Is(s.err, fileassociations.ErrConflict) { + message = i18n.Shared(language, "desktop.associations.conflict") + } + ui.Wrap(c, message).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 new file mode 100644 index 000000000..d6cec8f46 --- /dev/null +++ b/desktop/internal/settingswindow/file_associations_visual_test.go @@ -0,0 +1,121 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" +) + +func TestVisualFileAssociations(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.Chinese, i18n.English} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"-"+theme, func(t *testing.T) { + // These are actual, read-only OS observations. The test never applies defaults. + w := newWindow(NewController(Options{ + FileAssociations: fileassociations.New(), + Text: func() *i18n.Messages { return i18n.For(language) }, + Language: func() i18n.Language { return language }, SystemLanguage: language, + SystemDark: func() bool { return theme == "dark" }, + }), Values{Theme: theme, Language: language.Code()}) + config := w.config() + config.Width, config.Height = 1120, 820 + session, err := headless.Open(config, nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + d.pump() + await := func() { + t.Helper() + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + for w.associations.request != nil || w.cli.request != nil { + select { + case <-d.driver.Wakes(): + d.pump() + case <-deadline.C: + t.Fatal("native association read timed out") + } + } + if w.associations.err != nil { + t.Fatal(w.associations.err) + } + } + await() + s := &w.associations + if !s.loaded || len(s.state.Formats) < 2 || len(s.state.Formats) != len(s.state.Handlers) { + t.Fatal("actual OS handler list missing") + } + first := s.state.Formats[0].Extension + d.click(first) + d.pump() + if !s.picked[first] { + t.Fatal("format checkbox did not retain selection") + } + // List containers expose accessibility metadata rather than a clickable + // control. A real visible checkbox supplies the wheel event position. + listAccessible := false + for _, hit := range d.driver.Snapshot().Hits { + if hit.Role == gfx.RoleListBox && hit.Label == i18n.Shared(language, "desktop.associations.formats") { + listAccessible = true + } + } + if !listAccessible { + t.Fatal("format list has no accessible name") + } + firstHit := d.hit(first) + scroll := func(delta float32) { + t.Helper() + if err := d.driver.Scroll(gfx.ScrollEvent{X: firstHit.Bounds.X + firstHit.Bounds.Width/2, Y: firstHit.Bounds.Y + firstHit.Bounds.Height/2, DeltaY: delta, Precise: true}); err != nil { + t.Fatal(err) + } + d.pump() + } + last := s.state.Formats[len(s.state.Formats)-1].Extension + if d.has(last) { + t.Fatal("offscreen formats were all instantiated") + } + scroll(100000) + if !d.has(last) { + t.Fatal("mouse wheel did not reach the final format") + } + scroll(-100000) + if !s.picked[first] || !d.has(first) { + t.Fatal("scrolling lost checkbox selection") + } + d.click(i18n.Shared(language, "desktop.associations.selectAll")) + d.pump() + 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 { + t.Fatal(err) + } + d.click(i18n.Shared(language, "desktop.associations.clearSelection")) + d.pump() + if len(s.picked) != 0 { + t.Fatal("clear selection retained a draft") + } + d.click(i18n.Shared(language, "desktop.associations.refresh")) + d.pump() + await() + }) + } + } +} diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index 70787c1dc..1d40d5125 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -79,6 +79,7 @@ const ( // its window thread, but for the fields that say so. type window struct { cli cliRegistration + associations associationRegistration searchDraft searchPreferencesDraft editorDelay ui.Field editorDelayReady bool @@ -586,6 +587,7 @@ func (w *window) reportMarket(ended bool, kept error) { // paint, and in every paint, so leaving a page does not cancel what it asked for. func (w *window) declareWork(c ui.C) { w.declareCLI(c) + w.declareAssociations(c) if d := &w.searchDraft; d.effect != nil && d.work != nil { ui.Effect(c, d.effect, d.work) } diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index c9f23d5df..10417cea1 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -589,6 +589,7 @@ func (w *window) generalPage(c ui.C) { w.languagePick = languageCode(languageIndex(w.sess.values.Language)) w.pageScroll(c, pageGeneral, func() { w.cliCard(c) + w.associationsCard(c) w.card(c, settings.Appearance, settings.AppearanceHelp, func() { choice := func() { ui.Choice(c, &w.themePick, themeValues[:], w.themeLabel).Width(420).Shrink(1).MinWidth(0) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index f8833a2f7..74d4aa568 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -1156,6 +1156,11 @@ func (a *App) Run() error { return err } a.window = window + // Viva queues Finder events during startup. Register after the window is + // ready so even the first delivered document has an owned session and wake. + application.OnOpenFile(func(path string) { + a.post(func(a *App) { a.openSystemDocument(path) }) + }) a.startUpdates() a.startPluginAutoUpdates() if path := a.startupPath; path != "" { diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index 7c609e1f2..618923d82 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -9,6 +9,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildinfo" "github.com/1lck/Lithe-IDEA/desktop/internal/cli" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/fileassociations" "github.com/1lck/Lithe-IDEA/desktop/internal/fontprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/localshell" @@ -34,8 +35,15 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { navigation = kernel.SettingsNavigation } return settingswindow.NewController(settingswindow.Options{ - CLI: cli.New(), - CLIAction: func(action string) { a.post(func(a *App) { a.performed("settings.cli."+action, surfaceButton) }) }, + CLI: cli.New(), + CLIAction: func(action string) { a.post(func(a *App) { a.performed("settings.cli."+action, surfaceButton) }) }, + FileAssociations: fileassociations.New(), + AssociationAction: func(ctx context.Context, action string) context.Context { + return a.performedIn(ctx, "settings.fileAssociations."+action, surfaceButton) + }, + AssociationError: func(ctx context.Context, err error) { + a.operationFailedIn(ctx, "file_associations", err) + }, SearchPreferences: appSearchPreferences{app: a}, PluginInstallsClosed: func() { a.post(func(a *App) { a.closePluginDownloads() }) diff --git a/desktop/internal/workbench/standalone.go b/desktop/internal/workbench/standalone.go index a78a5fc4e..83a189a35 100644 --- a/desktop/internal/workbench/standalone.go +++ b/desktop/internal/workbench/standalone.go @@ -29,7 +29,7 @@ func (a *App) openStandaloneFile(path string) { func (a *App) standaloneWorkbench(c ui.C) { a.syncWindowTitle() a.layout.capture() - a.layout.insetW, a.layout.insetH = 0, titleBarHeight+statusBarHeight + a.layout.insetW, a.layout.insetH = 0, titleBarHeight+statusBarHeight+a.sessions.stripHeight() // Use the existing bottom panel and splitter without restoring any project panels. open := [slotCount]int{-1, -1, -1, -1, -1, -1} terminalIndex := catalogIndex[itemTerminal] @@ -76,6 +76,7 @@ func (a *App) standaloneWorkbench(c ui.C) { c.After(func() { a.openSettingsPage(surfaceButton, settingsHome) }) } }) + a.projectTabs(c) a.shellMain(c, plan, open, &hidden) ui.Row(c).FillWidth().Height(statusBarHeight).Shrink(0).Items(ui.Center).Gap(8).PadX(8).Children(func() { if d := a.selectedEditorDocument(); d != nil { diff --git a/desktop/internal/workbench/system_document.go b/desktop/internal/workbench/system_document.go new file mode 100644 index 000000000..2d5f5bae8 --- /dev/null +++ b/desktop/internal/workbench/system_document.go @@ -0,0 +1,58 @@ +package workbench + +import ( + "context" + "errors" + "os" + "path/filepath" +) + +// openSystemDocument receives Finder's Open With / default-app event. A file +// never replaces a project, opens its parent folder or enters project services. +func (a *App) openSystemDocument(path string) { + a.performed("editor.systemFile.open", surfaceMenu) + a.background(nil, kernelCallTimeout, func(ctx context.Context) func(*App) { + absolute, err := filepath.Abs(path) + if err == nil { + var info os.FileInfo + info, err = os.Stat(absolute) + if err == nil && !info.Mode().IsRegular() { + err = errors.New("system document is not a regular file") + } + } + if err == nil { + err = ctx.Err() + } + return func(a *App) { + if err != nil { + a.operationFailed("system_document_open", err) + a.notifyError(a.text.Errors.OpenFailed(err.Error())) + return + } + a.sessions.openDocumentTab(absolute) + } + }) +} + +// openDocumentTab reuses an editor-only workbench, with stable document identity, +// or constructs one with OpenFile before any plugin stack can be assembled. +func (s *windowSessions) openDocumentTab(path string) { + for _, session := range s.list { + if session.documentOnly && session.project != nil && session.project.docs.byPath(path) != nil { + s.activate(session) + session.openFile(session.project, path) + return + } + } + if a := s.active; a.documentOnly && a.project != nil { + a.openFile(a.project, path) + return + } + options := s.options + options.OpenPath, options.OpenFile = "", path + a := New(options) + a.startupFile = "" + s.list = append(s.list, a) + s.activate(a) + a.openStandaloneFile(path) +} diff --git a/desktop/internal/workbench/system_document_test.go b/desktop/internal/workbench/system_document_test.go new file mode 100644 index 000000000..ed734faa7 --- /dev/null +++ b/desktop/internal/workbench/system_document_test.go @@ -0,0 +1,49 @@ +package workbench + +import ( + "os" + "path/filepath" + "testing" +) + +func TestSystemDocumentsPreserveProjectAndReuseIsolatedSession(t *testing.T) { + h, alpha, beta := newTabsHarness(t) + h.open(alpha) + path := filepath.Join(t.TempDir(), "中文 source.go") + second := filepath.Join(t.TempDir(), "another.txt") + for _, name := range []string{path, second} { + if err := os.WriteFile(name, []byte("// document\n"), 0600); err != nil { + t.Fatal(err) + } + } + s := h.app.sessions + h.app.openSystemDocument(path) + h.await("system document", func() bool { + return s.active != h.app && s.active.project != nil && s.active.project.docs.byPath(path) != nil + }) + standalone := s.active + if len(s.list) != 2 || !standalone.documentOnly || standalone.plugins != nil || standalone.aiKernel != nil || !standalone.project.standalone { + t.Fatal("system document did not get an isolated editor session") + } + if h.app.project == nil || h.app.project.root != alpha || standalone.project.search.watch != nil { + t.Fatal("opening a system document replaced the project or started indexing") + } + h.clickNamed("alpha") + h.await("project tab", func() bool { return s.active == h.app }) + h.app.openSystemDocument(path) + h.await("existing system document tab", func() bool { return s.active == standalone }) + if len(s.list) != 2 { + t.Fatal("reopening a document created another session") + } + h.app.openSystemDocument(second) + h.await("second system document", func() bool { return standalone.project.docs.byPath(second) != nil }) + if len(s.list) != 2 || len(standalone.project.docs.list) != 2 { + t.Fatal("multiple files did not share the isolated session") + } + // Starting a normal project from this window must not inherit the first file. + s.openTab(beta) + h.await("new project tab", func() bool { return s.active.project != nil && s.active.project.root == beta }) + if s.active.documentOnly { + t.Fatal("a normal project inherited standalone mode") + } +} diff --git a/desktop/internal/workbench/window_sessions.go b/desktop/internal/workbench/window_sessions.go index 5fc88944b..7836719cb 100644 --- a/desktop/internal/workbench/window_sessions.go +++ b/desktop/internal/workbench/window_sessions.go @@ -68,6 +68,7 @@ const ( // newWindowSessions makes the sessions of the window whose first workbench is first. func newWindowSessions(first *App, options Options) *windowSessions { options.OpenPath = "" + options.OpenFile = "" options.first = first return &windowSessions{ list: []*App{first}, active: first, configs: map[*App]app.Config{}, options: options, diff --git a/desktop/viva.toml b/desktop/viva.toml index be4d94548..6cff4d448 100644 --- a/desktop/viva.toml +++ b/desktop/viva.toml @@ -15,6 +15,494 @@ package = "./cmd/lithe" # The full-bleed square of the SwiftUI client's icon; viva package shapes it into the macOS tile. icon = "assets/icon.png" +# BEGIN generated file associations +# Generated by scripts/desktop/generate-file-associations.sh; do not edit. +[[app.file_types]] +name = "Lithe Desktop .ascx" +extensions = ["ascx"] + +[[app.file_types]] +name = "Lithe Desktop .asp" +extensions = ["asp"] + +[[app.file_types]] +name = "Lithe Desktop .aspx" +extensions = ["aspx"] + +[[app.file_types]] +name = "Lithe Desktop .babelrc" +extensions = ["babelrc"] + +[[app.file_types]] +name = "Lithe Desktop .bash" +extensions = ["bash"] + +[[app.file_types]] +name = "Lithe Desktop .bowerrc" +extensions = ["bowerrc"] + +[[app.file_types]] +name = "Lithe Desktop .c" +extensions = ["c"] + +[[app.file_types]] +name = "Lithe Desktop .c++" +extensions = ["c++"] + +[[app.file_types]] +name = "Lithe Desktop .cake" +extensions = ["cake"] + +[[app.file_types]] +name = "Lithe Desktop .cc" +extensions = ["cc"] + +[[app.file_types]] +name = "Lithe Desktop .cfg" +extensions = ["cfg"] + +[[app.file_types]] +name = "Lithe Desktop .cjs" +extensions = ["cjs"] + +[[app.file_types]] +name = "Lithe Desktop .cmake" +extensions = ["cmake"] + +[[app.file_types]] +name = "Lithe Desktop .code-workspace" +extensions = ["code-workspace"] + +[[app.file_types]] +name = "Lithe Desktop .conf" +extensions = ["conf"] + +[[app.file_types]] +name = "Lithe Desktop .config" +extensions = ["config"] + +[[app.file_types]] +name = "Lithe Desktop .cpp" +extensions = ["cpp"] + +[[app.file_types]] +name = "Lithe Desktop .cpy" +extensions = ["cpy"] + +[[app.file_types]] +name = "Lithe Desktop .cs" +extensions = ["cs"] + +[[app.file_types]] +name = "Lithe Desktop .csproj" +extensions = ["csproj"] + +[[app.file_types]] +name = "Lithe Desktop .css" +extensions = ["css"] + +[[app.file_types]] +name = "Lithe Desktop .csx" +extensions = ["csx"] + +[[app.file_types]] +name = "Lithe Desktop .ctp" +extensions = ["ctp"] + +[[app.file_types]] +name = "Lithe Desktop .cts" +extensions = ["cts"] + +[[app.file_types]] +name = "Lithe Desktop .cxx" +extensions = ["cxx"] + +[[app.file_types]] +name = "Lithe Desktop .dockerfile" +extensions = ["dockerfile"] + +[[app.file_types]] +name = "Lithe Desktop .dtd" +extensions = ["dtd"] + +[[app.file_types]] +name = "Lithe Desktop .env" +extensions = ["env"] + +[[app.file_types]] +name = "Lithe Desktop .es6" +extensions = ["es6"] + +[[app.file_types]] +name = "Lithe Desktop .eslintrc" +extensions = ["eslintrc"] + +[[app.file_types]] +name = "Lithe Desktop .gemspec" +extensions = ["gemspec"] + +[[app.file_types]] +name = "Lithe Desktop .gitconfig" +extensions = ["gitconfig"] + +[[app.file_types]] +name = "Lithe Desktop .go" +extensions = ["go"] + +[[app.file_types]] +name = "Lithe Desktop .gql" +extensions = ["gql"] + +[[app.file_types]] +name = "Lithe Desktop .gradle" +extensions = ["gradle"] + +[[app.file_types]] +name = "Lithe Desktop .graphql" +extensions = ["graphql"] + +[[app.file_types]] +name = "Lithe Desktop .groovy" +extensions = ["groovy"] + +[[app.file_types]] +name = "Lithe Desktop .gyp" +extensions = ["gyp"] + +[[app.file_types]] +name = "Lithe Desktop .gypi" +extensions = ["gypi"] + +[[app.file_types]] +name = "Lithe Desktop .h" +extensions = ["h"] + +[[app.file_types]] +name = "Lithe Desktop .h++" +extensions = ["h++"] + +[[app.file_types]] +name = "Lithe Desktop .har" +extensions = ["har"] + +[[app.file_types]] +name = "Lithe Desktop .hh" +extensions = ["hh"] + +[[app.file_types]] +name = "Lithe Desktop .hpp" +extensions = ["hpp"] + +[[app.file_types]] +name = "Lithe Desktop .htm" +extensions = ["htm"] + +[[app.file_types]] +name = "Lithe Desktop .html" +extensions = ["html"] + +[[app.file_types]] +name = "Lithe Desktop .hxx" +extensions = ["hxx"] + +[[app.file_types]] +name = "Lithe Desktop .ini" +extensions = ["ini"] + +[[app.file_types]] +name = "Lithe Desktop .inl" +extensions = ["inl"] + +[[app.file_types]] +name = "Lithe Desktop .ipp" +extensions = ["ipp"] + +[[app.file_types]] +name = "Lithe Desktop .jav" +extensions = ["jav"] + +[[app.file_types]] +name = "Lithe Desktop .java" +extensions = ["java"] + +[[app.file_types]] +name = "Lithe Desktop .js" +extensions = ["js"] + +[[app.file_types]] +name = "Lithe Desktop .jscsrc" +extensions = ["jscsrc"] + +[[app.file_types]] +name = "Lithe Desktop .jshintrc" +extensions = ["jshintrc"] + +[[app.file_types]] +name = "Lithe Desktop .jshtm" +extensions = ["jshtm"] + +[[app.file_types]] +name = "Lithe Desktop .json" +extensions = ["json"] + +[[app.file_types]] +name = "Lithe Desktop .jsonc" +extensions = ["jsonc"] + +[[app.file_types]] +name = "Lithe Desktop .jsp" +extensions = ["jsp"] + +[[app.file_types]] +name = "Lithe Desktop .jsx" +extensions = ["jsx"] + +[[app.file_types]] +name = "Lithe Desktop .kt" +extensions = ["kt"] + +[[app.file_types]] +name = "Lithe Desktop .kts" +extensions = ["kts"] + +[[app.file_types]] +name = "Lithe Desktop .lua" +extensions = ["lua"] + +[[app.file_types]] +name = "Lithe Desktop .m" +extensions = ["m"] + +[[app.file_types]] +name = "Lithe Desktop .mak" +extensions = ["mak"] + +[[app.file_types]] +name = "Lithe Desktop .markdown" +extensions = ["markdown"] + +[[app.file_types]] +name = "Lithe Desktop .md" +extensions = ["md"] + +[[app.file_types]] +name = "Lithe Desktop .mdoc" +extensions = ["mdoc"] + +[[app.file_types]] +name = "Lithe Desktop .mdown" +extensions = ["mdown"] + +[[app.file_types]] +name = "Lithe Desktop .mdtext" +extensions = ["mdtext"] + +[[app.file_types]] +name = "Lithe Desktop .mdtxt" +extensions = ["mdtxt"] + +[[app.file_types]] +name = "Lithe Desktop .mdwn" +extensions = ["mdwn"] + +[[app.file_types]] +name = "Lithe Desktop .mjs" +extensions = ["mjs"] + +[[app.file_types]] +name = "Lithe Desktop .mk" +extensions = ["mk"] + +[[app.file_types]] +name = "Lithe Desktop .mkd" +extensions = ["mkd"] + +[[app.file_types]] +name = "Lithe Desktop .mkdn" +extensions = ["mkdn"] + +[[app.file_types]] +name = "Lithe Desktop .mm" +extensions = ["mm"] + +[[app.file_types]] +name = "Lithe Desktop .mts" +extensions = ["mts"] + +[[app.file_types]] +name = "Lithe Desktop .opf" +extensions = ["opf"] + +[[app.file_types]] +name = "Lithe Desktop .php" +extensions = ["php"] + +[[app.file_types]] +name = "Lithe Desktop .php4" +extensions = ["php4"] + +[[app.file_types]] +name = "Lithe Desktop .php5" +extensions = ["php5"] + +[[app.file_types]] +name = "Lithe Desktop .phtml" +extensions = ["phtml"] + +[[app.file_types]] +name = "Lithe Desktop .pp" +extensions = ["pp"] + +[[app.file_types]] +name = "Lithe Desktop .properties" +extensions = ["properties"] + +[[app.file_types]] +name = "Lithe Desktop .props" +extensions = ["props"] + +[[app.file_types]] +name = "Lithe Desktop .proto" +extensions = ["proto"] + +[[app.file_types]] +name = "Lithe Desktop .ps1" +extensions = ["ps1"] + +[[app.file_types]] +name = "Lithe Desktop .psd1" +extensions = ["psd1"] + +[[app.file_types]] +name = "Lithe Desktop .psm1" +extensions = ["psm1"] + +[[app.file_types]] +name = "Lithe Desktop .py" +extensions = ["py"] + +[[app.file_types]] +name = "Lithe Desktop .pyw" +extensions = ["pyw"] + +[[app.file_types]] +name = "Lithe Desktop .rb" +extensions = ["rb"] + +[[app.file_types]] +name = "Lithe Desktop .rbx" +extensions = ["rbx"] + +[[app.file_types]] +name = "Lithe Desktop .rjs" +extensions = ["rjs"] + +[[app.file_types]] +name = "Lithe Desktop .rpy" +extensions = ["rpy"] + +[[app.file_types]] +name = "Lithe Desktop .rs" +extensions = ["rs"] + +[[app.file_types]] +name = "Lithe Desktop .sh" +extensions = ["sh"] + +[[app.file_types]] +name = "Lithe Desktop .shtml" +extensions = ["shtml"] + +[[app.file_types]] +name = "Lithe Desktop .sql" +extensions = ["sql"] + +[[app.file_types]] +name = "Lithe Desktop .svg" +extensions = ["svg"] + +[[app.file_types]] +name = "Lithe Desktop .swift" +extensions = ["swift"] + +[[app.file_types]] +name = "Lithe Desktop .targets" +extensions = ["targets"] + +[[app.file_types]] +name = "Lithe Desktop .toml" +extensions = ["toml"] + +[[app.file_types]] +name = "Lithe Desktop .ts" +extensions = ["ts"] + +[[app.file_types]] +name = "Lithe Desktop .tsx" +extensions = ["tsx"] + +[[app.file_types]] +name = "Lithe Desktop .txt" +extensions = ["txt"] + +[[app.file_types]] +name = "Lithe Desktop .wxi" +extensions = ["wxi"] + +[[app.file_types]] +name = "Lithe Desktop .wxl" +extensions = ["wxl"] + +[[app.file_types]] +name = "Lithe Desktop .wxs" +extensions = ["wxs"] + +[[app.file_types]] +name = "Lithe Desktop .xaml" +extensions = ["xaml"] + +[[app.file_types]] +name = "Lithe Desktop .xhtml" +extensions = ["xhtml"] + +[[app.file_types]] +name = "Lithe Desktop .xml" +extensions = ["xml"] + +[[app.file_types]] +name = "Lithe Desktop .xsd" +extensions = ["xsd"] + +[[app.file_types]] +name = "Lithe Desktop .xsl" +extensions = ["xsl"] + +[[app.file_types]] +name = "Lithe Desktop .xslt" +extensions = ["xslt"] + +[[app.file_types]] +name = "Lithe Desktop .yaml" +extensions = ["yaml"] + +[[app.file_types]] +name = "Lithe Desktop .yml" +extensions = ["yml"] + +[[app.file_types]] +name = "Lithe Desktop .zig" +extensions = ["zig"] + +[[app.file_types]] +name = "Lithe Desktop .zon" +extensions = ["zon"] + +[[app.file_types]] +name = "Lithe Desktop .zsh" +extensions = ["zsh"] + +# END generated file associations + [mac] # scripts/desktop/desktop-go.sh builds the program and the core for macOS 13.0. min_system = "13.0" diff --git a/docs/ci-builds.md b/docs/ci-builds.md index c8a364bd2..e6416fb7b 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -68,6 +68,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 ### 独立工作树的本地编译 +文件关联的打包声明由 `scripts/desktop/generate-file-associations.sh` 读取编辑器内置高亮元数据并调用 Core 生成,作为 `desktop/viva.toml` 的一部分由 Git 管理;打包前以 `--check` 拒绝目录漂移。生成器始终使用构建主机架构执行,即使包的目标架构不同;最终应用和辅助程序仍使用所选目标架构。它是构建输入,不是可跨工作树复制的缓存。运行期只读取系统默认应用,明确应用后写入 LaunchServices 或当前用户的 Windows 注册表,不生成偏好副本,也不改写 bundle、安装目录或插件资源,因此不影响签名和增量更新基线。`TestVisualFileAssociations` 的真实系统读取截图通过 `LITHE_VISUAL_OUTPUT_DIR` 写到当前检出的 `.artifacts/visual/file-associations/`,绑定本次源码、Core/Viva 修订、平台、语言和主题,不跨工作树复制、不进入发行包,由开发者或 CI 清理。 + 插件市场 SVG 由网络适配器有界读取,在后台编译为 Viva 图标;下载字节只活到本次编译结束,编译结果与失败仅保存在当前市场页的内存缓存中(最多64项、同时读取最多4个、每次最多256 KiB和10秒)。滚动离屏取消未完成的读取,刷新索引、离开市场标签或关闭设置窗口释放缓存;没有磁盘缓存,不跨工作树复制,不写安装目录,也不影响代码签名或增量更新基线。`TestVisualMarketplaceSVG` 的中英文、明暗主题及加载前后截图写入本工作树的 `.artifacts/marketplace-icons-visual/`,绑定当前源码、固定 Viva/Core 修订、语言、主题和渲染环境,不跨工作树复制,由开发者清理,不进入发行包。 CLI 用户启动器由 `desktop/internal/cli` 在明确注册时生成到 `/Lithe/cli/bin/lithe`(Windows 为 `lithe.cmd`)。它绑定用户机器与当前应用可执行路径,随用户移除注册删除;它不是编译缓存,不跨工作树复制,不写安装目录,也不影响代码签名和增量更新基线。CLI 与单文件模式的无头截图可写入当前检出的 `.artifacts/cli-single-file/`;它们绑定本次源码、语言、主题、Viva/Core 修订和渲染环境,不跨工作树复制,由开发者或 CI 清理,不进入发行包。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 0b2fdef15..9e585f183 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -369,7 +369,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # workspace.createEntry, renameEntry, copyEntry and resolveEntry with the codes entry_not_found # and entry_exists, which the desktop calls for a plugin's create, rename, copy, trash and # saveAs (workbench/pluginfilechanges.go). -PINNED_CORE_REVISION="aadf63d7f69e762a3b2aac44cb6429f57ca5b880" +PINNED_CORE_REVISION="bb0ad53f9100954306fcd139bf0e5003e6a515fe" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/scripts/desktop/generate-file-associations.sh b/scripts/desktop/generate-file-associations.sh new file mode 100755 index 000000000..f67e13c03 --- /dev/null +++ b/scripts/desktop/generate-file-associations.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Generates (or --check verifies) package file types from the bundled editor catalog and Core. +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" +# This generator executes on the build host even when packaging another +# architecture. The package itself still uses its selected target stage. +GOARCH="$(go env GOHOSTARCH)" +export GOARCH +export LITHE_CORE_TARGET="" +exec "$ROOT_DIR/scripts/desktop/desktop-go.sh" run ./cmd/file-associations-manifest "$@" diff --git a/scripts/desktop/package-desktop.sh b/scripts/desktop/package-desktop.sh index 19a77095d..3acb14515 100755 --- a/scripts/desktop/package-desktop.sh +++ b/scripts/desktop/package-desktop.sh @@ -118,6 +118,9 @@ if [[ -z "$FORMATS" ]]; then fi MANIFEST="$ROOT_DIR/desktop/viva.toml" +# Refuse stale native declarations before signing. The same Core projection feeds +# Settings; runtime registration never rewrites the signed bundle or installer. +LITHE_DESKTOP_CORE_PROFILE=release "$ROOT_DIR/scripts/desktop/generate-file-associations.sh" --check VERSION="$(awk ' /^\[app\][[:space:]]*$/ { in_app = 1; next } /^\[/ { in_app = 0 } diff --git a/scripts/desktop/package-desktop.test.mjs b/scripts/desktop/package-desktop.test.mjs index 2d8d35c5f..2b8437a39 100644 --- a/scripts/desktop/package-desktop.test.mjs +++ b/scripts/desktop/package-desktop.test.mjs @@ -20,12 +20,16 @@ case "$1" in case "$2" in GOOS) printf '%s\\n' "\${GOOS:-$FIXTURE_GOOS}" ;; GOHOSTOS) printf '%s\\n' "$FIXTURE_GOOS" ;; + GOHOSTARCH) printf '%s\\n' "$FIXTURE_GOARCH" ;; GOARCH) printf '%s\\n' "\${GOARCH:-$FIXTURE_GOARCH}" ;; GOEXE) if [[ "$FIXTURE_GOOS" == windows ]]; then printf '.exe\\n'; else printf '\\n'; fi ;; *) printf 'unexpected go env %s\\n' "$2" >&2; exit 1 ;; esac ;; mod) ;; + run) + [[ "$2" == ./cmd/file-associations-manifest && "$3" == --check ]] + ;; list) case "$4" in *.Dir*) printf '%s\\n' "$FIXTURE_ROOT/viva-src" ;; @@ -123,7 +127,7 @@ async function withFixture(host, body) { await mkdir(path.join(root, 'scripts/desktop/verify'), { recursive: true }); await mkdir(path.join(root, 'viva-src')); await mkdir(bin); - for (const name of ['package-desktop.sh', 'build-viva-tool.sh', 'desktop-go.sh']) { + for (const name of ['package-desktop.sh', 'build-viva-tool.sh', 'desktop-go.sh', 'generate-file-associations.sh']) { await copyFile(path.join(scripts, name), path.join(root, 'scripts/desktop', name)); } await copyFile(path.join(desktop, 'Makefile'), path.join(root, 'desktop/Makefile')); @@ -191,7 +195,9 @@ test('Windows packaging stages and embeds the GNU core when rustc defaults to MS test('an amd64 macOS package on an arm64 host embeds the amd64 helper', async () => { await withFixture({ goos: 'darwin', goarch: 'arm64', rustHost: 'aarch64-apple-darwin' }, async ({ root, run, coreBuilds }) => { await run('bash', ['scripts/desktop/package-desktop.sh', '--arch', 'amd64', '--no-sign']); - assert.deepEqual(new Set(await coreBuilds()), new Set(['x86_64-apple-darwin --release'])); + // The catalog checker executes on the host; the packaged helper still comes + // from the target stage, independently of that first host-tool build. + assert.deepEqual(new Set(await coreBuilds()), new Set(['aarch64-apple-darwin --release', 'x86_64-apple-darwin --release'])); assert.equal(await readFile(path.join(root, 'embedded-helper.txt'), 'utf8'), 'lithe-mcp for x86_64-apple-darwin\n'); }); }); diff --git a/shared/i18n/features/file-associations.json b/shared/i18n/features/file-associations.json new file mode 100644 index 000000000..ceae74e7e --- /dev/null +++ b/shared/i18n/features/file-associations.json @@ -0,0 +1,203 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.associations.title", + "description": "System file associations: title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.helpMac", + "description": "System file associations: helpMac", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.helpWindows", + "description": "System file associations: helpWindows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.selectAll", + "description": "System file associations: selectAll", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.clearSelection", + "description": "System file associations: clearSelection", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.refresh", + "description": "System file associations: refresh", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.format", + "description": "System file associations: format", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.language", + "description": "System file associations: language", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.currentDefault", + "description": "System file associations: currentDefault", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.formats", + "description": "System file associations: formats", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.noDefault", + "description": "System file associations: noDefault", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.litheDefault", + "description": "System file associations: litheDefault", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.selected", + "description": "System file associations: selected", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.associations.applyMac", + "description": "System file associations: applyMac", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.applyWindows", + "description": "System file associations: applyWindows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.requiresInstalled", + "description": "System file associations: requiresInstalled", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.appliedMac", + "description": "System file associations: appliedMac", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.appliedWindows", + "description": "System file associations: appliedWindows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.failed", + "description": "System file associations: failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.conflict", + "description": "System file associations: conflict", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.associations.openWith", + "description": "System file associations: openWith", + "platforms": [ + "desktop" + ] + } + ], + "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.selectAll": "Select all", + "desktop.associations.clearSelection": "Clear selection", + "desktop.associations.refresh": "Refresh", + "desktop.associations.format": "Format", + "desktop.associations.language": "Highlighting", + "desktop.associations.currentDefault": "Current default application", + "desktop.associations.formats": "Supported text formats", + "desktop.associations.noDefault": "No default application", + "desktop.associations.litheDefault": "Lithe (default)", + "desktop.associations.selected": "{count} selected", + "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.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.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.selectAll": "全选", + "desktop.associations.clearSelection": "清空选择", + "desktop.associations.refresh": "刷新", + "desktop.associations.format": "格式", + "desktop.associations.language": "高亮语言", + "desktop.associations.currentDefault": "当前默认应用", + "desktop.associations.formats": "支持的文本格式", + "desktop.associations.noDefault": "未设置默认应用", + "desktop.associations.litheDefault": "Lithe(默认)", + "desktop.associations.selected": "已选 {count} 项", + "desktop.associations.applyMac": "将所选格式设为默认", + "desktop.associations.applyWindows": "注册并选择默认应用…", + "desktop.associations.requiresInstalled": "请安装并运行打包后的 Lithe 应用以注册文件关联。", + "desktop.associations.appliedMac": "已从系统重新读取默认应用。", + "desktop.associations.appliedWindows": "所选格式已注册。请在 Windows 设置中确认默认应用,再刷新此列表。", + "desktop.associations.failed": "无法读取或更新文件关联,部分格式可能已生效。请刷新确认当前状态后重试。", + "desktop.associations.conflict": "打开此页后系统关联发生了变化。请确认刷新后的默认应用,再重新应用。", + "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 new file mode 100644 index 000000000..d72779860 --- /dev/null +++ b/shared/platform-feature-matrix/features/system-file-associations.json @@ -0,0 +1,41 @@ +{ + "id": "system-file-associations", + "area": "应用与设置", + "group": "通用", + "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 原生流程与两端发布包验收未完成。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/fileassociations/registration.go", + "desktop/internal/fileassociations/registration_darwin.go", + "desktop/internal/fileassociations/registration_test.go", + "desktop/internal/settingswindow/file_associations_view.go", + "desktop/internal/settingswindow/file_associations_visual_test.go", + "desktop/internal/core/file_associations_test.go", + "desktop/internal/workbench/system_document.go", + "desktop/internal/workbench/system_document_test.go", + "desktop/viva.toml", + ".agents/notes/implemented/feature/2026-11-23-system-file-associations.md" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/fileassociations/registration.go", + "desktop/internal/fileassociations/registration_windows.go", + "desktop/internal/fileassociations/registration_test.go", + "desktop/internal/settingswindow/file_associations_view.go", + "desktop/internal/settingswindow/file_associations_visual_test.go", + "desktop/internal/core/file_associations_test.go", + "desktop/cmd/lithe/main.go", + "desktop/viva.toml", + "scripts/desktop/package-desktop.test.mjs", + ".agents/notes/implemented/feature/2026-11-23-system-file-associations.md" + ] + } +}