From 5406a5700297531d8ffaf6850bc7e24d503ad99b Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 20 Nov 2026 00:58:13 +0800 Subject: [PATCH 1/2] feat(search): finish IDEA search layout, counts and provider startup --- .../feature/2026-11-08-viva-project-search.md | 33 ++- desktop/internal/core/search_languages.go | 22 ++ .../internal/core/search_presentation_test.go | 51 ++++ desktop/internal/core/workspace.go | 26 ++- desktop/internal/core/workspace_replace.go | 2 + .../core/workspace_search_latency_test.go | 62 +++++ desktop/internal/i18n/shared.generated.go | 16 +- .../pluginservice/search_languages.go | 58 +++++ .../settingswindow/plugin_settings_model.go | 2 + .../settingswindow/plugin_settings_view.go | 16 +- .../settingswindow/source_settings_view.go | 12 +- desktop/internal/workbench/filetree.go | 2 + desktop/internal/workbench/filetree_watch.go | 7 + desktop/internal/workbench/pluginbackends.go | 1 + desktop/internal/workbench/plugins.go | 6 + desktop/internal/workbench/pluginsemantics.go | 6 + desktop/internal/workbench/search.go | 106 ++++++++- .../internal/workbench/search_everywhere.go | 27 ++- .../workbench/search_everywhere_lsp.go | 163 +++++++++++-- .../workbench/search_everywhere_view.go | 42 ++-- .../internal/workbench/search_idea_test.go | 217 ++++++++++++++++++ desktop/internal/workbench/search_replace.go | 1 + .../internal/workbench/search_scope_view.go | 2 +- desktop/internal/workbench/search_test.go | 14 +- desktop/internal/workbench/search_view.go | 62 +++-- .../internal/workbench/search_visual_test.go | 14 +- shared/i18n/locales/en-US.json | 10 +- shared/i18n/locales/zh-CN.json | 10 +- shared/i18n/messages.json | 60 ++++- .../features/search-global.json | 2 +- .../features/search-project.json | 2 +- 31 files changed, 943 insertions(+), 111 deletions(-) create mode 100644 desktop/internal/core/search_languages.go create mode 100644 desktop/internal/core/workspace_search_latency_test.go create mode 100644 desktop/internal/pluginservice/search_languages.go 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 41f8be2de3..2a2e38fbda 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 @@ -34,6 +34,16 @@ CRLF 行尾的 `\r` 不算行内容。 Core 解析的路径/glob 表达式;没有模块模型时不执行模块查询。包含 Git 忽略文件 是请求选项,不能绕过手动排除和结构隐藏。 +交互式项目分页与全局文本搜索使用同一冷查询策略:已有全文索引时复用,否则 +直接枚举文件并匹配当前页,不等所有文件建立三元组倒排表后才显示首屏。 +旧侧栏在首次查询时强制构建全文索引,导致同一查询比双 Shift 明显更慢; +不要把主动预热或旧同步消费者的索引构建放回交互式分页的必经路径。 +文件标题与命中行统一为24pt,文件名只在标题显示一次,命中行缩进并对齐 +行列号与正文。两种搜索结果的正文高亮均使用主题的13pt界面字体,避免与文件名 +切换字体;编辑器预览仍遵循编辑器自己的字体设置。 +全局搜索的类别称为“类型”,包含语言服务报告的类、枚举、接口和结构体, +“符号”保持其他声明;Go 等语言不再被 Java 的“类”文案误导。 + 宿主在 UI 线程捕获脏文档的不可变 rope 根,在后台生成文本交给 Core。快照加入 候选并替换磁盘文本;后续页复用同一快照,编辑变化取消并重查,查询不写盘。 全局搜索“全部”合并正文来源;名称匹配增加有序片段和低分跳字母匹配,但未完整 @@ -58,6 +68,8 @@ Core 解析的路径/glob 表达式;没有模块模型时不执行模块查询 - 一直复用现有索引而不接文件监听,会在外部编辑后产生静默漏报,不能采用。 - 每次按键并行启动新查询会积累索引构建任务,浪费资源并可能发布旧结果;采用 输入合并、取消和单查询串行。 +- 在冷分页之前强制建立全文索引会读取所有候选两次,增加首屏延迟和常驻倒排表; + 使用现成索引或文件清单直接匹配。低命中查询仍需读完可搜索文件,不保证常数时间。 - 项目搜索继续列出文件名匹配、只是排在内容行之后:Core 先收集文件名匹配,文件名 含查询词的文件一多就占满 200 条上限,内容行一条都不剩;IDE 的 Find in Files 也不列文件名,查文件名用全局搜索的“文件”。被否。 @@ -66,9 +78,23 @@ Core 解析的路径/glob 表达式;没有模块模型时不执行模块查询 结果显示后,收到文件变化事件会自动刷新;通知存在系统固有的投递延迟。 Linux 递归监听需要为目录分别注册,超出上限时会退回手动刷新。 -当前分组计数只覆盖已加载行。完整总数、生成目录的临时覆盖、无需先打开文件的 -全工作区类/符号索引、符号链接跟随、完整 IDEA 匹配质量与各平台实机验收仍由 -[#2199](https://github.com/1lck/Lithe-IDEA/issues/2199) 跟踪;不能把此次改进写成搜索已与 IDEA 对齐。 +首屏发布后独立统计全部文件、匹配行和出现次数;只返回当前加载文件的计数明细, +避免把全项目路径传到界面。计数显示进行中/失败与重试,查询、文件和脏文档变化 +立即取消旧统计,关闭项目等待统计退出再释放索引。 + +两个搜索入口提供包含 Git 忽略、插件生成目录和工作区内部符号链接的一次性选项。 +手动排除仍优先;外部链接不自动遍历,需要单独打开工作区根。Core 检查规范目标、 +祖先循环和目标排除,保留别名路径;替换按规范路径去重。原生目标事件使链接索引 +重建,保存使其失效;项目树可展开内部链接,已展开别名在目标事件到达时重新读取。 + +类型/符号搜索按已启用清单的文件选择器发现项目语言,再启动相关语言服务,不要求 +先打开文件。晚到的就绪事件只补问尚未查询的服务,保留其他服务答案;关闭面板、 +换查询会取消操作和截止计时器,过期排名结果不能覆盖新结果。语言语义完全来自 +标准 workspace/symbol,不维护 Core 语言解析器或第二份符号索引。类型包括 Class、 +Enum、Interface、Struct,其余作为符号。界面字体统一为13pt,侧栏24pt行高与图标列对齐。 + +实现覆盖 #2199 的列举场景,不声称完全等价于 IDEA 所有匹配质量和外部库能力。 +两端原生窗口和输入法验收仍须在目标平台完成,不能由无头截图替代。 名称匹配的宽松规则限于 Search Everywhere,通用 `rankNames` 保持原有边界匹配, 避免插件市场等现有候选列表出现额外结果。 @@ -80,6 +106,7 @@ Linux 递归监听需要为目录分别注册,超出上限时会退回手动 - `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`:全局文件名分页的索引复用与重建开销。 +- `scripts/desktop/desktop-go.sh test ./internal/core -run '^$' -bench '^BenchmarkWorkspaceColdContentSearch$' -benchtime=3x`:通过 `LITHE_SEARCH_BENCH_ROOT` 显式选择真实工作区,安装工作台同样的 Git 忽略策略后对比两种冷内容查询。 - `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/desktop/internal/core/search_languages.go b/desktop/internal/core/search_languages.go new file mode 100644 index 0000000000..1b3f9e2f83 --- /dev/null +++ b/desktop/internal/core/search_languages.go @@ -0,0 +1,22 @@ +package core + +import "context" + +// SearchLanguageSource contains selectors read from an enabled provider manifest. +type SearchLanguageSource struct { + LanguageID string `json:"languageId"` + FileExtensions []string `json:"fileExtensions,omitempty"` + FileNames []string `json:"fileNames,omitempty"` +} + +func (c *Client) SearchWorkspaceLanguages(ctx context.Context, root string, sources []SearchLanguageSource) ([]string, error) { + var result struct { + Languages []string `json:"languages"` + } + err := c.Execute(ctx, "workspace.search", struct { + Root string `json:"root"` + Query string `json:"query"` + LanguageSources []SearchLanguageSource `json:"languageSources"` + }{root, "", nonNil(sources)}, &result) + return result.Languages, err +} diff --git a/desktop/internal/core/search_presentation_test.go b/desktop/internal/core/search_presentation_test.go index 6ea7c1ef8d..4e1aa02f87 100644 --- a/desktop/internal/core/search_presentation_test.go +++ b/desktop/internal/core/search_presentation_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" "os" + "path/filepath" "reflect" "testing" "time" @@ -42,3 +43,53 @@ func TestSearchPreferencesAndPresentationSharedFixture(t *testing.T) { t.Fatalf("presentation %+v: %v", got, err) } } + +func TestSearchCountsAndLanguageDiscoverySharedFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("search/idea-search-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture map[string]json.RawMessage + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + for _, name := range []string{"completeCounts", "languageDiscovery"} { + t.Run(name, func(t *testing.T) { + var item struct { + Files map[string]string + Request json.RawMessage + Expected json.RawMessage + } + if err := json.Unmarshal(fixture[name], &item); err != nil { + t.Fatal(err) + } + root := t.TempDir() + for path, text := range item.Files { + file := filepath.Join(root, filepath.FromSlash(path)) + if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(file, []byte(text), 0600); err != nil { + t.Fatal(err) + } + } + var request map[string]any + if err := json.Unmarshal(item.Request, &request); err != nil { + t.Fatal(err) + } + request["root"] = root + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var got, want any + if err := NewClient().Execute(ctx, "workspace.search", request, &got); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(item.Expected, &want); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v, want %+v", got, want) + } + }) + } +} diff --git a/desktop/internal/core/workspace.go b/desktop/internal/core/workspace.go index 1bdc072211..6a47a21f41 100644 --- a/desktop/internal/core/workspace.go +++ b/desktop/internal/core/workspace.go @@ -263,6 +263,7 @@ type WorkspaceNode struct { // DirectoryListing is the visible children of one directory, directories first and then by // name, in the kernel's order. type DirectoryListing struct { + Linked bool `json:"linked"` // Path is relative to the project root; empty for the root. Path string `json:"path"` Children []WorkspaceNode `json:"children"` @@ -293,6 +294,7 @@ func (c *Client) ListDirectories(ctx context.Context, root string, paths []strin var response struct { Directories []struct { Path string `json:"path"` + Linked bool `json:"linked"` Children []rawWorkspaceNode `json:"children"` } `json:"directories"` } @@ -308,7 +310,7 @@ func (c *Client) ListDirectories(ctx context.Context, root string, paths []strin Leaf: child.IsDirectory && child.Children != nil && len(*child.Children) == 0, }) } - listings = append(listings, DirectoryListing{Path: d.Path, Children: children}) + listings = append(listings, DirectoryListing{Path: d.Path, Linked: d.Linked, Children: children}) } return listings, nil } @@ -325,6 +327,10 @@ type WorkspaceSearchRequest struct { ScopeExpression string `json:"scopeExpression,omitempty"` ScopePaths []string `json:"scopePaths,omitempty"` IncludeIgnored bool `json:"includeIgnored,omitempty"` + IncludeGenerated bool `json:"includeGenerated,omitempty"` + FollowSymlinks bool `json:"followSymlinks,omitempty"` + CountPaths []string `json:"countPaths,omitempty"` + CountOnly bool `json:"countOnly,omitempty"` MaxFileBytes uint64 `json:"maxFileBytes,omitempty"` TextOverrides map[string]string `json:"textOverrides,omitempty"` PageSize int `json:"pageSize,omitempty"` @@ -363,6 +369,22 @@ type WorkspaceSearchPage struct { NextCursor *string `json:"nextCursor"` } +// WorkspaceSearchCounts contains complete totals, independent of the loaded page. +type WorkspaceSearchCounts struct { + Files int `json:"files"` + Lines int `json:"lines"` + Occurrences int `json:"occurrences"` + FileOccurrences map[string]int `json:"fileOccurrences"` +} + +func (c *Client) CountWorkspaceSearch(ctx context.Context, request WorkspaceSearchRequest) (WorkspaceSearchCounts, error) { + request.CountOnly = true + request.Cursor = nil + var counts WorkspaceSearchCounts + err := c.Execute(ctx, "workspace.search", request, &counts) + return counts, err +} + type SearchPreferences struct { MaxFileBytes uint64 `json:"maxFileBytes"` ReplacementMaxFileBytes uint64 `json:"replacementMaxFileBytes"` @@ -409,6 +431,8 @@ type EverywhereSearchRequest struct { TextOverrides map[string]string `json:"textOverrides,omitempty"` ScopePaths []string `json:"scopePaths,omitempty"` IncludeIgnored bool `json:"includeIgnored,omitempty"` + IncludeGenerated bool `json:"includeGenerated,omitempty"` + FollowSymlinks bool `json:"followSymlinks,omitempty"` } type EverywhereSearchContext struct { diff --git a/desktop/internal/core/workspace_replace.go b/desktop/internal/core/workspace_replace.go index 2c4a2448ea..a99c0b0749 100644 --- a/desktop/internal/core/workspace_replace.go +++ b/desktop/internal/core/workspace_replace.go @@ -19,6 +19,8 @@ type WorkspaceReplaceRequest struct { ScopeExpression string `json:"scopeExpression,omitempty"` ScopePaths []string `json:"scopePaths,omitempty"` IncludeIgnored bool `json:"includeIgnored,omitempty"` + IncludeGenerated bool `json:"includeGenerated,omitempty"` + FollowSymlinks bool `json:"followSymlinks,omitempty"` MaxFileBytes uint64 `json:"maxFileBytes,omitempty"` } diff --git a/desktop/internal/core/workspace_search_latency_test.go b/desktop/internal/core/workspace_search_latency_test.go new file mode 100644 index 0000000000..8e85f2343f --- /dev/null +++ b/desktop/internal/core/workspace_search_latency_test.go @@ -0,0 +1,62 @@ +package core + +import ( + "context" + "os" + "testing" + "time" +) + +// BenchmarkWorkspaceColdContentSearch compares the sidebar and popup on the same real checkout. +// An explicit root avoids treating a small generated workspace as a large-project measurement. +func BenchmarkWorkspaceColdContentSearch(b *testing.B) { + root := os.Getenv("LITHE_SEARCH_BENCH_ROOT") + if root == "" { + b.Skip("set LITHE_SEARCH_BENCH_ROOT to a real workspace") + } + query := "LockOSThread" + client := NewClient() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + status, err := client.ConfigureIndexing(ctx, root, "search-latency-benchmark", IndexingPolicyOf(nil, true), false) + cancel() + if err != nil { + b.Fatal(err) + } + b.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := client.ReleaseIndexing(ctx, root, "search-latency-benchmark", status.Revision); err != nil { + b.Error(err) + } + }) + for _, popup := range []bool{false, true} { + name := "sidebar" + if popup { + name = "popup-text" + } + b.Run(name, func(b *testing.B) { + for b.Loop() { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + if err := client.InvalidateWorkspaceSearch(ctx, root); err != nil { + cancel() + b.Fatal(err) + } + var count int + var err error + if popup { + var page EverywhereSearchPage + page, err = client.SearchEverywherePage(ctx, EverywhereSearchRequest{Root: root, Query: query, PageSize: 50, ResultKinds: []string{"content"}, IncludeContentRanges: true, MaxFileBytes: 16 << 20}) + count = len(page.Matches) + } else { + var page WorkspaceSearchPage + page, err = client.SearchWorkspacePage(ctx, WorkspaceSearchRequest{Root: root, Query: query, PageSize: 50, IncludeContentRanges: true, MaxFileBytes: 16 << 20}) + count = len(page.Matches) + } + cancel() + if err != nil || count == 0 { + b.Fatalf("real search returned %d matches: %v", count, err) + } + } + }) + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 2217320205..9ff3e3e8d2 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -636,7 +636,6 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.errors.settingsFailed": "Could not open the settings window: {reason}", "desktop.everywhere.actions": "Actions", "desktop.everywhere.all": "All", - "desktop.everywhere.classes": "Classes", "desktop.everywhere.files": "Files", "desktop.everywhere.limit": "Showing the first 500 results. Narrow your search to see more.", "desktop.everywhere.more": "Load more", @@ -644,6 +643,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.everywhere.symbols": "Symbols", "desktop.everywhere.text": "Text", "desktop.everywhere.title": "Search Everywhere", + "desktop.everywhere.types": "Types", "desktop.everywhere.watchUnavailable": "Could not monitor project changes. Reopen search to refresh results.", "desktop.exit.body": "Closing will stop these programs started by Lithe:\n{processes}", "desktop.exit.cancel": "Cancel", @@ -1667,10 +1667,14 @@ var sharedCatalogs = map[string]map[string]string{ "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.countIncomplete": "Total unavailable", + "desktop.search.counting": "Counting all matches…", "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.followSymlinks": "Follow symbolic links", "desktop.search.group": "{path} ({count})", + "desktop.search.includeGenerated": "Include generated directories", "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.", @@ -1705,6 +1709,8 @@ var sharedCatalogs = map[string]map[string]string{ "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.symlinkHelp": "Only targets inside this project are searched; cycles are skipped.", + "desktop.search.totalCount": "{count} occurrences in {files} files", "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", @@ -3846,7 +3852,6 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.errors.settingsFailed": "无法打开设置窗口:{reason}", "desktop.everywhere.actions": "操作", "desktop.everywhere.all": "全部", - "desktop.everywhere.classes": "类", "desktop.everywhere.files": "文件", "desktop.everywhere.limit": "显示前 500 条结果。请缩小搜索范围以查看更多。", "desktop.everywhere.more": "加载更多", @@ -3854,6 +3859,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.everywhere.symbols": "符号", "desktop.everywhere.text": "文本", "desktop.everywhere.title": "全局搜索", + "desktop.everywhere.types": "类型", "desktop.everywhere.watchUnavailable": "无法监听项目变化。请重新打开搜索以刷新结果。", "desktop.exit.body": "关闭后将结束下列由 Lithe 启动的程序:\n{processes}", "desktop.exit.cancel": "取消", @@ -4877,10 +4883,14 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.runConfig.workingDirectoryPlaceholder": "工作区内的路径;留空使用默认目录", "desktop.search.collapseFile": "收起详情", "desktop.search.count": "{files} 个文件中有 {count} 行匹配", + "desktop.search.countIncomplete": "总数尚未统计完成", + "desktop.search.counting": "正在统计全部匹配…", "desktop.search.expandFile": "展开详情", "desktop.search.fileMaskPlaceholder": "文件掩码,例如 *.java、*.kt", "desktop.search.first200": "显示前 200 条结果。请缩小搜索范围以查看更多。", + "desktop.search.followSymlinks": "跟随符号链接", "desktop.search.group": "{path}({count})", + "desktop.search.includeGenerated": "包含生成目录", "desktop.search.includeIgnored": "包含 Git 忽略文件", "desktop.search.loadedCount": "已加载 {files} 个文件的 {count} 行匹配", "desktop.search.noModules": "没有可用的已导入模块。", @@ -4915,6 +4925,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.search.settings.search": "搜索文件上限", "desktop.search.settings.searchHelp": "搜索正文时允许读取的单个文件大小。文件名搜索不受此值影响。", "desktop.search.settings.title": "搜索", + "desktop.search.symlinkHelp": "仅搜索当前项目内的目标,并跳过循环链接。", + "desktop.search.totalCount": "{files} 个文件中有 {count} 处匹配", "desktop.search.watchUnavailable": "无法监听项目变化。请刷新搜索结果以检查更新。", "desktop.semantics.codeActionFailed": "无法应用该代码操作。", "desktop.semantics.codeActionOther": "操作", diff --git a/desktop/internal/pluginservice/search_languages.go b/desktop/internal/pluginservice/search_languages.go new file mode 100644 index 0000000000..65348e6d8e --- /dev/null +++ b/desktop/internal/pluginservice/search_languages.go @@ -0,0 +1,58 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" +) + +// SearchLanguageSources reads selectors of enabled language-server contributions. +// It does not load grammars, open source files or start unrelated servers. +func (s *Service) SearchLanguageSources(ctx context.Context) ([]core.SearchLanguageSource, error) { + entries, err := s.Manager.Installed() + if err != nil { + return nil, err + } + entries, err = s.selectInstalled(ctx, entries, false) + var failures []error + if err != nil { + failures = append(failures, err) + } + var sources []core.SearchLanguageSource + for _, entry := range entries { + manifest, err := readBounded(filepath.Join(entry.Installed.Path, pluginpkg.ManifestFile), MaxManifestBytes) + if err != nil { + failures = append(failures, fmt.Errorf("%s: %w", entry.Installed.ID, err)) + continue + } + var declaration struct { + Languages []struct { + ID string `json:"id"` + FileExtensions []string `json:"fileExtensions"` + FileNames []string `json:"fileNames"` + ProjectFileNames []string `json:"projectFileNames"` + } `json:"languages"` + LanguageServers []struct { + LanguageID string `json:"languageID"` + } `json:"languageServers"` + } + if err := json.Unmarshal(manifest, &declaration); err != nil { + failures = append(failures, fmt.Errorf("%s: %w", entry.Installed.ID, err)) + continue + } + for _, server := range declaration.LanguageServers { + for _, language := range declaration.Languages { + if server.LanguageID == language.ID { + sources = append(sources, core.SearchLanguageSource{LanguageID: language.ID, FileExtensions: language.FileExtensions, + FileNames: append(append([]string(nil), language.FileNames...), language.ProjectFileNames...)}) + } + } + } + } + return sources, errors.Join(failures...) +} diff --git a/desktop/internal/settingswindow/plugin_settings_model.go b/desktop/internal/settingswindow/plugin_settings_model.go index c675d06774..4ed75ded92 100644 --- a/desktop/internal/settingswindow/plugin_settings_model.go +++ b/desktop/internal/settingswindow/plugin_settings_model.go @@ -23,6 +23,8 @@ type pluginSettingControl struct { // text is the draft of a text, number or path row. text string input core.PluginSettingInput + // readOnly keeps native selection while a setting cannot be edited. + readOnly ui.Field // options are the indexes of an enumeration's options, the values of its select. options []int reset bool diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index 90ba3597b9..10a7c1a337 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -198,17 +198,6 @@ func (w *window) pluginSettingsListRow(row ui.ListRow, p *pluginSettingsForm, ha }) } -// readOnlyField shows value as a field that cannot be edited. Box.Disabled does not apply to -// a TextField in pinned Viva, so the field is the text it holds inside a frame, which -// assistive technology and the platform see as a read-only text field that takes no input. -func (w *window) readOnlyField(c ui.C, label, value string) { - ui.Row(c).Grow(1).MinWidth(0).Height(30).PadX(10).Border(1, w.pal.line).Radius(6).Items(ui.Center). - HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleTextField, Value: value, ReadOnly: true, Disabled: true}). - Children(func() { - ui.Text(c, value).FontSize(13).Color(w.pal.muted).Ellipsis() - }) -} - // readOnlyList shows a list value that cannot be edited one item per line, as the TextArea // shows it while it can be, so a read-only list is not cut down to its first item. func (w *window) readOnlyList(c ui.C, label, value string) { @@ -279,7 +268,10 @@ func (w *window) pluginSettingRow(c ui.C, index int, hasSource bool) { // Its options are listed under the line. default: if disabled { - w.readOnlyField(c, declaration.Title, control.text) + if control.readOnly.Text() != control.text { + control.readOnly.SetText(control.text) + } + ui.TextField(c, &control.readOnly, declaration.Title, declaration.Placeholder).ReadOnly(true).Grow(1).MinWidth(0).Height(30) } else { ui.TextField(c, &control.text, declaration.Title, declaration.Placeholder).Grow(1).MinWidth(0).Height(30) } diff --git a/desktop/internal/settingswindow/source_settings_view.go b/desktop/internal/settingswindow/source_settings_view.go index 396e4c0566..546c7380fd 100644 --- a/desktop/internal/settingswindow/source_settings_view.go +++ b/desktop/internal/settingswindow/source_settings_view.go @@ -20,6 +20,7 @@ import ( ) type sourceSettingControl struct { + readOnly ui.Field input core.SourceSettingInput base core.SourceSettingInput inherited core.SourceSettingInput @@ -527,7 +528,11 @@ func (w *window) sourceSettingsControl(c ui.C, p *sourceSettingsForm, source cor return i18n.SharedFormat(language, "desktop.sourceSettings.inherit", map[string]string{"value": value}) } if disabled { - w.readOnlyField(c, field.Title, label(control.selected)) + value := label(control.selected) + if control.readOnly.Text() != value { + control.readOnly.SetText(value) + } + ui.TextField(c, &control.readOnly, accessibleTitle, "").ReadOnly(true).Width(190).Height(30) return } if ui.Select(c, &control.selected, control.choices, label).Width(190).Label(accessibleTitle).Changed() { @@ -547,7 +552,10 @@ func (w *window) sourceSettingsControl(c ui.C, p *sourceSettingsForm, source cor if disabled && list { w.readOnlyList(c, field.Title, control.input.Text) } else if disabled { - w.readOnlyField(c, field.Title, control.input.Text) + if control.readOnly.Text() != control.input.Text { + control.readOnly.SetText(control.input.Text) + } + ui.TextField(c, &control.readOnly, accessibleTitle, "").ReadOnly(true).FillWidth().Height(30) } else if list { if ui.TextArea(c, &control.input.Text, field.Title, "").FillWidth().Height(100).Changed() { control.input.Inherit = false diff --git a/desktop/internal/workbench/filetree.go b/desktop/internal/workbench/filetree.go index 3fede411aa..f350d882f5 100644 --- a/desktop/internal/workbench/filetree.go +++ b/desktop/internal/workbench/filetree.go @@ -15,6 +15,7 @@ import ( // treeNode is a file or a folder of the project tree. A folder's children are listed by the // kernel the first time it is expanded. type treeNode struct { + linked bool // id identifies the node's row; it is never reused. id int // path is relative to the project root with "/" separators; empty for the root. @@ -283,6 +284,7 @@ func (a *App) pumpTreeListings(p *project) { continue } if listing, ok := byPath[path]; ok { + n.linked = listing.Linked t.replaceChildren(n, listing.Children) n.listed, n.empty = true, len(n.children) == 0 if n == t.root { diff --git a/desktop/internal/workbench/filetree_watch.go b/desktop/internal/workbench/filetree_watch.go index 61105cf854..6baec9c5eb 100644 --- a/desktop/internal/workbench/filetree_watch.go +++ b/desktop/internal/workbench/filetree_watch.go @@ -212,6 +212,13 @@ func (a *App) applyFilteredTreeEvents(p *project, names []string) { parent = treeParentPath(parent) } } + // Native recursive streams report physical target paths. Loaded linked listings + // must refresh too; Core revalidates their canonical boundary and cycles. + for name, node := range p.tree.byPath { + if node.linked && node.expanded { + selected[name] = struct{}{} + } + } paths := make([]string, 0, len(selected)) for name := range selected { paths = append(paths, name) diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index fc674a8553..840cb0e8b6 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -374,6 +374,7 @@ func (a *App) servePluginServer(server *pluginServer, ctx context.Context) { a.post(func(a *App) { if a.isCurrentPluginServer(server.session.PluginID, server) { a.resumeDeferredSemantics() + a.resumeEverywhereSymbols(server.project) if p := a.project; p != nil && p == server.project { for _, d := range p.docs.list { a.scheduleEditorActions(p, d) diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index dfaad87619..bac70f20b0 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -358,6 +358,12 @@ func (a *App) reloadPluginLanguages() { hidden := a.configureVisibility(ctx, entries, vcsPlugins) return func(a *App) { a.applyHiddenDirectories(hidden) + if p := a.project; p != nil && !p.everywhereSymbols.discovering { + p.everywhereSymbols.discoveryStarted = false + if a.everywhereView.open && everywhereShowsSymbols(p.everywhere.scope) { + a.discoverEverywhereLanguages(p) + } + } if commandsErr != nil { a.backgroundFailed("plugin_tool_commands", commandsErr) } diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index e5d6104e3c..ade0b329c8 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -821,6 +821,9 @@ func (a *App) applyServerFeatures(server *pluginServer, event core.BackendEvent) } // The features arrive after the documents opened: ask for the colors now. a.semanticTokensResume() + if server.features[featureWorkspaceSymbols] { + a.resumeEverywhereSymbols(server.project) + } } // scheduleAutoCompletion starts the debounce for one typed character. Each new @@ -942,6 +945,9 @@ func (a *App) semanticRequestStarted(pending *semanticPending, operation string, pending.operation = operation if err != nil { a.removePending(pending) + if pending.kind == pluginSemanticWorkspaceSymbols { + pending.project.everywhereSymbols.pending = removePendingEntry(pending.project.everywhereSymbols.pending, pending) + } a.settleMergeSide(pending.join, true, nil, false) if pending.kind == pluginSemanticCopyReference { a.applyReferenceSymbols(pending, core.BackendEvent{}, true) diff --git a/desktop/internal/workbench/search.go b/desktop/internal/workbench/search.go index 09269b5eab..2dad4c9592 100644 --- a/desktop/internal/workbench/search.go +++ b/desktop/internal/workbench/search.go @@ -21,7 +21,7 @@ var ( ) const ( - searchResultHeight = 52 + searchResultHeight = 24 searchMaxResults = 200 searchDebounce = 250 * time.Millisecond searchTimeout = 30 * time.Second @@ -40,9 +40,10 @@ var ( ) type searchQuery struct { - text, mask, scope string - matchCase, wholeWords, regex bool - includeIgnored bool + text, mask, scope string + matchCase, wholeWords, regex bool + includeIgnored bool + includeGenerated, followSymlinks bool } // searchView contains only controls and options; results belong to a project. @@ -51,6 +52,7 @@ type searchView struct { scopeModule string scope ui.Field includeIgnored bool + includeGenerated, followSymlinks bool query, mask ui.Field optionsOpen, matchCase, wholeWords, regex, focus bool // replace is the Replace in Files field, shown while replaceOpen. @@ -68,6 +70,7 @@ func (v *searchView) reset() { v.scope.SetText("") v.scopeMode, v.scopeModule = "project", "" v.includeIgnored = false + v.includeGenerated, v.followSymlinks = false, false v.replace.SetText("") v.replaceOpen = false v.optionsOpen, v.matchCase, v.wholeWords, v.regex, v.focus = false, false, false, false, false @@ -75,6 +78,11 @@ func (v *searchView) reset() { } type projectSearch struct { + counts *core.WorkspaceSearchCounts + countDone <-chan struct{} + countFailed bool + countRevision uint64 + countCancel context.CancelFunc request core.WorkspaceSearchRequest cursor *string next bool @@ -98,6 +106,11 @@ type projectSearch struct { } func (a *App) cancelProjectSearch(p *project) { + if p.search.countCancel != nil { + p.search.countCancel() + p.search.countCancel = nil + } + p.search.counts = nil p.search.generation++ p.search.presentationGeneration++ p.search.request = core.WorkspaceSearchRequest{} @@ -196,6 +209,12 @@ func (a *App) drainProjectSearchWatch(p *project, slot *documentWatch) { a.applyTreeRecursiveWatch(p, ready, watch != nil, err, events) } if changed { + if s.countCancel != nil { + s.countCancel() + s.countCancel = nil + } + s.counts = nil + s.countFailed = false s.generation++ if s.cancel != nil { s.cancel() @@ -217,6 +236,12 @@ func (a *App) updateProjectSearch(p *project, query searchQuery) { return } s.want = query + if s.countCancel != nil { + s.countCancel() + s.countCancel = nil + } + s.counts = nil + s.countFailed = false s.generation++ s.matches, s.failed = nil, false s.cursor, s.next = nil, false @@ -291,7 +316,8 @@ func (a *App) runProjectSearch(p *project) { 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} + ScopeExpression: query.scope, IncludeIgnored: query.includeIgnored, + IncludeGenerated: query.includeGenerated, FollowSymlinks: query.followSymlinks} s.request = request } else { request.Cursor = s.cursor @@ -347,6 +373,19 @@ func (a *App) runProjectSearch(p *project) { s.presentationGeneration++ } a.finishProjectSearch(p, generation, matches, err, full || len(paths) > 0) + if generation == s.generation && err == nil { + needsCounts := !next + for _, match := range matches[max(0, len(matches)-50):] { + if s.counts != nil { + if _, exists := s.counts.FileOccurrences[match.Path]; !exists { + needsCounts = true + } + } + } + if needsCounts { + a.countProjectSearch(p, request, generation) + } + } } }) } @@ -360,6 +399,56 @@ func (a *App) loadMoreProjectSearch(p *project) { a.runProjectSearch(p) } +// Count after publishing the first page so a complete scan cannot delay navigation. +func (a *App) countProjectSearch(p *project, request core.WorkspaceSearchRequest, generation uint64) { + if p.search.countCancel != nil { + p.search.countCancel() + } + p.search.countRevision++ + countRevision := p.search.countRevision + ctx, cancel := context.WithCancel(p.ctx) + p.search.countCancel = cancel + p.search.countFailed = false + finished := make(chan struct{}) + p.search.countDone = finished + // Only loaded headings cross the bridge; totals still cover the full query. + seen := map[string]bool{} + for _, match := range p.search.matches[max(0, len(p.search.matches)-50):] { + if !seen[match.Path] { + request.CountPaths = append(request.CountPaths, match.Path) + seen[match.Path] = true + } + } + a.background(p, searchTimeout, func(deadline context.Context) func(*App) { + defer close(finished) + defer cancel() + stop := context.AfterFunc(deadline, cancel) + defer stop() + counts, err := core.NewClient().CountWorkspaceSearch(ctx, request) + return func(a *App) { + if generation != p.search.generation || countRevision != p.search.countRevision { + return + } + p.search.countCancel = nil + if err != nil { + p.search.countFailed = true + if !errors.Is(err, context.Canceled) { + a.backgroundFailed("workspace_search_count", err) + } + return + } + if previous := p.search.counts; previous != nil { + for path, count := range previous.FileOccurrences { + if _, exists := counts.FileOccurrences[path]; !exists { + counts.FileOccurrences[path] = count + } + } + } + p.search.counts = &counts + } + }) +} + // 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 { @@ -385,6 +474,10 @@ func synchronizeSearchIndex(ctx context.Context, kernel Kernel, root string, ful // releaseProjectSearch drops Core's index after the project closes so switching // among projects does not retain every workspace inventory for the whole session. func (a *App) releaseProjectSearch(p *project) { + if p.search.countCancel != nil { + p.search.countCancel() + p.search.countCancel = nil + } if p.search.watch != nil { p.search.watch.close() p.search.watch = nil @@ -393,9 +486,10 @@ func (a *App) releaseProjectSearch(p *project) { return } kernel, root, sink, finished, everywhereFinished := a.kernel, p.root, a.logSink, p.search.done, p.everywhere.done + countFinished := p.search.countDone a.background(nil, kernelCallTimeout, func(ctx context.Context) func(*App) { var err error - for _, job := range []<-chan struct{}{finished, everywhereFinished} { + for _, job := range []<-chan struct{}{finished, everywhereFinished, countFinished} { if job == nil || err != nil { continue } diff --git a/desktop/internal/workbench/search_everywhere.go b/desktop/internal/workbench/search_everywhere.go index 1abc175039..bc7cee8d75 100644 --- a/desktop/internal/workbench/search_everywhere.go +++ b/desktop/internal/workbench/search_everywhere.go @@ -60,13 +60,15 @@ type everywhereView struct { hiddenKinds map[string]bool matchCase, wholeWords, regex bool // gesture is Core's double-Shift state (keymap.modifierGestureStep), opaque here. - gesture json.RawMessage + gesture json.RawMessage + includeIgnored, includeGenerated, followSymlinks bool } // everywhereOptions is what besides the query and the tab decides a search. type everywhereOptions struct { - kinds string - matchCase, wholeWords, regex bool + includeIgnored, includeGenerated, followSymlinks bool + kinds string + matchCase, wholeWords, regex bool } // effectiveScope is the tab the query is for: a query that starts with "/" lists @@ -107,7 +109,7 @@ func (v *everywhereView) resultKinds(scope int) []string { // options is the search options of a tab. func (v *everywhereView) options(scope int) everywhereOptions { - o := everywhereOptions{kinds: strings.Join(v.resultKinds(scope), ",")} + o := everywhereOptions{kinds: strings.Join(v.resultKinds(scope), ","), includeIgnored: v.includeIgnored, includeGenerated: v.includeGenerated, followSymlinks: v.followSymlinks} if scope == 5 { o.matchCase, o.wholeWords, o.regex = v.matchCase, v.wholeWords, v.regex } @@ -116,6 +118,9 @@ func (v *everywhereView) options(scope int) everywhereOptions { // filtered reports whether the current tab's filter differs from its default. func (v *everywhereView) filtered() bool { + if v.includeIgnored || v.includeGenerated || v.followSymlinks { + return true + } if v.scope == 5 { return v.matchCase || v.wholeWords || v.regex } @@ -173,6 +178,15 @@ func (a *App) closeEverywhere(p *project) { return } s := &p.everywhere + a.cancelEverywhereSymbols(p) + st := &p.everywhereSymbols + st.discoveryRevision++ + st.generation++ + if st.discoveryCancel != nil { + st.discoveryCancel() + st.discoveryCancel = nil + } + st.discoveryStarted, st.discovering = false, false s.generation++ s.query, s.loading, s.matches, s.cursor = "", false, nil, nil if s.cancel != nil { @@ -221,6 +235,7 @@ func (a *App) updateEverywhere(p *project, query string, scope int) { IncludeGeneratedFileNames: scope != 5, Context: &core.EverywhereSearchContext{OpenPaths: openPaths}, CaseSensitive: options.matchCase, WholeWords: options.wholeWords, RegularExpression: options.regex, IncludeContentRanges: scope == 5 || scope == 0, MaxFileBytes: a.searchPreferences.MaxFileBytes, + IncludeIgnored: options.includeIgnored, IncludeGenerated: options.includeGenerated, FollowSymlinks: options.followSymlinks, } s.loading = true if !s.watchAttached { @@ -280,6 +295,10 @@ func (a *App) applyEverywhereWatch(p *project, ready, available bool, err error, changed = true } if changed { + if !p.everywhereSymbols.discovering { + p.everywhereSymbols.discoveryStarted = false + a.discoverEverywhereLanguages(p) + } s.generation++ if s.cancel != nil { s.cancel() diff --git a/desktop/internal/workbench/search_everywhere_lsp.go b/desktop/internal/workbench/search_everywhere_lsp.go index a194c84c3a..04bbcee8e7 100644 --- a/desktop/internal/workbench/search_everywhere_lsp.go +++ b/desktop/internal/workbench/search_everywhere_lsp.go @@ -15,8 +15,8 @@ import ( // Search Everywhere also lists the symbols the project's language servers report through // workspace/symbol. Each server that declares workspaceSymbols is asked with the query, after the // query has settled; the answers are ranked by Core's workspace.rankNames and joined to the Core -// index's results on the Classes, Symbols and All tabs. A kind that is a class (LSP 5, 10, 11, 23) -// is listed as a class; the others as symbols. A match is removed again when the query changes. +// index's results on the Types, Symbols and All tabs. Type kinds (LSP 5, 10, 11, 23) +// are listed as types; the others as symbols. A match is removed again when the query changes. const ( // pluginSemanticWorkspaceSymbols is the operation, featureWorkspaceSymbols the feature a server @@ -30,24 +30,30 @@ const ( everywhereSymbolLimit = 1000 ) -// everywhereClassKinds are the LSP SymbolKind numbers listed on the Classes tab: Class, Enum, +// everywhereTypeKinds are the LSP SymbolKind numbers listed on the Types tab: Class, Enum, // Interface and Struct. -var everywhereClassKinds = map[int]bool{5: true, 10: true, 11: true, 23: true} +var everywhereTypeKinds = map[int]bool{5: true, 10: true, 11: true, 23: true} // everywhereSymbolState is the project's workspace/symbol query: its generation, the requests in // flight, the symbols answered so far and the ranked matches shown. type everywhereSymbolState struct { - generation uint64 - query string - cancel context.CancelFunc - pending []*semanticPending - items []core.WorkspaceSymbol - itemKeys map[string]bool - servers []string - ranked []core.WorkspaceSearchMatch + discoveryRevision uint64 + discoveryStarted bool + discovering bool + discoveryCancel context.CancelFunc + generation uint64 + query string + cancel context.CancelFunc + pending []*semanticPending + items []core.WorkspaceSymbol + itemKeys map[string]bool + servers []string + ranked []core.WorkspaceSearchMatch // lspKeys are the keys of the matches this state added to the Search Everywhere list, so // they can be taken out again before the list is rebuilt. - lspKeys map[string]bool + lspKeys map[string]bool + rankRevision uint64 + deadline *time.Timer } // everywhereMatchKey is the identity of a match for de-duplication: path, line and name. @@ -66,25 +72,56 @@ func (a *App) startEverywhereSymbols(p *project, query string, scope int) { a.cancelEverywhereSymbols(p) st.generation++ st.query = query - st.items, st.itemKeys, st.ranked = nil, nil, nil + st.items, st.itemKeys, st.ranked, st.servers = nil, nil, nil, nil if strings.TrimSpace(query) == "" || !everywhereShowsSymbols(scope) || a.plugins == nil { return } + a.discoverEverywhereLanguages(p) + a.requestEverywhereSymbols(p) +} + +// A newly ready server joins the current generation without discarding other answers. +func (a *App) requestEverywhereSymbols(p *project) { + st := &p.everywhereSymbols + query := st.query servers := a.workspaceSymbolServers(p) + servers = slices.DeleteFunc(servers, func(server *pluginServer) bool { return slices.Contains(st.servers, server.session.Session.ID) }) if len(servers) == 0 { return } - ctx, cancel := context.WithCancel(p.ctx) - st.cancel = cancel + if st.deadline != nil { + st.deadline.Stop() + } generation := st.generation - st.pending = nil + st.deadline = time.AfterFunc(searchTimeout, func() { + a.post(func(a *App) { + if a.project != p || st.generation != generation { + return + } + if len(st.pending) > 0 { + a.backgroundFailed("workspace_symbols", context.DeadlineExceeded) + } + a.cancelEverywhereSymbols(p) + }) + }) + ctx, cancel := context.WithTimeout(p.ctx, searchTimeout) + previousCancel := st.cancel + st.cancel = func() { + if previousCancel != nil { + previousCancel() + } + cancel() + } + var submitted []*semanticPending for _, server := range servers { + st.servers = append(st.servers, server.session.Session.ID) pending := &semanticPending{kind: pluginSemanticWorkspaceSymbols, generation: generation, project: p, server: server} st.pending = append(st.pending, pending) + submitted = append(submitted, pending) a.semantics.pending = append(a.semantics.pending, pending) } // The goroutine reads its own copy: the window thread keeps the list as answers arrive. - pendings := append([]*semanticPending(nil), st.pending...) + pendings := submitted plugins := a.plugins request := core.PluginSemanticRequest{Operation: pluginSemanticWorkspaceSymbols, Query: query} a.background(p, 0, func(context.Context) func(*App) { @@ -121,7 +158,60 @@ func (a *App) startEverywhereSymbols(p *project, query string, scope int) { }) } -// everywhereShowsSymbols reports whether a tab lists symbols: All, Classes and Symbols do. +// Discover providers once when symbol search is requested, before any file is opened. +func (a *App) discoverEverywhereLanguages(p *project) { + if p.everywhereSymbols.discoveryStarted || a.plugins == nil { + return + } + p.everywhereSymbols.discoveryRevision++ + revision := p.everywhereSymbols.discoveryRevision + p.everywhereSymbols.discoveryStarted = true + p.everywhereSymbols.discovering = true + ctx, cancel := context.WithCancel(p.ctx) + p.everywhereSymbols.discoveryCancel = cancel + plugins := a.plugins + a.background(p, searchTimeout, func(deadline context.Context) func(*App) { + defer cancel() + stop := context.AfterFunc(deadline, cancel) + defer stop() + sources, sourceErr := plugins.SearchLanguageSources(ctx) + languages, err := core.NewClient().SearchWorkspaceLanguages(ctx, p.root, sources) + return func(a *App) { + if a.project != p || p.everywhereSymbols.discoveryRevision != revision { + return + } + p.everywhereSymbols.discovering = false + p.everywhereSymbols.discoveryCancel = nil + if sourceErr != nil { + a.backgroundFailed("workspace_symbol_sources", sourceErr) + } + if err != nil { + p.everywhereSymbols.discoveryStarted = false + a.backgroundFailed("workspace_symbol_languages", err) + return + } + if !a.everywhereView.open || !everywhereShowsSymbols(p.everywhere.scope) { + p.everywhereSymbols.discoveryStarted = false + return + } + for _, language := range languages { + a.startPluginServer(language) + } + } + }) +} + +// A server that became available after the query must answer the current search too. +func (a *App) resumeEverywhereSymbols(p *project) { + if p == nil || a.project != p || !a.everywhereView.open || strings.TrimSpace(p.everywhere.query) == "" { + return + } + if everywhereShowsSymbols(p.everywhere.scope) { + a.requestEverywhereSymbols(p) + } +} + +// everywhereShowsSymbols reports whether a tab lists symbols: All, Types and Symbols do. func everywhereShowsSymbols(scope int) bool { return scope == 0 || scope == 1 || scope == 3 } @@ -130,12 +220,16 @@ func everywhereShowsSymbols(scope int) bool { // answer that arrives later is ignored because its pending entry is gone. func (a *App) cancelEverywhereSymbols(p *project) { st := &p.everywhereSymbols + if st.deadline != nil { + st.deadline.Stop() + st.deadline = nil + } if st.cancel != nil { st.cancel() st.cancel = nil } for _, pending := range st.pending { - a.removePending(pending) + a.cancelSemantic(pending) } st.pending = nil } @@ -206,11 +300,13 @@ func (a *App) applyWorkspaceSymbols(pending *semanticPending, event core.Backend candidates = append(candidates, core.RankCandidate{Name: item.Name, Path: path}) } items := append([]core.WorkspaceSymbol(nil), st.items...) + st.rankRevision++ + rankRevision := st.rankRevision query, generation, kernel := st.query, st.generation, a.kernel a.background(p, searchTimeout, func(ctx context.Context) func(*App) { order, err := kernel.RankNames(ctx, query, candidates) return func(a *App) { - if st.generation != generation { + if st.generation != generation || st.rankRevision != rankRevision { return } if err != nil { @@ -262,7 +358,7 @@ func everywhereRankedMatches(p *project, items []core.WorkspaceSymbol, order []i continue } kind := "symbol" - if everywhereClassKinds[item.Kind] { + if everywhereTypeKinds[item.Kind] { kind = "type" } name := item.Name @@ -342,3 +438,26 @@ func everywhereMatchOf(match core.WorkspaceSearchMatch) string { } return everywhereMatchKey(match.Path, line, name) } + +// Loading indicators reflect provider discovery, startup and pending symbol answers. +func (a *App) everywhereSymbolsLoading(p *project) bool { + if !everywhereShowsSymbols(p.everywhere.scope) { + return false + } + if p.everywhereSymbols.discovering || len(p.everywhereSymbols.pending) > 0 { + return true + } + a.pluginServerMu.Lock() + defer a.pluginServerMu.Unlock() + for _, preparation := range a.pluginServerPreparations { + if preparation.project == p { + return true + } + } + for _, server := range a.pluginServers { + if server != nil && server.project == p && server.state == "starting" { + return true + } + } + return false +} diff --git a/desktop/internal/workbench/search_everywhere_view.go b/desktop/internal/workbench/search_everywhere_view.go index fecdea8973..6483911d0b 100644 --- a/desktop/internal/workbench/search_everywhere_view.go +++ b/desktop/internal/workbench/search_everywhere_view.go @@ -73,7 +73,7 @@ func (a *App) everywherePopup(c ui.C) { return } switch { - case s.loading && len(s.matches) == 0: + case (s.loading || a.everywhereSymbolsLoading(p)) && len(s.matches) == 0: ui.Text(c, i18n.Shared(language, "quickOpen.searching")).Muted() case s.failed && len(s.matches) == 0: ui.Row(c).Gap(8).Items(ui.Center).Children(func() { @@ -100,7 +100,7 @@ func (a *App) everywhereScopes(c ui.C, p *project, language i18n.Language) { v := &a.everywhereView labels := [...]string{ i18n.Shared(language, "desktop.everywhere.all"), - i18n.Shared(language, "desktop.everywhere.classes"), + i18n.Shared(language, "desktop.everywhere.types"), i18n.Shared(language, "desktop.everywhere.files"), i18n.Shared(language, "desktop.everywhere.symbols"), i18n.Shared(language, "desktop.everywhere.actions"), @@ -132,7 +132,7 @@ func (a *App) everywhereScopes(c ui.C, p *project, language i18n.Language) { } a.focusEverywhere(p) } - if v.scope == 0 || v.scope == 5 { + if v.scope != everywhereScopeActions { a.everywhereFilter(c, p, language) } }) @@ -153,26 +153,33 @@ func (a *App) everywhereFilter(c ui.C, p *project, language i18n.Language) { if button.Clicked() { v.filterOpen = !v.filterOpen } - ui.PopoverWith(c, button, ui.PopoverSpec{Align: ui.End, Width: 230}, &v.filterOpen, func() { - if v.scope == 5 { - option := func(label, action string, value *bool) { - before := *value - ui.Checkbox(c, value, label) - if *value != before { - a.performed(action, surfaceButton) - } + ui.PopoverWith(c, button, ui.PopoverSpec{Align: ui.End, Width: 300}, &v.filterOpen, func() { + option := func(label, action string, value *bool) { + before := *value + ui.Checkbox(c, value, label) + if *value != before { + a.performed(action, surfaceButton) } + } + option(i18n.Shared(language, "desktop.search.includeIgnored"), "workspace.searchEverywhere.includeIgnored", &v.includeIgnored) + option(i18n.Shared(language, "desktop.search.includeGenerated"), "workspace.searchEverywhere.includeGenerated", &v.includeGenerated) + option(i18n.Shared(language, "desktop.search.followSymlinks"), "workspace.searchEverywhere.followSymlinks", &v.followSymlinks) + ui.Wrap(c, i18n.Shared(language, "desktop.search.symlinkHelp")).FontSize(11).Muted() + if v.scope == 5 { option(i18n.Shared(language, "native.matchCase"), "workspace.searchEverywhere.matchCase", &v.matchCase) option(i18n.Shared(language, "native.wholeWords"), "workspace.searchEverywhere.wholeWords", &v.wholeWords) option(i18n.Shared(language, "native.regularExpression"), "workspace.searchEverywhere.regularExpression", &v.regex) return } + if v.scope != 0 { + return + } if v.hiddenKinds == nil { v.hiddenKinds = map[string]bool{} } names := map[string]string{ "file": i18n.Shared(language, "desktop.everywhere.files"), - "type": i18n.Shared(language, "desktop.everywhere.classes"), + "type": i18n.Shared(language, "desktop.everywhere.types"), "symbol": i18n.Shared(language, "desktop.everywhere.symbols"), "content": i18n.Shared(language, "desktop.everywhere.text"), } @@ -309,7 +316,7 @@ func (a *App) everywhereRow(c ui.C, p *project, result core.WorkspaceSearchMatch if result.Kind == "content" { ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Children(func() { // With the line asked for, Core gives the matches in the preview it cut. - a.highlightedText(c, result.Preview, result.PreviewRanges, a.colors.Text, 12, true) + a.highlightedText(c, result.Preview, result.PreviewRanges, a.colors.Text, 13) location := name if result.Line != nil { location += ":" + strconv.Itoa(*result.Line) @@ -329,9 +336,9 @@ func (a *App) everywhereRow(c ui.C, p *project, result core.WorkspaceSearchMatch if selected { ranges = result.NameMatchRanges } - ui.Row(c).Shrink(0).Children(func() { a.highlightedText(c, label, ranges, a.colors.Text, 13, false) }) + ui.Row(c).Shrink(0).Children(func() { a.highlightedText(c, label, ranges, a.colors.Text, 13) }) if result.Kind != "file" && result.Line != nil { - ui.Text(c, ":"+strconv.Itoa(*result.Line)).Mono().FontSize(11).Color(a.colors.Subtle).Shrink(0) + ui.Text(c, ":"+strconv.Itoa(*result.Line)).FontSize(11).Color(a.colors.Subtle).Shrink(0) } if result.Kind != "file" { folder = result.Path @@ -344,16 +351,13 @@ func (a *App) everywhereRow(c ui.C, p *project, result core.WorkspaceSearchMatch // highlightedText declares text as runs, the ranges Core marked (UTF-16 units) on // the match color. Ranges that overlap, run backwards or leave the text are skipped. -func (a *App) highlightedText(c ui.C, text string, ranges []core.SearchNameRange, color gfx.Color, size float32, mono bool) { +func (a *App) highlightedText(c ui.C, text string, ranges []core.SearchNameRange, color gfx.Color, size float32) { spans := utf16Spans(text, ranges) declare := func(part string, marked bool) { if part == "" { return } t := ui.Text(c, part).FontSize(size).Color(color) - if mono { - t.Mono() - } if marked { t.Background(a.colors.Warning.WithAlpha(0.35)) } diff --git a/desktop/internal/workbench/search_idea_test.go b/desktop/internal/workbench/search_idea_test.go index e11f95dc5f..58044ff3ef 100644 --- a/desktop/internal/workbench/search_idea_test.go +++ b/desktop/internal/workbench/search_idea_test.go @@ -3,17 +3,118 @@ package workbench import ( "bytes" "context" + "encoding/json" "errors" + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" "os" "path/filepath" + "strings" "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" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" ) +func TestEverywhereTypesAndSymbolsUseSeparateTabs(t *testing.T) { + root := t.TempDir() + p := &project{root: root} + var symbols []core.WorkspaceSymbol + var order []int + for i, kind := range []int{5, 10, 11, 23, 6, 12, 13} { + uri, err := core.NewClient().PluginDocumentURI(context.Background(), filepath.Join(root, "source"+string(rune('a'+i))+".go"), "auto") + if err != nil { + t.Fatal(err) + } + symbols = append(symbols, core.WorkspaceSymbol{Name: "Search", Kind: kind, URI: uri}) + order = append(order, i) + } + ranked := everywhereRankedMatches(p, symbols, order) + for scope, want := range map[int]int{1: 4, 3: 3} { + p.everywhere = everywhereSearch{query: "Search", options: (&everywhereView{}).options(scope)} + p.everywhereSymbols = everywhereSymbolState{generation: 1, query: "Search", ranked: ranked} + (&App{}).everywhereSymbolsMerge(p) + if len(p.everywhere.matches) != want { + t.Fatalf("scope %d returned %d matches, want %d", scope, len(p.everywhere.matches), want) + } + for _, match := range p.everywhere.matches { + if match.Kind != p.everywhere.options.kinds { + t.Fatalf("scope %d includes another category: %+v", scope, match) + } + } + } +} + +func TestEverywhereContentUsesTheSameInterfaceFontAsFileNames(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.app.everywhereView.delay = 0 + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "LockOSThread.go"), []byte("runtime.LockOSThread()\n"), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + h.app.openEverywhere(h.app.project) + h.app.everywhereView.query.SetText("LockOSThread") + h.settleChain() + h.await("file and content results", func() bool { return !h.app.project.everywhere.loading && len(h.app.project.everywhere.matches) == 2 }) + h.settleChain() + seen := false + for _, label := range h.driver.Snapshot().Labels { + if label.Value == "runtime." || label.Value == "()" { + seen = true + if label.Mono || label.FontSize != 13 { + t.Fatalf("content uses a different font: %+v", label) + } + } + } + if !seen { + t.Fatal("content preview was not drawn") + } + if got := i18n.Shared(h.app.language(), "desktop.everywhere.types"); got != "类型" || !h.shows(got) { + t.Fatalf("type tab = %q", got) + } +} + +func TestProjectSearchUsesCompactGroupedRows(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.app.searchView.delay = 0 + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "main.go"), []byte("runtime.LockOSThread()\nruntime.LockOSThread()\n"), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + h.app.openFindInFiles(h.app.project, false) + h.app.searchView.query.SetText("LockOSThread") + h.settleChain() + h.await("grouped content results", func() bool { return !h.app.project.search.loading && len(h.app.project.search.presentation.Rows) == 3 }) + h.settleChain() + for _, name := range []string{"main.go", "main.go:1:9", "main.go:2:9"} { + hit := h.pageHit(name) + if hit.Bounds.Height > 28 { + t.Fatalf("%s row has excessive whitespace: %+v", name, hit.Bounds) + } + } + row := h.pageHit("main.go:1:9") + positions := 0 + for _, label := range h.driver.Snapshot().Labels { + if (label.Value == "1:9" || label.Value == "2:9") && label.Bounds.Y >= row.Bounds.Y { + positions++ + // The position starts at the file icon's column, after the heading chevron. + if label.Bounds.X != row.Bounds.X+31 { + t.Fatalf("position is indented beyond the file icon: %+v", label.Bounds) + } + } + } + if positions != 2 { + t.Fatalf("drawn positions = %d, want 2", positions) + } +} + func TestProjectSearchReadsUnsavedTextAndAllSearchesContents(t *testing.T) { h := newHarness(t, &testKernel{Client: core.NewClient()}) h.app.searchView.delay = 0 @@ -98,3 +199,119 @@ func TestProjectReplacePreservesOriginalEncodingAndRejectsChangedPreview(t *test }) } } + +func TestEverywhereStartsRelevantLanguageServerWithoutOpeningFiles(t *testing.T) { + kernel := &failingLSPPlanKernel{testKernel: &testKernel{Client: core.NewClient()}, msg: "fixture startup reached"} + h := newHarness(t, kernel) + plugins := t.TempDir() + raw, err := os.ReadFile(contractfixture.CoreFixture("plugins/settings-documents.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Manifest json.RawMessage `json:"manifest"` + } + if err := json.Unmarshal(raw, &fixture); err != nil { + t.Fatal(err) + } + dir := filepath.Join(plugins, "dev.example.settings", "1.0.0") + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "plugin.json"), fixture.Manifest, 0600); err != nil { + t.Fatal(err) + } + service, err := pluginservice.Open(kernel, store.At(t.TempDir()), plugins) + if err != nil { + t.Fatal(err) + } + if err := service.Manager.SetEnabled("dev.example.settings", true); err != nil { + t.Fatal(err) + } + h.app.plugins = service + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "source.fixture"), []byte("source\n"), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + p := h.app.project + h.app.openEverywhere(p) + h.app.everywhereView.scope = 1 + h.app.everywhereView.query.SetText("Search") + h.settleChain() + h.await("provider startup without open documents", func() bool { return h.app.pluginServerFailed["fixture"] != nil }) + if len(p.docs.list) != 0 { + t.Fatal("symbol discovery opened a source document") + } + if got := h.app.pluginServerFailed["fixture"].message; !strings.Contains(got, "fixture startup reached") { + t.Fatal(got) + } +} + +func TestEverywhereQueriesLateReadyServerAndSeparatesItsTypes(t *testing.T) { + kernel := &semanticTestKernel{testKernel: &testKernel{Client: core.NewClient()}} + h := newHarness(t, kernel) + h.open(t.TempDir()) + service, err := pluginservice.Open(kernel, h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + h.app.plugins = service + p := h.app.project + server := &pluginServer{session: &pluginservice.LanguageSession{PluginID: "dev.lithe.test.symbols", Session: pluginbackend.Session{ID: "symbols"}}, project: p, buildReady: true} + h.app.pluginServers = map[string]*pluginServer{"dev.lithe.test.symbols": server} + h.app.openEverywhere(p) + h.app.everywhereView.scope = 1 + h.app.everywhereView.query.SetText("Search") + h.settleChain() + if kernel.requestCount() != 0 { + t.Fatal("queried a server before it advertised workspace symbols") + } + h.app.applyServerFeatures(server, core.BackendEvent{Capabilities: []string{featureWorkspaceSymbols}}) + h.settleChain() + h.await("late ready workspace symbols request", func() bool { return kernel.requestCount() == 1 }) + h.app.applyServerFeatures(server, core.BackendEvent{Capabilities: []string{featureWorkspaceSymbols}}) + h.settleChain() + if kernel.requestCount() != 1 { + t.Fatal("duplicated current query on repeated feature event") + } + uri, err := core.NewClient().PluginDocumentURI(context.Background(), filepath.Join(p.root, "source.fixture"), "auto") + if err != nil { + t.Fatal(err) + } + result, err := json.Marshal(map[string]any{"symbols": []core.WorkspaceSymbol{{Name: "SearchType", Kind: 23, URI: uri}, {Name: "SearchFunction", Kind: 12, URI: uri}}}) + if err != nil { + t.Fatal(err) + } + h.app.applyPluginSemanticEvent(server, core.BackendEvent{Type: pluginSemanticCompleted, OperationID: "op-1", Method: pluginMethodWorkspaceSymbols, Result: result}) + h.settleChain() + h.await("ranked type result", func() bool { return len(p.everywhere.matches) == 1 }) + if p.everywhere.matches[0].Kind != "type" || len(p.docs.list) != 0 { + t.Fatal(p.everywhere.matches) + } + h.app.closeEverywhere(p) + delete(h.app.pluginServers, "dev.lithe.test.symbols") +} + +func TestProjectSearchCompleteCountsRefreshAfterFileChanges(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.app.searchView.delay = 0 + root := t.TempDir() + path := filepath.Join(root, "source.txt") + if err := os.WriteFile(path, []byte(strings.Repeat("needle needle\n", 75)), 0600); err != nil { + t.Fatal(err) + } + h.open(root) + p := h.app.project + h.app.openFindInFiles(p, false) + h.app.searchView.query.SetText("needle") + h.settleChain() + h.await("complete count beyond first page", func() bool { return p.search.counts != nil && p.search.counts.Occurrences == 150 }) + if p.search.counts.Files != 1 { + t.Fatal(p.search.counts) + } + if err := os.WriteFile(path, []byte("needle\n"), 0600); err != nil { + t.Fatal(err) + } + h.await("updated complete count", func() bool { return p.search.counts != nil && p.search.counts.Occurrences == 1 }) +} diff --git a/desktop/internal/workbench/search_replace.go b/desktop/internal/workbench/search_replace.go index 66f4f26dbc..73251dc067 100644 --- a/desktop/internal/workbench/search_replace.go +++ b/desktop/internal/workbench/search_replace.go @@ -71,6 +71,7 @@ func (a *App) previewProjectReplace(p *project, query searchQuery, replacement s Root: root, Query: query.text, Replacement: replacement, FileMask: query.mask, CaseSensitive: query.matchCase, WholeWords: query.wholeWords, RegularExpression: query.regex, TextOverrides: materializeSearchText(snapshots), MaxFileBytes: budget, ScopeExpression: query.scope, IncludeIgnored: query.includeIgnored, + IncludeGenerated: query.includeGenerated, FollowSymlinks: query.followSymlinks, }) return func(a *App) { if !r.open || r.query != query || r.replacement != replacement { diff --git a/desktop/internal/workbench/search_scope_view.go b/desktop/internal/workbench/search_scope_view.go index 59b989c971..934d2b9bb2 100644 --- a/desktop/internal/workbench/search_scope_view.go +++ b/desktop/internal/workbench/search_scope_view.go @@ -11,7 +11,7 @@ func (a *App) searchScopeControls(c ui.C, p *project, language i18n.Language) bo if v.scopeMode == "" { v.scopeMode = "project" } - ui.Column(c).FillWidth().PadX(10).Gap(4).Children(func() { + ui.Column(c).FillWidth().PadSides(0, 10, 6, 10).Gap(6).Children(func() { ui.Select(c.Part("scope-kind"), &v.scopeMode, []string{"project", "module", "directory", "custom"}, func(value string) string { switch value { case "module": diff --git a/desktop/internal/workbench/search_test.go b/desktop/internal/workbench/search_test.go index 37852958c3..086774c01d 100644 --- a/desktop/internal/workbench/search_test.go +++ b/desktop/internal/workbench/search_test.go @@ -513,15 +513,21 @@ func TestProjectSearchVirtualizesLoadedGroups(t *testing.T) { } return n } - if got := countRows(); got < 1 || got > 20 { - t.Fatalf("visible rows = %d", got) + first, last := h.app.searchView.list.Visible() + if got := countRows(); got < 1 || got > last-first+1 || got >= len(p.search.presentation.Rows) { + t.Fatalf("visible rows = %d, visible range = %d..%d, total = %d", got, first, last, len(p.search.presentation.Rows)) + } + if h.shows("file-199.txt (1)") { + t.Fatal("offscreen file heading was painted") } at := center(h.pageHit("file-000.txt").Bounds) if err := h.driver.Scroll(gfx.ScrollEvent{X: at.X, Y: at.Y, DeltaY: 20000, Precise: true}); err != nil { t.Fatal(err) } - if got := countRows(); got > 20 { - t.Fatalf("scrolled rows = %d", got) + h.settleChain() + first, last = h.app.searchView.list.Visible() + if got := countRows(); first == 0 || got < 1 || got > last-first+1 || got >= len(p.search.presentation.Rows) { + t.Fatalf("scrolled rows = %d, visible range = %d..%d", got, first, last) } if h.shows(i18n.Shared(h.app.language(), "desktop.search.first200")) { t.Fatal("obsolete total cap shown") diff --git a/desktop/internal/workbench/search_view.go b/desktop/internal/workbench/search_view.go index 68c63f0f7a..b7f279a0d7 100644 --- a/desktop/internal/workbench/search_view.go +++ b/desktop/internal/workbench/search_view.go @@ -22,7 +22,8 @@ func (a *App) searchPanel(c ui.C) { return } language := a.language() - 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} + query := searchQuery{text: v.query.Text(), mask: v.mask.Text(), scope: v.scope.Text(), includeIgnored: v.includeIgnored, + includeGenerated: v.includeGenerated, followSymlinks: v.followSymlinks, matchCase: v.matchCase, wholeWords: v.wholeWords, regex: v.regex} if v.focus { c.Canvas().RequestFocus(searchQueryID) v.focus = false @@ -94,7 +95,7 @@ func (a *App) searchOptions(c ui.C, language i18n.Language) { if button.Clicked() { v.optionsOpen = !v.optionsOpen } - ui.PopoverWith(c, button, ui.PopoverSpec{Align: ui.End, Width: 210}, &v.optionsOpen, func() { + ui.PopoverWith(c, button, ui.PopoverSpec{Align: ui.End, Width: 300}, &v.optionsOpen, func() { option := func(label, action string, value *bool) { before := *value ui.Checkbox(c, value, label) @@ -106,6 +107,9 @@ func (a *App) searchOptions(c ui.C, language i18n.Language) { 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) + option(i18n.Shared(language, "desktop.search.includeGenerated"), "workspace.search.includeGenerated", &v.includeGenerated) + option(i18n.Shared(language, "desktop.search.followSymlinks"), "workspace.search.followSymlinks", &v.followSymlinks) + ui.Wrap(c, i18n.Shared(language, "desktop.search.symlinkHelp")).FontSize(11).Muted() }) } @@ -120,7 +124,22 @@ func (a *App) searchResults(c ui.C, p *project, language i18n.Language) { 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) + if counts := p.search.counts; counts != nil { + summary = i18n.SharedFormat(language, "desktop.search.totalCount", map[string]string{ + "count": strconv.Itoa(counts.Occurrences), "files": strconv.Itoa(counts.Files)}) + } + ui.Row(c).FillWidth().PadX(11).Gap(8).Items(ui.Center).Children(func() { + ui.Text(c, summary).FontSize(12).Color(a.colors.Subtle) + if p.search.countCancel != nil { + ui.Text(c, i18n.Shared(language, "desktop.search.counting")).FontSize(11).Muted() + } + if p.search.countFailed { + ui.Text(c, i18n.Shared(language, "desktop.search.countIncomplete")).FontSize(11).Muted() + if ui.Button(c, i18n.Shared(language, "ui.retry")).Ghost().Clicked() { + c.After(func() { a.countProjectSearch(p, p.search.request, p.search.generation) }) + } + } + }) v.list.Label = func(i int) string { if rows[i].MatchIndex == nil { return rows[i].Path @@ -136,8 +155,20 @@ func (a *App) searchResults(c ui.C, p *project, language i18n.Language) { 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() + ui.Icon(row.C, icon).Size(14, 14).Shrink(0) + native := filepath.FromSlash(item.Path) + name, folder := filepath.Base(native), filepath.Dir(native) + ui.Icon(row.C, fileicons.ForFile(name, a.colors.Dark)).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) + count := item.Count + if p.search.counts != nil { + if complete, ok := p.search.counts.FileOccurrences[item.Path]; ok { + count = complete + } + } + ui.Text(row.C, i18n.SharedFormat(language, "desktop.search.group", map[string]string{"path": name, "count": strconv.Itoa(count)})).FontSize(13).Shrink(1).MinWidth(0).Ellipsis() + if folder != "." { + ui.Text(row.C, filepath.ToSlash(folder)).FontSize(11).Color(a.colors.Subtle).Shrink(1).MinWidth(0).Ellipsis() + } }) if row.Element.Clicked() { p.search.collapsed[item.Path] = !p.search.collapsed[item.Path] @@ -146,21 +177,12 @@ func (a *App) searchResults(c ui.C, p *project, language i18n.Language) { 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) - }) + row.Element.FillWidth().Height(searchResultHeight).PadSides(0, 11, 0, 31).Items(ui.Center).Gap(8).Children(func() { + if result.Line != nil { + ui.Text(row.C, strings.TrimPrefix(searchLinePosition(result), ":")).Width(36).Shrink(0).FontSize(11).Color(a.colors.Subtle) + } + ui.Row(row.C).Grow(1).Shrink(1).MinWidth(0).Clip().Children(func() { + a.highlightedText(row.C, result.Preview, result.PreviewRanges, a.colors.Text, 13) }) }) if row.Element.Clicked() { diff --git a/desktop/internal/workbench/search_visual_test.go b/desktop/internal/workbench/search_visual_test.go index bd430a4532..82a79e5e6d 100644 --- a/desktop/internal/workbench/search_visual_test.go +++ b/desktop/internal/workbench/search_visual_test.go @@ -28,7 +28,10 @@ func TestVisualSearchResults(t *testing.T) { 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"} { + for name, text := range map[string]string{"search-notes.txt": "Search results\nSearch in unsaved documents\n", "docs/guide.txt": "Search across the project\n"} { + if err := os.MkdirAll(filepath.Dir(filepath.Join(root, name)), 0755); err != nil { + t.Fatal(err) + } if err := os.WriteFile(filepath.Join(root, name), []byte(text), 0600); err != nil { t.Fatal(err) } @@ -50,13 +53,20 @@ func TestVisualSearchResults(t *testing.T) { 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 + return !p.search.loading && len(p.search.matches) == 3 && len(p.search.presentation.Rows) == 5 && p.search.counts != nil }) 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.searchView.optionsOpen = true + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "search-options-"+language+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + h.app.searchView.optionsOpen = false 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 }) diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index bebb98c1e0..cfbd14bd03 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1005,7 +1005,6 @@ "desktop.errors.settingsFailed": "Could not open the settings window: {reason}", "desktop.everywhere.actions": "Actions", "desktop.everywhere.all": "All", - "desktop.everywhere.classes": "Classes", "desktop.everywhere.files": "Files", "desktop.everywhere.limit": "Showing the first 500 results. Narrow your search to see more.", "desktop.everywhere.more": "Load more", @@ -11661,7 +11660,14 @@ "desktop.toolchains.layerPinned": "Pinned", "desktop.toolchains.layerProject": "Project", "desktop.toolchains.layerGlobal": "Global", - "desktop.toolchains.layerAutomatic": "Automatic" + "desktop.toolchains.layerAutomatic": "Automatic", + "desktop.everywhere.types": "Types", + "desktop.search.countIncomplete": "Total unavailable", + "desktop.search.counting": "Counting all matches…", + "desktop.search.followSymlinks": "Follow symbolic links", + "desktop.search.includeGenerated": "Include generated directories", + "desktop.search.symlinkHelp": "Only targets inside this project are searched; cycles are skipped.", + "desktop.search.totalCount": "{count} occurrences in {files} files" }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index e8118bc996..f576c50fcf 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1005,7 +1005,6 @@ "desktop.errors.settingsFailed": "无法打开设置窗口:{reason}", "desktop.everywhere.actions": "操作", "desktop.everywhere.all": "全部", - "desktop.everywhere.classes": "类", "desktop.everywhere.files": "文件", "desktop.everywhere.limit": "显示前 500 条结果。请缩小搜索范围以查看更多。", "desktop.everywhere.more": "加载更多", @@ -11661,7 +11660,14 @@ "desktop.toolchains.layerPinned": "已固定", "desktop.toolchains.layerProject": "项目环境", "desktop.toolchains.layerGlobal": "全局默认", - "desktop.toolchains.layerAutomatic": "自动发现" + "desktop.toolchains.layerAutomatic": "自动发现", + "desktop.everywhere.types": "类型", + "desktop.search.countIncomplete": "总数尚未统计完成", + "desktop.search.counting": "正在统计全部匹配…", + "desktop.search.followSymlinks": "跟随符号链接", + "desktop.search.includeGenerated": "包含生成目录", + "desktop.search.symlinkHelp": "仅搜索当前项目内的目标,并跳过循环链接。", + "desktop.search.totalCount": "{files} 个文件中有 {count} 处匹配" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 34037c4ba1..09c1aecb0a 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -9459,13 +9459,6 @@ "desktop" ] }, - { - "id": "desktop.everywhere.classes", - "description": "Classes tab in global search.", - "platforms": [ - "desktop" - ] - }, { "id": "desktop.everywhere.files", "description": "Files tab in global search.", @@ -110012,6 +110005,59 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.everywhere.types", + "description": "Types tab in global search (classes, interfaces, structs and enums).", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.countIncomplete", + "description": "Workspace search complete-count status", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.counting", + "description": "Workspace search complete-count status", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.followSymlinks", + "description": "Desktop project search options and complete totals", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.includeGenerated", + "description": "Desktop project search options and complete totals", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.symlinkHelp", + "description": "Desktop project search options and complete totals", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.search.totalCount", + "description": "Desktop project search options and complete totals", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string", + "files": "string" + } } ] } diff --git a/shared/platform-feature-matrix/features/search-global.json b/shared/platform-feature-matrix/features/search-global.json index f5bca0813f..be56124b50 100644 --- a/shared/platform-feature-matrix/features/search-global.json +++ b/shared/platform-feature-matrix/features/search-global.json @@ -75,5 +75,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:All 合并正文与文件/符号/动作;删除500条总截断,继续按需分页。Core 增强空格分词、星号片段、路径缩写、跳字母缩写和文件名:行号,未宣称完整MinusculeMatcher等价。正文读取脏文档快照并使用可配置大小。未启动语言服务器的全工作区符号、外部库及符号链接仍由 #2199 跟踪;两端原生验收保持pending。" + "notes": "Viva:All 合并正文与文件/符号/动作;删除500条总截断,继续按需分页。Core 增强空格分词、星号片段、路径缩写、跳字母缩写和文件名:行号,未宣称完整MinusculeMatcher等价。正文读取脏文档快照并使用可配置大小。外部库语义由语言服务提供;两端原生验收保持pending。 搜索结果的文件名、类型、符号与正文预览统一使用13pt界面字体;分类和来源筛选改为“类型 / Types”,包含Class、Enum、Interface、Struct,符号保持其他声明。回归验证两个来源分离、匹配片段仍用同一字体。 #2199补齐:首屏之后异步完整计数与已加载文件明细、计数失败重试;按清单选择器启动相关LSP并接入晚就绪符号查询;临时生成目录/内部链接选项,手动排除和外部链接边界保留,循环检测、目标监听重建和项目树别名刷新。验证使用真实文件和通用契约fixture,两端原生窗口仍pending。" } diff --git a/shared/platform-feature-matrix/features/search-project.json b/shared/platform-feature-matrix/features/search-project.json index 340e3446ec..8e9c1819c9 100644 --- a/shared/platform-feature-matrix/features/search-project.json +++ b/shared/platform-feature-matrix/features/search-project.json @@ -53,5 +53,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:Core 内容搜索按50行自动续页,同文件跨页不漏行;结果按文件分组/折叠,计数明确为已加载匹配行与文件数。支持脏文档快照、项目/已加载模块/目录/自定义路径和glob范围、临时包含Git忽略文件;手动排除和结构隐藏仍保留。大小来自工具→搜索设置。完整总数、生成目录覆盖、符号链接跟随及两端实机/性能验收仍由 #2199 跟踪。" + "notes": "Viva:Core 内容搜索按50行自动续页,同文件跨页不漏行;结果按文件分组/折叠,计数明确为已加载匹配行与文件数。支持脏文档快照、项目/已加载模块/目录/自定义路径和glob范围、临时包含Git忽略文件;手动排除和结构隐藏仍保留。大小来自工具→搜索设置。两端实机验收仍待完成。冷分页查询复用现成全文索引或直接扫描文件清单,不先建全文三元组索引。文件标题和命中行统一24pt,标题显示文件名/数量/次要目录,命中行从文件图标列显示左对齐的行列号与正文,复用13pt界面字体;检查明暗、中英文、折叠、滚动与跳转。 #2199补齐:首屏之后异步完整计数与已加载文件明细、计数失败重试;按清单选择器启动相关LSP并接入晚就绪符号查询;临时生成目录/内部链接选项,手动排除和外部链接边界保留,循环检测、目标监听重建和项目树别名刷新。验证使用真实文件和通用契约fixture,两端原生窗口仍pending。" } From 99bb6e1e43a8ac102e96822f572b7c2d319e6d0d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 20 Nov 2026 01:00:55 +0800 Subject: [PATCH 2/2] build(search): pin completed Core and retain current Viva baseline --- .../settingswindow/plugin_settings_model.go | 2 -- .../settingswindow/plugin_settings_view.go | 16 ++++++++++++---- .../settingswindow/source_settings_view.go | 12 ++---------- scripts/desktop/build-desktop-core.sh | 2 +- 4 files changed, 15 insertions(+), 17 deletions(-) diff --git a/desktop/internal/settingswindow/plugin_settings_model.go b/desktop/internal/settingswindow/plugin_settings_model.go index 4ed75ded92..c675d06774 100644 --- a/desktop/internal/settingswindow/plugin_settings_model.go +++ b/desktop/internal/settingswindow/plugin_settings_model.go @@ -23,8 +23,6 @@ type pluginSettingControl struct { // text is the draft of a text, number or path row. text string input core.PluginSettingInput - // readOnly keeps native selection while a setting cannot be edited. - readOnly ui.Field // options are the indexes of an enumeration's options, the values of its select. options []int reset bool diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index 10a7c1a337..90ba3597b9 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -198,6 +198,17 @@ func (w *window) pluginSettingsListRow(row ui.ListRow, p *pluginSettingsForm, ha }) } +// readOnlyField shows value as a field that cannot be edited. Box.Disabled does not apply to +// a TextField in pinned Viva, so the field is the text it holds inside a frame, which +// assistive technology and the platform see as a read-only text field that takes no input. +func (w *window) readOnlyField(c ui.C, label, value string) { + ui.Row(c).Grow(1).MinWidth(0).Height(30).PadX(10).Border(1, w.pal.line).Radius(6).Items(ui.Center). + HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleTextField, Value: value, ReadOnly: true, Disabled: true}). + Children(func() { + ui.Text(c, value).FontSize(13).Color(w.pal.muted).Ellipsis() + }) +} + // readOnlyList shows a list value that cannot be edited one item per line, as the TextArea // shows it while it can be, so a read-only list is not cut down to its first item. func (w *window) readOnlyList(c ui.C, label, value string) { @@ -268,10 +279,7 @@ func (w *window) pluginSettingRow(c ui.C, index int, hasSource bool) { // Its options are listed under the line. default: if disabled { - if control.readOnly.Text() != control.text { - control.readOnly.SetText(control.text) - } - ui.TextField(c, &control.readOnly, declaration.Title, declaration.Placeholder).ReadOnly(true).Grow(1).MinWidth(0).Height(30) + w.readOnlyField(c, declaration.Title, control.text) } else { ui.TextField(c, &control.text, declaration.Title, declaration.Placeholder).Grow(1).MinWidth(0).Height(30) } diff --git a/desktop/internal/settingswindow/source_settings_view.go b/desktop/internal/settingswindow/source_settings_view.go index 546c7380fd..396e4c0566 100644 --- a/desktop/internal/settingswindow/source_settings_view.go +++ b/desktop/internal/settingswindow/source_settings_view.go @@ -20,7 +20,6 @@ import ( ) type sourceSettingControl struct { - readOnly ui.Field input core.SourceSettingInput base core.SourceSettingInput inherited core.SourceSettingInput @@ -528,11 +527,7 @@ func (w *window) sourceSettingsControl(c ui.C, p *sourceSettingsForm, source cor return i18n.SharedFormat(language, "desktop.sourceSettings.inherit", map[string]string{"value": value}) } if disabled { - value := label(control.selected) - if control.readOnly.Text() != value { - control.readOnly.SetText(value) - } - ui.TextField(c, &control.readOnly, accessibleTitle, "").ReadOnly(true).Width(190).Height(30) + w.readOnlyField(c, field.Title, label(control.selected)) return } if ui.Select(c, &control.selected, control.choices, label).Width(190).Label(accessibleTitle).Changed() { @@ -552,10 +547,7 @@ func (w *window) sourceSettingsControl(c ui.C, p *sourceSettingsForm, source cor if disabled && list { w.readOnlyList(c, field.Title, control.input.Text) } else if disabled { - if control.readOnly.Text() != control.input.Text { - control.readOnly.SetText(control.input.Text) - } - ui.TextField(c, &control.readOnly, accessibleTitle, "").ReadOnly(true).FillWidth().Height(30) + w.readOnlyField(c, field.Title, control.input.Text) } else if list { if ui.TextArea(c, &control.input.Text, field.Title, "").FillWidth().Height(100).Changed() { control.input.Inherit = false diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 87c4d9ca0c..37f78c3a58 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -286,7 +286,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # rows), #13, #8, #7, #6 and #4. # 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" +PINNED_CORE_REVISION="77aa46ab1f5357e64ea5ba7e25fe3f2184504518" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in