diff --git a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md index cc7de05c8e..32f19c2a27 100644 --- a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md +++ b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md @@ -21,7 +21,7 @@ | 版本控制 | Git、SVN 等版本控制系统的配置 | | 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)和“调试器”(单步过滤等调试设置);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 | | 语言与框架 | 语言服务(LSP)的开关,以及 Spring Boot 等框架的配置 | -| 工具 | 终端等通用工具;插件带来的专用工具可以放进对应工具页。日志与诊断不属于设置,它是独立的日志窗口 | +| 工具 | 终端、搜索(搜索和替换文件大小预算)等通用工具;插件带来的专用工具可以放进对应工具页。日志与诊断不属于设置,它是独立的日志窗口 | | AI | 与 AI 有关的全部配置:MCP、Skill、全局指令、AI 提交信息、Agents、AI 服务商 | | 关于 | 应用本身是什么、怎样拿到新版本:版本信息、更新卡片(自动检查更新、更新渠道、发布源、立即检查)、交流群和项目链接(开源仓库、问题反馈、Rust Core、Viva 上游);一级页面,固定在侧栏最后,除更新卡片外不放设置项 | diff --git a/.agents/notes/implemented/feature/2026-11-08-viva-project-search.md b/.agents/notes/implemented/feature/2026-11-08-viva-project-search.md index e2545f7019..41f8be2de3 100644 --- a/.agents/notes/implemented/feature/2026-11-08-viva-project-search.md +++ b/.agents/notes/implemented/feature/2026-11-08-viva-project-search.md @@ -23,19 +23,30 @@ Viva 的项目搜索侧栏调用 Rust Core 搜索本地工作区,而不是在 提示用户,后续每次查询重建索引,用户可手动刷新。刷新按钮始终强制重建。 关闭搜索面板时释放监听,重新打开后重新注册;关闭项目时等待已在运行的搜索 结束,再异步释放 Core 索引。内容匹配、掩码、大小写、整词及正则均由 Core -决定,读取哪些文件也由 Core 决定:编辑器能当文本打开的文件都会搜(16 MiB 以内, -按 `file.read` 的编码识别解码,含 NUL 的二进制文件跳过),CRLF 行尾的 `\r` -不算行内容。项目搜索和 IDE 的 Find in Files 一样只列内容行,请求带 -`maxFileResults: 0`,文件名含查询词的文件不出结果,也不占用 200 条上限 -(#2198)。结果列表虚拟化,最多展示 200 项,达到上限时提示缩小范围; -点击内容结果会打开文件并跳到匹配处,输入法组合期间不强行移动光标。 - -全局搜索复用 Core 的 `workspace.searchEverywhere`,按 50 条分页并保留 Core -排序、打开文件的同分优先级与不透明游标;“全部”和“文件”查找文件名,“文本” -查找内容。结果上限为 500 条并提示缩小范围;用户可以加载下一页,重复游标或 -不产生新结果的续页会停止并记录失败。弹层关闭或输入改变会取消过期请求; -输入法组合期间不截获回车、方向键和 Escape。项目搜索和全局搜索按需共享一个 -递归监听,各自维护待处理事件和取消代次;最后一个消费者关闭后释放监听。 +决定。读取预算来自“工具 → 搜索”的真实用户偏好,默认 16 MiB,可设置 1–64 MiB; +替换缺省继承搜索预算。64 MiB 是当前解码和原生 I/O 安全边界,不能宣称支持无限文件。 +Core 按编辑器的自动编码识别解码,允许 ANSI escape,保留二进制控制字符检查; +CRLF 行尾的 `\r` 不算行内容。 + +项目搜索只列内容行,按 50 行自动续页,同一文件也可跨页。Core 根据已加载结果 +返回文件分组和折叠投影;界面只渲染投影,显示“已加载”的行数和文件数,不能把 +它当成完整匹配总数。项目、模块(来自已加载构建模型)、目录和自定义范围均使用 +Core 解析的路径/glob 表达式;没有模块模型时不执行模块查询。包含 Git 忽略文件 +是请求选项,不能绕过手动排除和结构隐藏。 + +宿主在 UI 线程捕获脏文档的不可变 rope 根,在后台生成文本交给 Core。快照加入 +候选并替换磁盘文本;后续页复用同一快照,编辑变化取消并重查,查询不写盘。 +全局搜索“全部”合并正文来源;名称匹配增加有序片段和低分跳字母匹配,但未完整 +复现 IDEA MinusculeMatcher。项目搜索取消 200 条总上限,全局搜索取消 500 条总上限, +按滚动需要追加页;失败保留已加载页并暂停,用户重试后继续。 + +替换先显示预览,确认才修改。磁盘预览绑定原始字节的 SHA-256,宿主重读核对后, +由 Core 解码、替换、按原编码和 BOM 编码,再原子条件写入;保留 CRLF。编辑器文档 +按版本验证后执行一次可撤销修改,预览后才打开的文件跳过,避免覆盖新文档。 + +搜索偏好来自平台 preferences 目录的 `search.json`;打开只读,Apply/恢复默认才 +条件写回并回读。外部冲突保留草稿,用户刷新后才能再次应用。无关 JSON 字段保留。 +查询、分组、默认值和验证在 Core,平台只负责文件 I/O、不可变编辑快照和界面。 查询拥有项目的取消上下文和 30 秒截止时间。用户切换项目、关闭搜索面板或输入 新查询时,不发布已过期结果;搜索结果的相对路径在打开文件之前再次检查是否 @@ -54,15 +65,12 @@ Viva 的项目搜索侧栏调用 Rust Core 搜索本地工作区,而不是在 ## 后果 结果显示后,收到文件变化事件会自动刷新;通知存在系统固有的投递延迟。 -2000 个小文件、三次运行的本机基准中,复用索引约 4.4 毫秒/次,重建约 -132 毫秒/次;这只是受控样本,不代表大型真实工作区。Linux 递归监听需要为 -目录分别注册,超出上限时会退回手动刷新。项目替换、完整原生搜索外观和 -各平台实机验收尚未完成,不能把该侧栏当作旧客户端搜索能力完全迁移。 -全局搜索的类、符号和操作入口尚未接入,暂时禁用;双击 Shift、预览、筛选、 -匹配高亮、自动续页与完整视觉对齐仍未完成。 -同样使用 2000 个小文件、三次运行的全局文件名搜索基准,复用索引约 28.2 毫秒/次, -失效重建约 47.2 毫秒/次;结果包含 Core 排序与第一页 JSON 传输,不代表真实大型 -项目或界面端到端延迟。 +Linux 递归监听需要为目录分别注册,超出上限时会退回手动刷新。 +当前分组计数只覆盖已加载行。完整总数、生成目录的临时覆盖、无需先打开文件的 +全工作区类/符号索引、符号链接跟随、完整 IDEA 匹配质量与各平台实机验收仍由 +[#2199](https://github.com/1lck/Lithe-IDEA/issues/2199) 跟踪;不能把此次改进写成搜索已与 IDEA 对齐。 +名称匹配的宽松规则限于 Search Everywhere,通用 `rankNames` 保持原有边界匹配, +避免插件市场等现有候选列表出现额外结果。 ## 验证 @@ -72,9 +80,10 @@ Viva 的项目搜索侧栏调用 Rust Core 搜索本地工作区,而不是在 - `scripts/desktop/desktop-go.sh test ./internal/workbench -run TestSearchPanels`:两个搜索界面共享监听并在最后一个消费者关闭时释放。 - `scripts/desktop/desktop-go.sh test ./internal/core -run '^$' -bench '^BenchmarkWorkspaceSearchIndex$' -benchtime=3x`:索引复用与重建开销。 - `scripts/desktop/desktop-go.sh test ./internal/core -run '^$' -bench '^BenchmarkEverywhereSearchIndex$' -benchtime=3x`:全局文件名分页的索引复用与重建开销。 -- Windows Server 2022 上实际执行 Viva `internal/filewatch` 的交叉编译测试二进制,递归监听新建、移动、重命名、删除和事件溢出测试通过;受系统限制的监听中删除目录测试跳过。这只验证原生监听组件,尚未验证 Windows 的完整搜索界面及 Core 接线。 -- 原版 macOS 搜索窗口和 Viva 无头界面已截图对照,输入框按原版组合搜索图标、清除和选项按钮;Viva 仍缺项目替换入口、结果的两行预览及其他整体布局细节,尚未逐像素验收。 -- 原版 macOS 全局搜索和 Viva 无头弹层已截图对照,确认基础尺寸、背景、焦点边框和选中行;匹配高亮、预览、筛选与完整逐像素验收仍待完成。 +- `scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestProjectSearchReadsUnsavedTextAndAllSearchesContents|TestProjectReplacePreservesOriginalEncodingAndRejectsChangedPreview'`:脏文档/All正文及五种编码替换、外部改动保护。 +- `scripts/desktop/desktop-go.sh test ./internal/settingswindow ./internal/searchprefs -run 'TestSearchPage|TestSearchPreferences'`:真实来源读写、应用、回读及冲突。 +- `scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench ./internal/settingswindow -run '^TestVisualSearch(Results|Preferences)$'`:明暗主题和中英文截图,需指定 `LITHE_VISUAL_OUTPUT_DIR`。 +- 组件测试与无头截图不替代两端原生窗口、大型真实项目和输入法验收。 ## 适用范围 diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 772e29cc33..a5de9ea1c3 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -208,6 +208,25 @@ jobs: if-no-files-found: error retention-days: 14 + - name: Capture search screenshots + id: search-visual + if: ${{ !cancelled() && steps.rust.outcome == 'success' }} + timeout-minutes: 5 + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/search-visual + run: | + ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench ./internal/settingswindow \ + -run '^TestVisualSearch(Results|Preferences)$' -count=1 -timeout=120s + + - name: Upload search screenshots + if: ${{ !cancelled() && steps.search-visual.outcome != 'skipped' }} + uses: actions/upload-artifact@v7 + with: + name: search-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/search-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Upload native verification reports if: always() uses: actions/upload-artifact@v7 diff --git a/desktop/internal/core/search_presentation.go b/desktop/internal/core/search_presentation.go new file mode 100644 index 0000000000..8d53676cc7 --- /dev/null +++ b/desktop/internal/core/search_presentation.go @@ -0,0 +1,25 @@ +package core + +import "context" + +// SearchPresentationRow references a loaded match, or heads its file group. +type SearchPresentationRow struct { + Path string `json:"path"` + Count int `json:"count"` + MatchIndex *int `json:"matchIndex"` +} + +type SearchPresentation struct { + Rows []SearchPresentationRow `json:"rows"` + Files int `json:"files"` + Lines int `json:"lines"` +} + +func (c *Client) SearchPresentation(ctx context.Context, paths []string, collapsed []string) (SearchPresentation, error) { + var result SearchPresentation + err := c.Execute(ctx, "workspace.searchPresentation", struct { + Paths []string `json:"paths"` + Collapsed []string `json:"collapsed"` + }{nonNil(paths), nonNil(collapsed)}, &result) + return result, err +} diff --git a/desktop/internal/core/search_presentation_test.go b/desktop/internal/core/search_presentation_test.go new file mode 100644 index 0000000000..6ea7c1ef8d --- /dev/null +++ b/desktop/internal/core/search_presentation_test.go @@ -0,0 +1,44 @@ +package core + +import ( + "context" + "encoding/json" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "os" + "reflect" + "testing" + "time" +) + +func TestSearchPreferencesAndPresentationSharedFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("search/idea-search-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Preferences []struct { + Request StoredSearchPreferences + Expected SearchPreferences + } + Presentation struct { + Request struct{ Paths, Collapsed []string } + Expected SearchPresentation + } + } + if err = json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client := NewClient() + for _, item := range fixture.Preferences { + got, err := client.ResolveSearchPreferences(ctx, item.Request.MaxFileBytes, item.Request.ReplacementMaxFileBytes) + if err != nil || got != item.Expected { + t.Fatalf("preferences %+v: %v", got, err) + } + } + got, err := client.SearchPresentation(ctx, fixture.Presentation.Request.Paths, fixture.Presentation.Request.Collapsed) + if err != nil || !reflect.DeepEqual(got, fixture.Presentation.Expected) { + t.Fatalf("presentation %+v: %v", got, err) + } +} diff --git a/desktop/internal/core/workspace.go b/desktop/internal/core/workspace.go index d02defa383..1bdc072211 100644 --- a/desktop/internal/core/workspace.go +++ b/desktop/internal/core/workspace.go @@ -316,13 +316,21 @@ func (c *Client) ListDirectories(ctx context.Context, root string, paths []strin // WorkspaceSearchRequest is the shared Core search query and its visibility options. // Paths in the response are workspace-relative with forward slashes. type WorkspaceSearchRequest struct { - Root string `json:"root"` - Query string `json:"query"` - CaseSensitive bool `json:"caseSensitive,omitempty"` - WholeWords bool `json:"wholeWords,omitempty"` - RegularExpression bool `json:"regularExpression,omitempty"` - FileMask string `json:"fileMask,omitempty"` - MaxResults int `json:"maxResults"` + Root string `json:"root"` + Query string `json:"query"` + CaseSensitive bool `json:"caseSensitive,omitempty"` + WholeWords bool `json:"wholeWords,omitempty"` + RegularExpression bool `json:"regularExpression,omitempty"` + FileMask string `json:"fileMask,omitempty"` + ScopeExpression string `json:"scopeExpression,omitempty"` + ScopePaths []string `json:"scopePaths,omitempty"` + IncludeIgnored bool `json:"includeIgnored,omitempty"` + MaxFileBytes uint64 `json:"maxFileBytes,omitempty"` + TextOverrides map[string]string `json:"textOverrides,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Cursor *string `json:"cursor,omitempty"` + ProjectPage bool `json:"projectPage,omitempty"` + MaxResults int `json:"maxResults"` // MaxFileResults caps the file-name matches within MaxResults; nil leaves them // capped only by MaxResults and zero asks for content matches alone. MaxFileResults *int `json:"maxFileResults,omitempty"` @@ -350,6 +358,31 @@ type WorkspaceSearchMatch struct { PreviewRanges []SearchNameRange `json:"previewRanges,omitempty"` } +type WorkspaceSearchPage struct { + Matches []WorkspaceSearchMatch `json:"matches"` + NextCursor *string `json:"nextCursor"` +} + +type SearchPreferences struct { + MaxFileBytes uint64 `json:"maxFileBytes"` + ReplacementMaxFileBytes uint64 `json:"replacementMaxFileBytes"` + MaximumFileBytes uint64 `json:"maximumFileBytes"` +} + +type StoredSearchPreferences struct { + MaxFileBytes *uint64 `json:"maxFileBytes,omitempty"` + ReplacementMaxFileBytes *uint64 `json:"replacementMaxFileBytes,omitempty"` +} + +func (c *Client) ResolveSearchPreferences(ctx context.Context, maxFileBytes, replacementMaxFileBytes *uint64) (SearchPreferences, error) { + var result SearchPreferences + err := c.Execute(ctx, "workspace.searchPreferences", struct { + MaxFileBytes *uint64 `json:"maxFileBytes,omitempty"` + ReplacementMaxFileBytes *uint64 `json:"replacementMaxFileBytes,omitempty"` + }{maxFileBytes, replacementMaxFileBytes}, &result) + return result, err +} + // SearchNameRange locates one Core-selected highlight in UTF-16 code units. type SearchNameRange struct { Start int `json:"start"` @@ -368,10 +401,14 @@ type EverywhereSearchRequest struct { IncludeGeneratedFileNames bool `json:"includeGeneratedFileNames"` Context *EverywhereSearchContext `json:"context,omitempty"` // The text options apply to content matches, as in Find in Files. - CaseSensitive bool `json:"caseSensitive,omitempty"` - WholeWords bool `json:"wholeWords,omitempty"` - RegularExpression bool `json:"regularExpression,omitempty"` - IncludeContentRanges bool `json:"includeContentRanges,omitempty"` + CaseSensitive bool `json:"caseSensitive,omitempty"` + WholeWords bool `json:"wholeWords,omitempty"` + RegularExpression bool `json:"regularExpression,omitempty"` + IncludeContentRanges bool `json:"includeContentRanges,omitempty"` + MaxFileBytes uint64 `json:"maxFileBytes,omitempty"` + TextOverrides map[string]string `json:"textOverrides,omitempty"` + ScopePaths []string `json:"scopePaths,omitempty"` + IncludeIgnored bool `json:"includeIgnored,omitempty"` } type EverywhereSearchContext struct { @@ -404,6 +441,13 @@ func (c *Client) SearchWorkspace(ctx context.Context, request WorkspaceSearchReq return response.Matches, nil } +func (c *Client) SearchWorkspacePage(ctx context.Context, request WorkspaceSearchRequest) (WorkspaceSearchPage, error) { + request.ProjectPage = true + var response WorkspaceSearchPage + err := c.Execute(ctx, "workspace.search", request, &response) + return response, err +} + // InvalidateWorkspaceSearch discards Core's cached filesystem inventory, so the // next search observes file additions and edits even when native events were lost. func (c *Client) InvalidateWorkspaceSearch(ctx context.Context, root string) error { diff --git a/desktop/internal/core/workspace_replace.go b/desktop/internal/core/workspace_replace.go index 6a676f8532..2c4a2448ea 100644 --- a/desktop/internal/core/workspace_replace.go +++ b/desktop/internal/core/workspace_replace.go @@ -16,6 +16,10 @@ type WorkspaceReplaceRequest struct { FileMask string `json:"fileMask,omitempty"` Paths []string `json:"paths,omitempty"` TextOverrides map[string]string `json:"textOverrides,omitempty"` + ScopeExpression string `json:"scopeExpression,omitempty"` + ScopePaths []string `json:"scopePaths,omitempty"` + IncludeIgnored bool `json:"includeIgnored,omitempty"` + MaxFileBytes uint64 `json:"maxFileBytes,omitempty"` } // WorkspaceReplaceMatch is one changed line of a file, before and after. @@ -31,6 +35,7 @@ type WorkspaceReplaceFile struct { Path string `json:"path"` Matches []WorkspaceReplaceMatch `json:"matches"` ReplacementText string `json:"replacementText"` + SourceIdentity string `json:"sourceIdentity,omitempty"` } // PreviewWorkspaceReplace runs workspace.replacePreview. diff --git a/desktop/internal/documentio/read.go b/desktop/internal/documentio/read.go index 890e940d56..0896c90eac 100644 --- a/desktop/internal/documentio/read.go +++ b/desktop/internal/documentio/read.go @@ -16,7 +16,7 @@ func ReadFile(path string) (data []byte, err error) { // refuses content beyond limit, including bytes added after the size check. // It is intended for small native metadata whose limit comes from a Core contract. func ReadFileLimit(path string, limit int64) (data []byte, err error) { - if limit < 0 || limit > maxBytes { + if limit < 0 || limit > maxNativeBytes { return nil, ErrTooLarge } source, info, err := openReadable(path) diff --git a/desktop/internal/documentio/write.go b/desktop/internal/documentio/write.go index f0b1a24ab5..3a83140b34 100644 --- a/desktop/internal/documentio/write.go +++ b/desktop/internal/documentio/write.go @@ -34,6 +34,9 @@ var ( const maxBytes = 16 << 20 +// Native allocation guard; feature budgets come from the shared Core policy. +const maxNativeBytes = 64 << 20 + // Locks bound concurrent writes without retaining a per-path lock forever. var writeLocks [64]sync.Mutex @@ -146,7 +149,19 @@ func WriteGuarded(path string, data, expected []byte) error { // WriteGuardedLinked is WriteGuarded with the user's answer for a hard-linked document: // nil refuses one, HardLinkReplacePath saves this path as its own file and // HardLinkUpdateShared writes the shared file in place. -func WriteGuardedLinked(path string, data, expected []byte, consent *HardLinkConsent) (err error) { +func WriteGuardedLinked(path string, data, expected []byte, consent *HardLinkConsent) error { + return writeGuardedLimit(path, data, expected, consent, maxBytes) +} + +// WriteGuardedLimit preserves native conflict and metadata protection for a Core-selected budget. +func WriteGuardedLimit(path string, data, expected []byte, limit int64) error { + if limit < 0 || limit > maxNativeBytes { + return ErrTooLarge + } + return writeGuardedLimit(path, data, expected, nil, limit) +} + +func writeGuardedLimit(path string, data, expected []byte, consent *HardLinkConsent, limit int64) (err error) { lock := writeLock(path) lock.Lock() defer lock.Unlock() @@ -158,11 +173,11 @@ func WriteGuardedLinked(path string, data, expected []byte, consent *HardLinkCon return err } defer func() { err = errors.Join(err, source.Close()) }() - current, err := io.ReadAll(io.LimitReader(source, maxBytes+1)) + current, err := io.ReadAll(io.LimitReader(source, limit+1)) if err != nil { return err } - if len(current) > maxBytes || len(data) > maxBytes { + if int64(len(current)) > limit || int64(len(data)) > limit { return ErrTooLarge } if !bytes.Equal(current, expected) { @@ -208,7 +223,7 @@ func WriteGuardedLinked(path string, data, expected []byte, consent *HardLinkCon if err != nil { return err } - latestBytes, readErr := io.ReadAll(io.LimitReader(latest, maxBytes+1)) + latestBytes, readErr := io.ReadAll(io.LimitReader(latest, limit+1)) closeErr := latest.Close() if err = errors.Join(readErr, closeErr); err != nil { return err diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index 6a6e9fe865..5d4cc6f17c 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -579,6 +579,7 @@ type SettingsMessages struct { Debuggers string Languages string Tools string + SearchPage string AI string IDEAPI string // PageLater is the body of a page the new desktop client does not offer yet. diff --git a/desktop/internal/i18n/settings_messages.go b/desktop/internal/i18n/settings_messages.go index 8399564b98..7fe10c0a62 100644 --- a/desktop/internal/i18n/settings_messages.go +++ b/desktop/internal/i18n/settings_messages.go @@ -21,6 +21,7 @@ func settingsMessages(language Language) SettingsMessages { Debuggers: Shared(language, "desktop.buildSettings.debuggers"), Languages: Shared(language, "settings.groups.languages"), Tools: Shared(language, "settings.groups.tools"), + SearchPage: Shared(language, "desktop.search.settings.title"), AI: Shared(language, "native.ai"), AIGeneration: Shared(language, "desktop.settings.aiGeneration.page"), IDEAPI: Shared(language, "desktop.ideApi.title"), diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 49cacde494..2217320205 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1666,9 +1666,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.workingDirectory": "Working directory", "desktop.runConfig.workingDirectoryPlaceholder": "Path inside the workspace; empty uses the default", "desktop.search.collapseFile": "Hide details", + "desktop.search.count": "{count} matching lines in {files} files", "desktop.search.expandFile": "Show details", "desktop.search.fileMaskPlaceholder": "File mask, e.g. *.java, *.kt", "desktop.search.first200": "Showing the first 200 results. Narrow your search to see more.", + "desktop.search.group": "{path} ({count})", + "desktop.search.includeIgnored": "Include Git-ignored files", + "desktop.search.loadedCount": "Loaded {count} matching lines in {files} files", + "desktop.search.noModules": "No imported modules are available.", "desktop.search.noReplacements": "Nothing to replace.", "desktop.search.replace": "Replace", "desktop.search.replaceAll": "Replace All…", @@ -1683,6 +1688,23 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.search.replaceSkipped": "Replaced in {changed} files; {skipped} files were left unchanged because they changed or are not UTF-8", "desktop.search.replaceSummary": "{occurrences} occurrences in {files} files", "desktop.search.replaceToggle": "Toggle Replace", + "desktop.search.retry": "Retry search", + "desktop.search.scope": "Scope", + "desktop.search.scopeCustom": "Custom Scope", + "desktop.search.scopeDirectory": "Directory", + "desktop.search.scopeHelp": "Use project-relative directories or files, comma-separated. Wildcards include paths; prefix a rule with ! to exclude it.", + "desktop.search.scopeModule": "Module", + "desktop.search.scopeProject": "In Project", + "desktop.search.settings.failed": "Could not read or save search settings. Refresh and try again. Your draft is kept.", + "desktop.search.settings.invalid": "Enter a whole number of MiB within the supported range.", + "desktop.search.settings.limits": "File size limits (MiB)", + "desktop.search.settings.limitsHelp": "These application preferences apply to every project. Larger limits use more memory while searching and replacing. Changes take effect after Apply.", + "desktop.search.settings.range": "Application scope · supported range: 1–{maximum} MiB", + "desktop.search.settings.replace": "Replace files up to", + "desktop.search.settings.replaceHelp": "Maximum size of each file included in Replace in Files. Original encoding, BOM and line endings are preserved.", + "desktop.search.settings.search": "Search files up to", + "desktop.search.settings.searchHelp": "Maximum size of each file whose contents are searched. File names remain searchable.", + "desktop.search.settings.title": "Search", "desktop.search.watchUnavailable": "Could not monitor project changes. Refresh search results to check for changes.", "desktop.semantics.codeActionFailed": "The code action could not be applied.", "desktop.semantics.codeActionOther": "Action", @@ -4854,9 +4876,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.workingDirectory": "工作目录", "desktop.runConfig.workingDirectoryPlaceholder": "工作区内的路径;留空使用默认目录", "desktop.search.collapseFile": "收起详情", + "desktop.search.count": "{files} 个文件中有 {count} 行匹配", "desktop.search.expandFile": "展开详情", "desktop.search.fileMaskPlaceholder": "文件掩码,例如 *.java、*.kt", "desktop.search.first200": "显示前 200 条结果。请缩小搜索范围以查看更多。", + "desktop.search.group": "{path}({count})", + "desktop.search.includeIgnored": "包含 Git 忽略文件", + "desktop.search.loadedCount": "已加载 {files} 个文件的 {count} 行匹配", + "desktop.search.noModules": "没有可用的已导入模块。", "desktop.search.noReplacements": "没有可替换的内容。", "desktop.search.replace": "替换", "desktop.search.replaceAll": "全部替换…", @@ -4871,6 +4898,23 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.search.replaceSkipped": "已在 {changed} 个文件中替换;{skipped} 个文件已变化或不是 UTF-8,未修改", "desktop.search.replaceSummary": "{files} 个文件中的 {occurrences} 处", "desktop.search.replaceToggle": "切换替换", + "desktop.search.retry": "重试搜索", + "desktop.search.scope": "范围", + "desktop.search.scopeCustom": "自定义范围", + "desktop.search.scopeDirectory": "目录", + "desktop.search.scopeHelp": "填写项目内的目录或文件,以逗号分隔。通配规则包含路径;以 ! 开头的规则排除路径。", + "desktop.search.scopeModule": "模块", + "desktop.search.scopeProject": "项目", + "desktop.search.settings.failed": "无法读取或保存搜索设置,请刷新后重试。已保留草稿。", + "desktop.search.settings.invalid": "请输入支持范围内的 MiB 整数。", + "desktop.search.settings.limits": "文件大小上限(MiB)", + "desktop.search.settings.limitsHelp": "这些应用设置作用于所有项目。提高上限会增加搜索和替换时的内存开销,点击应用后生效。", + "desktop.search.settings.range": "应用范围 · 支持范围:1–{maximum} MiB", + "desktop.search.settings.replace": "替换文件上限", + "desktop.search.settings.replaceHelp": "项目替换允许处理的单个文件大小。保留原编码、BOM 和换行符。", + "desktop.search.settings.search": "搜索文件上限", + "desktop.search.settings.searchHelp": "搜索正文时允许读取的单个文件大小。文件名搜索不受此值影响。", + "desktop.search.settings.title": "搜索", "desktop.search.watchUnavailable": "无法监听项目变化。请刷新搜索结果以检查更新。", "desktop.semantics.codeActionFailed": "无法应用该代码操作。", "desktop.semantics.codeActionOther": "操作", diff --git a/desktop/internal/searchprefs/source.go b/desktop/internal/searchprefs/source.go new file mode 100644 index 0000000000..45fe81d51a --- /dev/null +++ b/desktop/internal/searchprefs/source.go @@ -0,0 +1,88 @@ +// Package searchprefs owns the native source of application-wide search preferences. +// Only explicit Apply writes this source, outside installed application resources. +package searchprefs + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "reflect" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +const relativePath = "search.json" +const maximumSourceBytes = 64 << 10 + +// Snapshot binds editable preferences to the exact native source read by the page. +type Snapshot struct { + Stored core.StoredSearchPreferences + Effective core.SearchPreferences + Path string + source configfile.Snapshot +} + +// Source resolves its location from platform application storage, never an app bundle. +type Source struct{ Root string } + +func (s Source) Load(ctx context.Context) (Snapshot, error) { + file, err := configfile.Capture(ctx, s.Root, relativePath, maximumSourceBytes) + if err != nil { + return Snapshot{}, err + } + result := Snapshot{source: file, Path: file.Path()} + if file.Exists() { + if !bytes.HasPrefix(bytes.TrimSpace(file.Bytes()), []byte("{")) { + return Snapshot{}, errors.New("invalid search preference document") + } + if err = json.Unmarshal(file.Bytes(), &result.Stored); err != nil { + return Snapshot{}, err + } + } + result.Effective, err = core.NewClient().ResolveSearchPreferences(ctx, result.Stored.MaxFileBytes, result.Stored.ReplacementMaxFileBytes) + return result, err +} + +// Save preserves unrelated keys, rejects external changes and returns a fresh read-back. +func (s Source) Save(ctx context.Context, baseline Snapshot, stored core.StoredSearchPreferences) (Snapshot, error) { + if _, err := core.NewClient().ResolveSearchPreferences(ctx, stored.MaxFileBytes, stored.ReplacementMaxFileBytes); err != nil { + return Snapshot{}, err + } + if err := baseline.source.Verify(ctx); err != nil { + return Snapshot{}, err + } + if reflect.DeepEqual(baseline.Stored, stored) { + return s.Load(ctx) + } + fields := map[string]json.RawMessage{} + if baseline.source.Exists() { + if err := json.Unmarshal(baseline.source.Bytes(), &fields); err != nil { + return Snapshot{}, err + } + } + for key, value := range map[string]*uint64{"maxFileBytes": stored.MaxFileBytes, "replacementMaxFileBytes": stored.ReplacementMaxFileBytes} { + if value == nil { + delete(fields, key) + } else { + encoded, err := json.Marshal(*value) + if err != nil { + return Snapshot{}, err + } + fields[key] = encoded + } + } + data, err := json.MarshalIndent(fields, "", " ") + if err != nil { + return Snapshot{}, err + } + if _, err = baseline.source.Replace(ctx, append(data, '\n'), nil); err != nil { + return Snapshot{}, err + } + result, err := s.Load(ctx) + if err == nil && !reflect.DeepEqual(result.Stored, stored) { + err = errors.New("search preferences changed during read-back") + } + return result, err +} diff --git a/desktop/internal/searchprefs/source_test.go b/desktop/internal/searchprefs/source_test.go new file mode 100644 index 0000000000..598b2baf4b --- /dev/null +++ b/desktop/internal/searchprefs/source_test.go @@ -0,0 +1,59 @@ +package searchprefs + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func TestSearchPreferencesReadOnlyOpenGuardedSaveAndReadBack(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + source := Source{Root: filepath.Join(t.TempDir(), "preferences")} + initial, err := source.Load(ctx) + if err != nil { + t.Fatal(err) + } + if _, err = os.Stat(source.Root); !errors.Is(err, os.ErrNotExist) { + t.Fatal("read-only opening created preferences", err) + } + search, replace := uint64(32<<20), uint64(24<<20) + saved, err := source.Save(ctx, initial, core.StoredSearchPreferences{MaxFileBytes: &search, ReplacementMaxFileBytes: &replace}) + if err != nil { + t.Fatal(err) + } + if saved.Effective.MaxFileBytes != search || saved.Effective.ReplacementMaxFileBytes != replace { + t.Fatalf("read-back %+v", saved.Effective) + } + reopened, err := source.Load(ctx) + if err != nil || reopened.Effective != saved.Effective { + t.Fatalf("reopen %+v %v", reopened, err) + } + if err = os.WriteFile(saved.Path, []byte(`{"maxFileBytes":1048576,"future":true}`), 0600); err != nil { + t.Fatal(err) + } + if _, err = source.Save(ctx, saved, core.StoredSearchPreferences{}); !errors.Is(err, configfile.ErrConflict) { + t.Fatalf("external edit not protected: %v", err) + } + latest, err := source.Load(ctx) + if err != nil { + t.Fatal(err) + } + reset, err := source.Save(ctx, latest, core.StoredSearchPreferences{}) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(reset.Path) + if err != nil { + t.Fatal(err) + } + if string(data) != "{\n \"future\": true\n}\n" { + t.Fatalf("reset lost unrelated value: %s", data) + } +} diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index ec118146a4..96573b94a1 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -10,6 +10,7 @@ package settingswindow import ( "context" "encoding/json" + "github.com/1lck/Lithe-IDEA/desktop/internal/searchprefs" "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" "sync" "time" @@ -328,8 +329,15 @@ type CommandInstallTarget struct { Directory string } +// SearchPreferencesSource owns a read-only opening and explicit guarded Save with read-back. +type SearchPreferencesSource interface { + Load(context.Context) (searchprefs.Snapshot, error) + Save(context.Context, searchprefs.Snapshot, core.StoredSearchPreferences) (searchprefs.Snapshot, error) +} + // Options configure the settings window. type Options struct { + SearchPreferences SearchPreferencesSource // PluginInstallsClosed releases downloads retained by the settings session. PluginInstallsClosed func() // GitHub is the account the Version Control page shows and drives; nil hides the card. diff --git a/desktop/internal/settingswindow/model.go b/desktop/internal/settingswindow/model.go index 801eaa221d..099ecab129 100644 --- a/desktop/internal/settingswindow/model.go +++ b/desktop/internal/settingswindow/model.go @@ -41,6 +41,7 @@ const ( // pageTools is the group "Tools"; the page after it belongs to it. pageTools pageTerminal + pageSearch // pageAI is the group "AI"; the two pages after it belong to it. pageAI pageAIGeneration @@ -72,6 +73,7 @@ var parents = [pageCount]pageID{ pageLanguages: noPage, pageTools: noPage, pageTerminal: pageTools, + pageSearch: pageTools, pageAI: noPage, pageAIGeneration: pageAI, pageIDEAPI: pageAI, @@ -136,6 +138,8 @@ func titleOf(messages *i18n.SettingsMessages, id pageID) string { return messages.Tools case pageTerminal: return messages.Terminal + case pageSearch: + return messages.SearchPage case pageAI: return messages.AI case pageAIGeneration: diff --git a/desktop/internal/settingswindow/search_view.go b/desktop/internal/settingswindow/search_view.go new file mode 100644 index 0000000000..f283271b75 --- /dev/null +++ b/desktop/internal/settingswindow/search_view.go @@ -0,0 +1,133 @@ +package settingswindow + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/searchprefs" + "github.com/vivaui/viva/ui" +) + +type searchPreferencesWork struct { + source SearchPreferencesSource + baseline searchprefs.Snapshot + stored *core.StoredSearchPreferences +} +type searchPreferencesDraft struct { + ready, busy, stale bool + search, replace ui.Field + failure string + snapshot searchprefs.Snapshot + work *searchPreferencesWork + effect *ui.EffectState[searchprefs.Snapshot, *searchPreferencesWork] +} + +func (w *window) startSearchPreferences(stored *core.StoredSearchPreferences) { + d := &w.searchDraft + if d.busy || w.sess.finished.Load() { + return + } + if d.effect == nil { + d.effect = ui.NewEffectKeyed[searchprefs.Snapshot, *searchPreferencesWork](func(ctx context.Context, work *searchPreferencesWork) (searchprefs.Snapshot, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if work.source == nil { + return searchprefs.Snapshot{}, errors.New("search preference source unavailable") + } + if work.stored == nil { + return work.source.Load(ctx) + } + return work.source.Save(ctx, work.baseline, *work.stored) + }).Sequential() + } + d.work = &searchPreferencesWork{source: w.ctrl.opts.SearchPreferences, baseline: d.snapshot, stored: stored} + d.busy = true + d.failure = "" + w.inv.Invalidate() +} +func (w *window) takeSearchPreferences() { + d := &w.searchDraft + if d.effect == nil { + return + } + result, err, ok := d.effect.Take() + if !ok { + return + } + d.busy = false + if err != nil { + d.stale = true + d.failure = i18n.Shared(w.marketLanguage(), "desktop.search.settings.failed") + w.reportEssentialsFailure("search_preferences", err) + return + } + d.snapshot = result + d.ready = true + d.stale = false + d.failure = "" + d.search.SetText(strconv.FormatUint(result.Effective.MaxFileBytes>>20, 10)) + d.replace.SetText(strconv.FormatUint(result.Effective.ReplacementMaxFileBytes>>20, 10)) +} +func (w *window) searchPage(c ui.C) { + d := &w.searchDraft + language := w.marketLanguage() + if d.work == nil { + w.startSearchPreferences(nil) + } + w.pageScroll(c, pageSearch, func() { + w.card(c, i18n.Shared(language, "desktop.search.settings.limits"), i18n.Shared(language, "desktop.search.settings.limitsHelp"), func() { + if !d.ready && d.busy { + ui.Text(c, i18n.Shared(language, "quickOpen.searching")).Muted() + return + } + w.settingsRow(c, i18n.Shared(language, "desktop.search.settings.search"), i18n.Shared(language, "desktop.search.settings.searchHelp"), func() { + ui.TextField(c.Part("search-budget"), &d.search, i18n.Shared(language, "desktop.search.settings.search"), "").Width(100).Disabled(d.busy) + }) + w.settingsRow(c, i18n.Shared(language, "desktop.search.settings.replace"), i18n.Shared(language, "desktop.search.settings.replaceHelp"), func() { + ui.TextField(c.Part("replace-budget"), &d.replace, i18n.Shared(language, "desktop.search.settings.replace"), "").Width(100).Disabled(d.busy) + }) + if d.ready { + ui.Text(c, i18n.SharedFormat(language, "desktop.search.settings.range", map[string]string{"maximum": strconv.FormatUint(d.snapshot.Effective.MaximumFileBytes>>20, 10)})).FontSize(12).Muted() + ui.Text(c, d.snapshot.Path).FontSize(11).Muted().Ellipsis() + } + if d.failure != "" { + ui.Wrap(c, d.failure).Color(w.pal.danger) + } + ui.Row(c).Gap(8).Children(func() { + if ui.Button(c, i18n.Shared(language, "desktop.buildSettings.apply")).Disabled(!d.ready || d.busy || d.stale).Clicked() { + w.applySearchPreferences(false) + } + if ui.Button(c.Part("search-reset"), w.text.Settings.RestoreDefaults).Outline().Disabled(!d.ready || d.busy || d.stale).Clicked() { + w.applySearchPreferences(true) + } + if ui.Button(c, i18n.Shared(language, "ui.refresh")).Outline().Disabled(d.busy).Clicked() { + w.startSearchPreferences(nil) + } + }) + }) + }) +} +func (w *window) applySearchPreferences(reset bool) { + d := &w.searchDraft + if !d.ready || d.busy || d.stale || w.sess.finished.Load() { + return + } + stored := core.StoredSearchPreferences{} + if !reset { + search, err := strconv.ParseUint(strings.TrimSpace(d.search.Text()), 10, 64) + replace, replaceErr := strconv.ParseUint(strings.TrimSpace(d.replace.Text()), 10, 64) + if err != nil || replaceErr != nil || search == 0 || replace == 0 || search > d.snapshot.Effective.MaximumFileBytes>>20 || replace > d.snapshot.Effective.MaximumFileBytes>>20 { + d.failure = i18n.Shared(w.marketLanguage(), "desktop.search.settings.invalid") + w.reportEssentialsFailure("search_preferences", errors.New("invalid_file_budget")) + return + } + search, replace = search<<20, replace<<20 + stored = core.StoredSearchPreferences{MaxFileBytes: &search, ReplacementMaxFileBytes: &replace} + } + w.startSearchPreferences(&stored) +} diff --git a/desktop/internal/settingswindow/search_view_test.go b/desktop/internal/settingswindow/search_view_test.go new file mode 100644 index 0000000000..2cab5f788c --- /dev/null +++ b/desktop/internal/settingswindow/search_view_test.go @@ -0,0 +1,62 @@ +package settingswindow + +import ( + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/searchprefs" +) + +// Observe the page-owned effect through frame wakes; no real user preferences are touched. +func waitSearchPage(t *testing.T, d *windowDriver, ready func() bool) { + t.Helper() + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + d.pump() + for !ready() { + select { + case <-d.driver.Wakes(): + d.pump() + case <-deadline.C: + t.Fatal("search settings did not settle before the deadline") + } + } +} + +func TestSearchPageReadsAppliesAndKeepsDraftOnConflict(t *testing.T) { + root := filepath.Join(t.TempDir(), "preferences") + w := newWindow(NewController(Options{SearchPreferences: searchprefs.Source{Root: root}}), Values{Language: "en", Theme: "dark"}) + w.sess.page = pageSearch + d := openWindow(t, w) + waitSearchPage(t, d, func() bool { return w.searchDraft.ready && !w.searchDraft.busy }) + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatal("opening settings wrote a source", err) + } + w.searchDraft.search.SetText("32") + w.searchDraft.replace.SetText("24") + d.pump() + d.click(i18n.Shared(w.marketLanguage(), "desktop.buildSettings.apply")) + waitSearchPage(t, d, func() bool { return !w.searchDraft.busy }) + if w.searchDraft.snapshot.Effective.MaxFileBytes != 32<<20 || w.searchDraft.snapshot.Effective.ReplacementMaxFileBytes != 24<<20 { + t.Fatalf("saved %+v", w.searchDraft.snapshot.Effective) + } + if err := os.WriteFile(w.searchDraft.snapshot.Path, []byte(`{"maxFileBytes":1048576}`), 0600); err != nil { + t.Fatal(err) + } + w.searchDraft.search.SetText("48") + d.pump() + d.click(i18n.Shared(w.marketLanguage(), "desktop.buildSettings.apply")) + waitSearchPage(t, d, func() bool { return !w.searchDraft.busy }) + if !w.searchDraft.stale || w.searchDraft.search.Text() != "48" || w.searchDraft.failure == "" { + t.Fatal("conflict lost draft or remained writable") + } + d.click(i18n.Shared(w.marketLanguage(), "ui.refresh")) + waitSearchPage(t, d, func() bool { return !w.searchDraft.busy && !w.searchDraft.stale }) + if w.searchDraft.search.Text() != "1" { + t.Fatal("refresh did not read real source") + } +} diff --git a/desktop/internal/settingswindow/search_visual_test.go b/desktop/internal/settingswindow/search_visual_test.go new file mode 100644 index 0000000000..d6368379af --- /dev/null +++ b/desktop/internal/settingswindow/search_visual_test.go @@ -0,0 +1,43 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/searchprefs" + "github.com/vivaui/viva/headless" + "os" + "path/filepath" + "testing" +) + +func TestVisualSearchPreferences(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) { + w := newWindow(NewController(Options{SearchPreferences: searchprefs.Source{Root: t.TempDir()}, Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }}), Values{Language: language.Code(), Theme: theme}) + w.sess.page = pageSearch + 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()} + waitSearchPage(t, d, func() bool { return w.searchDraft.ready && !w.searchDraft.busy }) + d.pump() + if err := session.Screenshot(filepath.Join(out, "search-settings-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/settingswindow/settingswindow_test.go b/desktop/internal/settingswindow/settingswindow_test.go index 3030be0d72..703b494b3a 100644 --- a/desktop/internal/settingswindow/settingswindow_test.go +++ b/desktop/internal/settingswindow/settingswindow_test.go @@ -68,7 +68,7 @@ func TestTerminalIsTheOnePageOfTheToolsGroup(t *testing.T) { t.Fatal("the Terminal page does not directly follow its group, which appendVisible relies on") } for id := pageID(0); id < pageCount; id++ { - if id != pageTerminal && parents[id] == pageTools { + if id != pageTerminal && id != pageSearch && parents[id] == pageTools { t.Errorf("page %d is also in Tools", id) } } @@ -150,7 +150,7 @@ func TestExpandedToolsGroupListsTerminal(t *testing.T) { open := initialOpen() open[pageTools] = true rows := appendVisible(nil, english(), &open, "") - if len(rows) != 15 { + if len(rows) != 16 { t.Fatalf("rows = %v, want the 14 of the default sidebar and the Terminal page", rows) } for i, r := range rows { @@ -190,7 +190,7 @@ func TestSearchFindsTerminalInsideItsGroup(t *testing.T) { func TestSearchOnTheToolsGroupKeepsTerminal(t *testing.T) { open := initialOpen() rows := appendVisible(nil, english(), &open, foldQuery("tools")) - want := []pageID{pageTools, pageTerminal} + want := []pageID{pageTools, pageTerminal, pageSearch} if got := pagesOf(rows); !slices.Equal(got, want) { t.Fatalf("pages = %v, want %v", got, want) } diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index a2748addb4..172b8caebc 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -75,6 +75,7 @@ const ( // window is one open settings window and the model of its Page. Everything in it runs on // its window thread, but for the fields that say so. type window struct { + searchDraft searchPreferencesDraft editorDelay ui.Field editorDelayReady bool editorPrefsError string @@ -475,6 +476,7 @@ func (w *window) collect() { w.terminal.take() w.fonts.take() w.takeKeymapImport() + w.takeSearchPreferences() w.commands.take() if w.dynamic.take() { w.rowsValid = false @@ -509,6 +511,9 @@ func (w *window) reportMarket(previous marketStatus) { // of the declaration, so a request made while the page was declared starts in the same // paint, and in every paint, so leaving a page does not cancel what it asked for. func (w *window) declareWork(c ui.C) { + if d := &w.searchDraft; d.effect != nil && d.work != nil { + ui.Effect(c, d.effect, d.work) + } w.toolchains.declare(c) w.stepping.declare(c) w.terminal.declare(c) diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index 940741899f..80ce01be42 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -374,6 +374,8 @@ func (w *window) content(c ui.C) { w.debuggersPage(c) case w.sess.page == pageTerminal && w.ctrl.opts.TerminalShells != nil: w.terminalPage(c) + case w.sess.page == pageSearch: + w.searchPage(c) case w.sess.page == pageAIGeneration: w.generationPage(c) case w.sess.page == pageVersionControl: diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 62ada9b541..f49c50bb30 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -222,6 +222,7 @@ type Kernel interface { ReduceDocumentSaveBatch(ctx context.Context, members []string, results []core.SaveBatchResult, documents []core.SaveBatchDocument) (core.SaveBatchDecision, error) ReduceDocument(ctx context.Context, state core.DocumentState, event core.DocumentEvent) (core.DocumentDecision, error) SearchWorkspace(ctx context.Context, request core.WorkspaceSearchRequest) ([]core.WorkspaceSearchMatch, error) + SearchWorkspacePage(ctx context.Context, request core.WorkspaceSearchRequest) (core.WorkspaceSearchPage, error) InvalidateWorkspaceSearch(ctx context.Context, root string) error FilterWorkspaceChanges(ctx context.Context, paths []string) ([]string, error) UpdateWorkspaceSearch(ctx context.Context, root string, paths []string) error @@ -539,6 +540,7 @@ type App struct { recentFiles recentFileState drafts draftListState editorPreferences core.EditorPreferences + searchPreferences core.SearchPreferences // clipboardImage and pasteDirectory replace, in tests, reading the clipboard's picture // and the cache folder a picture pasted into a terminal is saved in // (terminal_paste_image.go); nil is the system's. @@ -925,6 +927,7 @@ func New(options Options) *App { if restoreErr != nil { a.backgroundFailed("update_snapshot", restoreErr) } + a.loadSearchPreferences() a.openPlugins(options) a.settingsWindow = a.newSettingsWindow() a.loadRecent() diff --git a/desktop/internal/workbench/document_observation.go b/desktop/internal/workbench/document_observation.go index a9c8815035..0f5a32d0f3 100644 --- a/desktop/internal/workbench/document_observation.go +++ b/desktop/internal/workbench/document_observation.go @@ -11,6 +11,7 @@ import ( "sync" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -197,6 +198,23 @@ func (a *App) scheduleDocumentChecks(p *project) { baseline := d.view.SavedSnapshot() missing := d.recreateMissing read := a.documentReader + maximum := int64(a.searchPreferences.MaximumFileBytes) + if baseline.Len() > 16<<20 { + read = func(path string) ([]byte, error) { + data, err := documentio.ReadFileLimit(path, maximum) + if err != nil { + return nil, err + } + kind, err := core.ClassifyDocumentText(data) + if kind == core.DocumentInvalidUTF8 { + return nil, errUnsupportedEncoding + } + if kind == core.DocumentBinary { + return nil, errNotText + } + return data, err + } + } kernel, _ := a.kernel.(editorKernel) encoding, hasBOM, disk := d.encoding, d.hasBOM, d.diskBytes a.background(p, 0, func(ctx context.Context) func(*App) { diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index a6948d65c5..4ba2bab3e0 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -289,8 +289,9 @@ func (a *App) openFile(p *project, path string) { registry := a.syntaxRegistry() name := filepath.Base(path) kernel, _ := a.kernel.(editorKernel) + budget := int64(a.searchPreferences.MaxFileBytes) a.background(p, 0, func(ctx context.Context) func(*App) { - read, err := readDocumentEncoded(ctx, kernel, path) + read, err := readDocumentEncodedLimit(ctx, kernel, path, budget) restored := a.prepareRecoveredDocument(ctx, p, path, read.text, err) if restored.found && restored.missing { err = nil @@ -636,6 +637,12 @@ func (a *App) saveDocumentMode(p *project, id int, auto bool) { before := append([]byte(nil), d.view.SavedBytes()...) path, name, revision := d.path, d.name, d.view.Revision() write := a.documentWriter + if len(data) > 16<<20 { + budget := int64(a.searchPreferences.MaximumFileBytes) + write = func(path string, data, expected []byte) error { + return documentio.WriteGuardedLimit(path, data, expected, budget) + } + } writeLinked := a.documentLinkedWriter create := a.documentCreator missing := d.recreateMissing diff --git a/desktop/internal/workbench/encoding.go b/desktop/internal/workbench/encoding.go index 46849a1eb6..e1608a1e58 100644 --- a/desktop/internal/workbench/encoding.go +++ b/desktop/internal/workbench/encoding.go @@ -67,7 +67,21 @@ type documentRead struct { // before; a file with a UTF-8 byte order mark, UTF-16 or a legacy encoding is detected and // decoded by Core. A file Core cannot decode is refused for the reason readDocument gave. func readDocumentEncoded(ctx context.Context, kernel editorKernel, path string) (documentRead, error) { - data, err := readDocument(path) + return readDocumentEncodedLimit(ctx, kernel, path, 16<<20) +} + +func readDocumentEncodedLimit(ctx context.Context, kernel editorKernel, path string, limit int64) (documentRead, error) { + data, err := documentio.ReadFileLimit(path, limit) + if err == nil { + kind, classifyErr := core.ClassifyDocumentText(data) + err = classifyErr + if kind == core.DocumentInvalidUTF8 { + err = errUnsupportedEncoding + } + if kind == core.DocumentBinary { + err = errNotText + } + } if err == nil && !bytes.HasPrefix(data, utf8BOM) { return documentRead{text: data}, nil } @@ -80,7 +94,7 @@ func readDocumentEncoded(ctx context.Context, kernel editorKernel, path string) raw := data if err != nil { var readErr error - if raw, readErr = documentio.ReadFile(path); readErr != nil { + if raw, readErr = documentio.ReadFileLimit(path, limit); readErr != nil { return documentRead{}, err } } @@ -272,7 +286,7 @@ func (d *document) revertEncodingChoice() { // readRawDocument reads a file's bytes without judging them as text, for a document whose // file is compared and decoded through Core. -func readRawDocument(path string) ([]byte, error) { return documentio.ReadFile(path) } +func readRawDocument(path string) ([]byte, error) { return documentio.ReadFileLimit(path, 64<<20) } // decodeExternal is the editor text of bytes read from the file of a document: the bytes // themselves for plain UTF-8, or Core's decoding in the encoding the document was opened with. diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index e9c690ba92..df715632eb 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -3,6 +3,7 @@ package workbench import ( "context" "errors" + "strings" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -80,6 +81,16 @@ func (a *App) documentEdited(p *project, d *document, edit editorview.Edit) { a.scheduleEditorActions(p, d) a.checkpointDocument(p, d) a.markRecentlyEdited(p, d) + if a.project == p && !d.virtual { + if p.search.watchAttached && strings.TrimSpace(p.search.want.text) != "" { + query := p.search.want + p.search.want = searchQuery{} + a.updateProjectSearch(p, query) + } + if a.everywhereView.open { + p.everywhere.query = "" + } + } if d.scratch { return } diff --git a/desktop/internal/workbench/search.go b/desktop/internal/workbench/search.go index ce8c7838f9..09269b5eab 100644 --- a/desktop/internal/workbench/search.go +++ b/desktop/internal/workbench/search.go @@ -40,12 +40,17 @@ var ( ) type searchQuery struct { - text, mask string + text, mask, scope string matchCase, wholeWords, regex bool + includeIgnored bool } // searchView contains only controls and options; results belong to a project. type searchView struct { + scopeMode string + scopeModule string + scope ui.Field + includeIgnored bool query, mask ui.Field optionsOpen, matchCase, wholeWords, regex, focus bool // replace is the Replace in Files field, shown while replaceOpen. @@ -60,6 +65,9 @@ type searchView struct { func (v *searchView) reset() { v.query.SetText("") v.mask.SetText("") + v.scope.SetText("") + v.scopeMode, v.scopeModule = "project", "" + v.includeIgnored = false v.replace.SetText("") v.replaceOpen = false v.optionsOpen, v.matchCase, v.wholeWords, v.regex, v.focus = false, false, false, false, false @@ -67,24 +75,35 @@ func (v *searchView) reset() { } type projectSearch struct { - want searchQuery - generation uint64 - cancel context.CancelFunc - running, loading bool - indexUsed bool - matches []core.WorkspaceSearchMatch - failed bool - watch *documentWatch - watchAttached bool - watchReady bool - watchAvailable bool - fullResync bool - pending []string - done <-chan struct{} + request core.WorkspaceSearchRequest + cursor *string + next bool + want searchQuery + generation uint64 + cancel context.CancelFunc + running, loading bool + indexUsed bool + matches []core.WorkspaceSearchMatch + collapsed map[string]bool + presentation core.SearchPresentation + presentationGeneration uint64 + failed bool + watch *documentWatch + watchAttached bool + watchReady bool + watchAvailable bool + fullResync bool + pending []string + done <-chan struct{} } func (a *App) cancelProjectSearch(p *project) { p.search.generation++ + p.search.presentationGeneration++ + p.search.request = core.WorkspaceSearchRequest{} + p.search.cursor = nil + p.search.matches = nil + p.search.presentation = core.SearchPresentation{} p.search.want = searchQuery{} p.search.loading = false a.searchView.optionsOpen = false @@ -200,6 +219,10 @@ func (a *App) updateProjectSearch(p *project, query searchQuery) { s.want = query s.generation++ s.matches, s.failed = nil, false + s.cursor, s.next = nil, false + s.collapsed = make(map[string]bool) + s.presentation = core.SearchPresentation{} + s.presentationGeneration++ a.searchView.list.ScrollTo(0, ui.ListStart) if s.cancel != nil { s.cancel() @@ -251,6 +274,28 @@ func (a *App) runProjectSearch(p *project) { delay = searchDebounce } kernel, root := a.kernel, p.root + previous := s.matches + collapsed := []string{} + for path, value := range s.collapsed { + if value { + collapsed = append(collapsed, path) + } + } + snapshots := captureSearchText(p) + request := s.request + next := s.next + s.next = false + if !next { + noFileResults := 0 + request = core.WorkspaceSearchRequest{Root: root, Query: query.text, FileMask: query.mask, + CaseSensitive: query.matchCase, WholeWords: query.wholeWords, RegularExpression: query.regex, + MaxResults: searchMaxResults, MaxFileResults: &noFileResults, IncludeContentRanges: true, + PageSize: 50, MaxFileBytes: a.searchPreferences.MaxFileBytes, + ScopeExpression: query.scope, IncludeIgnored: query.includeIgnored} + s.request = request + } else { + request.Cursor = s.cursor + } a.background(p, 0, func(context.Context) func(*App) { defer close(finished) defer cancel() @@ -263,20 +308,58 @@ func (a *App) runProjectSearch(p *project) { return func(a *App) { a.finishProjectSearch(p, generation, nil, ctx.Err(), full || len(paths) > 0) } } } + if !next { + request.TextOverrides = materializeSearchText(snapshots) + } operation, done := context.WithTimeout(ctx, searchTimeout) defer done() - err := synchronizeSearchIndex(operation, kernel, root, full, paths) + var err error + if !next { + err = synchronizeSearchIndex(operation, kernel, root, full, paths) + } var matches []core.WorkspaceSearchMatch + var cursor *string + if err == nil { + page, pageErr := kernel.SearchWorkspacePage(operation, request) + matches, cursor, err = page.Matches, page.NextCursor, pageErr + } + if next && err == nil { + if cursor != nil && ((request.Cursor != nil && *cursor == *request.Cursor) || len(matches) == 0) { + err = errors.New("search page did not advance") + } else { + matches = append(previous, matches...) + } + } + var presentation core.SearchPresentation if err == nil { - // Find in Files lists only lines, as the IDE's does; file names that contain - // the query would otherwise fill the result cap before any line. - noFileResults := 0 - matches, err = kernel.SearchWorkspace(operation, core.WorkspaceSearchRequest{Root: root, Query: query.text, FileMask: query.mask, CaseSensitive: query.matchCase, WholeWords: query.wholeWords, RegularExpression: query.regex, MaxResults: searchMaxResults, MaxFileResults: &noFileResults, IncludeContentRanges: true}) + identities := make([]string, len(matches)) + for i := range matches { + identities[i] = matches[i].Path + } + presentation, err = core.NewClient().SearchPresentation(operation, identities, collapsed) + } + return func(a *App) { + if generation == s.generation && err == nil { + s.cursor = cursor + s.request = request + s.request.Cursor = nil + s.presentation = presentation + s.presentationGeneration++ + } + a.finishProjectSearch(p, generation, matches, err, full || len(paths) > 0) } - return func(a *App) { a.finishProjectSearch(p, generation, matches, err, full || len(paths) > 0) } }) } +func (a *App) loadMoreProjectSearch(p *project) { + s := &p.search + if s.running || s.failed || s.cursor == nil { + return + } + s.next = true + a.runProjectSearch(p) +} + // synchronizeSearchIndex delegates visibility and incremental updates to Core. // A lost or excessively large event batch requires a complete rebuild instead. func synchronizeSearchIndex(ctx context.Context, kernel Kernel, root string, full bool, paths []string) error { diff --git a/desktop/internal/workbench/search_everywhere.go b/desktop/internal/workbench/search_everywhere.go index 209e360816..1abc175039 100644 --- a/desktop/internal/workbench/search_everywhere.go +++ b/desktop/internal/workbench/search_everywhere.go @@ -26,11 +26,10 @@ const everywhereScopeActions = 4 // All tab lists (each can be filtered out). const everywhereScopeCount = 6 -var everywhereKinds = []string{"file", "type", "symbol"} +var everywhereKinds = []string{"file", "type", "symbol", "content"} const ( everywherePageSize = 50 - everywhereMaxResults = 500 everywhereDebounce = 180 * time.Millisecond everywhereFileHeight = 24 everywhereTextHeight = 40 @@ -221,7 +220,8 @@ func (a *App) updateEverywhere(p *project, query string, scope int) { s.request = core.EverywhereSearchRequest{Root: p.root, Query: query, PageSize: everywherePageSize, ResultKinds: kinds, IncludeGeneratedFileNames: scope != 5, Context: &core.EverywhereSearchContext{OpenPaths: openPaths}, CaseSensitive: options.matchCase, WholeWords: options.wholeWords, RegularExpression: options.regex, - IncludeContentRanges: scope == 5} + IncludeContentRanges: scope == 5 || scope == 0, MaxFileBytes: a.searchPreferences.MaxFileBytes, + } s.loading = true if !s.watchAttached { a.startEverywhereWatch(p) @@ -299,8 +299,9 @@ func (a *App) runEverywhere(p *project, next bool) { return } request, generation := s.request, s.generation + snapshots := captureSearchText(p) if next { - if s.cursor == nil || len(s.matches) >= everywhereMaxResults { + if s.cursor == nil { return } request.Cursor = s.cursor @@ -335,6 +336,9 @@ func (a *App) runEverywhere(p *project, next bool) { } } } + if !next { + request.TextOverrides = materializeSearchText(snapshots) + } operation, done := context.WithTimeout(ctx, searchTimeout) defer done() var err error @@ -345,7 +349,13 @@ func (a *App) runEverywhere(p *project, next bool) { if err == nil { page, err = kernel.SearchEverywherePage(operation, request) } - return func(a *App) { a.finishEverywhere(p, generation, next, page, err, full || len(paths) > 0) } + return func(a *App) { + if generation == s.generation && err == nil { + s.request = request + s.request.Cursor = nil + } + a.finishEverywhere(p, generation, next, page, err, full || len(paths) > 0) + } }) } @@ -411,9 +421,6 @@ func (a *App) finishEverywhere(p *project, generation uint64, next bool, page co } else { s.matches = page.Matches } - if len(s.matches) > everywhereMaxResults { - s.matches = s.matches[:everywhereMaxResults] - } s.cursor = page.NextCursor } diff --git a/desktop/internal/workbench/search_everywhere_lsp.go b/desktop/internal/workbench/search_everywhere_lsp.go index 0b59c0b9f4..a194c84c3a 100644 --- a/desktop/internal/workbench/search_everywhere_lsp.go +++ b/desktop/internal/workbench/search_everywhere_lsp.go @@ -328,9 +328,6 @@ func (a *App) everywhereSymbolsMerge(p *project) { st.lspKeys[key] = true s.matches = append(s.matches, match) } - if len(s.matches) > everywhereMaxResults { - s.matches = s.matches[:everywhereMaxResults] - } } // everywhereMatchOf is the de-duplication key of a match: its path, line and name. diff --git a/desktop/internal/workbench/search_everywhere_view.go b/desktop/internal/workbench/search_everywhere_view.go index 7157a80df2..fecdea8973 100644 --- a/desktop/internal/workbench/search_everywhere_view.go +++ b/desktop/internal/workbench/search_everywhere_view.go @@ -171,9 +171,10 @@ func (a *App) everywhereFilter(c ui.C, p *project, language i18n.Language) { v.hiddenKinds = map[string]bool{} } names := map[string]string{ - "file": i18n.Shared(language, "desktop.everywhere.files"), - "type": i18n.Shared(language, "desktop.everywhere.classes"), - "symbol": i18n.Shared(language, "desktop.everywhere.symbols"), + "file": i18n.Shared(language, "desktop.everywhere.files"), + "type": i18n.Shared(language, "desktop.everywhere.classes"), + "symbol": i18n.Shared(language, "desktop.everywhere.symbols"), + "content": i18n.Shared(language, "desktop.everywhere.text"), } for _, kind := range everywhereKinds { shown := !v.hiddenKinds[kind] @@ -234,10 +235,6 @@ func (a *App) everywhereWithPreview(c ui.C, p *project, language i18n.Language) // end of what was loaded asks for the next page. func (a *App) everywhereResults(c ui.C, p *project, language i18n.Language) { v, s := &a.everywhereView, &p.everywhere - rowHeight := float32(everywhereFileHeight) - if s.scope == 5 { - rowHeight = everywhereTextHeight - } v.list.Label = func(i int) string { return searchMatchLabel(s.matches[i]) } // The list learns its row count when it is declared, so the first paint with matches // cannot select one yet and the next does. Only a selection that moved scrolls the list; @@ -253,6 +250,10 @@ func (a *App) everywhereResults(c ui.C, p *project, language i18n.Language) { ui.List(c, &v.list, len(s.matches), func(row ui.ListRow) { result := s.matches[row.Index] selected := row.Index == s.selected + rowHeight := float32(everywhereFileHeight) + if result.Kind == "content" { + rowHeight = everywhereTextHeight + } row.Element.FillWidth().Height(rowHeight).Items(ui.Center).PadX(10).Gap(8).Children(func() { a.everywhereRow(row.C, p, result, selected) }) @@ -286,10 +287,6 @@ func (a *App) everywhereResults(c ui.C, p *project, language i18n.Language) { }) return } - if s.cursor != nil && len(s.matches) >= everywhereMaxResults { - ui.Paragraph(c, i18n.Shared(language, "desktop.everywhere.limit"), 2).Muted() - return - } if s.cursor != nil && !s.loading && !s.running { // A wheel scroll paints without an event pass, which drops c.After, so the next page is // asked for through the window's queue. diff --git a/desktop/internal/workbench/search_idea_test.go b/desktop/internal/workbench/search_idea_test.go new file mode 100644 index 0000000000..e11f95dc5f --- /dev/null +++ b/desktop/internal/workbench/search_idea_test.go @@ -0,0 +1,100 @@ +package workbench + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" +) + +func TestProjectSearchReadsUnsavedTextAndAllSearchesContents(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.app.searchView.delay = 0 + h.app.everywhereView.delay = 0 + h.app.settings.DisableAutoSave = true + root := t.TempDir() + path := filepath.Join(root, "notes.txt") + if err := os.WriteFile(path, []byte("old disk text\n"), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.settle() + doc := p.docs.byPath(path) + if err := doc.view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{Start: 0, End: 0}, Text: "unsaved needle\n"}}); err != nil { + t.Fatal(err) + } + h.app.updateProjectSearch(p, searchQuery{text: "needle"}) + awaitDocumentState(t, h, func() bool { return !p.search.loading && len(p.search.matches) == 1 }) + if *p.search.matches[0].Line != 1 { + t.Fatal(p.search.matches) + } + h.app.openEverywhere(p) + h.app.everywhereView.query.SetText("needle") + h.settle() + awaitDocumentState(t, h, func() bool { return !p.everywhere.loading && len(p.everywhere.matches) == 1 }) + if p.everywhere.matches[0].Kind != "content" { + t.Fatal(p.everywhere.matches) + } + data, err := os.ReadFile(path) + if err != nil || string(data) != "old disk text\n" { + t.Fatalf("search wrote disk: %q %v", data, err) + } +} + +func TestProjectReplacePreservesOriginalEncodingAndRejectsChangedPreview(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := core.NewClient() + for _, encoding := range []string{"gbk", "utf-16le-bom", "utf-16be-bom", "utf-8-bom", "windows-1252"} { + t.Run(encoding, func(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "source.txt") + text := "needle\r\nnext\r\n" + if encoding == "gbk" { + text = "中文 " + text + } + if encoding == "windows-1252" { + text = "café " + text + } + before, err := client.EncodeFileText(ctx, text, encoding, nil) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(path, before.Bytes, 0600); err != nil { + t.Fatal(err) + } + preview, err := client.PreviewWorkspaceReplace(ctx, core.WorkspaceReplaceRequest{Root: root, Query: "needle", Replacement: "found", MaxFileBytes: 1 << 20}) + if err != nil || len(preview) != 1 { + t.Fatalf("preview %+v %v", preview, err) + } + outcome := replacePreviewInFile(ctx, client, documentio.WriteGuarded, path, searchQuery{text: "needle"}, "found", 1<<20, preview[0].SourceIdentity) + if outcome.err != nil || outcome.skipped { + t.Fatalf("replace %+v", outcome) + } + want, err := client.EncodeFileText(ctx, string(bytes.ReplaceAll([]byte(text), []byte("needle"), []byte("found"))), encoding, nil) + if err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(path) + if err != nil || !bytes.Equal(got, want.Bytes) { + t.Fatalf("encoding/BOM/CRLF changed: %x %v", got, err) + } + if err = os.WriteFile(path, []byte("external needle"), 0600); err != nil { + t.Fatal(err) + } + outcome = replacePreviewInFile(ctx, client, documentio.WriteGuarded, path, searchQuery{text: "needle"}, "found", 1<<20, preview[0].SourceIdentity) + if !errors.Is(outcome.err, documentio.ErrConflict) { + t.Fatalf("stale preview wrote: %+v", outcome) + } + }) + } +} diff --git a/desktop/internal/workbench/search_preferences.go b/desktop/internal/workbench/search_preferences.go new file mode 100644 index 0000000000..f1bcc88ad7 --- /dev/null +++ b/desktop/internal/workbench/search_preferences.go @@ -0,0 +1,77 @@ +package workbench + +import ( + "context" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/searchprefs" +) + +type appSearchPreferences struct{ app *App } + +func (s appSearchPreferences) Load(ctx context.Context) (searchprefs.Snapshot, error) { + return (searchprefs.Source{Root: s.app.store.Dir()}).Load(ctx) +} +func (s appSearchPreferences) Save(ctx context.Context, baseline searchprefs.Snapshot, stored core.StoredSearchPreferences) (searchprefs.Snapshot, error) { + result, err := (searchprefs.Source{Root: s.app.store.Dir()}).Save(ctx, baseline, stored) + if err == nil { + s.app.post(func(a *App) { + a.searchPreferences = result.Effective + if p := a.project; p != nil { + a.refreshProjectSearch(p) + if a.everywhereView.open { + p.everywhere.query = "" + } + } + }) + } + return result, err +} +func (a *App) loadSearchPreferences() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + value, err := (appSearchPreferences{app: a}).Load(ctx) + if err != nil { + a.backgroundFailed("search_preferences_load", err) + defaults, defaultErr := core.NewClient().ResolveSearchPreferences(ctx, nil, nil) + if defaultErr != nil { + a.backgroundFailed("search_preferences_defaults", defaultErr) + return + } + a.searchPreferences = defaults + return + } + a.searchPreferences = value.Effective +} + +// Capture immutable rope roots on the window thread; materialize text only on the worker. +func captureSearchText(p *project) map[string]rope.Rope { + var snapshots map[string]rope.Rope + for _, doc := range p.docs.list { + if doc.virtual || doc.scratch || !doc.dirty() { + continue + } + path, inside := projectRelative(p.root, doc.path) + if !inside { + continue + } + if snapshots == nil { + snapshots = make(map[string]rope.Rope) + } + snapshots[path] = doc.view.TextSnapshot() + } + return snapshots +} + +func materializeSearchText(snapshots map[string]rope.Rope) map[string]string { + if len(snapshots) == 0 { + return nil + } + text := make(map[string]string, len(snapshots)) + for path, snapshot := range snapshots { + text[path] = snapshot.String() + } + return text +} diff --git a/desktop/internal/workbench/search_presentation.go b/desktop/internal/workbench/search_presentation.go new file mode 100644 index 0000000000..391b1544be --- /dev/null +++ b/desktop/internal/workbench/search_presentation.go @@ -0,0 +1,37 @@ +package workbench + +import ( + "context" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// Only lightweight path identities cross Core again when a page or collapse changes. +func (a *App) projectSearchPresentation(p *project) { + s := &p.search + s.presentationGeneration++ + generation := s.presentationGeneration + paths := make([]string, len(s.matches)) + for i := range s.matches { + paths[i] = s.matches[i].Path + } + var collapsed []string + for path, value := range s.collapsed { + if value { + collapsed = append(collapsed, path) + } + } + a.background(p, kernelCallTimeout, func(ctx context.Context) func(*App) { + projection, err := core.NewClient().SearchPresentation(ctx, paths, collapsed) + return func(a *App) { + if generation != s.presentationGeneration { + return + } + if err != nil { + a.operationFailed("workspace_search_presentation", err) + s.failed = true + return + } + s.presentation = projection + } + }) +} diff --git a/desktop/internal/workbench/search_replace.go b/desktop/internal/workbench/search_replace.go index 3852a9e67a..66f4f26dbc 100644 --- a/desktop/internal/workbench/search_replace.go +++ b/desktop/internal/workbench/search_replace.go @@ -1,13 +1,13 @@ package workbench import ( - "bytes" "context" + "crypto/sha256" + "encoding/hex" "errors" "path/filepath" "strconv" "strings" - "unicode/utf8" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" @@ -26,6 +26,8 @@ import ( type searchReplacer interface { PreviewWorkspaceReplace(context.Context, core.WorkspaceReplaceRequest) ([]core.WorkspaceReplaceFile, error) ReplaceText(context.Context, core.TextReplaceRequest) (string, int, error) + DecodeFileBytes(context.Context, []byte, string) (core.DecodedFile, error) + EncodeFileText(context.Context, string, string, *bool) (core.EncodedText, error) } // projectReplace is one project's Replace in Files preview and its application. @@ -46,34 +48,29 @@ type projectReplace struct { // previewProjectReplace asks Core what Replace All would change and opens the preview. func (a *App) previewProjectReplace(p *project, query searchQuery, replacement string) { + if p == nil { + return + } replacer, ok := a.kernel.(searchReplacer) r := &p.replace if !ok || p == nil || strings.TrimSpace(query.text) == "" || r.loading || r.applying { return } - overrides := map[string]string{} + snapshots := captureSearchText(p) revisions := map[string]int{} - for _, d := range p.docs.list { - if d.virtual { - continue - } - rel, inside := projectRelative(p.root, d.path) - if !inside { - continue - } - revisions[rel] = d.view.Revision() - if d.dirty() { - data, _ := d.view.Text() - overrides[rel] = string(data) + for _, doc := range p.docs.list { + if path, inside := projectRelative(p.root, doc.path); inside && !doc.virtual { + revisions[path] = doc.view.Revision() } } *r = projectReplace{open: true, loading: true, query: query, replacement: replacement, revisions: revisions, expanded: map[string]bool{}} root := p.root + budget := a.searchPreferences.ReplacementMaxFileBytes a.background(p, searchTimeout, func(ctx context.Context) func(*App) { files, err := replacer.PreviewWorkspaceReplace(ctx, core.WorkspaceReplaceRequest{ Root: root, Query: query.text, Replacement: replacement, FileMask: query.mask, CaseSensitive: query.matchCase, WholeWords: query.wholeWords, RegularExpression: query.regex, - TextOverrides: overrides, + TextOverrides: materializeSearchText(snapshots), MaxFileBytes: budget, ScopeExpression: query.scope, IncludeIgnored: query.includeIgnored, }) return func(a *App) { if !r.open || r.query != query || r.replacement != replacement { @@ -81,6 +78,7 @@ func (a *App) previewProjectReplace(p *project, query searchQuery, replacement s } r.loading = false if err != nil { + a.operationFailed("workspace_replace_preview", err) r.failure = a.text.Search.ReplaceFailed(err.Error()) return } @@ -140,18 +138,30 @@ func (a *App) applyProjectReplace(p *project) { } path := filepath.Join(p.root, filepath.FromSlash(file.Path)) if d := p.docs.byPath(path); d != nil && !d.virtual { - outcomes = append(outcomes, a.replaceInDocument(d, file, r.revisions[file.Path])) + revision, previewed := r.revisions[file.Path] + if !previewed { + outcomes = append(outcomes, replaceOutcome{path: path, skipped: true}) + continue + } + outcomes = append(outcomes, a.replaceInDocument(d, file, revision)) + continue + } + if _, wasOpen := r.revisions[file.Path]; wasOpen { + outcomes = append(outcomes, replaceOutcome{path: path, skipped: true}) continue } closed = append(closed, file) } query, replacement, root := r.query, r.replacement, p.root - write := a.documentWriter + budget := int64(a.searchPreferences.ReplacementMaxFileBytes) + write := func(path string, data, expected []byte) error { + return documentio.WriteGuardedLimit(path, data, expected, budget) + } r.applying = true a.background(p, searchTimeout, func(ctx context.Context) func(*App) { for _, file := range closed { path := filepath.Join(root, filepath.FromSlash(file.Path)) - outcomes = append(outcomes, replaceInFile(ctx, replacer, write, path, query, replacement)) + outcomes = append(outcomes, replacePreviewInFile(ctx, replacer, write, path, query, replacement, budget, file.SourceIdentity)) } return func(a *App) { p.replace = projectReplace{} @@ -187,35 +197,38 @@ func (a *App) replaceInDocument(d *document, file core.WorkspaceReplaceFile, rev return outcome } -// replaceInFile replaces the matches of a closed file. It reads the file again so the -// write is guarded by the bytes the replacement was computed from; a file that is not -// UTF-8 is left alone rather than re-encoded. -func replaceInFile(ctx context.Context, replacer searchReplacer, write func(string, []byte, []byte) error, path string, query searchQuery, replacement string) replaceOutcome { +// A closed file is decoded and re-encoded by Core; native writes guard exact disk bytes. +func replacePreviewInFile(ctx context.Context, replacer searchReplacer, write func(string, []byte, []byte) error, path string, query searchQuery, replacement string, limit int64, identity string) replaceOutcome { outcome := replaceOutcome{path: path} - data, err := documentio.ReadFile(path) + data, err := documentio.ReadFileLimit(path, limit) if err != nil { outcome.err = err return outcome } - body, bom := bytes.CutPrefix(data, utf8BOM) - if !utf8.Valid(body) { - outcome.skipped = true + if identity != "" { + hash := sha256.Sum256(data) + if hex.EncodeToString(hash[:]) != identity { + outcome.err = documentio.ErrConflict + return outcome + } + } + decoded, err := replacer.DecodeFileBytes(ctx, data, "") + if err != nil { + outcome.err = err return outcome } - text, count, err := replacer.ReplaceText(ctx, core.TextReplaceRequest{ - Text: string(body), Query: query.text, Replacement: replacement, - CaseSensitive: query.matchCase, WholeWords: query.wholeWords, RegularExpression: query.regex, - }) + text, count, err := replacer.ReplaceText(ctx, core.TextReplaceRequest{Text: decoded.Text, Query: query.text, Replacement: replacement, CaseSensitive: query.matchCase, WholeWords: query.wholeWords, RegularExpression: query.regex}) if err != nil || count == 0 { outcome.err, outcome.skipped = err, err == nil return outcome } - out := []byte(text) - if bom { - out = append(append([]byte{}, utf8BOM...), out...) + encoded, err := replacer.EncodeFileText(ctx, text, decoded.Encoding, &decoded.HasBOM) + if err != nil { + outcome.err = err + return outcome } - outcome.err = write(path, out, data) - outcome.before = body + outcome.err = write(path, encoded.Bytes, data) + outcome.before = []byte(decoded.Text) return outcome } diff --git a/desktop/internal/workbench/search_scope_view.go b/desktop/internal/workbench/search_scope_view.go new file mode 100644 index 0000000000..59b989c971 --- /dev/null +++ b/desktop/internal/workbench/search_scope_view.go @@ -0,0 +1,74 @@ +package workbench + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" +) + +func (a *App) searchScopeControls(c ui.C, p *project, language i18n.Language) bool { + ready := true + v := &a.searchView + if v.scopeMode == "" { + v.scopeMode = "project" + } + ui.Column(c).FillWidth().PadX(10).Gap(4).Children(func() { + ui.Select(c.Part("scope-kind"), &v.scopeMode, []string{"project", "module", "directory", "custom"}, func(value string) string { + switch value { + case "module": + return i18n.Shared(language, "desktop.search.scopeModule") + case "directory": + return i18n.Shared(language, "desktop.search.scopeDirectory") + case "custom": + return i18n.Shared(language, "desktop.search.scopeCustom") + default: + return i18n.Shared(language, "desktop.search.scopeProject") + } + }).FillWidth().Label(i18n.Shared(language, "desktop.search.scope")) + switch v.scopeMode { + case "project": + v.scope.SetText("") + case "module": + paths := []string{} + titles := map[string]string{} + for _, instance := range p.build.instances { + if !instance.modelLoaded || instance.modelLoading || instance.modelReloadPending { + continue + } + for _, module := range instance.Model.Projects { + paths = append(paths, module.Path) + title := module.DisplayName + if title == "" { + title = module.Name + } + titles[module.Path] = title + } + } + if len(paths) == 0 { + ui.Text(c, i18n.Shared(language, "desktop.search.noModules")).Muted() + + ready = false + return + } + if _, ok := titles[v.scopeModule]; !ok { + v.scopeModule = paths[0] + } + ui.Select(c.Part("scope-module"), &v.scopeModule, paths, func(path string) string { return titles[path] }).FillWidth().Label(i18n.Shared(language, "desktop.search.scopeModule")) + v.scope.SetText(v.scopeModule) + default: + ui.TextField(c.Part("scope-paths"), &v.scope, i18n.Shared(language, "desktop.search.scope"), "").FillWidth().Tooltip(i18n.Shared(language, "desktop.search.scopeHelp")) + } + }) + return ready +} + +func (a *App) projectSearchRetry(c ui.C, p *project, language i18n.Language) { + if ui.Button(c, i18n.Shared(language, "desktop.search.retry")).Outline().Clicked() { + a.performed("workspace.search.retry", surfaceButton) + p.search.failed = false + if p.search.cursor != nil { + a.loadMoreProjectSearch(p) + } else { + a.refreshProjectSearch(p) + } + } +} diff --git a/desktop/internal/workbench/search_test.go b/desktop/internal/workbench/search_test.go index 772d8d6001..37852958c3 100644 --- a/desktop/internal/workbench/search_test.go +++ b/desktop/internal/workbench/search_test.go @@ -116,12 +116,12 @@ type delayedSearchKernel struct { } func (k *delayedSearchKernel) InvalidateWorkspaceSearch(context.Context, string) error { return nil } -func (k *delayedSearchKernel) SearchWorkspace(_ context.Context, request core.WorkspaceSearchRequest) ([]core.WorkspaceSearchMatch, error) { +func (k *delayedSearchKernel) SearchWorkspacePage(_ context.Context, request core.WorkspaceSearchRequest) (core.WorkspaceSearchPage, error) { k.started <- request.Query if request.Query == "first" { <-k.release } - return []core.WorkspaceSearchMatch{{Path: request.Query}}, nil + return core.WorkspaceSearchPage{Matches: []core.WorkspaceSearchMatch{{Path: request.Query}}}, nil } func TestProjectSearchCancelsAndSerializesSupersededQueries(t *testing.T) { @@ -284,8 +284,8 @@ func (k *cleanupSearchKernel) InvalidateWorkspaceSearch(context.Context, string) k.invalidations.Add(1) return nil } -func (k *cleanupSearchKernel) SearchWorkspace(context.Context, core.WorkspaceSearchRequest) ([]core.WorkspaceSearchMatch, error) { - return nil, nil +func (k *cleanupSearchKernel) SearchWorkspacePage(context.Context, core.WorkspaceSearchRequest) (core.WorkspaceSearchPage, error) { + return core.WorkspaceSearchPage{}, nil } func TestProjectSearchDropsIndexWhenProjectCloses(t *testing.T) { @@ -454,10 +454,10 @@ type closeSearchKernel struct { release chan struct{} } -func (k *closeSearchKernel) SearchWorkspace(context.Context, core.WorkspaceSearchRequest) ([]core.WorkspaceSearchMatch, error) { +func (k *closeSearchKernel) SearchWorkspacePage(context.Context, core.WorkspaceSearchRequest) (core.WorkspaceSearchPage, error) { close(k.started) <-k.release - return nil, nil + return core.WorkspaceSearchPage{}, nil } func TestProjectSearchCloseWaitsForInflightIndexBeforeCleanup(t *testing.T) { @@ -491,7 +491,7 @@ func TestProjectSearchCloseWaitsForInflightIndexBeforeCleanup(t *testing.T) { } } -func TestProjectSearchVirtualizesAndDisclosesResultLimit(t *testing.T) { +func TestProjectSearchVirtualizesLoadedGroups(t *testing.T) { h := newHarness(t, &testKernel{Client: core.NewClient()}) h.open(t.TempDir()) h.click(center(h.button(itemFind))) @@ -502,10 +502,8 @@ func TestProjectSearchVirtualizesAndDisclosesResultLimit(t *testing.T) { for i := range p.search.matches { p.search.matches[i] = core.WorkspaceSearchMatch{Path: fmt.Sprintf("file-%03d.txt", i), Preview: "sample"} } - h.app.invalidator.Invalidate() - if err := h.driver.Pump(); err != nil { - t.Fatal(err) - } + h.app.projectSearchPresentation(p) + h.settle() countRows := func() int { n := 0 for _, hit := range h.driver.Snapshot().Hits { @@ -525,15 +523,8 @@ func TestProjectSearchVirtualizesAndDisclosesResultLimit(t *testing.T) { if got := countRows(); got > 20 { t.Fatalf("scrolled rows = %d", got) } - want := i18n.Shared(h.app.language(), "desktop.search.first200") - found := false - for _, label := range h.driver.Snapshot().Labels { - if len(label.Value) > 8 && strings.HasPrefix(want, label.Value) { - found = true - } - } - if !found { - t.Fatal("result limit is not disclosed") + if h.shows(i18n.Shared(h.app.language(), "desktop.search.first200")) { + t.Fatal("obsolete total cap shown") } } @@ -636,6 +627,9 @@ func TestProjectSearchF4OpensTheSelectedMatchAndKeepsItsPlace(t *testing.T) { } } labels := map[string]bool{} + for _, row := range p.search.presentation.Rows { + labels[row.Path] = true + } for _, match := range p.search.matches { labels[searchMatchLabel(match)] = true } @@ -669,15 +663,15 @@ func TestProjectSearchF4OpensTheSelectedMatchAndKeepsItsPlace(t *testing.T) { } } - focusRow(1) + focusRow(3) press(gfx.KeyF4) opensAt(p.search.matches[1], 1) - if got := h.app.searchView.list.Selected(); got != 1 { - t.Fatalf("the result list selects row %d after F4, want the opened match (1)", got) + if got := h.app.searchView.list.Selected(); got != 3 { + t.Fatalf("the result list selects row %d after F4, want the opened match (3)", got) } h.app.settings.Keymap = h.app.settings.Keymap.With(shortcuts.OpenSelected, []keymap.Chord{chordF7(t)}) - focusRow(0) + focusRow(1) press(gfx.KeyF4) if n := countPerformed(log, "workspace.search.openResult"); n != 1 { t.Fatalf("F4 opened a match while Open Selected File is on F7 (%d opens)", n) diff --git a/desktop/internal/workbench/search_view.go b/desktop/internal/workbench/search_view.go index 51bfd1b1fd..68c63f0f7a 100644 --- a/desktop/internal/workbench/search_view.go +++ b/desktop/internal/workbench/search_view.go @@ -22,8 +22,7 @@ func (a *App) searchPanel(c ui.C) { return } language := a.language() - query := searchQuery{text: v.query.Text(), mask: v.mask.Text(), matchCase: v.matchCase, wholeWords: v.wholeWords, regex: v.regex} - a.updateProjectSearch(p, query) + query := searchQuery{text: v.query.Text(), mask: v.mask.Text(), scope: v.scope.Text(), includeIgnored: v.includeIgnored, matchCase: v.matchCase, wholeWords: v.wholeWords, regex: v.regex} if v.focus { c.Canvas().RequestFocus(searchQueryID) v.focus = false @@ -47,6 +46,12 @@ func (a *App) searchPanel(c ui.C) { c.After(func() { a.refreshProjectSearch(p) }) } }) + scopeReady := a.searchScopeControls(c, p, language) + query.scope = v.scope.Text() + if !scopeReady { + query.text = "" + } + a.updateProjectSearch(p, query) a.searchReplaceRow(c, query) ui.Row(c).FillWidth().PadX(10).PadSides(0, 10, 10, 10).Children(func() { label := i18n.Shared(language, "native.fileMask") @@ -65,10 +70,13 @@ func (a *App) searchPanel(c ui.C) { ui.Icon(c, icons.Search).Size(28, 28).Color(a.colors.Subtle) ui.Text(c, i18n.Shared(language, "native.searchAcrossTheProject")).Color(a.colors.Subtle) }) - case p.search.loading: + case p.search.loading && len(p.search.matches) == 0: ui.Column(c).Fill().Center().Children(func() { ui.Text(c, i18n.Shared(language, "quickOpen.searching")).Muted() }) - case p.search.failed: - ui.Column(c).Fill().Center().Children(func() { ui.Text(c, i18n.Shared(language, "search.failed")).Color(a.theme.Danger) }) + case p.search.failed && len(p.search.matches) == 0: + ui.Column(c).Fill().Center().Children(func() { + ui.Text(c, i18n.Shared(language, "search.failed")).Color(a.theme.Danger) + a.projectSearchRetry(c, p, language) + }) case len(p.search.matches) == 0: ui.Column(c).Fill().Center().Children(func() { ui.Text(c, i18n.Shared(language, "native.noMatches")).Muted() }) default: @@ -97,6 +105,7 @@ func (a *App) searchOptions(c ui.C, language i18n.Language) { option(i18n.Shared(language, "native.matchCase"), "workspace.search.matchCase", &v.matchCase) option(i18n.Shared(language, "native.wholeWords"), "workspace.search.wholeWords", &v.wholeWords) option(i18n.Shared(language, "native.regularExpression"), "workspace.search.regularExpression", &v.regex) + option(i18n.Shared(language, "desktop.search.includeIgnored"), "workspace.search.includeIgnored", &v.includeIgnored) }) } @@ -105,23 +114,53 @@ func (a *App) searchOptions(c ui.C, language i18n.Language) { func (a *App) searchResults(c ui.C, p *project, language i18n.Language) { v := &a.searchView results := p.search.matches - v.list.Label = func(i int) string { return searchMatchLabel(results[i]) } + projection := p.search.presentation + rows := projection.Rows + summary := i18n.SharedFormat(language, "desktop.search.count", map[string]string{"count": strconv.Itoa(projection.Lines), "files": strconv.Itoa(projection.Files)}) + if p.search.cursor != nil { + summary = i18n.SharedFormat(language, "desktop.search.loadedCount", map[string]string{"count": strconv.Itoa(projection.Lines), "files": strconv.Itoa(projection.Files)}) + } + ui.Text(c, summary).FontSize(12).Color(a.colors.Subtle).PadX(11) + v.list.Label = func(i int) string { + if rows[i].MatchIndex == nil { + return rows[i].Path + } + return searchMatchLabel(results[*rows[i].MatchIndex]) + } opened := -1 - resultList := ui.List(c, &v.list, len(results), func(row ui.ListRow) { - result := results[row.Index] - row.Element.FillWidth().Height(searchResultHeight).PadX(11).PadY(6).Gap(2).Hover(ui.Look{}.Background(a.colors.Hover)).Children(func() { - ui.Row(row.C).FillWidth().Items(ui.Center).Gap(6).Children(func() { - name := filepath.Base(filepath.FromSlash(result.Path)) - ui.Icon(row.C, fileicons.ForFile(name, a.colors.Dark)).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) - ui.Text(row.C, name).Grow(1).Shrink(1).FontSize(12.5).Ellipsis() - if result.Line != nil { - ui.Text(row.C, searchLinePosition(result)).FontSize(12).Color(a.colors.Subtle) + resultList := ui.List(c, &v.list, len(rows), func(row ui.ListRow) { + item := rows[row.Index] + if item.MatchIndex == nil { + row.Element.FillWidth().Height(searchResultHeight).PadX(11).Items(ui.Center).Gap(6).Children(func() { + icon := icons.ChevronDown + if p.search.collapsed[item.Path] { + icon = icons.ChevronRight } + ui.Icon(row.C, icon).Size(14, 14) + ui.Text(row.C, i18n.SharedFormat(language, "desktop.search.group", map[string]string{"path": item.Path, "count": strconv.Itoa(item.Count)})).FontSize(12).Ellipsis() }) - // Core gives the line as a result row shows it, and the matches in it. - preview, ranges := result.Preview, result.PreviewRanges - ui.Row(row.C).FillWidth().MinWidth(0).Clip().Children(func() { - a.highlightedText(row.C, preview, ranges, a.colors.Subtle, 11.5, true) + if row.Element.Clicked() { + p.search.collapsed[item.Path] = !p.search.collapsed[item.Path] + a.projectSearchPresentation(p) + } + return + } + result := results[*item.MatchIndex] + row.Element.FillWidth().Height(searchResultHeight).PadX(11).PadY(6).Gap(2).Hover(ui.Look{}.Background(a.colors.Hover)).Children(func() { + ui.Column(row.C).FillWidth().Gap(2).Children(func() { + ui.Row(row.C).FillWidth().Items(ui.Center).Gap(6).Children(func() { + name := filepath.Base(filepath.FromSlash(result.Path)) + ui.Icon(row.C, fileicons.ForFile(name, a.colors.Dark)).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) + ui.Text(row.C, name).Grow(1).Shrink(1).FontSize(12.5).Ellipsis() + if result.Line != nil { + ui.Text(row.C, searchLinePosition(result)).FontSize(12).Color(a.colors.Subtle) + } + }) + // Core gives the line as a result row shows it, and the matches in it. + preview, ranges := result.Preview, result.PreviewRanges + ui.Row(row.C).FillWidth().MinWidth(0).Clip().Children(func() { + a.highlightedText(row.C, preview, ranges, a.colors.Subtle, 11.5, true) + }) }) }) if row.Element.Clicked() { @@ -137,15 +176,28 @@ func (a *App) searchResults(c ui.C, p *project, language i18n.Language) { if a.elementShortcut(resultList, shortcuts.OpenSelected) && v.list.Selected() >= 0 { opened = v.list.Selected() } - if opened >= 0 && opened < len(results) { - result := results[opened] + if opened >= 0 && opened < len(rows) && rows[opened].MatchIndex == nil { + path := rows[opened].Path + if p.search.collapsed == nil { + p.search.collapsed = map[string]bool{} + } + p.search.collapsed[path] = !p.search.collapsed[path] + a.projectSearchPresentation(p) + } + if opened >= 0 && opened < len(rows) && rows[opened].MatchIndex != nil { + result := results[*rows[opened].MatchIndex] c.After(func() { a.performed("workspace.search.openResult", surfaceButton) a.openSearchResult(p, result) }) } - if len(results) == searchMaxResults { - ui.Paragraph(c, i18n.Shared(language, "desktop.search.first200"), 2).PadX(11).PadY(8).Color(a.colors.Subtle) + if p.search.failed { + a.projectSearchRetry(c, p, language) + } + if p.search.cursor != nil && !p.search.running && !p.search.failed { + if _, last := v.list.Visible(); last >= len(rows)-8 { + a.post(func(a *App) { a.loadMoreProjectSearch(p) }) + } } } diff --git a/desktop/internal/workbench/search_visual_test.go b/desktop/internal/workbench/search_visual_test.go new file mode 100644 index 0000000000..bd430a4532 --- /dev/null +++ b/desktop/internal/workbench/search_visual_test.go @@ -0,0 +1,71 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" + "os" + "path/filepath" + "testing" +) + +func TestVisualSearchResults(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 []string{"zh-Hans", "en"} { + for _, theme := range []string{"dark", "light"} { + t.Run(language+"-"+theme, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + root := t.TempDir() + for name, text := range map[string]string{"search-notes.txt": "Search results\nSearch in unsaved documents\n", "guide.txt": "Search across the project\n"} { + if err := os.WriteFile(filepath.Join(root, name), []byte(text), 0600); err != nil { + t.Fatal(err) + } + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1440, 900 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.app.searchView.delay = 0 + h.app.everywhereView.delay = 0 + h.open(root) + p := h.app.project + h.app.openFindInFiles(p, false) + h.app.searchView.query.SetText("Search") + h.await("grouped search", func() bool { + return !p.search.loading && len(p.search.matches) == 3 && len(p.search.presentation.Rows) == 5 + }) + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "search-project-"+language+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + h.app.openEverywhere(p) + h.app.everywhereView.query.SetText("Search") + h.await("All content", func() bool { return !p.everywhere.loading && len(p.everywhere.matches) >= 4 }) + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "search-all-"+language+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index fb693972a0..05c29f9b29 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -31,6 +31,7 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { navigation = kernel.SettingsNavigation } return settingswindow.NewController(settingswindow.Options{ + SearchPreferences: appSearchPreferences{app: a}, PluginInstallsClosed: func() { a.post(func(a *App) { a.closePluginDownloads() }) }, diff --git a/desktop/internal/workbench/source_preview.go b/desktop/internal/workbench/source_preview.go index da16a5e83b..7c1ab7cf20 100644 --- a/desktop/internal/workbench/source_preview.go +++ b/desktop/internal/workbench/source_preview.go @@ -181,11 +181,12 @@ func (a *App) showSourcePreview(p *project, sp *sourcePreview, path string, line } registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) + budget := int64(a.searchPreferences.MaxFileBytes) a.background(p, 0, func(ctx context.Context) func(*App) { data, err := openText, error(nil) if !open { var read documentRead - read, err = readDocumentEncoded(ctx, kernel, path) + read, err = readDocumentEncodedLimit(ctx, kernel, path, budget) data = read.text } var content editorview.Content diff --git a/docs/ci-builds.md b/docs/ci-builds.md index fb72ce5f90..3de94534ab 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -68,6 +68,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 ### 独立工作树的本地编译 +搜索偏好 `/search.json` 由桌面原生存储适配器持有,最多64 KiB;只在用户应用/恢复默认时条件原子写回,打开页面不创建文件。它是用户状态,没有源码、版本、平台、架构或工具链复用身份,不跨工作树复制。搜索索引和未保存快照仅在当前进程内,绑定工作区、可见性与读取预算,关闭项目后释放,不写入安装目录。它们不改变代码签名或增量更新基线。`TestVisualSearchResults` 和 `TestVisualSearchPreferences` 的截图写入当前检出的 `.artifacts/search-visual/`,绑定本次源码、语言、主题和渲染环境,不跨工作树复制;Linux Desktop CI上传后由runner清理,不进入发行包。 + Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树的 `.artifacts/lsp-editor-visual/`。截图是当前提交与当前渲染环境的验证产物,绑定源码、平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复用。CI 上传后由运行器清理工作树,截图不进入安装包。 Desktop CI 的 Build 命令发现截图由 `TestVisualBuildCommandDiscovery` 写入当前工作树的 `.artifacts/build-command-discovery-visual/`。该结果绑定提交、平台、Go 工具链和固定的 Viva 与 Core 版本,上传后由 CI 清理,不跨工作树复制,也不进入安装包。 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index ef6199cca8..87c4d9ca0c 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -284,7 +284,9 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="42e360168f05a65488b75af6b71a6d347d8f467b" +# Search pages, unsaved snapshots, source identities and budgets from Core #125, +# merged on top of the build-option changes through Core #124. +PINNED_CORE_REVISION="6a2c0826b54eec385880f64da4a5e6b613d00dbe" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/features/search.json b/shared/i18n/features/search.json new file mode 100644 index 0000000000..36d1252940 --- /dev/null +++ b/shared/i18n/features/search.json @@ -0,0 +1,224 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.search.settings.title", + "description": "Search and search preferences: title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.limits", + "description": "Search and search preferences: limits", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.limitsHelp", + "description": "Search and search preferences: limitsHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.search", + "description": "Search and search preferences: search", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.searchHelp", + "description": "Search and search preferences: searchHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.replace", + "description": "Search and search preferences: replace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.replaceHelp", + "description": "Search and search preferences: replaceHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.invalid", + "description": "Search and search preferences: invalid", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.scope", + "description": "Search and search preferences: scope", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.scopeHelp", + "description": "Search and search preferences: scopeHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.includeIgnored", + "description": "Search and search preferences: includeIgnored", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.retry", + "description": "Search and search preferences: retry", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.count", + "description": "Search and search preferences: count", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string", + "files": "string" + } + }, + { + "id": "desktop.search.group", + "description": "Search and search preferences: group", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string", + "count": "string" + } + }, + { + "id": "desktop.search.scopeProject", + "description": "Search: scopeProject", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.scopeModule", + "description": "Search: scopeModule", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.scopeDirectory", + "description": "Search: scopeDirectory", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.scopeCustom", + "description": "Search: scopeCustom", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.noModules", + "description": "Search: noModules", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.loadedCount", + "description": "Search: loadedCount", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string", + "files": "string" + } + }, + { + "id": "desktop.search.settings.failed", + "description": "Search: failed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.settings.range", + "description": "Search: range", + "platforms": [ + "desktop" + ], + "parameters": { + "maximum": "string" + } + } + ], + "locales": { + "en-US": { + "desktop.search.settings.title": "Search", + "desktop.search.settings.limits": "File size limits (MiB)", + "desktop.search.settings.limitsHelp": "These application preferences apply to every project. Larger limits use more memory while searching and replacing. Changes take effect after Apply.", + "desktop.search.settings.search": "Search files up to", + "desktop.search.settings.searchHelp": "Maximum size of each file whose contents are searched. File names remain searchable.", + "desktop.search.settings.replace": "Replace files up to", + "desktop.search.settings.replaceHelp": "Maximum size of each file included in Replace in Files. Original encoding, BOM and line endings are preserved.", + "desktop.search.settings.invalid": "Enter a whole number of MiB within the supported range.", + "desktop.search.scope": "Scope", + "desktop.search.scopeHelp": "Use project-relative directories or files, comma-separated. Wildcards include paths; prefix a rule with ! to exclude it.", + "desktop.search.includeIgnored": "Include Git-ignored files", + "desktop.search.retry": "Retry search", + "desktop.search.count": "{count} matching lines in {files} files", + "desktop.search.group": "{path} ({count})", + "desktop.search.scopeProject": "In Project", + "desktop.search.scopeModule": "Module", + "desktop.search.scopeDirectory": "Directory", + "desktop.search.scopeCustom": "Custom Scope", + "desktop.search.noModules": "No imported modules are available.", + "desktop.search.loadedCount": "Loaded {count} matching lines in {files} files", + "desktop.search.settings.failed": "Could not read or save search settings. Refresh and try again. Your draft is kept.", + "desktop.search.settings.range": "Application scope · supported range: 1–{maximum} MiB" + }, + "zh-CN": { + "desktop.search.settings.title": "搜索", + "desktop.search.settings.limits": "文件大小上限(MiB)", + "desktop.search.settings.limitsHelp": "这些应用设置作用于所有项目。提高上限会增加搜索和替换时的内存开销,点击应用后生效。", + "desktop.search.settings.search": "搜索文件上限", + "desktop.search.settings.searchHelp": "搜索正文时允许读取的单个文件大小。文件名搜索不受此值影响。", + "desktop.search.settings.replace": "替换文件上限", + "desktop.search.settings.replaceHelp": "项目替换允许处理的单个文件大小。保留原编码、BOM 和换行符。", + "desktop.search.settings.invalid": "请输入支持范围内的 MiB 整数。", + "desktop.search.scope": "范围", + "desktop.search.scopeHelp": "填写项目内的目录或文件,以逗号分隔。通配规则包含路径;以 ! 开头的规则排除路径。", + "desktop.search.includeIgnored": "包含 Git 忽略文件", + "desktop.search.retry": "重试搜索", + "desktop.search.count": "{files} 个文件中有 {count} 行匹配", + "desktop.search.group": "{path}({count})", + "desktop.search.scopeProject": "项目", + "desktop.search.scopeModule": "模块", + "desktop.search.scopeDirectory": "目录", + "desktop.search.scopeCustom": "自定义范围", + "desktop.search.noModules": "没有可用的已导入模块。", + "desktop.search.loadedCount": "已加载 {files} 个文件的 {count} 行匹配", + "desktop.search.settings.failed": "无法读取或保存搜索设置,请刷新后重试。已保留草稿。", + "desktop.search.settings.range": "应用范围 · 支持范围:1–{maximum} MiB" + } + } +} diff --git a/shared/platform-feature-matrix/features/search-global.json b/shared/platform-feature-matrix/features/search-global.json index 3b02511e3b..f5bca0813f 100644 --- a/shared/platform-feature-matrix/features/search-global.json +++ b/shared/platform-feature-matrix/features/search-global.json @@ -10,7 +10,9 @@ "desktop/internal/workbench/search_everywhere.go", "desktop/internal/workbench/search_everywhere_test.go", "desktop/internal/core/workspace_everywhere_test.go", - ".agents/notes/implemented/feature/2026-11-08-viva-project-search.md" + ".agents/notes/implemented/feature/2026-11-08-viva-project-search.md", + "desktop/internal/workbench/search_idea_test.go", + "desktop/internal/workbench/search_visual_test.go" ] }, "windows": { @@ -20,11 +22,13 @@ "desktop/internal/workbench/search_everywhere.go", "desktop/internal/workbench/search_everywhere_test.go", "desktop/internal/core/workspace_everywhere_test.go", - ".agents/notes/implemented/feature/2026-11-08-viva-project-search.md" + ".agents/notes/implemented/feature/2026-11-08-viva-project-search.md", + "desktop/internal/workbench/search_idea_test.go", + "desktop/internal/workbench/search_visual_test.go" ] }, "owner": "Search", - "verification": "使用快捷键搜索命令、设置和工作区内容,确认结果来源和跳转行为。 macOS 双 Shift 打开 Search Everywhere,按 Community Islands 源码核对普通字重的圆角分类选中框、统一弹窗背景、内嵌圆角搜索框及 IDEA 明暗搜索/筛选/关闭图标;在深浅主题与窄窗口检查外框裁剪、搜索框不越界、输入焦点与中文组词,切换分类、清除、筛选、Esc、点击外部及执行命令保持原行为。 搜索弹窗使用独立无边框 NSPanel 和系统 NORMAL 阴影,不绘制 SwiftUI 模糊投影;父窗口移动/缩放后仍居中于顶部指定位置,点击外部与失焦关闭,筛选子菜单获焦时搜索保留;关闭与重新打开均无残留子窗口。 空查询只显示分类与搜索框,输入后展开、清空后收起;原生窗口使用 sRGB backing store,顶部分类复用共享标签聚焦/失焦状态,并从面板自身读取 controlActiveState,父窗口失焦不将活动分类错误画灰。 打开后无需点击即可直接输入首个字符;搜索进行中在输入框右侧、命令提示之前显示加载指示器,分类栏不重复显示;完成后加载指示器消失,输入后命令提示仍保留。 使用同一工作区输入 name,确认 .build/checkouts/Name.swift、rust/target 中的名称及 NativeMenu/navigation-menu 的分段命中;文件名范围来自 Core 的 UTF-16 nameMatchRanges,选中行高亮,名称先排序再按来源截断。漏斗只筛选已实现的 Classes/Files/Symbols/Actions,All/None/Invert 生效,All 包含动作;单独标签不受 All 来源筛选影响。预览按钮开启后,单击/上下键选中文件更新独立只读 Monaco,不能输入、格式化或重命名;回车/双击仍打开,关闭预览不改变主编辑器可写状态或未保存内容。生成目录名称更新沿用索引刷新;未覆盖 IDEA 的外部库、语言服务全量符号、历史/机器学习排序。 点击只读预览后结果行仍为活动焦点色;鼠标选择文件保持列表滚动偏移和面板位置/尺寸不变,上下键仅在必要时滚动显示选中项,不强制居中。 新查询或切换来源仍恢复首项可见。 在深浅主题与宽窄窗口按住顶部空白区拖向右下,确认窗口实际位置改变(原生命中区域须填满标题栏高度),输入展开、预览切换和父窗缩放后保持拖动位置,重开恢复默认;标签/输入/按钮不被拖动区域抢占。筛选行按名称排序,使用原始 IDEA 明暗复选框与共享行悬停/选中,固定底部 72×28 All/None/Invert 按钮,200pt 最小高度、共享弹层外框;连续勾选和批量操作不关闭菜单。 筛选内容背景沿 Islands Table/Panel 继承 tool-window-bg(深/浅 #191A1C/#FFFFFF),共享原生下拉面板使用 sRGB;复选框保留 24pt viewBox 自带边距,不叠加普通菜单图标的水平内边距。 筛选行 hover 是共享失焦灰,点击才保留主体蓝,移动到另一行同时保留蓝色选中行与灰色 hover 行,hover 不改变勾选。批量按钮上方使用滚动列表的 1pt 内侧矩形底边(Borders.color,深/浅 #26282C/#D1D3D9),不使用系统 Divider。 关闭时按来源保存非空查询,会话内每来源去重保留 50 条,All 重开恢复最后草稿并全选(包括空草稿);清空关闭后重开必须为空,不从非空历史回填,项目 reset 清除历史,侧栏查询保持独立。输入框清除按钮使用 16pt 槽位。结果文件名复用 Git 文件状态前景色,选中匹配片段保留金底黑字;被 Git 忽略的文件由 Core 批量 check-ignore 获取真实规则,包含 info/exclude、否定规则和已跟踪文件例外,按 Islands Dark/Light 的 #D69A6B/#8C4F00 着色;Git 不可用时保留未知,不按目录名猜测。右上角设置左侧的搜索图标与双 Shift 调用同一动作,提示快捷键,无工作区时禁用;浅深主题和宽窄窗口核对位置、hover 和点击。Windows 仅兼容可选 isIgnored 字段,ignored 前景色与此工具栏入口尚未同步。 打开搜索时激活并刷新惰性 Git 模块,将已归一化的 GitTreeStatusProjection 发布到当前搜索会话,未打开 Commit 也能得到未跟踪/修改状态色;工作区切换或关闭后不回写旧快照。 顶栏搜索使用 Community 原始 search@20x20 明暗 SVG,不放大 16pt 图标;与设置同用 LitheMainToolbarButtonStyle,放入 spacing=0 的同组工具栏,移除外层 9pt 间距和侧栏 37pt 槽位差异。 关闭搜索释放干净的暂存预览并撤销未完成打开;有未保存输入则保留为正式文档,项目替换仍显示时由替换面板继续持有并负责清理。 Text 预览沿用当前大小写/整词/正则选项,名称预览保持默认;生成名称索引扫描和增量更新均排除嵌套 linked worktree。 审核修复:Problems 与搜索共用或分别预览时,关闭搜索只释放搜索使用权,最后使用方退出才清理;待加载共享请求亦同。Text 只读预览用实际 Monaco nativeFind 显示大小写/整词/正则匹配而不抢焦点。搜索使用用户指定 Git且保持非交互。macOS 双 Shift 漏斗面板可编辑、应用并持久保存仅此窗口生效的排除表达式(*.log、**/.*/、.*、cache/),通用设置入口移除,侧栏搜索、项目替换和 Agent 补全不受影响;树与监听不隐藏;清空应用后重开仍为空并恢复范围,不同规则缓存随文件修改同步。Windows 共享 Rust 换行文件名仅 Unix 创建,保留全平台空格文件名测试;Windows 设置 UI 未同步。 全局搜索显式启用生成目录名称,Agent 的空 @ 与 @Name 都只用项目可见性,不受 *.log 搜索排除影响。cache/ 与 **/.*/ 必须在进入目录前剪枝,真实枚举探针不记录这些目录;直接上报排除后代的增量事件也不回填。连续修改排除规则只使搜索缓存失效,不重建项目树;失效屏障不被后续更新跳过,每根目录最多一个内容及一个名称缓存,旧分配在请求完成后释放;覆盖 32 次切换和更新。 排除规则改为漏斗列表首项(Actions 上方),与来源行共用复选框和 hover/点击样式,右侧原始 16pt 编辑图标打开由搜索窗口持有的独立编辑弹窗;漏斗不再内嵌文本框。应用按钮使用主题主色,应用保存并关闭、取消/Escape 丢弃未保存草稿但不关闭搜索;多行 Enter 换行。勾选开关独立记忆,取消勾选不删除规则,编辑已禁用规则不重新启用,重新勾选刷新当前搜索;来源批量按钮不改此开关。覆盖保存、取消、清空、关闭重开及禁用后重新启用,侧栏/替换/Agent 范围继续不受影响。 排除规则右侧编辑按钮按 Community ActionButton 小动作规格使用原始 16pt 明暗 edit.svg、22pt 点击和 hover 区、四边各 3pt 留白及 4pt 圆角,采用专用 ActionButton hover/pressed 主题色而非通用按钮底色;默认箭头光标,不影响行勾选。深浅主题检查普通、hover、按下、移出恢复及点击打开弹窗。 规则编辑输入框打开即获得原生焦点,点击弹窗空白保留光标/选区;复用共享多行输入框的单一外部焦点绑定与 2pt 焦点描边/向外 1pt 扩展,不能重复绑定导致焦点色或宽度脱节。深浅主题检查真实 firstResponder、空白点击不丢选区及两列边框像素,取消/应用和 Tab 导航仍可用。 排除规则行的灰色悬停和蓝色选中背景覆盖右侧编辑按钮区域,与来源行右边缘对齐;编辑按钮独立悬停,点击只编辑、不切换规则开关。 名称索引遇到不可访问或消失的后代目录时保留正常源码和 Text 结果,根目录错误及取消仍传播;搜索预览连续切换 A/B/C、清空结果或收起时按路径和请求标识释放旧持有,保留其他面板及未保存内容,旧请求晚返回不得误清新请求。 核对 src/Foo/src/Foo.swift 的路径回退以及 Agent @src 候选,文件名命中排在目录回退之前,路径命中不绘制文件名片段;Actions-only 不发送工作区请求,Text-only 不构建生成名称索引,Files-only 不构建正文索引,All 切换来源会重查并丢弃过期来源响应。2000 个生成文件冷索引回归核对构建种类、目录访问及驻留文件数。预览开启后单击只选择,辅助功能默认 Open、命名 Open 与 Return 可打开文件;VoiceOver 实机状态单独验收。 Unicode 名称连续匹配保持整串小写语义:i、i 加组合点及组合点本身均命中 İ.txt;补充非 BMP 前缀与希腊 sigma 回归,并核对原始 UTF-16 范围。 #1564:macOS 开启预览,在深浅主题下分别返回 199 和 200 条文件结果;列表大批结果到达后,文件列表与预览仍各在自己的面板内、互不重叠,鼠标选择、键盘滚动与 Return 打开保持有效;共享分隔容器覆盖横纵布局的空、单项及多项面板。 #1564 增量搜索:macOS 文件名候选先于正文/符号索引发布,首批立即发送,后续约100ms替换快照刷新并在来源结束flush;最终结果保留排名、上限及Git忽略状态。真实Rust桥接、取消、旧查询晚返回、reset及突发批次最终结果回归;深浅主题40/199/200条结果追加高排名候选后选择、预览与滚动保持稳定。输入防抖仍180ms,冷名称枚举及失效屏障仍需完成;Text随最终结果返回。Windows仍等待最终响应,未宣称流式展示验收。 #1564 自动分页:删除更多提示及每来源200条总上限,每来源50条、接近底部自动续查;首屏仍流式,后续整页去重追加并保持已加载页和动作顺序。深浅主题实际滚动加载257文件,保持非零像素偏移、选择和预览;Core四来源超过200、整页/空页耗尽、错误/跨查询游标拒绝。模块覆盖失败暂停、显式Retry、重复游标/无新增停止;取消与过期响应仍隔离。名称/符号每页扫描已有索引,只保留51个候选;实时索引游标前新增项需重查。Windows保留旧最终响应,未同步自动分页。 默认选择与主动选择分开:未进行鼠标/键盘导航时,Actions先到或首屏更优候选后到,预览和Enter跟随当前首项;主动选择后仍按ID保持,所选项消失才退回默认首项。原生窗口回归覆盖两种到达顺序并保留主动选择重排用例。 #1624:macOS 查询不等待内容预热;Core 名称和正文构建独立,Text 冷查询按文件清单匹配当前页。原生拖动右下角可缩放,左上角与输入不跳;Text 代码主行、路径次行。覆盖深浅主题、窄窗口、查询清空恢复、索引失效和取消;Windows 共享 Core 查询改善,原生缩放与两行呈现未同步,真实大项目延迟仍需验收。 中文界面操作搜索输入“切换终端”“显示或隐藏终端”及英文 Toggle Terminal 均命中同一动作,隐藏终端入口后执行可恢复;切回英文重查不保留旧中文标题。原始文案及当前语言文案一次交给 Core search.actions 匹配,保持候选顺序、插件自有标题原文及模块可用性。Windows 既有本地化命令搜索保留,尚未接入此 Core 匹配命令;真实完整弹窗验收待完成。 Windows 项目内容搜索使用 Core 连续游标,包含/排除规则在分页前执行;覆盖同文件跨页、多根切换、真实 UTF-16 命中范围和提供者批量读取。真实大项目与 WSL 产品验收待完成。", + "verification": "使用快捷键搜索命令、设置和工作区内容,确认结果来源和跳转行为。 macOS 双 Shift 打开 Search Everywhere,按 Community Islands 源码核对普通字重的圆角分类选中框、统一弹窗背景、内嵌圆角搜索框及 IDEA 明暗搜索/筛选/关闭图标;在深浅主题与窄窗口检查外框裁剪、搜索框不越界、输入焦点与中文组词,切换分类、清除、筛选、Esc、点击外部及执行命令保持原行为。 搜索弹窗使用独立无边框 NSPanel 和系统 NORMAL 阴影,不绘制 SwiftUI 模糊投影;父窗口移动/缩放后仍居中于顶部指定位置,点击外部与失焦关闭,筛选子菜单获焦时搜索保留;关闭与重新打开均无残留子窗口。 空查询只显示分类与搜索框,输入后展开、清空后收起;原生窗口使用 sRGB backing store,顶部分类复用共享标签聚焦/失焦状态,并从面板自身读取 controlActiveState,父窗口失焦不将活动分类错误画灰。 打开后无需点击即可直接输入首个字符;搜索进行中在输入框右侧、命令提示之前显示加载指示器,分类栏不重复显示;完成后加载指示器消失,输入后命令提示仍保留。 使用同一工作区输入 name,确认 .build/checkouts/Name.swift、rust/target 中的名称及 NativeMenu/navigation-menu 的分段命中;文件名范围来自 Core 的 UTF-16 nameMatchRanges,选中行高亮,名称先排序再按来源截断。漏斗只筛选已实现的 Classes/Files/Symbols/Actions,All/None/Invert 生效,All 包含动作;单独标签不受 All 来源筛选影响。预览按钮开启后,单击/上下键选中文件更新独立只读 Monaco,不能输入、格式化或重命名;回车/双击仍打开,关闭预览不改变主编辑器可写状态或未保存内容。生成目录名称更新沿用索引刷新;未覆盖 IDEA 的外部库、语言服务全量符号、历史/机器学习排序。 点击只读预览后结果行仍为活动焦点色;鼠标选择文件保持列表滚动偏移和面板位置/尺寸不变,上下键仅在必要时滚动显示选中项,不强制居中。 新查询或切换来源仍恢复首项可见。 在深浅主题与宽窄窗口按住顶部空白区拖向右下,确认窗口实际位置改变(原生命中区域须填满标题栏高度),输入展开、预览切换和父窗缩放后保持拖动位置,重开恢复默认;标签/输入/按钮不被拖动区域抢占。筛选行按名称排序,使用原始 IDEA 明暗复选框与共享行悬停/选中,固定底部 72×28 All/None/Invert 按钮,200pt 最小高度、共享弹层外框;连续勾选和批量操作不关闭菜单。 筛选内容背景沿 Islands Table/Panel 继承 tool-window-bg(深/浅 #191A1C/#FFFFFF),共享原生下拉面板使用 sRGB;复选框保留 24pt viewBox 自带边距,不叠加普通菜单图标的水平内边距。 筛选行 hover 是共享失焦灰,点击才保留主体蓝,移动到另一行同时保留蓝色选中行与灰色 hover 行,hover 不改变勾选。批量按钮上方使用滚动列表的 1pt 内侧矩形底边(Borders.color,深/浅 #26282C/#D1D3D9),不使用系统 Divider。 关闭时按来源保存非空查询,会话内每来源去重保留 50 条,All 重开恢复最后草稿并全选(包括空草稿);清空关闭后重开必须为空,不从非空历史回填,项目 reset 清除历史,侧栏查询保持独立。输入框清除按钮使用 16pt 槽位。结果文件名复用 Git 文件状态前景色,选中匹配片段保留金底黑字;被 Git 忽略的文件由 Core 批量 check-ignore 获取真实规则,包含 info/exclude、否定规则和已跟踪文件例外,按 Islands Dark/Light 的 #D69A6B/#8C4F00 着色;Git 不可用时保留未知,不按目录名猜测。右上角设置左侧的搜索图标与双 Shift 调用同一动作,提示快捷键,无工作区时禁用;浅深主题和宽窄窗口核对位置、hover 和点击。Windows 仅兼容可选 isIgnored 字段,ignored 前景色与此工具栏入口尚未同步。 打开搜索时激活并刷新惰性 Git 模块,将已归一化的 GitTreeStatusProjection 发布到当前搜索会话,未打开 Commit 也能得到未跟踪/修改状态色;工作区切换或关闭后不回写旧快照。 顶栏搜索使用 Community 原始 search@20x20 明暗 SVG,不放大 16pt 图标;与设置同用 LitheMainToolbarButtonStyle,放入 spacing=0 的同组工具栏,移除外层 9pt 间距和侧栏 37pt 槽位差异。 关闭搜索释放干净的暂存预览并撤销未完成打开;有未保存输入则保留为正式文档,项目替换仍显示时由替换面板继续持有并负责清理。 Text 预览沿用当前大小写/整词/正则选项,名称预览保持默认;生成名称索引扫描和增量更新均排除嵌套 linked worktree。 审核修复:Problems 与搜索共用或分别预览时,关闭搜索只释放搜索使用权,最后使用方退出才清理;待加载共享请求亦同。Text 只读预览用实际 Monaco nativeFind 显示大小写/整词/正则匹配而不抢焦点。搜索使用用户指定 Git且保持非交互。macOS 双 Shift 漏斗面板可编辑、应用并持久保存仅此窗口生效的排除表达式(*.log、**/.*/、.*、cache/),通用设置入口移除,侧栏搜索、项目替换和 Agent 补全不受影响;树与监听不隐藏;清空应用后重开仍为空并恢复范围,不同规则缓存随文件修改同步。Windows 共享 Rust 换行文件名仅 Unix 创建,保留全平台空格文件名测试;Windows 设置 UI 未同步。 全局搜索显式启用生成目录名称,Agent 的空 @ 与 @Name 都只用项目可见性,不受 *.log 搜索排除影响。cache/ 与 **/.*/ 必须在进入目录前剪枝,真实枚举探针不记录这些目录;直接上报排除后代的增量事件也不回填。连续修改排除规则只使搜索缓存失效,不重建项目树;失效屏障不被后续更新跳过,每根目录最多一个内容及一个名称缓存,旧分配在请求完成后释放;覆盖 32 次切换和更新。 排除规则改为漏斗列表首项(Actions 上方),与来源行共用复选框和 hover/点击样式,右侧原始 16pt 编辑图标打开由搜索窗口持有的独立编辑弹窗;漏斗不再内嵌文本框。应用按钮使用主题主色,应用保存并关闭、取消/Escape 丢弃未保存草稿但不关闭搜索;多行 Enter 换行。勾选开关独立记忆,取消勾选不删除规则,编辑已禁用规则不重新启用,重新勾选刷新当前搜索;来源批量按钮不改此开关。覆盖保存、取消、清空、关闭重开及禁用后重新启用,侧栏/替换/Agent 范围继续不受影响。 排除规则右侧编辑按钮按 Community ActionButton 小动作规格使用原始 16pt 明暗 edit.svg、22pt 点击和 hover 区、四边各 3pt 留白及 4pt 圆角,采用专用 ActionButton hover/pressed 主题色而非通用按钮底色;默认箭头光标,不影响行勾选。深浅主题检查普通、hover、按下、移出恢复及点击打开弹窗。 规则编辑输入框打开即获得原生焦点,点击弹窗空白保留光标/选区;复用共享多行输入框的单一外部焦点绑定与 2pt 焦点描边/向外 1pt 扩展,不能重复绑定导致焦点色或宽度脱节。深浅主题检查真实 firstResponder、空白点击不丢选区及两列边框像素,取消/应用和 Tab 导航仍可用。 排除规则行的灰色悬停和蓝色选中背景覆盖右侧编辑按钮区域,与来源行右边缘对齐;编辑按钮独立悬停,点击只编辑、不切换规则开关。 名称索引遇到不可访问或消失的后代目录时保留正常源码和 Text 结果,根目录错误及取消仍传播;搜索预览连续切换 A/B/C、清空结果或收起时按路径和请求标识释放旧持有,保留其他面板及未保存内容,旧请求晚返回不得误清新请求。 核对 src/Foo/src/Foo.swift 的路径回退以及 Agent @src 候选,文件名命中排在目录回退之前,路径命中不绘制文件名片段;Actions-only 不发送工作区请求,Text-only 不构建生成名称索引,Files-only 不构建正文索引,All 切换来源会重查并丢弃过期来源响应。2000 个生成文件冷索引回归核对构建种类、目录访问及驻留文件数。预览开启后单击只选择,辅助功能默认 Open、命名 Open 与 Return 可打开文件;VoiceOver 实机状态单独验收。 Unicode 名称连续匹配保持整串小写语义:i、i 加组合点及组合点本身均命中 İ.txt;补充非 BMP 前缀与希腊 sigma 回归,并核对原始 UTF-16 范围。 #1564:macOS 开启预览,在深浅主题下分别返回 199 和 200 条文件结果;列表大批结果到达后,文件列表与预览仍各在自己的面板内、互不重叠,鼠标选择、键盘滚动与 Return 打开保持有效;共享分隔容器覆盖横纵布局的空、单项及多项面板。 #1564 增量搜索:macOS 文件名候选先于正文/符号索引发布,首批立即发送,后续约100ms替换快照刷新并在来源结束flush;最终结果保留排名、上限及Git忽略状态。真实Rust桥接、取消、旧查询晚返回、reset及突发批次最终结果回归;深浅主题40/199/200条结果追加高排名候选后选择、预览与滚动保持稳定。输入防抖仍180ms,冷名称枚举及失效屏障仍需完成;Text随最终结果返回。Windows仍等待最终响应,未宣称流式展示验收。 #1564 自动分页:删除更多提示及每来源200条总上限,每来源50条、接近底部自动续查;首屏仍流式,后续整页去重追加并保持已加载页和动作顺序。深浅主题实际滚动加载257文件,保持非零像素偏移、选择和预览;Core四来源超过200、整页/空页耗尽、错误/跨查询游标拒绝。模块覆盖失败暂停、显式Retry、重复游标/无新增停止;取消与过期响应仍隔离。名称/符号每页扫描已有索引,只保留51个候选;实时索引游标前新增项需重查。Windows保留旧最终响应,未同步自动分页。 默认选择与主动选择分开:未进行鼠标/键盘导航时,Actions先到或首屏更优候选后到,预览和Enter跟随当前首项;主动选择后仍按ID保持,所选项消失才退回默认首项。原生窗口回归覆盖两种到达顺序并保留主动选择重排用例。 #1624:macOS 查询不等待内容预热;Core 名称和正文构建独立,Text 冷查询按文件清单匹配当前页。原生拖动右下角可缩放,左上角与输入不跳;Text 代码主行、路径次行。覆盖深浅主题、窄窗口、查询清空恢复、索引失效和取消;Windows 共享 Core 查询改善,原生缩放与两行呈现未同步,真实大项目延迟仍需验收。 中文界面操作搜索输入“切换终端”“显示或隐藏终端”及英文 Toggle Terminal 均命中同一动作,隐藏终端入口后执行可恢复;切回英文重查不保留旧中文标题。原始文案及当前语言文案一次交给 Core search.actions 匹配,保持候选顺序、插件自有标题原文及模块可用性。Windows 既有本地化命令搜索保留,尚未接入此 Core 匹配命令;真实完整弹窗验收待完成。 Windows 项目内容搜索使用 Core 连续游标,包含/排除规则在分页前执行;覆盖同文件跨页、多根切换、真实 UTF-16 命中范围和提供者批量读取。真实大项目与 WSL 产品验收待完成。 #2199:核对超过200条的同文件/多文件分页、文件折叠、未保存文本、范围过滤;设置16/32/64 MiB、恢复默认及外部冲突,确认查询/替换生效且不写安装目录。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -71,5 +75,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva 已接入 Core 文件名与文本搜索、按需分页、输入法保护、打开结果和共享递归监听;类、符号、操作、双击 Shift、结果高亮、预览、筛选、自动续页及完整 UI 对齐仍未完成。macOS 无头测试不替代两端实机验收。" + "notes": "Viva:All 合并正文与文件/符号/动作;删除500条总截断,继续按需分页。Core 增强空格分词、星号片段、路径缩写、跳字母缩写和文件名:行号,未宣称完整MinusculeMatcher等价。正文读取脏文档快照并使用可配置大小。未启动语言服务器的全工作区符号、外部库及符号链接仍由 #2199 跟踪;两端原生验收保持pending。" } diff --git a/shared/platform-feature-matrix/features/search-project.json b/shared/platform-feature-matrix/features/search-project.json index e512f94f26..340e3446ec 100644 --- a/shared/platform-feature-matrix/features/search-project.json +++ b/shared/platform-feature-matrix/features/search-project.json @@ -9,7 +9,11 @@ "evidence": [ "desktop/internal/workbench/search.go", "desktop/internal/workbench/search_test.go", - "desktop/internal/core/workspace.go" + "desktop/internal/core/workspace.go", + "desktop/internal/workbench/search_idea_test.go", + "desktop/internal/workbench/search_presentation.go", + "desktop/internal/workbench/search_scope_view.go", + "desktop/internal/workbench/search_visual_test.go" ] }, "windows": { @@ -18,11 +22,15 @@ "evidence": [ "desktop/internal/workbench/search.go", "desktop/internal/workbench/search_test.go", - "desktop/internal/core/workspace.go" + "desktop/internal/core/workspace.go", + "desktop/internal/workbench/search_idea_test.go", + "desktop/internal/workbench/search_presentation.go", + "desktop/internal/workbench/search_scope_view.go", + "desktop/internal/workbench/search_visual_test.go" ] }, "owner": "Search", - "verification": "使用同一项目和查询 fixture 对比命中路径、行号、列号和结果排序;在 macOS 深浅主题检查搜索框输入、焦点与失焦、工具按钮及文件类型图标;点击侧栏 Search 时第一个输入框不自动获得焦点,使用 Cmd+Shift+F 时仍获得焦点。 Search 查询与文件掩码、Database 连接搜索、Redis Key pattern 和 Nacos 配置/服务搜索均直接使用 Git Log 同源的全局唯一 LitheSearchFieldStyle;在深浅主题核对 36pt 外框、30pt 可见高度、4pt 圆角、1pt 常态边框、2pt 聚焦边框、3pt 外留白及 13pt 常规文字和提示色,确认无局部背景或原生边框叠加,并保留搜索、清除与键盘提交行为。 使用原生 NSHostingView 渲染验证共享 LitheSearchTextField 的占位文字在深浅主题均为 IDEA Component.infoForeground 对应的 #73767C、13pt 常规字重;空输入框单独绘制占位文字,避免 SwiftUI 原生 prompt 替换其颜色与字重,有内容时占位文字消失并保留原生编辑和主文字色。 中文输入法组词期间,即使绑定文本仍为空,共享 LitheSearchTextField 占位文字立即隐藏;取消组词或删空后恢复,确认中文后仍隐藏。原生 setMarkedText 回归覆盖明暗主题和两个输入框互不影响;保留焦点、键盘提交、搜索/过滤语义及占位字号颜色。原生背景观察视图卸载和移出窗口时清理通知,匹配当前窗口的字段编辑器及所属输入区域,不修改业务绑定。 共享搜索字段未聚焦时悬停立即显示文本编辑光标,离开或禁用时恢复箭头;保留中文组词、焦点及键盘动作。 macOS 项目树文件、目录、项目根和多选右键菜单均显示 Find in Files,调用已有项目范围搜索并聚焦查询框;验证编辑器选中文字预填与现有搜索规则。该菜单入口沿用整个项目范围。 在同一项目放入大量文件名含查询词的文件、GBK 与 UTF-16 文件、2–16 MiB 日志和 CRLF 文件,确认结果只有内容行、各文件都能命中、正则 `$` 在 CRLF 行尾生效,点击结果跳到匹配列。", + "verification": "使用同一项目和查询 fixture 对比命中路径、行号、列号和结果排序;在 macOS 深浅主题检查搜索框输入、焦点与失焦、工具按钮及文件类型图标;点击侧栏 Search 时第一个输入框不自动获得焦点,使用 Cmd+Shift+F 时仍获得焦点。 Search 查询与文件掩码、Database 连接搜索、Redis Key pattern 和 Nacos 配置/服务搜索均直接使用 Git Log 同源的全局唯一 LitheSearchFieldStyle;在深浅主题核对 36pt 外框、30pt 可见高度、4pt 圆角、1pt 常态边框、2pt 聚焦边框、3pt 外留白及 13pt 常规文字和提示色,确认无局部背景或原生边框叠加,并保留搜索、清除与键盘提交行为。 使用原生 NSHostingView 渲染验证共享 LitheSearchTextField 的占位文字在深浅主题均为 IDEA Component.infoForeground 对应的 #73767C、13pt 常规字重;空输入框单独绘制占位文字,避免 SwiftUI 原生 prompt 替换其颜色与字重,有内容时占位文字消失并保留原生编辑和主文字色。 中文输入法组词期间,即使绑定文本仍为空,共享 LitheSearchTextField 占位文字立即隐藏;取消组词或删空后恢复,确认中文后仍隐藏。原生 setMarkedText 回归覆盖明暗主题和两个输入框互不影响;保留焦点、键盘提交、搜索/过滤语义及占位字号颜色。原生背景观察视图卸载和移出窗口时清理通知,匹配当前窗口的字段编辑器及所属输入区域,不修改业务绑定。 共享搜索字段未聚焦时悬停立即显示文本编辑光标,离开或禁用时恢复箭头;保留中文组词、焦点及键盘动作。 macOS 项目树文件、目录、项目根和多选右键菜单均显示 Find in Files,调用已有项目范围搜索并聚焦查询框;验证编辑器选中文字预填与现有搜索规则。该菜单入口沿用整个项目范围。 在同一项目放入大量文件名含查询词的文件、GBK 与 UTF-16 文件、2–16 MiB 日志和 CRLF 文件,确认结果只有内容行、各文件都能命中、正则 `$` 在 CRLF 行尾生效,点击结果跳到匹配列。 #2199:核对超过200条的同文件/多文件分页、文件折叠、未保存文本、范围过滤;设置16/32/64 MiB、恢复默认及外部冲突,确认查询/替换生效且不写安装目录。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -45,5 +53,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva 已接入 Core 项目搜索、掩码与选项、结果跳转和递归监听增量刷新;结果只列内容行,文件名匹配不再占满 200 条上限;编辑器能打开的 GBK/GB18030、UTF-16、16 MiB 以内的文件和 CRLF 行尾都能搜到(#2198);预览换行、右键入口、列位置、完整视觉对齐及 Windows 整机验收仍待完成。macOS 无头界面和 Windows 监听组件测试不替代两端完整验收。" + "notes": "Viva:Core 内容搜索按50行自动续页,同文件跨页不漏行;结果按文件分组/折叠,计数明确为已加载匹配行与文件数。支持脏文档快照、项目/已加载模块/目录/自定义路径和glob范围、临时包含Git忽略文件;手动排除和结构隐藏仍保留。大小来自工具→搜索设置。完整总数、生成目录覆盖、符号链接跟随及两端实机/性能验收仍由 #2199 跟踪。" } diff --git a/shared/platform-feature-matrix/features/search-replace.json b/shared/platform-feature-matrix/features/search-replace.json index c34d3f7036..8bb339a409 100644 --- a/shared/platform-feature-matrix/features/search-replace.json +++ b/shared/platform-feature-matrix/features/search-replace.json @@ -12,7 +12,8 @@ ".agents/notes/implemented/feature/2026-11-08-viva-project-search.md", "desktop/internal/workbench/search_replace.go", "desktop/internal/workbench/search_replace_view.go", - "desktop/internal/workbench/search_replace_menu_test.go" + "desktop/internal/workbench/search_replace_menu_test.go", + "desktop/internal/workbench/search_idea_test.go" ] }, "windows": { @@ -24,11 +25,12 @@ ".agents/notes/implemented/feature/2026-11-08-viva-project-search.md", "desktop/internal/workbench/search_replace.go", "desktop/internal/workbench/search_replace_view.go", - "desktop/internal/workbench/search_replace_menu_test.go" + "desktop/internal/workbench/search_replace_menu_test.go", + "desktop/internal/workbench/search_idea_test.go" ] }, "owner": "Search", - "verification": "执行替换预览、确认替换和取消操作,确认未保存文件与异常文件不会被静默覆盖。 macOS 项目树文件、目录、项目根和多选右键菜单均显示 Replace in Files,打开已有项目范围替换面板;验证查询预填、预览、确认与取消流程,菜单点击本身不写入文件。该菜单入口沿用整个项目范围。 Windows 替换与内容搜索共享逐行匹配,覆盖整词、正则捕获、Unicode、缓冲区和磁盘身份冲突;WSL 写入前复查原文但尚无原子条件写。", + "verification": "执行替换预览、确认替换和取消操作,确认未保存文件与异常文件不会被静默覆盖。 macOS 项目树文件、目录、项目根和多选右键菜单均显示 Replace in Files,打开已有项目范围替换面板;验证查询预填、预览、确认与取消流程,菜单点击本身不写入文件。该菜单入口沿用整个项目范围。 Windows 替换与内容搜索共享逐行匹配,覆盖整词、正则捕获、Unicode、缓冲区和磁盘身份冲突;WSL 写入前复查原文但尚无原子条件写。 #2199:核对超过200条的同文件/多文件分页、文件折叠、未保存文本、范围过滤;设置16/32/64 MiB、恢复默认及外部冲突,确认查询/替换生效且不写安装目录。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -52,5 +54,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:Replace in Files 由 Core 根据文件和打开文档的未保存文本规划替换(workspace.replacePreview),用户确认预览后宿主应用;打开的文档在编辑器里作为一次可撤销编辑、由用户保存,关闭的文件重新读取、由 Core 替换(workspace.replaceText),仅在内容未变时写回;预览可取消。search_replace_menu_test.go 覆盖入口与预览。 替换预览按去掉 CRLF 行尾 \\r 的行匹配,写回时保留原换行符;按磁盘内容替换时只替换 2 MiB 以内的 UTF-8 文件,搜索能找到的 GBK、UTF-16 和更大的文件不进替换预览(#2199 跟进);有未保存修改的打开文档按编辑器内容替换,不受此限。" + "notes": "Viva:预览覆盖搜索支持的自动编码,按设置预算读取;确认后保留原编码、BOM和CRLF。磁盘预览绑定SHA-256身份,写前重读并条件写入;预览后打开的文档跳过,打开的文档按版本核对后进行可撤销编辑。覆盖GBK、UTF-16LE/BE BOM、UTF-8 BOM、Windows-1252与外部改动冲突。原生完整验收保持pending。" } diff --git a/shared/platform-feature-matrix/features/search-settings.json b/shared/platform-feature-matrix/features/search-settings.json new file mode 100644 index 0000000000..22abfad232 --- /dev/null +++ b/shared/platform-feature-matrix/features/search-settings.json @@ -0,0 +1,33 @@ +{ + "id": "search-settings", + "area": "搜索", + "group": "搜索与导航", + "capability": "搜索与替换文件大小设置", + "owner": "Search", + "verification": "打开工具→搜索回显真实search.json;确认打开不写文件,应用后回读并在搜索和替换生效;外部编辑后Apply拒绝且保留草稿,刷新重读,恢复默认;明暗主题中英文及两端原生验收。", + "notes": "共用Viva页面和Core解析,默认16 MiB、可设置1–64 MiB,替换缺省继承搜索;64 MiB是当前解码和原生I/O安全边界,未支持无限大小。偏好位于平台用户目录,不进入bundle。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/settingswindow/search_view.go", + "desktop/internal/settingswindow/search_view_test.go", + "desktop/internal/settingswindow/search_visual_test.go", + "desktop/internal/searchprefs/source.go", + "desktop/internal/searchprefs/source_test.go", + "desktop/internal/workbench/search_preferences.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/settingswindow/search_view.go", + "desktop/internal/settingswindow/search_view_test.go", + "desktop/internal/settingswindow/search_visual_test.go", + "desktop/internal/searchprefs/source.go", + "desktop/internal/searchprefs/source_test.go", + "desktop/internal/workbench/search_preferences.go" + ] + } +}