diff --git a/desktop/internal/core/references.go b/desktop/internal/core/references.go new file mode 100644 index 0000000000..d0e7918028 --- /dev/null +++ b/desktop/internal/core/references.go @@ -0,0 +1,116 @@ +package core + +import "context" + +// ReferenceLocation is one location of a Find Usages answer as Core groups it. +type ReferenceLocation struct { + // FileKey is the file's identity under the platform's path equality: the path of a local + // file, or the URI of a location that is not one. + FileKey string `json:"fileKey"` + // DisplayPath is the path shown to the user, with / separators, relative to the project for + // a file in it. It decides the file order. + DisplayPath string `json:"displayPath"` + // Line and Column are the zero-based start, the column in UTF-16 units. + Line int `json:"line"` + Column int `json:"column"` +} + +// ReferencesQuery asks Core to lay the References tool window out: the locations, the file +// nodes the user closed (by FileKey), whether the Usages node is closed, and the selected key. +type ReferencesQuery struct { + Locations []ReferenceLocation `json:"locations"` + RootCollapsed bool `json:"rootCollapsed,omitempty"` + Collapsed []string `json:"collapsed,omitempty"` + Selected string `json:"selected,omitempty"` +} + +// ReferenceGroup is the usages in one file. +type ReferenceGroup struct { + // Key is the key of the file's row. + Key string `json:"key"` + FileKey string `json:"fileKey"` + DisplayPath string `json:"displayPath"` + // Name and Folder are DisplayPath's last segment and the rest; Folder is empty at the root. + Name string `json:"name"` + Folder string `json:"folder"` + // Indices point into the query's locations, in display order. + Indices []int `json:"indices"` +} + +// The kinds of a References row. +const ( + ReferenceRowRoot = "root" + ReferenceRowFile = "file" + ReferenceRowUsage = "usage" +) + +// ReferenceRow is a row of the References tree that shows. +type ReferenceRow struct { + // Key stays the row's while the nodes above it open and close. + Key string `json:"key"` + Kind string `json:"kind"` + Depth int `json:"depth"` + // Expanded is whether a node's children show; nil on a usage. + Expanded *bool `json:"expanded,omitempty"` + // Group is the group of a file or usage row. + Group *int `json:"group,omitempty"` + // Shows is the location the row previews and opens: the usage itself or a node's first. + Shows int `json:"shows"` + // Previous and Next are the usages before and after the row in the tree's order, counting + // the usages under closed nodes; nil at either end. + Previous *int `json:"previous,omitempty"` + Next *int `json:"next,omitempty"` +} + +// ReferencesResult is the References tree Core laid out. +type ReferencesResult struct { + Groups []ReferenceGroup `json:"groups"` + Rows []ReferenceRow `json:"rows"` + // Selected is the selected row's key, always one of Rows, and SelectedRow its place; both + // are absent when Rows is empty. + Selected string `json:"selected,omitempty"` + SelectedRow *int `json:"selectedRow,omitempty"` +} + +// ReferenceUsageLine is a usage and the text of the line it starts on, by index. +type ReferenceUsageLine struct { + Text int `json:"text"` + Line int `json:"line"` + Column int `json:"column"` + EndLine int `json:"endLine"` + EndColumn int `json:"endColumn"` +} + +// ReferenceLinesRequest is the distinct texts of the usages' lines and the usages on them. +type ReferenceLinesRequest struct { + Texts []string `json:"texts"` + Usages []ReferenceUsageLine `json:"usages"` +} + +// ReferenceLine is a usage's line as its row shows it, the usage's UTF-16 range in it. +type ReferenceLine struct { + Text string `json:"text"` + Ranges []SearchNameRange `json:"ranges"` +} + +// QueryReferences groups a Find Usages answer by file and lays its rows out. +func (c *Client) QueryReferences(ctx context.Context, request ReferencesQuery) (ReferencesResult, error) { + request.Locations = nonNil(request.Locations) + var result ReferencesResult + if err := c.Execute(ctx, "lsp.references.query", request, &result); err != nil { + return ReferencesResult{}, err + } + return result, nil +} + +// ReferenceLines shows the usages' lines, one per usage in order. +func (c *Client) ReferenceLines(ctx context.Context, request ReferenceLinesRequest) ([]ReferenceLine, error) { + request.Texts, request.Usages = nonNil(request.Texts), nonNil(request.Usages) + var result struct { + Lines []ReferenceLine `json:"lines"` + } + if err := c.Execute(ctx, "lsp.references.lines", request, &result); err != nil { + return nil, err + } + return result.Lines, nil +} diff --git a/desktop/internal/core/references_test.go b/desktop/internal/core/references_test.go new file mode 100644 index 0000000000..68ceaaa20e --- /dev/null +++ b/desktop/internal/core/references_test.go @@ -0,0 +1,72 @@ +package core + +import ( + "encoding/json" + "os" + "reflect" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +// The shared fixtures run through the real kernel, so a bridge type that drifted from the JSON +// Core emits fails here. +func TestQueryReferencesSharedFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("lsp/references-query-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Cases []struct { + Name string `json:"name"` + Request ReferencesQuery `json:"request"` + Response ReferencesResult `json:"response"` + } `json:"cases"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + client := NewClient() + for _, c := range fixture.Cases { + t.Run(c.Name, func(t *testing.T) { + got, err := client.QueryReferences(testContext(t), c.Request) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, c.Response) { + t.Fatalf("result = %+v, want %+v", got, c.Response) + } + }) + } +} + +func TestReferenceLinesSharedFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("lsp/references-lines-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Cases []struct { + Name string `json:"name"` + Request ReferenceLinesRequest `json:"request"` + Response struct { + Lines []ReferenceLine `json:"lines"` + } `json:"response"` + } `json:"cases"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + client := NewClient() + for _, c := range fixture.Cases { + t.Run(c.Name, func(t *testing.T) { + got, err := client.ReferenceLines(testContext(t), c.Request) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, c.Response.Lines) { + t.Fatalf("lines = %+v, want %+v", got, c.Response.Lines) + } + }) + } +} diff --git a/desktop/internal/core/workspace.go b/desktop/internal/core/workspace.go index 24a0a76482..0e19c2ace1 100644 --- a/desktop/internal/core/workspace.go +++ b/desktop/internal/core/workspace.go @@ -342,6 +342,9 @@ type WorkspaceSearchMatch struct { // its matches in UTF-16 units, returned when the request sets IncludeContentRanges. SourceLine *string `json:"sourceLine,omitempty"` ContentMatchRanges []SearchNameRange `json:"contentMatchRanges,omitempty"` + // PreviewRanges, returned with SourceLine, are the matches in Preview, which is then the + // line as a result row shows it: without its indentation, cut in front of a far match. + PreviewRanges []SearchNameRange `json:"previewRanges,omitempty"` } // SearchNameRange locates one Core-selected highlight in UTF-16 code units. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 8444420cb8..4f6f4c005f 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1270,7 +1270,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.recentFiles.failed": "Could not read recent files.", "desktop.recentFiles.query": "Search recent files", "desktop.recentFiles.title": "Recent files", + "desktop.references.closeSearch": "Close Search Results", "desktop.references.empty": "Run Find Usages (Shift+F12) to list references here.", + "desktop.references.nextUsage": "Next Usage", + "desktop.references.previewEmpty": "Select a usage to preview it.", + "desktop.references.previousUsage": "Previous Usage", + "desktop.references.resultCount": "{count} results", + "desktop.references.resultCountOne": "1 result", + "desktop.references.showPreview": "Show Preview", + "desktop.references.usageCount": "{count} usages", + "desktop.references.usageCountOne": "1 usage", + "desktop.references.usages": "Usages", "desktop.refs.checkedOutAndRebased": "Checked out {branch} and rebased it onto the previous branch", "desktop.refs.mergeConfirm": "Merge {branch} into the current branch. If Git stops at conflicts, the Commit tool window shows the merge until you continue or abort it.", "desktop.refs.merged": "Merged {branch} into the current branch", @@ -3223,7 +3233,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorMenu.back": "后退", "desktop.editorMenu.deleteLine": "删除行", "desktop.editorMenu.duplicateLine": "复制行", - "desktop.editorMenu.findUsages": "查找引用", + "desktop.editorMenu.findUsages": "查找用法", "desktop.editorMenu.forward": "前进", "desktop.editorMenu.goToDefinition": "跳转到定义", "desktop.editorMenu.goToLine": "跳转到行…", @@ -4062,7 +4072,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.recentFiles.failed": "无法读取最近文件记录。", "desktop.recentFiles.query": "搜索最近文件", "desktop.recentFiles.title": "最近文件", - "desktop.references.empty": "使用“查找引用”(Shift+F12)后,结果显示在这里。", + "desktop.references.closeSearch": "关闭搜索结果", + "desktop.references.empty": "使用“查找用法”(Shift+F12)后,结果显示在这里。", + "desktop.references.nextUsage": "下一个用法", + "desktop.references.previewEmpty": "选择一个用法以预览。", + "desktop.references.previousUsage": "上一个用法", + "desktop.references.resultCount": "{count} 个结果", + "desktop.references.resultCountOne": "1 个结果", + "desktop.references.showPreview": "显示预览", + "desktop.references.usageCount": "{count} 个用法", + "desktop.references.usageCountOne": "1 个用法", + "desktop.references.usages": "用法", "desktop.refs.checkedOutAndRebased": "已检出 {branch} 并把它变基到之前的分支", "desktop.refs.mergeConfirm": "把 {branch} 合并到当前分支。如果 Git 因冲突停下,提交工具窗口会显示这次合并,直到你继续或中止。", "desktop.refs.merged": "已把 {branch} 合并到当前分支", diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 8b42c34771..900297a99a 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -204,6 +204,8 @@ type Kernel interface { PlainPluginSnippet(ctx context.Context, value string) (string, error) PlanPluginWorkspaceEdit(ctx context.Context, workspaceRoot string, changes map[string][]core.PluginTextEdit, open []core.PluginOpenDocument) (core.PluginWorkspaceEditPlan, error) QueryProblems(ctx context.Context, request core.ProblemsQuery) (core.ProblemsResult, error) + QueryReferences(ctx context.Context, request core.ReferencesQuery) (core.ReferencesResult, error) + ReferenceLines(ctx context.Context, request core.ReferenceLinesRequest) ([]core.ReferenceLine, error) ResolveMarketplaceSource(context.Context, string) (core.MarketplaceSource, error) ValidateMarketplaceIndex(context.Context, json.RawMessage, core.MarketplaceSourceKind, string, map[string][]int) (core.MarketplaceIndex, error) } diff --git a/desktop/internal/workbench/editor_menu.go b/desktop/internal/workbench/editor_menu.go index 16c2e56aae..22037ac29b 100644 --- a/desktop/internal/workbench/editor_menu.go +++ b/desktop/internal/workbench/editor_menu.go @@ -31,6 +31,8 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem a.startPluginDefinition(p, d, line, column, true) }) } + // A right click outside the selection has put the caret on the word clicked, so the + // usages are of that word. if menu.Item(i18n.Shared(language, "desktop.editorMenu.findUsages")).Keys(gfx.ModifierShift, "f12").Clicked() { c.After(func() { line, column := d.view.CaretUTF16() diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index c11253100d..04a1f7753e 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -172,11 +172,8 @@ type completionState struct { // definitionState is the multi-target definition popup. type definitionState struct { - open bool - targets []core.PluginSemanticLocation - // references marks a find-references list, which is shown even for a - // single result instead of jumping. - references bool + open bool + targets []core.PluginSemanticLocation selected int offset int documentID int @@ -972,7 +969,16 @@ func (a *App) applySemanticDefinition(pending *semanticPending, event core.Backe return } if pending.kind == pluginSemanticReferences { - a.presentDefinitionTargets(p, d, pending.kind, a.usableDefinitionTargets(locations, maxReferenceTargets), len(locations), pending.revision) + targets := a.usableDefinitionTargets(locations, maxReferenceTargets) + if len(targets) == 0 { + a.presentDefinitionTargets(p, d, pending.kind, targets, len(locations), pending.revision) + return + } + // Find Usages fills the References tool window, which keeps the answer while the + // user works through it, instead of a popup that closes on the first click. The + // window's tab names what was searched for, and Rerun asks at the same place again. + query := referenceQuery{documentID: d.id, line: pending.line, column: pending.column} + a.showReferences(p, targets, query, identifierAt(d.view.TextSnapshot(), d.view, pending.line, pending.column)) return } if a.plugins != nil && a.plugins.HasDefinitionProvider(p.root, d.path, d.languageID) { @@ -1047,8 +1053,9 @@ func (a *App) mergeProviderDefinitions(p *project, d *document, pending *semanti }) } -// presentDefinitionTargets shows the locations of a definition or references answer, from a language -// server or a plugin provider: one definition opens, several wait in the list, and nothing found says so. +// presentDefinitionTargets shows the locations of a definition answer, from a language server or a +// plugin provider: one definition opens, several wait in the list, and nothing found says so. A +// references answer comes here only when nothing was found; its usages fill the References tool window. func (a *App) presentDefinitionTargets(p *project, d *document, kind semanticKind, targets []core.PluginSemanticLocation, answered int, revision int) { references := kind == pluginSemanticReferences if len(targets) == 0 { @@ -1065,19 +1072,12 @@ func (a *App) presentDefinitionTargets(p *project, d *document, kind semanticKin } return } - if len(targets) == 1 && !references { + if len(targets) == 1 { a.openDefinitionTarget(targets[0]) return } - if references { - // Find Usages fills the References tool window, which keeps the answer while the - // user works through it, instead of a popup that closes on the first click. - a.showReferences(p, targets, "") - return - } a.semantics.definition = definitionState{ open: true, - references: references, targets: targets, documentID: d.id, revision: revision, @@ -1771,10 +1771,7 @@ func popupOrigin(x, y, width float32, bounds gfx.Rect) (float32, float32) { } // definitionPopupTitle is the accessibility title of the open location list. -func (a *App) definitionPopupTitle(references bool) string { - if references { - return i18n.Shared(a.language(), "desktop.semantics.references") - } +func (a *App) definitionPopupTitle() string { return i18n.Shared(a.language(), "desktop.semantics.definitions") } diff --git a/desktop/internal/workbench/pluginsemantics_test.go b/desktop/internal/workbench/pluginsemantics_test.go index 7d28e62d58..f0dd13937f 100644 --- a/desktop/internal/workbench/pluginsemantics_test.go +++ b/desktop/internal/workbench/pluginsemantics_test.go @@ -462,25 +462,74 @@ func TestFindReferencesFillsTheReferencesPaneAndOpensChosen(t *testing.T) { if got := f.kernel.request(0).Operation; got != pluginSemanticReferences { t.Fatalf("operation = %q", got) } - f.deliver(t, "op-1", pluginMethodReferences, locationsResult(t, locationAt(target, 1, 1))) + f.deliver(t, "op-1", pluginMethodReferences, locationsResult(t, locationAt(target, 1, 4))) if f.h.app.semantics.definition.open { t.Fatal("references opened the popup") } if !f.h.app.chrome.isOpen(catalogIndex[itemReferences]) { t.Fatal("the References tool window did not open") } + s := &f.h.app.editor.refs + if s.symbol != "one" { + t.Fatalf("searched symbol = %q, want the name under the caret", s.symbol) + } f.h.settle() - if !f.h.shows("B.java") || !f.h.shows("one();") { + if !f.h.shows("B.java") || !f.h.shows("one();") || !f.h.shows("1 个结果") { t.Fatalf("pane rows missing: %v", f.h.driver.Snapshot().Labels) } - s := &f.h.app.editor.refs - if len(s.groups) != 1 || len(s.groups[0].indices) != 1 { + if len(s.groups) != 1 || len(s.groups[0].Indices) != 1 { t.Fatalf("groups = %+v", s.groups) } - f.h.app.openReference(f.p, s.targets[0]) + if got := s.lines[0]; got.Text != "one();" || len(got.Ranges) != 1 || got.Ranges[0] != (core.SearchNameRange{Start: 0, Length: 3}) { + t.Fatalf("usage line = %+v", got) + } + // The first usage is selected, and the preview shows its file with the usage selected. + f.h.await("the usage's preview", func() bool { + view := s.preview.view + if view == nil { + return false + } + anchor, active := view.SelectionOffsets() + return s.preview.path == target && anchor == len("zero\n ") && active == len("zero\n one") + }) + f.h.app.openReference(s.targets[0]) awaitDocumentState(t, f.h, func() bool { return f.p.docs.byPath(target) != nil }) } +// A right click elsewhere in the text puts the caret there, so the menu's Find Usages asks for +// the usages of what was clicked, not of where the caret was. +func TestEditorMenuFindUsagesAsksAtTheRightClickedPlace(t *testing.T) { + f := newSemanticFixture(t) + // The click goes to the cell of "n" in "one"; the caret then waits at the line's end. + f.d.view.GoToNavigation(0, 1, false) + f.h.settle() + cell, ok := f.d.view.CaretRect() + if !ok { + t.Fatal("the editor has not painted") + } + f.d.view.GoToNavigation(0, 3, false) + f.h.settle() + if err := f.h.driver.ClickButton(cell.X+1, cell.Y+cell.Height/2, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + f.h.settle() + f.h.clickNamed(f.h.shared("desktop.editorMenu.findUsages")) + // The pointer resting on the text may have asked for a hover first. + var request *core.PluginSemanticRequest + awaitDocumentState(t, f.h, func() bool { + for i := range f.kernel.requestCount() { + if r := f.kernel.request(i); r.Operation == pluginSemanticReferences { + request = &r + return true + } + } + return false + }) + if request.Position == nil || *request.Position != (core.PluginDocumentPosition{Line: 0, UTF16Column: 1}) { + t.Fatalf("references asked at %+v, want the clicked column", request.Position) + } +} + func TestReferencesPaneGroupsByFileAndIsBounded(t *testing.T) { f := newSemanticFixture(t) locations := make([]core.PluginSemanticLocation, 0, maxReferenceTargets+20) @@ -501,14 +550,19 @@ func TestReferencesPaneGroupsByFileAndIsBounded(t *testing.T) { if got := len(s.targets); got != maxReferenceTargets { t.Fatalf("targets = %d, want %d", got, maxReferenceTargets) } - if len(s.groups) != 2 || s.rows != maxReferenceTargets+2 { - t.Fatalf("groups = %d rows = %d", len(s.groups), s.rows) + // The Usages node, a node per file and every usage under them. + if len(s.groups) != 2 || len(s.rows) != maxReferenceTargets+3 { + t.Fatalf("groups = %d rows = %d", len(s.groups), len(s.rows)) + } + second := 2 + len(s.groups[0].Indices) + if r := s.rows[second]; r.Kind != core.ReferenceRowFile || referenceRowGroup(r) != 1 { + t.Fatalf("second file's row = %+v", r) } - if group, index, header := s.rowAt(s.starts[1]); group != 1 || !header || index != -1 { - t.Fatalf("second header = %d %d %v", group, index, header) + if r := s.rows[second+3]; r.Kind != core.ReferenceRowUsage || referenceRowGroup(r) != 1 || r.Shows != s.groups[1].Indices[2] { + t.Fatalf("row in second file = %+v", r) } - if group, index, header := s.rowAt(s.starts[1] + 3); group != 1 || index != 2 || header { - t.Fatalf("row in second group = %d %d %v", group, index, header) + if s.selected != "usage:0" || s.selectedRow != 2 { + t.Fatalf("selected key %q at row %d, want the first usage", s.selected, s.selectedRow) } } diff --git a/desktop/internal/workbench/pluginsemantics_view.go b/desktop/internal/workbench/pluginsemantics_view.go index 356862d591..cd05bcd7b0 100644 --- a/desktop/internal/workbench/pluginsemantics_view.go +++ b/desktop/internal/workbench/pluginsemantics_view.go @@ -70,7 +70,7 @@ func (a *App) definitionPopup(c ui.C) { x, y := popupOrigin(anchor.X, anchor.Y+anchor.Height+2, semanticDefinitionWidth, c.Bounds()) chosen := -1 a.semanticPopup(c, x, y, semanticDefinitionWidth, float32(visibleSemanticRows)*semanticRowHeight+2*semanticPopupPad, - a.definitionPopupTitle(state.references), semanticPopupPad, func() { + a.definitionPopupTitle(), semanticPopupPad, func() { ui.Column(c).FillWidth().Gap(1).Children(func() { for i := first; i < last; i++ { label := a.definitionLabel(state.targets[i]) diff --git a/desktop/internal/workbench/problems.go b/desktop/internal/workbench/problems.go index 38c351b5b1..b7159f6ce2 100644 --- a/desktop/internal/workbench/problems.go +++ b/desktop/internal/workbench/problems.go @@ -36,7 +36,7 @@ type problemsView struct { // show says the Show Editor Preview option is on: a read-only source view beside the list // shows the selected diagnostic's line. preview is that view. show bool - preview problemsPreview + preview sourcePreview // split is the width of the list beside the preview; the user drags it. split ui.SplitterState // hideErrors, hideWarnings and hideInfo narrow the severities shown; a query sends them diff --git a/desktop/internal/workbench/problems_preview.go b/desktop/internal/workbench/problems_preview.go index 67bcdb402b..6ba7b24535 100644 --- a/desktop/internal/workbench/problems_preview.go +++ b/desktop/internal/workbench/problems_preview.go @@ -1,42 +1,13 @@ package workbench import ( - "context" - "path/filepath" - - "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" - "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) -// problemsPreview is the read-only source view beside the Problems list. It shows the file of the -// selected diagnostic and reveals its line; it never takes the keyboard focus of the window or -// writes the file. Its text is the open document's when the file is open, so unsaved edits show. -type problemsPreview struct { - // path and line are the file and zero-based line the preview was asked for. A load replaces - // view when its answer arrives for the same generation. - path string - line int - generation uint64 - failure error - view *editorview.View - hit gfx.ID - input ui.Handlers - draw func(*ui.DrawContext) -} - -// close releases the view's highlighter and forgets the file. -func (pv *problemsPreview) close() { - if pv.view != nil { - pv.view.Close() - } - pv.view = nil - pv.path = "" - pv.failure = nil - pv.generation++ -} +// The Problems list's preview is the shared read-only source view (sourcePreview): it shows the +// file of the selected diagnostic and reveals its line, never takes the keyboard focus of the +// window or writes the file, and shows an open document's text, unsaved edits included. // selectedProblemLocation is the file and zero-based line of the selected diagnostic, and false // when no diagnostic row is selected. @@ -67,124 +38,10 @@ func (a *App) syncProblemsPreview(p *project) { if !ok { return } - pv := &v.preview - if pv.path != path { - a.loadProblemsPreview(p, path, line) - return - } - if pv.line != line { - pv.line = line - if pv.view != nil { - pv.view.GoToLine(line + 1) - } - } -} - -// loadProblemsPreview reads the file's text off the window thread. An open document contributes its -// current text, so the preview shows what the editor shows. -func (a *App) loadProblemsPreview(p *project, path string, line int) { - pv := &a.problems.preview - if pv.view != nil { - pv.view.Close() - } - pv.view = nil - pv.failure = nil - pv.path, pv.line = path, line - pv.generation++ - generation := pv.generation - var openText []byte - open := false - if d := p.docs.byPath(path); d != nil { - data, _ := d.view.Text() - openText = append([]byte(nil), data...) - open = true - } - registry := a.syntaxRegistry() - kernel, _ := a.kernel.(editorKernel) - 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) - data = read.text - } - var content editorview.Content - var grammar *syntax.Syntax - if err == nil { - content = editorview.Prepare(data) - grammar = registry.SyntaxForPath(path) - } - return func(a *App) { - pv := &a.problems.preview - if pv.generation != generation || a.project != p || !a.problems.show { - return - } - if err != nil { - pv.failure = err - return - } - a.installProblemsPreview(path, content, grammar) - } - }) -} - -// installProblemsPreview makes the read-only view of the loaded text and reveals the requested line. -func (a *App) installProblemsPreview(path string, content editorview.Content, grammar *syntax.Syntax) { - pv := &a.problems.preview - view := editorview.New(editorview.Config{ - Label: filepath.Base(path), - Content: content, - Syntax: grammar, - Notify: a.invalidator.Invalidate, - }) - view.SetReadOnly(true) - view.SetWrap(false) - view.SetMinimap(false) - view.GoToLine(pv.line + 1) - pv.view = view - pv.input = ui.Handlers{ - Role: gfx.RoleTerminal, - Key: func(event gfx.KeyEvent) gfx.EventResult { - result, _ := view.Key(event) - return result - }, - Pointer: func(event gfx.PointerEvent) gfx.EventResult { - result, _ := view.Pointer(event) - return result - }, - Scroll: func(event gfx.ScrollEvent) gfx.EventResult { - result, _ := view.Scroll(event) - return result - }, - } - pv.draw = func(dc *ui.DrawContext) { a.drawProblemsPreview(dc, pv) } + a.showSourcePreview(p, &v.preview, path, line+1, func(a *App) bool { return a.problems.show }) } // problemsPreviewPane declares the preview beside the list, or the reason there is none. -func (a *App) problemsPreviewPane(c ui.C, p *project) { - lang := a.language() - pv := &a.problems.preview - switch { - case pv.failure != nil: - a.panelMessage(c, a.text.Errors.Core(pv.failure.Error()), a.theme.Danger) - case pv.view == nil: - a.panelMessage(c, i18n.Shared(lang, "desktop.problems.previewEmpty"), a.colors.Subtle) - default: - pv.hit = ui.ID(c.Part("problemsPreview")) - ui.Control(c.Part("problemsPreview"), filepath.Base(pv.path), &pv.input).Grow(1).Basis(0).FillHeight().Draw(pv.draw) - } -} - -// drawProblemsPreview paints the preview into its control. -func (a *App) drawProblemsPreview(dc *ui.DrawContext, pv *problemsPreview) { - v := pv.view - if v == nil { - return - } - v.BindWithoutMinimap(pv.hit, pv.input.Parts()) - v.HideVerticalBar() - v.SetFont(a.editorFont()) - v.SetWrap(false) - v.SetMessages(a.editorMessages()) - v.Paint(dc.Canvas, dc.Rect, a.editorLook()) +func (a *App) problemsPreviewPane(c ui.C) { + a.sourcePreviewPane(c, &a.problems.preview, "problemsPreview", i18n.Shared(a.language(), "desktop.problems.previewEmpty")) } diff --git a/desktop/internal/workbench/problems_test.go b/desktop/internal/workbench/problems_test.go index c89b420cf2..801a00cea7 100644 --- a/desktop/internal/workbench/problems_test.go +++ b/desktop/internal/workbench/problems_test.go @@ -246,6 +246,42 @@ func TestProblemsCacheIsDroppedWhenThePanelCloses(t *testing.T) { } } +// With the preview on, a click on a diagnostic only selects it: the shared source preview shows its +// file at its line without opening an editor, and a file that cannot be read shows why. +func TestProblemsPreviewFollowsTheSelectedDiagnostic(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + root := t.TempDir() + present := filepath.Join(root, "present.txt") + if err := os.WriteFile(present, []byte("zero\none\ntwo\n"), 0o600); err != nil { + t.Fatal(err) + } + missing := filepath.Join(root, "missing.txt") + h.open(root) + h.app.pluginDiagnostics = map[string]*plugindiag.Set{"demo": problemSet(t, + plugindiag.Diagnostic{FileKey: present, DisplayPath: "present.txt", Line: 2, Column: 0, Severity: plugindiag.SeverityError, Message: "on two"}, + plugindiag.Diagnostic{FileKey: missing, DisplayPath: "missing.txt", Line: 0, Column: 0, Severity: plugindiag.SeverityWarning, Message: "gone"}, + )} + h.app.markProblemsChanged() + h.app.problems.show = true + openProblemsPanel(t, h) + + preview := &h.app.problems.preview + h.clickNamed("on two") + awaitDocumentState(t, h, func() bool { return preview.view != nil && preview.path == present }) + if line, _ := preview.view.Caret(); line != 2 || preview.line != 3 { + t.Fatalf("preview at line %d (asked %d), want the diagnostic's zero-based 2", line, preview.line) + } + if h.app.project.docs.byPath(present) != nil { + t.Fatal("selecting a diagnostic with the preview on opened its file") + } + + h.clickNamed("gone") + awaitDocumentState(t, h, func() bool { return preview.failure != nil }) + if preview.path != missing || preview.view != nil { + t.Fatalf("preview of an unreadable file = %q, view %v", preview.path, preview.view != nil) + } +} + // A serve loop that ends without an explicit stop (a crash or self-exit) still // withdraws the diagnostics its process published. func TestExitedServerWithdrawsDiagnostics(t *testing.T) { diff --git a/desktop/internal/workbench/problems_view.go b/desktop/internal/workbench/problems_view.go index f124287da7..23b6acbda1 100644 --- a/desktop/internal/workbench/problems_view.go +++ b/desktop/internal/workbench/problems_view.go @@ -105,7 +105,7 @@ func (a *App) problemsPanel(c ui.C, p *project) { ui.Row(c).FillWidth().Grow(1).Basis(0).Shrink(1).MinHeight(0).Children(func() { ui.Column(c).Width(v.split.Pos).Shrink(0).FillHeight().MinHeight(0).Children(func() { list(c) }) ui.Splitter(c, &v.split).Mins(problemsListMin, problemsPreviewMin).Label(a.text.Panel.Resize) - a.problemsPreviewPane(c, p) + a.problemsPreviewPane(c) }) } else { list(c) diff --git a/desktop/internal/workbench/references.go b/desktop/internal/workbench/references.go index e0865e2b13..ac466ad954 100644 --- a/desktop/internal/workbench/references.go +++ b/desktop/internal/workbench/references.go @@ -2,143 +2,399 @@ package workbench import ( "context" + "errors" + "io" "os" "path/filepath" + "slices" + "strconv" "strings" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) -// The References tool window: the answer of Find Usages as a list grouped by file, each row -// showing its position and the line it points at. +// The References tool window: the answer of Find Usages laid out the way IntelliJ IDEA's Find +// tool window lays out its usages. A tree holds a Usages node over a node per file, each over +// its usages (the line number and the line, the found text in bold), and a read-only preview of +// the selected usage's file sits beside the tree with every usage in that file marked. // -// Core normalizes the locations; this file groups them by file in the order the server gave -// them, reads the lines to show in the background (an open file's from its editor, a closed -// one's from disk, bounded), and opens a row's file at its position. +// Core groups the usages by file and orders them, lays the visible rows out under the nodes the +// user closed, moves a selection that a closed node hides, and says which usage each row shows +// and which usages come before and after it (lsp.references.query); it also cuts the usages' +// lines as their rows show them (lsp.references.lines). This file keeps which nodes are closed +// and which row is selected, reads the lines (an open file's from its editor, a closed one's +// from disk, bounded), and opens a usage's file at its position. const ( // referencePreviewLimit bounds how much of one closed file is read to show its lines. referencePreviewLimit = 2 << 20 - // referencePreviewWidth cuts a shown line, in bytes. - referencePreviewWidth = 240 - referenceRowHeight = 22 + // referenceTreeWidth is the tree's width beside the preview until the user drags the + // splitter; the tree and the preview keep at least their minimums while it is dragged. + referenceTreeWidth = 380 + referenceTreeMin = 180 + referencePreviewMin = 200 ) -// usageGroup is the references that lie in one file. -type usageGroup struct { - path string - display string - // indices point into the state's targets. - indices []int +// referenceQuery is the document and position Find Usages was asked at, which Rerun asks again. +type referenceQuery struct { + documentID int + line, column int } -// referencesState is the References tool window's answer. +// referenceMarks is the view and the usage the preview's marks were set for, so they are set +// once per change and not in every frame. +type referenceMarks struct { + view *editorview.View + target int +} + +// referencesState is the References tool window's answer and how it is shown. type referencesState struct { project *project targets []core.PluginSemanticLocation - groups []usageGroup - // starts holds the flat row index of each group's header; rows is the row count. - starts []int - rows int - // previews is the line of each target, in step with targets; empty until read. - previews []string + // locations are the targets as Core groups them, in step with targets. + locations []core.ReferenceLocation + // groups and rows are Core's layout of the answer: the files, and the rows that show. + groups []core.ReferenceGroup + rows []core.ReferenceRow + // groupOf is the group of each target, in step with targets. + groupOf []int + // lines is the line of each target as its row shows it, in step with targets; empty until + // read. + lines []core.ReferenceLine generation uint64 - list ui.ListState - // symbol is what was searched for, shown as the window's subtitle. + // collapsed holds the fileKeys of the file nodes the user closed; rootCollapsed closes the + // Usages node. + collapsed map[string]bool + rootCollapsed bool + // selected is the key of the selected row and selectedRow its place in rows, -1 for none; + // reveal asks the next frame to scroll it into view. + selected string + selectedRow int + reveal bool + // focus is the keyboard focus the last frame saw, so only a move of it selects a row. + focus gfx.ID + view ui.TreeState + // hidePreview turns the preview off; it stays off for the next answers. + hidePreview bool + split ui.SplitterState + preview sourcePreview + marked referenceMarks + query referenceQuery + // symbol is the name that was searched for, shown on the header's tab. symbol string } -// rowAt locates a flat row: a group header, or the reference at index of group. -func (s *referencesState) rowAt(row int) (group, index int, header bool) { - if row < 0 || row >= s.rows { - return 0, 0, false +// showReferences makes targets the contents of the References tool window and opens it, with +// the first usage selected. query is where they were asked for, and symbol the name there. +func (a *App) showReferences(p *project, targets []core.PluginSemanticLocation, query referenceQuery, symbol string) { + s := &a.editor.refs + if s.project != p { + s.preview.close() + } + s.generation++ + s.project, s.targets, s.query, s.symbol = p, targets, query, symbol + s.locations = make([]core.ReferenceLocation, len(targets)) + for i, target := range targets { + s.locations[i] = referenceLocation(p.root, target) + } + s.lines = make([]core.ReferenceLine, len(targets)) + s.collapsed, s.rootCollapsed, s.selected, s.marked = nil, false, "", referenceMarks{} + if !a.layoutReferences() { + s.targets, s.locations, s.lines, s.groups, s.rows, s.selectedRow = nil, nil, nil, nil, nil, -1 + return } - for g := len(s.starts) - 1; g >= 0; g-- { - if row >= s.starts[g] { - offset := row - s.starts[g] - return g, offset - 1, offset == 0 + s.reveal = true + a.reduceChrome(core.SetChromeOpen(itemReferences, true)) + a.loadReferenceLines(p, s.generation) +} + +// referenceLocation is target as Core groups it: under its path, compared as this platform +// compares paths, or under its URI when it is not a local file; shown relative to the project +// root when it lies in it. +func referenceLocation(root string, target core.PluginSemanticLocation) core.ReferenceLocation { + key, display := target.FilePath, target.URI + if key == "" { + key = target.URI + } else { + display = key + if rel, err := filepath.Rel(root, key); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + display = rel } + display = filepath.ToSlash(display) + } + return core.ReferenceLocation{ + FileKey: key, + DisplayPath: display, + Line: max(target.Range.Start.Line, 0), + Column: max(target.Range.Start.UTF16Column, 0), } - return 0, 0, false } -// showReferences makes targets the contents of the References tool window and opens it. -func (a *App) showReferences(p *project, targets []core.PluginSemanticLocation, symbol string) { +// layoutReferences asks Core for the rows under the nodes that are closed and the selection +// that is kept. When Core fails it reports the failure and is false, and the rows stay. +func (a *App) layoutReferences() bool { s := &a.editor.refs - s.generation++ - s.project, s.targets, s.symbol = p, targets, symbol - s.groups, s.starts, s.rows = s.groups[:0], s.starts[:0], 0 - s.previews = make([]string, len(targets)) - s.list = ui.ListState{} - byPath := map[string]int{} - for i, target := range targets { - key := target.FilePath - if key == "" { - key = target.URI + collapsed := make([]string, 0, len(s.collapsed)) + for key := range s.collapsed { + collapsed = append(collapsed, key) + } + slices.Sort(collapsed) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), kernelCallTimeout) + defer cancel() + result, err := a.kernel.QueryReferences(ctx, core.ReferencesQuery{ + Locations: s.locations, RootCollapsed: s.rootCollapsed, Collapsed: collapsed, Selected: s.selected, + }) + if err != nil { + a.operationFailed("references_query", err) + a.notifyError(a.text.Errors.Core(err.Error())) + return false + } + s.groups, s.rows, s.selected, s.selectedRow = result.Groups, result.Rows, result.Selected, -1 + if result.SelectedRow != nil { + s.selectedRow = *result.SelectedRow + } + s.groupOf = make([]int, len(s.targets)) + for g, group := range s.groups { + for _, i := range group.Indices { + if i >= 0 && i < len(s.groupOf) { + s.groupOf[i] = g + } } - g, ok := byPath[key] - if !ok { - display := key - if rel, err := filepath.Rel(p.root, key); err == nil && !strings.HasPrefix(rel, "..") { - display = rel + } + return true +} + +// closeReferences forgets the answer, as closing the header's tab does. +func (a *App) closeReferences() { + s := &a.editor.refs + s.preview.close() + *s = referencesState{hidePreview: s.hidePreview, split: s.split, preview: s.preview, generation: s.generation + 1, selectedRow: -1} +} + +// rerunReferences asks for the usages again at the position they were asked at, while that +// document is open. +func (a *App) rerunReferences(p *project) { + s := &a.editor.refs + if d := s.queryDocument(p); d != nil { + a.startPluginLocations(pluginSemanticReferences, p, d, s.query.line, s.query.column, false, false) + } +} + +// queryDocument is the open document the usages were asked in, or nil once it was closed. +func (s *referencesState) queryDocument(p *project) *document { + if p == nil || s.project != p || s.query.documentID <= 0 { + return nil + } + return p.docs.find(s.query.documentID) +} + +// key is the Tree's key of visible row i: the Usages node is 0, a file's node follows, then the +// usages, so a row keeps its key while the nodes above it open and close. +func (s *referencesState) key(i int) int { + r := s.rows[i] + switch r.Kind { + case core.ReferenceRowRoot: + return 0 + case core.ReferenceRowFile: + return 1 + referenceRowGroup(r) + default: + return 1 + len(s.groups) + r.Shows + } +} + +// referenceRowGroup is the group of a file or usage row. +func referenceRowGroup(r core.ReferenceRow) int { + if r.Group == nil { + return 0 + } + return *r.Group +} + +// referenceUsageKey is Core's key of the row of usage target. +func referenceUsageKey(target int) string { + return core.ReferenceRowUsage + ":" + strconv.Itoa(target) +} + +// node describes visible row i to the Tree. +func (s *referencesState) node(i int) ui.TreeNode { + r := s.rows[i] + return ui.TreeNode{ + Depth: r.Depth, + Branch: r.Kind != core.ReferenceRowUsage, + Expanded: r.Expanded != nil && *r.Expanded, + Selected: i == s.selectedRow, + } +} + +// rowOf is the visible row with key, or -1 when it is hidden under a closed node. +func (s *referencesState) rowOf(key string) int { + return slices.IndexFunc(s.rows, func(r core.ReferenceRow) bool { return r.Key == key }) +} + +// selectRow selects the visible row with key; it is false when that row does not show. +func (s *referencesState) selectRow(key string) bool { + i := s.rowOf(key) + if i < 0 { + return false + } + s.selected, s.selectedRow = key, i + return true +} + +// toggleReference opens or closes the node with key. Core moves the selection to the node when +// it was under it. +func (a *App) toggleReference(key string) { + s := &a.editor.refs + i := s.rowOf(key) + if i < 0 { + return + } + switch r := s.rows[i]; r.Kind { + case core.ReferenceRowRoot: + s.rootCollapsed = !s.rootCollapsed + case core.ReferenceRowFile: + file := s.groups[referenceRowGroup(r)].FileKey + if s.collapsed[file] { + delete(s.collapsed, file) + } else { + if s.collapsed == nil { + s.collapsed = map[string]bool{} } - g = len(s.groups) - byPath[key] = g - s.groups = append(s.groups, usageGroup{path: target.FilePath, display: display}) + s.collapsed[file] = true } - s.groups[g].indices = append(s.groups[g].indices, i) + default: + return } - for _, g := range s.groups { - s.starts = append(s.starts, s.rows) - s.rows += 1 + len(g.indices) + a.layoutReferences() +} + +// expandReferences opens or closes every file's node; the Usages node stays open so the files +// show. A usage that was selected hands the selection to its file when its node closes. +func (a *App) expandReferences(expanded bool) { + s := &a.editor.refs + s.rootCollapsed, s.collapsed = false, nil + if !expanded { + s.collapsed = make(map[string]bool, len(s.groups)) + for _, g := range s.groups { + s.collapsed[g.FileKey] = true + } } - a.reduceChrome(core.SetChromeOpen(itemReferences, true)) - a.loadReferencePreviews(p, s.generation) + a.layoutReferences() + s.reveal = true } -// loadReferencePreviews reads the line of every reference. An open file's lines come from its -// editor on the window thread, which only reads rope lines; closed files are read off it. -func (a *App) loadReferencePreviews(p *project, generation uint64) { +// shownTarget is the usage the preview shows for the selected row: the usage itself, or the +// first usage of a file or of the whole answer. +func (s *referencesState) shownTarget() (int, bool) { + if s.selectedRow < 0 || s.selectedRow >= len(s.rows) { + return 0, false + } + return s.rows[s.selectedRow].Shows, true +} + +// stepTarget is the usage after the selected row in the tree's order, or before it when forward +// is false, counting the usages under closed nodes too, and false at either end. +func (s *referencesState) stepTarget(forward bool) (int, bool) { + if s.selectedRow < 0 || s.selectedRow >= len(s.rows) { + return 0, false + } + step := s.rows[s.selectedRow].Previous + if forward { + step = s.rows[s.selectedRow].Next + } + if step == nil { + return 0, false + } + return *step, true +} + +// selectUsage selects the usage target, opening the nodes it lies under, and scrolls it into +// view. +func (a *App) selectUsage(target int) { s := &a.editor.refs - var closed []usageGroup + s.rootCollapsed = false + if target >= 0 && target < len(s.groupOf) && s.groupOf[target] < len(s.groups) { + delete(s.collapsed, s.groups[s.groupOf[target]].FileKey) + } + s.selected = referenceUsageKey(target) + a.layoutReferences() + s.reveal = true +} + +// stepReference selects the next or previous usage and opens it in the editor, as IDEA's Next +// and Previous Occurrence do. +func (a *App) stepReference(forward bool) { + s := &a.editor.refs + target, ok := s.stepTarget(forward) + if !ok { + return + } + a.selectUsage(target) + a.openReference(s.targets[target]) +} + +// loadReferenceLines reads the line of every reference and has Core cut it for its row. An open +// file's lines come from its editor on the window thread, which only reads rope lines; closed +// files are read off it. +func (a *App) loadReferenceLines(p *project, generation uint64) { + s := &a.editor.refs + targets := s.targets + // texts holds the text of each target's start line once read, and read says which are. + texts, read := make([]string, len(targets)), make([]bool, len(targets)) + var closed []core.ReferenceGroup for _, g := range s.groups { - if g.path == "" { + path := targets[g.Indices[0]].FilePath + if path == "" { continue } - if d := p.docs.byPath(g.path); d != nil { + if d := p.docs.byPath(path); d != nil { text := d.view.TextSnapshot() - for _, i := range g.indices { - if line := s.targets[i].Range.Start.Line; line >= 0 && line < text.LineCount() { - s.previews[i] = previewLine(text.Line(line)) + for _, i := range g.Indices { + if line := targets[i].Range.Start.Line; line >= 0 && line < text.LineCount() { + texts[i], read[i] = text.Line(line), true } } continue } closed = append(closed, g) } - if len(closed) == 0 { - return - } - targets := s.targets - a.background(p, 0, func(context.Context) func(*App) { - previews := make(map[int]string) + kernel := a.kernel + a.background(p, 0, func(ctx context.Context) func(*App) { for _, g := range closed { - lines := readLines(g.path, referencePreviewLimit) - for _, i := range g.indices { - if line := targets[i].Range.Start.Line; line >= 0 && line < len(lines) { - previews[i] = previewLine(lines[line]) + // A file that cannot be read keeps its rows without their lines. + file := readLines(targets[g.Indices[0]].FilePath, referencePreviewLimit) + for _, i := range g.Indices { + if line := targets[i].Range.Start.Line; line >= 0 && line < len(file) { + texts[i], read[i] = file[line], true } } } + request, asked := referenceLinesRequest(targets, texts, read) + if len(asked) == 0 { + return nil + } + call, cancel := context.WithTimeout(ctx, kernelCallTimeout) + defer cancel() + lines, err := kernel.ReferenceLines(call, request) return func(a *App) { s := &a.editor.refs if s.generation != generation || s.project != p { return } - for i, text := range previews { - if i < len(s.previews) { - s.previews[i] = text + if err == nil && len(lines) != len(asked) { + err = errors.New("references lines answer does not match its usages") + } + if err != nil { + a.backgroundFailed("references_lines", err) + return + } + for k, i := range asked { + if i < len(s.lines) { + s.lines[i] = lines[k] } } a.invalidator.Invalidate() @@ -146,6 +402,32 @@ func (a *App) loadReferencePreviews(p *project, generation uint64) { }) } +// referenceLinesRequest asks Core to show the lines that were read, each distinct text sent +// once, and says which target each asked usage is. +func referenceLinesRequest(targets []core.PluginSemanticLocation, texts []string, read []bool) (core.ReferenceLinesRequest, []int) { + var request core.ReferenceLinesRequest + var asked []int + index := map[string]int{} + for i, target := range targets { + if !read[i] { + continue + } + k, ok := index[texts[i]] + if !ok { + k = len(request.Texts) + index[texts[i]] = k + request.Texts = append(request.Texts, texts[i]) + } + at := target.Range + request.Usages = append(request.Usages, core.ReferenceUsageLine{ + Text: k, Line: max(at.Start.Line, 0), Column: max(at.Start.UTF16Column, 0), + EndLine: max(at.End.Line, 0), EndColumn: max(at.End.UTF16Column, 0), + }) + asked = append(asked, i) + } + return request, asked +} + // readLines is the lines of the file at path, read up to limit bytes; nil when it cannot be // read. func readLines(path string, limit int64) []string { @@ -155,25 +437,78 @@ func readLines(path string, limit int64) []string { } defer file.Close() buf := make([]byte, limit) - n, _ := file.Read(buf) + n, err := io.ReadFull(file, buf) + if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) { + return nil + } return strings.Split(string(buf[:n]), "\n") } -// previewLine is a line trimmed of its indentation and its carriage return and cut to a width -// that fits a row. -func previewLine(line string) string { - line = strings.TrimSpace(strings.TrimSuffix(line, "\r")) - if len(line) > referencePreviewWidth { - line = line[:referencePreviewWidth] - for len(line) > 0 && line[len(line)-1]&0xC0 == 0x80 { - line = line[:len(line)-1] +// referenceRange is the byte range of a usage in view's text, and false when it is not there. +func referenceRange(view *editorview.View, at core.PluginDocumentRange) (editorview.Range, bool) { + start, ok := view.ByteOffset(at.Start.Line, at.Start.UTF16Column) + if !ok { + return editorview.Range{}, false + } + end, ok := view.ByteOffset(at.End.Line, at.End.UTF16Column) + if !ok || end < start { + end = start + } + return editorview.Range{Start: start, End: end}, true +} + +// syncReferencePreview makes the preview follow the selection: the shown usage's file, with every +// usage in it marked, the shown one selected and its line in the middle of the view. A location +// that is not a local file has no preview. +func (a *App) syncReferencePreview(p *project) { + s := &a.editor.refs + target, ok := s.shownTarget() + if s.hidePreview || !ok { + return + } + path := s.targets[target].FilePath + if path == "" { + if s.preview.path != "" || s.preview.view != nil { + s.preview.close() + } + return + } + at := s.targets[target].Range + a.showSourcePreview(p, &s.preview, path, at.Start.Line+1, func(a *App) bool { + return a.editor.refs.project == p && !a.editor.refs.hidePreview + }) + view := s.preview.view + marks := referenceMarks{view: view, target: target} + if view == nil || s.marked == marks { + return + } + s.marked = marks + group := s.groups[s.groupOf[target]] + matches := make([]editorview.Range, 0, len(group.Indices)) + for _, i := range group.Indices { + if r, ok := referenceRange(view, s.targets[i].Range); ok { + matches = append(matches, r) } } - return line + slices.SortFunc(matches, func(x, y editorview.Range) int { return x.Start - y.Start }) + view.SetSearchMatches(matches) + if r, ok := referenceRange(view, at); ok { + view.SetSelection(r.Start, r.End) + } + view.CenterLine(at.Start.Line) +} + +// setReferencePreview turns the preview on or off; off releases its view. +func (a *App) setReferencePreview(show bool) { + s := &a.editor.refs + s.hidePreview = !show + s.marked = referenceMarks{} + if !show { + s.preview.close() + } } // openReference opens the file of a target at its position. -func (a *App) openReference(p *project, target core.PluginSemanticLocation) { +func (a *App) openReference(target core.PluginSemanticLocation) { a.openDefinitionTarget(target) - _ = p } diff --git a/desktop/internal/workbench/references_test.go b/desktop/internal/workbench/references_test.go new file mode 100644 index 0000000000..b1d9313749 --- /dev/null +++ b/desktop/internal/workbench/references_test.go @@ -0,0 +1,246 @@ +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// referencesFixture opens a project holding b.go and a.go and shows five usages in the order a +// server could give them: b.go lines 2 and 7, a.go lines 0, 4 and 9, interleaved. Core lays them +// out with the real kernel, so a.go comes first and each file's usages go by line. +func referencesFixture(t *testing.T) (*harness, *referencesState) { + t.Helper() + h := newHarness(t, &testKernel{Client: core.NewClient()}) + dir := t.TempDir() + for name, text := range map[string]string{ + "a.go": "foo\n\tx\n\n\n\t\tbar := foo\n\n\n\n\n baz(foo)\n", + "b.go": "\n\n\tfoo()\n\n\n\n\n x := foo()\n", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(text), 0o600); err != nil { + t.Fatal(err) + } + } + h.open(dir) + p := h.app.project + files := []string{"b.go", "a.go", "b.go", "a.go", "a.go"} + lines := []int{2, 0, 7, 4, 9} + columns := []int{1, 0, 9, 9, 6} + var targets []core.PluginSemanticLocation + for i, file := range files { + targets = append(targets, locationAt(filepath.Join(p.root, file), lines[i], columns[i])) + } + h.app.showReferences(p, targets, referenceQuery{}, "foo") + return h, &h.app.editor.refs +} + +// rowKeys is the keys of the visible rows. +func rowKeys(s *referencesState) []string { + keys := make([]string, len(s.rows)) + for i, r := range s.rows { + keys[i] = r.Key + } + return keys +} + +func sameKeys(got, want []string) bool { + if len(got) != len(want) { + return false + } + for i := range got { + if got[i] != want[i] { + return false + } + } + return true +} + +func TestReferencesTreeNestsUsagesUnderFilesInFileOrder(t *testing.T) { + _, s := referencesFixture(t) + a, b := "file:"+s.locations[1].FileKey, "file:"+s.locations[0].FileKey + want := []string{"root", a, "usage:1", "usage:3", "usage:4", b, "usage:0", "usage:2"} + if got := rowKeys(s); !sameKeys(got, want) { + t.Fatalf("rows = %v, want %v", got, want) + } + if s.locations[0].DisplayPath != "b.go" || s.groups[0].Name != "a.go" || s.groups[0].Folder != "" { + t.Fatalf("location %+v, first group %+v", s.locations[0], s.groups[0]) + } + if s.groupOf[0] != 1 || s.groupOf[1] != 0 { + t.Fatalf("groupOf = %v", s.groupOf) + } + // Every row keeps a distinct Tree key. + seen := map[int]bool{} + for i := range s.rows { + if seen[s.key(i)] { + t.Fatalf("row %d repeats key %d", i, s.key(i)) + } + seen[s.key(i)] = true + } + if n := s.node(0); n.Depth != 0 || !n.Branch || !n.Expanded { + t.Fatalf("Usages node = %+v", n) + } + if n := s.node(5); n.Depth != 1 || !n.Branch || !n.Expanded { + t.Fatalf("file node = %+v", n) + } + if n := s.node(2); n.Depth != 2 || n.Branch || !n.Selected || s.selected != "usage:1" { + t.Fatalf("first usage = %+v, selected %q; want a selected leaf", n, s.selected) + } +} + +func TestClosingANodeHandsItTheSelectionOfAUsageUnderIt(t *testing.T) { + h, s := referencesFixture(t) + a, b := "file:"+s.locations[1].FileKey, "file:"+s.locations[0].FileKey + if !s.selectRow("usage:3") { + t.Fatal("usage:3 does not show") + } + h.app.toggleReference(a) + if len(s.rows) != 5 || s.selected != a || s.selectedRow != 1 { + t.Fatalf("rows %v, selected %q at %d after closing a.go", rowKeys(s), s.selected, s.selectedRow) + } + // Closing the Usages node takes the selection of a file under it. + s.selectRow(b) + h.app.toggleReference("root") + if len(s.rows) != 1 || s.selected != "root" { + t.Fatalf("rows %v, selected %q after closing Usages", rowKeys(s), s.selected) + } + h.app.toggleReference("root") + if len(s.rows) != 5 || s.rowOf(b) != 2 { + t.Fatalf("rows after opening Usages = %v", rowKeys(s)) + } + // A usage row has nothing to open or close. + h.app.toggleReference("usage:0") + if len(s.rows) != 5 { + t.Fatalf("toggling a usage changed the rows: %v", rowKeys(s)) + } +} + +func TestCollapseAllKeepsTheFilesAndExpandAllShowsEveryUsage(t *testing.T) { + h, s := referencesFixture(t) + b := "file:" + s.locations[0].FileKey + s.selectRow("usage:2") + h.app.toggleReference("root") + h.app.expandReferences(false) + if got := rowKeys(s); len(got) != 3 || s.rows[1].Kind != core.ReferenceRowFile || s.rows[2].Kind != core.ReferenceRowFile { + t.Fatalf("rows after collapse all = %v", got) + } + // Closing Usages first moved the selection to it, so it stays there. + if s.selected != "root" || !s.reveal { + t.Fatalf("selected %q, reveal %v", s.selected, s.reveal) + } + s.selectRow(b) + h.app.expandReferences(true) + if len(s.rows) != 8 || s.selected != b { + t.Fatalf("rows %d, selected %q after expand all", len(s.rows), s.selected) + } + s.selectRow("usage:2") + h.app.expandReferences(false) + if s.selected != b { + t.Fatalf("collapse all left the selection on %q, want b.go's node", s.selected) + } +} + +func TestStepTargetWalksUsagesInTreeOrderWithoutWrapping(t *testing.T) { + h, s := referencesFixture(t) + b := "file:" + s.locations[0].FileKey + var order []int + for target, ok := s.shownTarget(); ok; target, ok = s.stepTarget(true) { + order = append(order, target) + h.app.selectUsage(target) + } + if want := []int{1, 3, 4, 0, 2}; len(order) != len(want) || order[0] != 1 || order[1] != 3 || order[2] != 4 || order[3] != 0 || order[4] != 2 { + t.Fatalf("forward order = %v, want %v", order, want) + } + if _, ok := s.stepTarget(true); ok { + t.Fatal("next went past the last usage") + } + if target, ok := s.stepTarget(false); !ok || target != 0 { + t.Fatalf("previous of the last usage = %d %v", target, ok) + } + // From a node, next is its first usage and previous the usage before it, also under closed + // nodes, which the step opens. + h.app.toggleReference("file:" + s.locations[1].FileKey) + s.selectRow(b) + if target, ok := s.stepTarget(false); !ok || target != 4 { + t.Fatalf("previous of b.go's node = %d %v", target, ok) + } + if target, ok := s.stepTarget(true); !ok || target != 0 { + t.Fatalf("next of b.go's node = %d %v", target, ok) + } + h.app.selectUsage(4) + if s.rowOf("usage:4") != 4 || s.selected != "usage:4" || !s.reveal { + t.Fatalf("selecting a hidden usage did not open its file: %v, selected %q", rowKeys(s), s.selected) + } + s.selectRow("root") + if _, ok := s.stepTarget(false); ok { + t.Fatal("previous of the Usages node found a usage") + } + if target, ok := s.stepTarget(true); !ok || target != 1 { + t.Fatalf("next of the Usages node = %d %v", target, ok) + } +} + +func TestShownTargetFollowsTheSelectedRow(t *testing.T) { + _, s := referencesFixture(t) + cases := []struct { + key string + want int + }{ + {"root", 1}, + {"file:" + s.locations[0].FileKey, 0}, + {"usage:4", 4}, + } + for _, c := range cases { + s.selectRow(c.key) + if got, ok := s.shownTarget(); !ok || got != c.want { + t.Fatalf("shown for %q = %d %v, want %d", c.key, got, ok, c.want) + } + } + if _, ok := (&referencesState{selectedRow: -1}).shownTarget(); ok { + t.Fatal("an empty answer showed a usage") + } +} + +func TestReferenceLinesComeFromCoreWithTheUsageMarked(t *testing.T) { + h, s := referencesFixture(t) + h.await("the usages' lines", func() bool { return s.lines[4].Text != "" }) + // Each row's line loses its indentation and keeps the usage marked in what is left. + want := map[int]string{0: "foo()", 1: "foo", 2: "x := foo()", 3: "bar := foo", 4: "baz(foo)"} + for i, text := range want { + line := s.lines[i] + spans := utf16Spans(line.Text, line.Ranges) + if line.Text != text || len(spans) != 1 || line.Text[spans[0][0]:spans[0][1]] != "foo" { + t.Fatalf("line %d = %+v, want %q with foo marked", i, line, text) + } + } +} + +func TestReferenceLocationKeysFilesByPathAndOthersByURI(t *testing.T) { + root := filepath.Join(string(filepath.Separator), "w") + inside := referenceLocation(root, locationAt(filepath.Join(root, "ui", "absolute.go"), 3, 7)) + if inside.FileKey != filepath.Join(root, "ui", "absolute.go") || inside.DisplayPath != "ui/absolute.go" || inside.Line != 3 || inside.Column != 7 { + t.Fatalf("file in the project = %+v", inside) + } + outsidePath := filepath.Join(string(filepath.Separator), "lib", "x.go") + if outside := referenceLocation(root, locationAt(outsidePath, 0, 0)); outside.DisplayPath != filepath.ToSlash(outsidePath) { + t.Fatalf("file outside the project = %+v", outside) + } + jar := "jar:file:///lib/rt.jar!/java/lang/String.class" + if other := referenceLocation(root, core.PluginSemanticLocation{URI: jar}); other.FileKey != jar || other.DisplayPath != jar { + t.Fatalf("location that is not a file = %+v", other) + } +} + +func TestReferenceLinesRequestSendsEachTextOnce(t *testing.T) { + targets := []core.PluginSemanticLocation{ + locationAt("/w/a.go", 0, 0), locationAt("/w/a.go", 0, 4), locationAt("/w/b.go", 1, 2), + } + request, asked := referenceLinesRequest(targets, []string{"a = a", "a = a", ""}, []bool{true, true, false}) + if len(request.Texts) != 1 || len(request.Usages) != 2 || len(asked) != 2 || asked[1] != 1 { + t.Fatalf("request %+v, asked %v", request, asked) + } + if u := request.Usages[1]; u.Text != 0 || u.Column != 4 || u.EndColumn != 7 { + t.Fatalf("second usage = %+v", u) + } +} diff --git a/desktop/internal/workbench/references_view.go b/desktop/internal/workbench/references_view.go index ba0299619e..79e20a083b 100644 --- a/desktop/internal/workbench/references_view.go +++ b/desktop/internal/workbench/references_view.go @@ -4,86 +4,325 @@ import ( "strconv" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/fileicons" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/treelist" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) -// referencesPanel declares the References tool window: a header per file over its references. +// referencesPanel declares the References tool window: the toolbar, the tree of usages and, +// beside it, the preview of the selected usage's file. func (a *App) referencesPanel(c ui.C, p *project) { s := &a.editor.refs - if s.project != p || s.rows == 0 { + if s.project != p || len(s.targets) == 0 { a.panelMessage(c, i18n.Shared(a.language(), "desktop.references.empty"), a.colors.Subtle) return } - if s.list.Key == nil { - s.list.Header = func(i int) bool { _, _, header := s.rowAt(i); return header } - s.list.Label = s.rowLabel - } - opened := -1 - ui.List(c, &s.list, s.rows, func(row ui.ListRow) { - group, index, header := s.rowAt(row.Index) - if header { - a.drawReferenceHeader(row, s.groups[group]) - } else if a.drawReferenceRow(row, group, index) { - opened = row.Index - } - }).Scrollbars().Label(i18n.Shared(a.language(), "desktop.semantics.references")).FillWidth().Grow(1).Shrink(1).MinHeight(0) - if row, ok := s.list.Submitted(); ok { - opened = row - } - if group, index, header := s.rowAt(opened); opened >= 0 && !header { - if target, ok := s.target(group, index); ok { + lang := a.language() + ui.Row(c).Fill().Clip().Children(func() { + a.referencesToolbar(c, p, lang) + ui.Divider(c) + if s.hidePreview { + ui.Column(c).Grow(1).Basis(0).Shrink(1).MinWidth(0).FillHeight().MinHeight(0).Children(func() { a.referencesTree(c, lang) }) + return + } + a.syncReferencePreview(p) + if s.split.Pos <= 0 { + s.split.Pos = referenceTreeWidth + } + ui.Row(c).Grow(1).Basis(0).Shrink(1).MinWidth(0).FillHeight().MinHeight(0).Children(func() { + ui.Column(c).Width(s.split.Pos).Shrink(0).FillHeight().MinHeight(0).Children(func() { a.referencesTree(c, lang) }) + ui.Splitter(c, &s.split).Mins(referenceTreeMin, referencePreviewMin).Label(a.text.Panel.Resize) + a.referencesPreviewPane(c, lang) + }) + }) +} + +// referencesToolbar declares the column of actions left of the tree, as IDEA's Find tool window +// puts them: ask again, step to the previous or next usage, open or close every file's node, and +// turn the preview on or off. +func (a *App) referencesToolbar(c ui.C, p *project, lang i18n.Language) { + s := &a.editor.refs + ui.Column(c).FillHeight().Shrink(0).Gap(2).Pad(4).Children(func() { + if _, clicked := a.toolIconButton(c.Part("rerun"), i18n.Shared(lang, "native.rerun"), icons.RotateCcw, false, s.queryDocument(p) == nil); clicked { + c.After(func() { + a.performed("editor.references.rerun", surfaceButton) + a.rerunReferences(p) + }) + } + _, hasPrevious := s.stepTarget(false) + if _, clicked := a.toolIconButton(c.Part("previous"), i18n.Shared(lang, "desktop.references.previousUsage"), icons.ArrowUp, false, !hasPrevious); clicked { + c.After(func() { + a.performed("editor.references.previous", surfaceButton) + a.stepReference(false) + }) + } + _, hasNext := s.stepTarget(true) + if _, clicked := a.toolIconButton(c.Part("next"), i18n.Shared(lang, "desktop.references.nextUsage"), icons.ArrowDown, false, !hasNext); clicked { + c.After(func() { + a.performed("editor.references.next", surfaceButton) + a.stepReference(true) + }) + } + if _, clicked := a.toolIconButton(c.Part("expand"), i18n.Shared(lang, "outline.expandAll"), icons.ChevronsUpDown, false, false); clicked { + c.After(func() { a.expandReferences(true) }) + } + if _, clicked := a.toolIconButton(c.Part("collapse"), i18n.Shared(lang, "outline.collapseAll"), icons.ChevronsDownUp, false, false); clicked { + c.After(func() { a.expandReferences(false) }) + } + if _, clicked := a.toolIconButton(c.Part("preview"), i18n.Shared(lang, "desktop.references.showPreview"), icons.PanelRight, !s.hidePreview, false); clicked { + show := s.hidePreview c.After(func() { - a.performed("editor.references.open", surfaceButton) - a.openReference(p, target) + a.performed("editor.references.preview", surfaceButton) + a.setReferencePreview(show) }) } + }) +} + +// referencesTree declares the tree of usages. A click selects a row, and the preview follows it; +// a double click or Enter opens a usage, or opens or closes a node. With the preview off, a click +// on a usage opens it, as there is nothing else to show it. +func (a *App) referencesTree(c ui.C, lang i18n.Language) { + s := &a.editor.refs + if s.view.Node == nil { + s.view.Node = s.node + s.view.Key = s.key + s.view.Label = func(i int) string { return a.referenceRowLabel(i) } + s.view.RowHeight = treelist.RowHeight + s.view.Indent = treelist.Indent + } + s.view.Disclosure = &components.TreeDisclosure{ + Collapsed: fileicons.TreeChevron(false, a.colors.Dark), + Expanded: fileicons.TreeChevron(true, a.colors.Dark), + Size: 16, } + a.syncReferenceSelection(c.Canvas()) + ui.Tree(c, &s.view, len(s.rows), s.view.Label, func(i int) { + a.drawReferenceRow(c, i, lang) + }).Scrollbars().Label(i18n.Shared(lang, "desktop.semantics.references")).Grow(1).FillWidth().MinHeight(0).PadY(treelist.PadY) + if i, ok := s.view.Toggled(); ok && i < len(s.rows) { + key := s.rows[i].Key + c.After(func() { a.toggleReference(key) }) + } + i, ok := s.view.Chosen() + if !ok || i >= len(s.rows) { + return + } + info, clicked := c.Canvas().ClickInfo() + repeated := clicked && info.Clicks >= 2 + row := s.rows[i] + // The row a click chose takes the keyboard, so the arrow keys go on from it. + c.Canvas().RequestFocus(s.view.RowID(i)) + c.After(func() { + if !s.selectRow(row.Key) { + return // a node above it closed in this frame + } + if clicked && !repeated && (row.Kind != core.ReferenceRowUsage || !s.hidePreview) { + return // a single click only selects + } + if row.Kind == core.ReferenceRowUsage { + a.performed("editor.references.open", surfaceButton) + a.openReference(s.targets[row.Shows]) + return + } + a.toggleReference(row.Key) + }) } -// target is the reference at index of group. -func (s *referencesState) target(group, index int) (core.PluginSemanticLocation, bool) { - if group < 0 || group >= len(s.groups) || index < 0 || index >= len(s.groups[group].indices) { - return core.PluginSemanticLocation{}, false +// syncReferenceSelection makes the selection follow the keyboard: a row the arrow keys moved the +// focus to is selected. Only a move of the focus selects, so a selection the toolbar made stays +// while the focus is on another row. A selection asked to show is scrolled into view, and takes +// the keyboard when the tree has it. +func (a *App) syncReferenceSelection(canvas *gfx.Canvas) { + s := &a.editor.refs + focused := canvas.Focused() + inTree := false + if focused != s.focus || s.reveal { + for i := range s.rows { + if s.view.RowID(i) == focused { + inTree = true + if focused != s.focus { + s.selected, s.selectedRow = s.rows[i].Key, i + } + break + } + } + s.focus = focused + } + selected := s.selectedRow + if selected >= len(s.rows) { + selected = -1 + } + if s.reveal && selected >= 0 { + if first, last := s.view.Visible(); selected < first || selected > last { + s.view.ScrollTo(selected, ui.ListCenter) + canvas.RequestFrame() + } + if inTree { + canvas.RequestFocus(s.view.RowID(selected)) + } + s.reveal = false + } + if s.view.Selected() != selected { + s.view.Select(selected) } - return s.targets[s.groups[group].indices[index]], true } -// rowLabel names a row to assistive technology: a file's path, or a reference's line. -func (s *referencesState) rowLabel(i int) string { - group, index, header := s.rowAt(i) - if header { - return s.groups[group].display +// referenceRowLabel names row i to assistive technology: the Usages node with the number found, a +// file with its path and number of usages, or a usage with its file, line and text. +func (a *App) referenceRowLabel(i int) string { + s := &a.editor.refs + if i < 0 || i >= len(s.rows) { + return "" } - if s.groups[group].indices != nil && index >= 0 && index < len(s.groups[group].indices) { - at := s.groups[group].indices[index] - return s.groups[group].display + ":" + strconv.Itoa(s.targets[at].Range.Start.Line+1) + " " + s.previews[at] + lang := a.language() + switch r := s.rows[i]; r.Kind { + case core.ReferenceRowRoot: + return i18n.Shared(lang, "desktop.references.usages") + " " + referenceResults(lang, len(s.targets)) + case core.ReferenceRowFile: + g := s.groups[referenceRowGroup(r)] + return g.DisplayPath + " " + referenceUsages(lang, len(g.Indices)) + default: + at := s.targets[r.Shows].Range.Start.Line + 1 + return s.groups[referenceRowGroup(r)].DisplayPath + ":" + strconv.Itoa(at) + " " + s.lines[r.Shows].Text } - return "" } -func (a *App) drawReferenceHeader(row ui.ListRow, group usageGroup) { - c := row.C - row.Element.FillWidth().Height(referenceRowHeight).PadX(10).Items(ui.Center).Gap(6).Background(a.colors.Panel).Children(func() { - ui.Text(c, group.display).Grow(1).Shrink(1).FontSize(12.5).Bold().Color(a.colors.Text).Ellipsis() - ui.Text(c, strconv.Itoa(len(group.indices))).Shrink(0).FontSize(11.5).Color(a.colors.Subtle) - }) +// referenceResults is how many usages were found, as the Usages node and the preview say it. +func referenceResults(lang i18n.Language, n int) string { + if n == 1 { + return i18n.Shared(lang, "desktop.references.resultCountOne") + } + return i18n.SharedFormat(lang, "desktop.references.resultCount", map[string]string{"count": strconv.Itoa(n)}) +} + +// referenceUsages is how many usages a file holds. +func referenceUsages(lang i18n.Language, n int) string { + if n == 1 { + return i18n.Shared(lang, "desktop.references.usageCountOne") + } + return i18n.SharedFormat(lang, "desktop.references.usageCount", map[string]string{"count": strconv.Itoa(n)}) } -// drawReferenceRow declares one reference and reports whether it was clicked. -func (a *App) drawReferenceRow(row ui.ListRow, group, index int) bool { +// drawReferenceRow declares what row i shows after its chevron: the Usages node in bold with the +// number found; a file's icon, name, folder and number of usages; or a usage's line number and +// line, the usage in bold. A usage row has no chevron, so it keeps the chevron's room empty and +// its text lines up under its file's icon. +func (a *App) drawReferenceRow(c ui.C, i int, lang i18n.Language) { s := &a.editor.refs - target, ok := s.target(group, index) - if !ok { - return false + switch r := s.rows[i]; r.Kind { + case core.ReferenceRowRoot: + ui.Text(c, i18n.Shared(lang, "desktop.references.usages")).FontSize(treeFontSize).Bold().Color(a.colors.Text).Shrink(0) + ui.Text(c, referenceResults(lang, len(s.targets))).FontSize(treeFontSize).Color(a.colors.Subtle).Shrink(0) + case core.ReferenceRowFile: + g := s.groups[referenceRowGroup(r)] + ui.Icon(c, fileicons.ForFile(g.Name, a.colors.Dark)).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, g.Name).FontSize(treeFontSize).Color(a.colors.Text).Shrink(0) + if g.Folder != "" { + ui.Text(c, g.Folder).FontSize(treeFontSize).Color(a.colors.Subtle).Shrink(1).MinWidth(0).Ellipsis() + } + ui.Text(c, referenceUsages(lang, len(g.Indices))).FontSize(treeFontSize).Color(a.colors.Subtle).Shrink(0) + default: + line := strconv.Itoa(s.targets[r.Shows].Range.Start.Line + 1) + ui.Row(c).Shrink(1).MinWidth(0).Items(ui.Center).Gap(c.Theme().Metrics.GapItem).PadLeft(treeChevron).Children(func() { + ui.Text(c, line).FontSize(treeFontSize).Color(a.colors.Subtle).Shrink(0) + a.referenceLineText(c, s.lines[r.Shows]) + }) } - at := s.groups[group].indices[index] - c := row.C - position := strconv.Itoa(target.Range.Start.Line+1) + ":" + strconv.Itoa(target.Range.Start.UTF16Column+1) - row.Element.FillWidth().Height(referenceRowHeight).PadX(10).Items(ui.Center).Gap(8). - Hover(ui.Look{}.Background(a.colors.Hover)).Children(func() { - ui.Text(c, position).Shrink(0).FontSize(11.5).Color(a.colors.Subtle).Width(52) - ui.Text(c, s.previews[at]).Grow(1).Shrink(1).FontSize(12.5).Color(a.colors.Text).Ellipsis() +} + +// referenceLineText declares a usage's line in the editor's font, the usage in bold (semibold barely +// shows in a fixed-pitch face), cut short at the row's end. +func (a *App) referenceLineText(c ui.C, line core.ReferenceLine) { + spans := utf16Spans(line.Text, line.Ranges) + part := func(text string, bold bool) { + if text == "" { + return + } + t := ui.Text(c, text).Mono().FontSize(treeFontSize).Color(a.colors.Text) + if bold { + t.Weight(gfx.WeightBold).Shrink(0) + } else { + t.Shrink(1).MinWidth(0).Ellipsis() + } + } + ui.Row(c).Shrink(1).MinWidth(0).Clip().Children(func() { + cursor := 0 + for _, span := range spans { + part(line.Text[cursor:span[0]], false) + part(line.Text[span[0]:span[1]], true) + cursor = span[1] + } + part(line.Text[cursor:], false) + }) +} + +// referencesPreviewPane declares the preview of the selected usage's file: its name and how many +// usages it holds over the read-only source. +func (a *App) referencesPreviewPane(c ui.C, lang i18n.Language) { + s := &a.editor.refs + ui.Column(c).Grow(1).Basis(0).Shrink(1).MinWidth(0).FillHeight().MinHeight(0).Children(func() { + if target, ok := s.shownTarget(); ok { + g := s.groups[s.groupOf[target]] + ui.Row(c).FillWidth().Height(treelist.RowHeight + 6).Shrink(0).Items(ui.Center).Gap(6).PadX(10).Children(func() { + ui.Icon(c, fileicons.ForFile(g.Name, a.colors.Dark)).Size(treelist.Icon, treelist.Icon).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, g.Name).FontSize(treeFontSize).Color(a.colors.Accent).Shrink(0) + if g.Folder != "" { + ui.Text(c, g.Folder).FontSize(treeFontSize).Color(a.colors.Subtle).Shrink(1).MinWidth(0).Ellipsis() + } + ui.Spacer(c) + ui.Text(c, referenceUsages(lang, len(g.Indices))).FontSize(treeFontSize).Color(a.colors.Subtle).Shrink(0) + }) + ui.Divider(c) + } + a.sourcePreviewPane(c, &s.preview, "referencesPreview", i18n.Shared(lang, "desktop.references.previewEmpty")) + }) +} + +// referencesSearchTab declares the header's tab of the shown answer, named for the symbol it was +// asked for, as IDEA's Find tool window names its tab, with the × that closes it. Closing the +// only tab closes the tool window, as IDEA does. The row takes the room a spacer would. +func (a *App) referencesSearchTab(c ui.C, p *project) { + s := &a.editor.refs + ui.Row(c).Grow(1).Shrink(1).MinWidth(0).Height(panelHeaderHeight).Items(ui.Center).Gap(2).Clip().Children(func() { + if s.project == p && len(s.targets) > 0 { + lang := a.language() + name := s.symbol + if name == "" { + name = i18n.Shared(lang, "desktop.references.usages") + } + k := c.Key("referencesSearch") + chip := ui.Row(k).Height(rowHeight).Shrink(1).MinWidth(0).Items(ui.Center).Gap(6).PadSides(0, 2, 0, toolTabPad). + Background(a.colors.TabIdle).Stroke(1, a.colors.TabIdleBorder).Radius(6). + HitWith(ui.ID(k), name, gfx.HitOptions{Role: gfx.RoleTab, Selected: true, PosInSet: 1, SetSize: 1}). + Tooltip(name) + var closeButton ui.Box + chip.Children(func() { + ui.Text(k, name).Color(a.colors.Text).Ellipsis().Shrink(1) + cc := k.Part("close") + label := i18n.Shared(lang, "desktop.references.closeSearch") + closeButton = ui.Row(cc).Size(terminalCloseSize, terminalCloseSize).Shrink(0).Center(). + Radius(a.theme.Metrics.RadiusItem()). + HitWith(ui.ID(cc), label, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand}). + Tooltip(label). + Hover(ui.Look{}.Background(a.colors.Hover)).Pressed(ui.Look{}.Background(a.colors.Active)) + closeButton.Children(func() { + ui.Icon(cc, icons.X).Size(terminalCloseIcon, terminalCloseIcon).Color(a.colors.Subtle). + StateFrom(closeButton).Hover(ui.Look{}.Color(a.colors.Text)) + }) + }) + if closeButton.Clicked() { + c.After(func() { + a.performed("editor.references.close", surfaceButton) + a.closeReferences() + a.reduceChrome(core.SetChromeOpen(itemReferences, false)) + }) + } + } + ui.Spacer(c) }) - return row.Element.Clicked() } diff --git a/desktop/internal/workbench/references_visual_test.go b/desktop/internal/workbench/references_visual_test.go new file mode 100644 index 0000000000..db2294fcfa --- /dev/null +++ b/desktop/internal/workbench/references_visual_test.go @@ -0,0 +1,136 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "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/gfx" + "github.com/vivaui/viva/headless" +) + +// TestVisualReferencesToolWindow captures the References tool window after Find Usages on a +// constant used in two files: the tree of usages under their files, the toolbar, the header's +// tab and the preview of the selected usage; then the editor's menu opened on the constant. +// Dark/light x Chinese/English are independent sessions and OS-free. +func TestVisualReferencesToolWindow(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 _, look := range []struct{ theme, language string }{ + {"dark", "zh-Hans"}, {"dark", "en"}, + {"light", "zh-Hans"}, {"light", "en"}, + } { + t.Run(look.theme+"-"+look.language, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{ + Theme: themeChoice(look.theme), Language: look.language, + DisableAutoSave: true, + }); err != nil { + t.Fatal(err) + } + root := filepath.Join(t.TempDir(), "viva") + if err := os.MkdirAll(filepath.Join(root, "ui"), 0700); err != nil { + t.Fatal(err) + } + absolute := filepath.Join(root, "ui", "absolute.go") + layout := filepath.Join(root, "ui", "layout.go") + files := map[string]string{ + absolute: "package ui\n\n// The ways a box is placed.\nconst (\n\tabsSelf uint8 = 1 << 0\n\tabsChild uint8 = 1 << 1\n)\n\n// placedSelf reports whether the box is placed by itself.\nfunc placedSelf(flags uint8) bool {\n\treturn flags&absSelf != 0\n}\n", + layout: "package ui\n\nfunc (b *Box) Absolute() *Box {\n\tb.flags |= absSelf\n\treturn b\n}\n\nfunc (b *Box) measure() {\n\tif b.flags&absSelf == 0 {\n\t\tb.flow()\n\t}\n}\n", + } + for path, source := range files { + if err := os.WriteFile(path, []byte(source), 0600); err != nil { + t.Fatal(err) + } + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + Store: prefs, Languages: []string{look.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.open(root) + p := h.app.project + h.app.openFile(p, absolute) + h.settleChain() + d := p.docs.byPath(absolute) + if d == nil { + t.Fatal("editor not opened") + } + usage := func(path string, line, column int) core.PluginSemanticLocation { + return core.PluginSemanticLocation{ + URI: "file://" + filepath.ToSlash(path), FilePath: path, + Range: core.PluginDocumentRange{ + Start: core.PluginDocumentPosition{Line: line, UTF16Column: column}, + End: core.PluginDocumentPosition{Line: line, UTF16Column: column + len("absSelf")}, + }, + } + } + targets := []core.PluginSemanticLocation{ + usage(absolute, 4, 1), usage(absolute, 10, 14), + usage(layout, 3, 12), usage(layout, 8, 12), + } + showVisualReferences(h.app, p, d, targets) + h.settleChain() + h.await("the usage's preview", func() bool { return visualReferencesReady(h.app) }) + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "references-"+look.theme+"-"+look.language+".png")); err != nil { + t.Fatal(err) + } + + // The editor's menu opened on absSelf, whose Find Usages asks at the word clicked. + d.view.GoToNavigation(4, 3, false) + h.settleChain() + cell, ok := d.view.CaretRect() + if !ok { + t.Fatal("the editor has not painted") + } + if err := session.Driver().ClickButton(cell.X, cell.Y+cell.Height/2, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + h.settleChain() + h.popupHit(h.shared("desktop.editorMenu.findUsages")) + if err := session.Screenshot(filepath.Join(out, "references-menu-"+look.theme+"-"+look.language+".png")); err != nil { + t.Fatal(err) + } + }) + } +} + +// showVisualReferences fills the References tool window as an answer of Find Usages on absSelf +// at its declaration does. +func showVisualReferences(a *App, p *project, d *document, targets []core.PluginSemanticLocation) { + a.showReferences(p, targets, referenceQuery{documentID: d.id, line: 4, column: 1}, "absSelf") +} + +// visualReferencesReady reports whether the window shows what is captured: the preview loaded +// and every usage's line, which Core cuts off the window thread. +func visualReferencesReady(a *App) bool { + s := &a.editor.refs + if s.preview.view == nil { + return false + } + for _, line := range s.lines { + if line.Text == "" { + return false + } + } + return true +} diff --git a/desktop/internal/workbench/search.go b/desktop/internal/workbench/search.go index 735d084e80..e46185eaf9 100644 --- a/desktop/internal/workbench/search.go +++ b/desktop/internal/workbench/search.go @@ -389,44 +389,6 @@ func searchMatchColumn(match core.WorkspaceSearchMatch) int { return match.ContentMatchRanges[0].Start + 1 } -// searchPreviewLead is how many UTF-16 units of a line are kept in front of its first -// match; a match further right is brought into view by cutting the start of the line. -const searchPreviewLead = 32 - -// searchPreviewLine is the preview of a content match with its highlights: the line -// without its indentation, cut in front of a far match so the match is not lost to the -// row's end. -func searchPreviewLine(match core.WorkspaceSearchMatch) (string, []core.SearchNameRange) { - if match.SourceLine == nil { - return match.Preview, nil - } - line, ranges := trimHighlightedLine(*match.SourceLine, match.ContentMatchRanges) - if len(ranges) == 0 || ranges[0].Start <= searchPreviewLead { - return line, ranges - } - cut := ranges[0].Start - searchPreviewLead/2 - // Walk to the byte offset of UTF-16 unit cut, not splitting a surrogate pair. - units, offset := 0, len(line) - for i, r := range line { - if units >= cut { - offset = i - break - } - units++ - if r >= 0x10000 { - units++ - } - } - shifted := make([]core.SearchNameRange, 0, len(ranges)) - for _, r := range ranges { - if r.Start >= units { - // One unit for the ellipsis put in front. - shifted = append(shifted, core.SearchNameRange{Start: r.Start - units + 1, Length: r.Length}) - } - } - return "…" + line[offset:], shifted -} - // openFindInFiles shows the Find in Files tool window with the keyboard in its query, and // replace opens its Replace field too. A selection of one line in the editor becomes the // query, as in the IDE; otherwise the last query stays. diff --git a/desktop/internal/workbench/search_everywhere_view.go b/desktop/internal/workbench/search_everywhere_view.go index f002a0b268..7157a80df2 100644 --- a/desktop/internal/workbench/search_everywhere_view.go +++ b/desktop/internal/workbench/search_everywhere_view.go @@ -311,11 +311,8 @@ 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() { - text, ranges := result.Preview, []core.SearchNameRange(nil) - if result.SourceLine != nil { - text, ranges = trimHighlightedLine(*result.SourceLine, result.ContentMatchRanges) - } - a.highlightedText(c, text, ranges, a.colors.Text, 12, true) + // 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) location := name if result.Line != nil { location += ":" + strconv.Itoa(*result.Line) @@ -403,19 +400,6 @@ func utf16Spans(text string, ranges []core.SearchNameRange) [][2]int { return spans } -// trimHighlightedLine drops the line's leading whitespace and moves the ranges with it. -func trimHighlightedLine(line string, ranges []core.SearchNameRange) (string, []core.SearchNameRange) { - trimmed := strings.TrimLeft(line, " \t") - removed := len(line) - len(trimmed) // spaces and tabs are one UTF-16 unit each - out := make([]core.SearchNameRange, 0, len(ranges)) - for _, r := range ranges { - if r.Start >= removed { - out = append(out, core.SearchNameRange{Start: r.Start - removed, Length: r.Length}) - } - } - return strings.TrimRight(trimmed, "\r\n"), out -} - // searchResultMenu is the context menu of a search result, in Search Everywhere and in the // Find in Files results: open it, show it in the file manager, or copy its path. The actions // are recorded under surface; leave, when set, runs before the result opens. diff --git a/desktop/internal/workbench/search_view.go b/desktop/internal/workbench/search_view.go index d2b22efe78..51bfd1b1fd 100644 --- a/desktop/internal/workbench/search_view.go +++ b/desktop/internal/workbench/search_view.go @@ -118,7 +118,8 @@ func (a *App) searchResults(c ui.C, p *project, language i18n.Language) { ui.Text(row.C, searchLinePosition(result)).FontSize(12).Color(a.colors.Subtle) } }) - preview, ranges := searchPreviewLine(result) + // 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) }) diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 58dcf36ee8..f15c9869db 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -86,7 +86,7 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { p := a.project tabbed := tool.id == itemGit header := float32(toolTitleHeight) - if tabbed || tool.id == itemTerminal || tool.id == itemCommit || tool.id == itemRun { + if tabbed || tool.id == itemTerminal || tool.id == itemCommit || tool.id == itemRun || tool.id == itemReferences { header = panelHeaderHeight } if tool.id == itemFind && p != nil { @@ -117,6 +117,9 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { case tool.id == itemRun && p != nil: // So do the tabs of the Run window's executions. a.runSessionTabs(c, p) + case tool.id == itemReferences && p != nil: + // And the tab of the usages the References window shows. + a.referencesSearchTab(c, p) default: ui.Spacer(c) } diff --git a/desktop/internal/workbench/source_preview.go b/desktop/internal/workbench/source_preview.go index 631fb98cc6..40ae93b6fb 100644 --- a/desktop/internal/workbench/source_preview.go +++ b/desktop/internal/workbench/source_preview.go @@ -11,8 +11,9 @@ import ( ) // sourcePreview is a read-only view of one file that follows a selection in a list -// (Search Everywhere). It never takes the window's keyboard focus or writes the file, -// and an open document lends it its current text, so unsaved edits show. +// (Search Everywhere, Problems, References). It never takes the window's keyboard focus +// or writes the file, and an open document lends it its current text, so unsaved edits +// show. type sourcePreview struct { // path is the file shown and line the one-based line revealed. A load replaces // view when its answer arrives for the same generation. diff --git a/docs/assets/references-find-usages/after/references-dark-zh-Hans.png b/docs/assets/references-find-usages/after/references-dark-zh-Hans.png new file mode 100644 index 0000000000..783e613e61 Binary files /dev/null and b/docs/assets/references-find-usages/after/references-dark-zh-Hans.png differ diff --git a/docs/assets/references-find-usages/after/references-light-en.png b/docs/assets/references-find-usages/after/references-light-en.png new file mode 100644 index 0000000000..d9aba2a836 Binary files /dev/null and b/docs/assets/references-find-usages/after/references-light-en.png differ diff --git a/docs/assets/references-find-usages/after/references-menu-dark-zh-Hans.png b/docs/assets/references-find-usages/after/references-menu-dark-zh-Hans.png new file mode 100644 index 0000000000..409f3de507 Binary files /dev/null and b/docs/assets/references-find-usages/after/references-menu-dark-zh-Hans.png differ diff --git a/docs/assets/references-find-usages/after/references-menu-light-en.png b/docs/assets/references-find-usages/after/references-menu-light-en.png new file mode 100644 index 0000000000..466e581c6b Binary files /dev/null and b/docs/assets/references-find-usages/after/references-menu-light-en.png differ diff --git a/docs/assets/references-find-usages/before/references-dark-zh-Hans.png b/docs/assets/references-find-usages/before/references-dark-zh-Hans.png new file mode 100644 index 0000000000..5ce3bbec06 Binary files /dev/null and b/docs/assets/references-find-usages/before/references-dark-zh-Hans.png differ diff --git a/docs/assets/references-find-usages/before/references-light-en.png b/docs/assets/references-find-usages/before/references-light-en.png new file mode 100644 index 0000000000..7c4538832e Binary files /dev/null and b/docs/assets/references-find-usages/before/references-light-en.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 77a557daa3..30457f086f 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,13 @@ native_path() { fi } +# Lithe-core-rust #80 at 81a6ecf, the branch of the draft on top of main 788e61e (#79, #78): +# lsp.references.query lays out the References tool window (usages grouped in natural file +# order, the rows visible under the folds the desktop sends, the usage each row previews and the +# usages before and after it, a selection behind a closed node moved to that node); +# lsp.references.lines cuts each usage's line by the rule search results use, and +# workspace.search answers previewRanges with that preview (#2096). The pin moves to the squash +# merge once #80 is in main. # Lithe-core-rust main at 6a29169, #70 squash-merged on top of c928514 (#73): # editor.copyReferenceLocation formats the innermost document symbol a language server reports # around the caret, with a one-based line, and falls back to the file path when none contains it; @@ -178,7 +185,7 @@ 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="788e61eb62177dff4cb0bfe11a48eed0a1083fb3" +PINNED_CORE_REVISION="81a6ecf947ccde35d4abc9a56111acce892470ed" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 8fd1f51394..b628e06960 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -722,6 +722,16 @@ "debugger.variablesEmpty": "Pause on a frame to inspect values.", "debugger.watch": "Watch", "debugger.watchEmpty": "Add expressions to inspect while paused.", + "desktop.references.closeSearch": "Close Search Results", + "desktop.references.nextUsage": "Next Usage", + "desktop.references.previewEmpty": "Select a usage to preview it.", + "desktop.references.previousUsage": "Previous Usage", + "desktop.references.resultCount": "{count} results", + "desktop.references.resultCountOne": "1 result", + "desktop.references.showPreview": "Show Preview", + "desktop.references.usageCount": "{count} usages", + "desktop.references.usageCountOne": "1 usage", + "desktop.references.usages": "Usages", "desktop.search.collapseFile": "Hide details", "desktop.search.expandFile": "Show details", "desktop.aiCommit.cancel": "Cancel generation", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 5db2d566af..1d1af58846 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -722,6 +722,16 @@ "debugger.variablesEmpty": "暂停在栈帧上以查看变量值。", "debugger.watch": "监视", "debugger.watchEmpty": "添加表达式,以便暂停时查看。", + "desktop.references.closeSearch": "关闭搜索结果", + "desktop.references.nextUsage": "下一个用法", + "desktop.references.previewEmpty": "选择一个用法以预览。", + "desktop.references.previousUsage": "上一个用法", + "desktop.references.resultCount": "{count} 个结果", + "desktop.references.resultCountOne": "1 个结果", + "desktop.references.showPreview": "显示预览", + "desktop.references.usageCount": "{count} 个用法", + "desktop.references.usageCountOne": "1 个用法", + "desktop.references.usages": "用法", "desktop.search.collapseFile": "收起详情", "desktop.search.expandFile": "展开详情", "desktop.aiCommit.cancel": "取消生成", @@ -952,7 +962,7 @@ "desktop.editorMenu.back": "后退", "desktop.editorMenu.deleteLine": "删除行", "desktop.editorMenu.duplicateLine": "复制行", - "desktop.editorMenu.findUsages": "查找引用", + "desktop.editorMenu.findUsages": "查找用法", "desktop.editorMenu.forward": "前进", "desktop.editorMenu.goToDefinition": "跳转到定义", "desktop.editorMenu.goToLine": "跳转到行…", @@ -1361,7 +1371,7 @@ "desktop.project.readFailed": "读取失败:{reason}", "desktop.project.rootUnavailable": "项目目录不可用。", "desktop.project.watchUnavailable": "项目文件可能无法自动更新。", - "desktop.references.empty": "使用“查找引用”(Shift+F12)后,结果显示在这里。", + "desktop.references.empty": "使用“查找用法”(Shift+F12)后,结果显示在这里。", "desktop.run.closeSession": "关闭", "desktop.run.durationHours": "{hours}小时{minutes}分", "desktop.run.durationMilliseconds": "{milliseconds}毫秒", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index a33aa06cee..f094fd0152 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -14830,6 +14830,13 @@ "desktop" ] }, + { + "id": "desktop.references.closeSearch", + "description": "References tool window header tab: button that closes the find-usages results", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.references.empty", "description": "References tool window text before any find-usages answer", @@ -14837,6 +14844,75 @@ "desktop" ] }, + { + "id": "desktop.references.nextUsage", + "description": "References tool window toolbar: select and open the next usage", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.references.previewEmpty", + "description": "References tool window preview pane before a usage with a local file is selected", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.references.previousUsage", + "description": "References tool window toolbar: select and open the previous usage", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.references.resultCount", + "description": "References tool window: number of usages found, more than one", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "integer" + } + }, + { + "id": "desktop.references.resultCountOne", + "description": "References tool window: exactly one usage found", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.references.showPreview", + "description": "References tool window toolbar: toggle the preview of the selected usage's file", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.references.usageCount", + "description": "References tool window: number of usages in one file, more than one", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "integer" + } + }, + { + "id": "desktop.references.usageCountOne", + "description": "References tool window: exactly one usage in a file", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.references.usages", + "description": "References tool window: root node of the usages tree, and the header tab's name when no symbol is known", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.refs.checkedOutAndRebased", "description": "Desktop Git log reference menu: notice after {branch} was checked out and replayed onto the branch checked out before.", diff --git a/shared/platform-feature-matrix/features/references-pane.json b/shared/platform-feature-matrix/features/references-pane.json index a2112dd2a0..f5a326d201 100644 --- a/shared/platform-feature-matrix/features/references-pane.json +++ b/shared/platform-feature-matrix/features/references-pane.json @@ -9,9 +9,13 @@ "evidence": [ "desktop/internal/workbench/references.go", "desktop/internal/workbench/references_view.go", + "desktop/internal/workbench/references_test.go", + "desktop/internal/workbench/references_visual_test.go", "desktop/internal/workbench/pluginsemantics.go", "desktop/internal/workbench/pluginsemantics_test.go", - "desktop/internal/workbench/pluginsemantics_e2e_test.go" + "desktop/internal/workbench/pluginsemantics_e2e_test.go", + "desktop/internal/core/references.go", + "desktop/internal/core/references_test.go" ] }, "windows": { @@ -20,13 +24,17 @@ "evidence": [ "desktop/internal/workbench/references.go", "desktop/internal/workbench/references_view.go", + "desktop/internal/workbench/references_test.go", + "desktop/internal/workbench/references_visual_test.go", "desktop/internal/workbench/pluginsemantics.go", "desktop/internal/workbench/pluginsemantics_test.go", - "desktop/internal/workbench/pluginsemantics_e2e_test.go" + "desktop/internal/workbench/pluginsemantics_e2e_test.go", + "desktop/internal/core/references.go", + "desktop/internal/core/references_test.go" ] }, "owner": "Language Tooling", - "verification": "Viva(2026-11-10):Shift+F12 查找引用,以光标处弹出的可键盘导航列表(虚拟化窗口,上限 500)呈现,点击或回车打开所在文件位置;按文件分组与专用面板尚未接入。 从符号发起引用查询,验证结果分组、文件定位、关闭和重新查询。 Viva(2026-11-10):用测试内联的合成语言服务器插件服务的文件(如调用系统 clangd 的 C 文件)发起引用查询,核对分组、行预览、文件定位、关闭与重新查询。", + "verification": "Viva(2026-11-10):Shift+F12 查找引用,以光标处弹出的可键盘导航列表(虚拟化窗口,上限 500)呈现,点击或回车打开所在文件位置;按文件分组与专用面板尚未接入。 从符号发起引用查询,验证结果分组、文件定位、关闭和重新查询。 Viva(2026-11-10):用测试内联的合成语言服务器插件服务的文件(如调用系统 clangd 的 C 文件)发起引用查询,核对分组、行预览、文件定位、关闭与重新查询。 Viva(2026-11-17):无头截图(references_visual_test.go,深浅主题 × 中英)核对结果树、竖排工具栏、搜索标签与预览;待在原生窗口核对单击预览、双击或回车打开、上一个/下一个用法、全部展开/折叠、拖动分隔条、关闭预览和关闭搜索标签。 Viva(2026-11-17):引用结果的分组排序、可见行、步进和行文本改由 Core 计算,Core 契约 fixture(references-query-v1、references-lines-v1)经桌面端桥接测试;单元测试覆盖右键点在其他位置后菜单“查找用法”按点击处请求,无头截图核对右键菜单里的“查找用法”与快捷键。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -44,5 +52,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:Shift+F12 或右键“查找引用”把结果放入 References 工具窗口(底部区),按文件分组、显示行预览(已打开文件读编辑器,未打开文件在后台有界读取),点击或回车打开所在位置,上限 500 条;无头 clangd 测试不是原生窗口验收,平台验证保持 pending。" + "notes": "Viva:Shift+F12 或右键“查找用法”把结果放入 References 工具窗口(底部区);右键点在选区外时先把光标移到点击处,查的是被点的词。分组与文件自然排序、可见行投影(折叠时选中项移到可见的上级)、上一个/下一个用法和用法行文本裁剪由 Core 的 lsp.references.query / lsp.references.lines 计算,桌面端只保留折叠状态、选中、读取文件与绘制。布局对齐 IntelliJ IDEA 的查找用法:标题栏有搜索标签(符号名 + 关闭,关闭即清空结果并收起窗口);左侧竖排工具栏(重新查找、上一个/下一个用法、全部展开/折叠、显示预览);结果树为“用法 → 文件 → 用法”,文件行带目录和用法数,用法行带行号并加粗命中词(已打开文件读编辑器,未打开文件在后台有界读取);右侧只读预览选中用法所在文件,标出该文件全部用法并选中当前用法,宽度可拖动。单击选中并预览,双击或回车打开所在位置,预览关闭时单击直接打开;上限 500 条。无头测试和截图不是原生窗口验收,平台验证保持 pending。" }