From 0e43de9e65dfb6e2ca50a0ec29421bbcd44704b8 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 22:17:48 +0800 Subject: [PATCH 1/8] feat(editor): present LSP actions, signatures and inlay hints --- desktop/internal/core/editor_essentials.go | 2 + desktop/internal/core/plugin_documents.go | 51 +- desktop/internal/core/plugin_semantics.go | 178 ++++ desktop/internal/core/plugin_session.go | 22 +- desktop/internal/editorview/fold.go | 1 + desktop/internal/editorview/inlayhints.go | 434 +++++++++ .../internal/editorview/inlayhints_test.go | 156 ++++ desktop/internal/editorview/lineicons.go | 12 +- desktop/internal/editorview/longline.go | 6 + desktop/internal/editorview/markers.go | 15 +- desktop/internal/editorview/paint.go | 42 +- desktop/internal/editorview/prepared_edit.go | 1 + desktop/internal/editorview/scrollbar.go | 3 +- desktop/internal/editorview/view.go | 16 +- desktop/internal/editorview/wrap.go | 32 +- desktop/internal/i18n/shared.generated.go | 44 + desktop/internal/pluginhost/pluginhost.go | 9 +- .../settingswindow/editor_preferences_view.go | 15 +- desktop/internal/workbench/app.go | 3 +- desktop/internal/workbench/documents.go | 5 + desktop/internal/workbench/editor_menu.go | 11 + desktop/internal/workbench/editor_requests.go | 27 + desktop/internal/workbench/editor_view.go | 19 + desktop/internal/workbench/inlay_hints.go | 488 +++++++++++ .../internal/workbench/lsp_actions_test.go | 152 ++++ .../workbench/lsp_actions_visual_test.go | 243 ++++++ desktop/internal/workbench/pluginbackends.go | 11 +- .../internal/workbench/plugindiagnostics.go | 4 + desktop/internal/workbench/pluginrename.go | 71 +- desktop/internal/workbench/pluginsemantics.go | 182 +++- .../workbench/pluginsemantics_codeactions.go | 822 ++++++++++++++++++ .../workbench/pluginsemantics_hover.go | 19 + .../workbench/pluginsemantics_view.go | 9 + desktop/internal/workbench/pluginsync.go | 3 + desktop/internal/workbench/settings.go | 4 + desktop/internal/workbench/signature_help.go | 567 ++++++++++++ scripts/desktop/build-desktop-core.sh | 3 +- shared/i18n/locales/en-US.json | 22 + shared/i18n/locales/zh-CN.json | 22 + shared/i18n/messages.json | 158 ++++ .../features/lsp-code-actions.json | 27 + .../features/lsp-inlay-hints.json | 29 + .../features/lsp-signature-help.json | 27 + 43 files changed, 3867 insertions(+), 100 deletions(-) create mode 100644 desktop/internal/editorview/inlayhints.go create mode 100644 desktop/internal/editorview/inlayhints_test.go create mode 100644 desktop/internal/workbench/inlay_hints.go create mode 100644 desktop/internal/workbench/lsp_actions_test.go create mode 100644 desktop/internal/workbench/lsp_actions_visual_test.go create mode 100644 desktop/internal/workbench/pluginsemantics_codeactions.go create mode 100644 desktop/internal/workbench/signature_help.go create mode 100644 shared/platform-feature-matrix/features/lsp-code-actions.json create mode 100644 shared/platform-feature-matrix/features/lsp-inlay-hints.json create mode 100644 shared/platform-feature-matrix/features/lsp-signature-help.json diff --git a/desktop/internal/core/editor_essentials.go b/desktop/internal/core/editor_essentials.go index c9daa8bda9..980124f973 100644 --- a/desktop/internal/core/editor_essentials.go +++ b/desktop/internal/core/editor_essentials.go @@ -11,6 +11,7 @@ import ( type EditorStoredPreferences struct { LineNumbers *bool `json:"lineNumbers,omitempty"` Whitespace *bool `json:"whitespace,omitempty"` + InlayHints *bool `json:"inlayHints,omitempty"` CursorStyle string `json:"cursorStyle,omitempty"` CursorBlink *bool `json:"cursorBlink,omitempty"` AutoSaveDelayMilliseconds *uint64 `json:"autoSaveDelayMilliseconds,omitempty"` @@ -20,6 +21,7 @@ type EditorStoredPreferences struct { type EditorPreferences struct { LineNumbers bool `json:"lineNumbers"` Whitespace bool `json:"whitespace"` + InlayHints bool `json:"inlayHints"` CursorStyle string `json:"cursorStyle"` CursorBlink bool `json:"cursorBlink"` AutoSaveDelayMilliseconds uint64 `json:"autoSaveDelayMilliseconds"` diff --git a/desktop/internal/core/plugin_documents.go b/desktop/internal/core/plugin_documents.go index 39816eb82b..0179382f20 100644 --- a/desktop/internal/core/plugin_documents.go +++ b/desktop/internal/core/plugin_documents.go @@ -97,14 +97,19 @@ func (c *Client) ClosePluginDocument(ctx context.Context, session, uri string) e // operation name rather than a raw LSP method, so Core decides which server // feature answers it. type PluginSemanticRequest struct { - SessionID string - Operation string - URI string - Position *PluginDocumentPosition - CompletionContext json.RawMessage + SessionID string + Operation string + URI string + Position *PluginDocumentPosition + Diagnostics []PluginDiagnostic + CodeActionContext json.RawMessage + CompletionContext json.RawMessage + SignatureHelpContext json.RawMessage + CodeAction json.RawMessage + InlayHint json.RawMessage // NewName is the rename operation's replacement identifier. NewName string - // Range is the range rangeFormatting formats; Core requires it for that operation. + // Range is the range rangeFormatting, codeActions or inlayHints covers. Range *PluginDocumentRange // FormattingOptions is optional for formatting and rangeFormatting; Core fills unset // fields with its defaults. @@ -152,18 +157,23 @@ func (c *Client) PluginDocumentURI(ctx context.Context, path, platform string) ( // pluginSemanticBody is the lsp.request payload. type pluginSemanticBody struct { - SessionID string `json:"sessionId"` - Operation string `json:"operation"` - URI string `json:"uri,omitempty"` - Position *PluginDocumentPosition `json:"position,omitempty"` - CompletionContext json.RawMessage `json:"completionContext,omitempty"` - NewName string `json:"newName,omitempty"` - Range *PluginDocumentRange `json:"range,omitempty"` - FormattingOptions *FormattingOptions `json:"formattingOptions,omitempty"` - OperationID string `json:"operationId,omitempty"` - Command json.RawMessage `json:"command,omitempty"` - Query string `json:"query,omitempty"` - IncludeDeclaration *bool `json:"includeDeclaration,omitempty"` + SessionID string `json:"sessionId"` + Operation string `json:"operation"` + URI string `json:"uri,omitempty"` + Position *PluginDocumentPosition `json:"position,omitempty"` + Diagnostics []PluginDiagnostic `json:"diagnostics,omitempty"` + CodeActionContext json.RawMessage `json:"codeActionContext,omitempty"` + CompletionContext json.RawMessage `json:"completionContext,omitempty"` + SignatureHelpContext json.RawMessage `json:"signatureHelpContext,omitempty"` + CodeAction json.RawMessage `json:"codeAction,omitempty"` + InlayHint json.RawMessage `json:"inlayHint,omitempty"` + NewName string `json:"newName,omitempty"` + Range *PluginDocumentRange `json:"range,omitempty"` + FormattingOptions *FormattingOptions `json:"formattingOptions,omitempty"` + OperationID string `json:"operationId,omitempty"` + Command json.RawMessage `json:"command,omitempty"` + Query string `json:"query,omitempty"` + IncludeDeclaration *bool `json:"includeDeclaration,omitempty"` } // RequestPluginSemantics submits a semantic request and returns Core's opaque @@ -171,7 +181,10 @@ type pluginSemanticBody struct { func (c *Client) RequestPluginSemantics(ctx context.Context, request PluginSemanticRequest) (string, error) { body := pluginSemanticBody{ SessionID: request.SessionID, Operation: request.Operation, URI: request.URI, - Position: request.Position, CompletionContext: request.CompletionContext, NewName: request.NewName, + Position: request.Position, Diagnostics: request.Diagnostics, + CodeActionContext: request.CodeActionContext, CompletionContext: request.CompletionContext, + SignatureHelpContext: request.SignatureHelpContext, CodeAction: request.CodeAction, + InlayHint: request.InlayHint, NewName: request.NewName, Range: request.Range, FormattingOptions: request.FormattingOptions, OperationID: request.OperationID, Command: request.Command, Query: request.Query, IncludeDeclaration: request.IncludeDeclaration, diff --git a/desktop/internal/core/plugin_semantics.go b/desktop/internal/core/plugin_semantics.go index 7aea50126b..21b70ba6da 100644 --- a/desktop/internal/core/plugin_semantics.go +++ b/desktop/internal/core/plugin_semantics.go @@ -196,3 +196,181 @@ func (c *Client) PlanPluginWorkspaceEdit(ctx context.Context, workspaceRoot stri }{"auto", workspaceRoot, changes, open}, &plan) return plan, err } + +// PluginSemanticCommand is a normalised LSP Command attached to a code action. +type PluginSemanticCommand struct { + Title string `json:"title"` + Command string `json:"command"` + Arguments json.RawMessage `json:"arguments,omitempty"` +} + +// PluginSemanticWorkspaceEdit wraps the normalised file-to-edits map of a code action. +type PluginSemanticWorkspaceEdit struct { + Changes map[string][]PluginTextEdit `json:"changes"` + DocumentVersions map[string]int64 `json:"documentVersions"` +} + +// PluginSemanticCodeAction is one Core-normalised, deterministically ordered code action. +type PluginSemanticCodeAction struct { + Title string `json:"title"` + Kind *string `json:"kind"` + Group string `json:"group"` + IsPreferred bool `json:"isPreferred"` + Edit *PluginSemanticWorkspaceEdit `json:"edit"` + Command *PluginSemanticCommand `json:"command"` + Data json.RawMessage `json:"data"` + Raw json.RawMessage `json:"-"` +} + +// UnmarshalJSON decodes the normalised code action while keeping the raw payload for resolveCodeAction. +func (a *PluginSemanticCodeAction) UnmarshalJSON(data []byte) error { + type alias PluginSemanticCodeAction + var decoded alias + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *a = PluginSemanticCodeAction(decoded) + a.Raw = append(json.RawMessage(nil), data...) + return nil +} + +// PluginSemanticCodeActions decodes a completed codeActions event. +func PluginSemanticCodeActions(event BackendEvent) ([]PluginSemanticCodeAction, error) { + var payload struct { + Actions []PluginSemanticCodeAction `json:"actions"` + } + if err := decodePluginSemanticResult(event, &payload); err != nil { + return nil, err + } + return payload.Actions, nil +} + +// PluginSemanticResolvedCodeAction decodes a completed resolveCodeAction event. +func PluginSemanticResolvedCodeAction(event BackendEvent) (*PluginSemanticCodeAction, error) { + var payload struct { + Action *PluginSemanticCodeAction `json:"action"` + } + if err := decodePluginSemanticResult(event, &payload); err != nil { + return nil, err + } + return payload.Action, nil +} + +// PluginSemanticParameterInfo is one parameter of a normalised signature, with both UTF-16 and UTF-8 byte spans. +type PluginSemanticParameterInfo struct { + Label string `json:"label"` + UTF16Start *int `json:"utf16Start"` + UTF16End *int `json:"utf16End"` + ByteStart *int `json:"byteStart"` + ByteEnd *int `json:"byteEnd"` + Documentation *string `json:"documentation"` + IsMarkdown bool `json:"isMarkdown"` +} + +// PluginSemanticSignatureInfo is one overload in a normalised signatureHelp answer. +type PluginSemanticSignatureInfo struct { + Label string `json:"label"` + Documentation *string `json:"documentation"` + IsMarkdown bool `json:"isMarkdown"` + Parameters []PluginSemanticParameterInfo `json:"parameters"` + ActiveParameter *int `json:"activeParameter"` +} + +// PluginSemanticSignatureHelp is Core's normalised signatureHelp answer. +type PluginSemanticSignatureHelp struct { + Signatures []PluginSemanticSignatureInfo `json:"signatures"` + ActiveSignature int `json:"activeSignature"` + ActiveParameter *int `json:"activeParameter"` + Raw json.RawMessage `json:"-"` +} + +// UnmarshalJSON decodes the signature help while retaining the normalised JSON for activeSignatureHelp retriggering. +func (s *PluginSemanticSignatureHelp) UnmarshalJSON(data []byte) error { + type alias PluginSemanticSignatureHelp + var decoded alias + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *s = PluginSemanticSignatureHelp(decoded) + s.Raw = append(json.RawMessage(nil), data...) + return nil +} + +// PluginSemanticSignatureHelpFromEvent decodes a completed signatureHelp event. +func PluginSemanticSignatureHelpFromEvent(event BackendEvent) (*PluginSemanticSignatureHelp, error) { + var payload struct { + SignatureHelp *PluginSemanticSignatureHelp `json:"signatureHelp"` + } + if err := decodePluginSemanticResult(event, &payload); err != nil { + return nil, err + } + return payload.SignatureHelp, nil +} + +// PluginSemanticInlayHint is one Core-normalised, viewport-culled inlay hint. +type PluginSemanticInlayHint struct { + Position PluginDocumentPosition `json:"position"` + Label string `json:"label"` + Kind *int `json:"kind"` + Tooltip *string `json:"tooltip"` + PaddingLeft bool `json:"paddingLeft"` + PaddingRight bool `json:"paddingRight"` + TextEdits []PluginTextEdit `json:"textEdits"` + Data json.RawMessage `json:"data,omitempty"` + Raw json.RawMessage `json:"-"` + ResolvePayload json.RawMessage `json:"resolvePayload,omitempty"` +} + +// UnmarshalJSON decodes the hint while keeping the raw JSON for resolveInlayHint. +func (h *PluginSemanticInlayHint) UnmarshalJSON(data []byte) error { + type alias PluginSemanticInlayHint + var decoded alias + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *h = PluginSemanticInlayHint(decoded) + h.Raw = append(json.RawMessage(nil), data...) + return nil +} + +// PluginSemanticInlayHints decodes a completed inlayHints event. +func PluginSemanticInlayHints(event BackendEvent) ([]PluginSemanticInlayHint, error) { + var payload struct { + Hints []PluginSemanticInlayHint `json:"hints"` + } + if err := decodePluginSemanticResult(event, &payload); err != nil { + return nil, err + } + return payload.Hints, nil +} + +// PluginSemanticResolvedInlayHint decodes a completed resolveInlayHint event. +func PluginSemanticResolvedInlayHint(event BackendEvent) (*PluginSemanticInlayHint, error) { + var payload struct { + Hint *PluginSemanticInlayHint `json:"hint"` + } + if err := decodePluginSemanticResult(event, &payload); err != nil { + return nil, err + } + return payload.Hint, nil +} + +// PluginWorkspaceApplyEdit is the payload of a server-initiated workspaceApplyEdit event. +type PluginWorkspaceApplyEdit struct { + ApplyEditID string `json:"applyEditId"` + Label *string `json:"label"` + Changes map[string][]PluginTextEdit `json:"changes"` + DocumentVersions map[string]int64 `json:"documentVersions"` +} + +// PluginWorkspaceApplyEditFromEvent decodes a workspaceApplyEdit runtime event. +func PluginWorkspaceApplyEditFromEvent(event BackendEvent) (PluginWorkspaceApplyEdit, error) { + var payload PluginWorkspaceApplyEdit + if len(event.Result) == 0 || string(event.Result) == "null" { + return payload, errors.New("workspaceApplyEdit event has no result") + } + if err := json.Unmarshal(event.Result, &payload); err != nil || payload.ApplyEditID == "" { + return PluginWorkspaceApplyEdit{}, errors.New("workspaceApplyEdit event is not the normalised shape") + } + return payload, nil +} diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index f9b976e3bf..9b4869a1fa 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -328,6 +328,13 @@ type CompletionOptions struct { AllCommitCharacters []string `json:"allCommitCharacters"` } +// SignatureHelpOptions is the signature-help trigger and retrigger characters a language +// server session declares, as Core reports them on a featuresChanged event. +type SignatureHelpOptions struct { + TriggerCharacters []string `json:"triggerCharacters"` + RetriggerCharacters []string `json:"retriggerCharacters"` +} + type BackendEvent struct { Type string `json:"type"` Channel string `json:"channel"` @@ -353,7 +360,9 @@ type BackendEvent struct { Capabilities []string `json:"capabilities"` // CompletionOptions is set on featuresChanged while completion is offered. CompletionOptions *CompletionOptions `json:"completionOptions"` - ServerInfo json.RawMessage `json:"serverInfo"` + // SignatureHelpOptions is set on featuresChanged while signatureHelp is offered. + SignatureHelpOptions *SignatureHelpOptions `json:"signatureHelpOptions"` + ServerInfo json.RawMessage `json:"serverInfo"` } type pluginFunctionReference struct { @@ -384,6 +393,17 @@ func (c *Client) RespondPluginHostRequest(ctx context.Context, session, requestI }{session, requestID, result, failure}, nil) } +// RespondWorkspaceApplyEdit answers one server-initiated workspaceApplyEdit event. +func (c *Client) RespondWorkspaceApplyEdit(ctx context.Context, session, applyEditID string, applied bool, failureReason string) error { + body := struct { + SessionID string `json:"sessionId"` + ApplyEditID string `json:"applyEditId"` + Applied bool `json:"applied"` + FailureReason string `json:"failureReason,omitempty"` + }{session, applyEditID, applied, failureReason} + return c.Execute(ctx, "lsp.applyEditResponse", body, nil) +} + // StartPluginBackend starts a Core-owned process; initialization completes via // session events. No host service is granted unless explicitly supplied. func (c *Client) StartPluginBackend(ctx context.Context, request PluginBackendStart) (PluginBackendStarted, error) { diff --git a/desktop/internal/editorview/fold.go b/desktop/internal/editorview/fold.go index 3d5990678f..ffceeecb78 100644 --- a/desktop/internal/editorview/fold.go +++ b/desktop/internal/editorview/fold.go @@ -256,6 +256,7 @@ func (v *View) refold() { } v.rowsDirty = true } + v.reflowInlayRows() } // revealHiddenCaret unfolds every collapsed range that hides the caret's line. A move, a search diff --git a/desktop/internal/editorview/inlayhints.go b/desktop/internal/editorview/inlayhints.go new file mode 100644 index 0000000000..a31beefd45 --- /dev/null +++ b/desktop/internal/editorview/inlayhints.go @@ -0,0 +1,434 @@ +package editorview + +import ( + "context" + "math" + "slices" + "sort" + "strings" + "unicode" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/vivaui/viva/gfx" +) + +// InlayHintSpec describes a Core-normalized virtual hint to lay out against a +// captured document. +type InlayHintSpec struct { + ID int + Line int + UTF16Column int + Label string + PaddingLeft bool + PaddingRight bool + Interactive bool +} + +// PreparedInlayHints is immutable geometry for one document revision. +type PreparedInlayHints struct { + text rope.Rope + revision int + lines map[int]inlayLine + order []int + widest int + maxRuns int +} + +type inlayLine struct { + hints []preparedInlayHint + cells int +} + +type preparedInlayHint struct { + id int + byteCol int + cell int + label string + padLeft int + textCells int + cells int + interactive bool + runs []gfx.TextRun +} + +type inlayState struct { + prepared PreparedInlayHints + wraps map[int][]wrapRow + // Additional wrapped rows are sparse. Updating viewport hints must never + // recompute the base row positions of a complete document. + rowDeltas []inlayRowDelta +} + +type inlayRowDelta struct{ line, total int } + +// PrepareInlayHints calculates virtual positions off the window thread. Very +// long lines use the editor's paged renderer and get no inline decorations. +func PrepareInlayHints(ctx context.Context, text rope.Rope, revision int, specs []InlayHintSpec) (PreparedInlayHints, error) { + if err := ctx.Err(); err != nil { + return PreparedInlayHints{}, err + } + out := PreparedInlayHints{text: text, revision: revision} + byLine := make(map[int][]InlayHintSpec) + for _, spec := range specs { + if spec.Line < 0 || spec.Line >= text.LineCount() || spec.Label == "" { + continue + } + if text.LineEnd(spec.Line)-text.LineStart(spec.Line) <= longLine { + byLine[spec.Line] = append(byLine[spec.Line], spec) + } + } + if len(byLine) == 0 { + return out, nil + } + out.lines = make(map[int]inlayLine, len(byLine)) + for line, items := range byLine { + if err := ctx.Err(); err != nil { + return PreparedInlayHints{}, err + } + slices.SortStableFunc(items, func(a, b InlayHintSpec) int { + switch { + case a.UTF16Column < b.UTF16Column: + return -1 + case a.UTF16Column > b.UTF16Column: + return 1 + default: + return 0 + } + }) + value, _ := text.Substring(text.LineStart(line), text.LineEnd(line)) + hints := make([]preparedInlayHint, 0, len(items)) + at, cell := 0, 0 + for _, item := range items { + label, runs, textCells := prepareInlayLabel(item.Label) + if textCells == 0 { + continue + } + byteCol := inlayByteColumn(value, item.UTF16Column) + cell = inlayCells(value[at:byteCol], cell) + left, right := 0, 0 + if item.PaddingLeft { + left = 1 + } + if item.PaddingRight { + right = 1 + } + hintCells := left + textCells + right + hints = append(hints, preparedInlayHint{ + id: item.ID, byteCol: byteCol, cell: cell, label: label, + padLeft: left, textCells: textCells, cells: hintCells, + interactive: item.Interactive, runs: runs, + }) + out.maxRuns = max(out.maxRuns, len(runs)) + at, cell = byteCol, cell+hintCells + } + if len(hints) > 0 { + cells := inlayCells(value[at:], cell) + out.lines[line] = inlayLine{hints: hints, cells: cells} + out.order = append(out.order, line) + out.widest = max(out.widest, cells) + } + } + slices.Sort(out.order) + return out, nil +} + +func inlayByteColumn(line string, column int) int { + line = strings.TrimSuffix(line, "\r") + for i, r := range line { + units := 1 + if r > 0xffff { + units = 2 + } + if column < units { + return i + } + column -= units + } + return len(line) +} + +func prepareInlayLabel(label string) (string, []gfx.TextRun, int) { + // One hint occupies one row. Keep the label bytes aligned with the runs + // handed to Viva even when the server supplies controls or invalid UTF-8. + label = strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return ' ' + } + return r + }, label) + runs := make([]gfx.TextRun, 0, min(len(label), 4)) + cells := 0 + ascii := false + for _, r := range label { + size, width := utf8.RuneLen(r), runeCells(r, 0) + if r < utf8.RuneSelf && ascii { + last := &runs[len(runs)-1] + last.Bytes += int32(size) + last.Cells += int32(width) + } else { + runs = append(runs, gfx.TextRun{Column: int32(cells), Bytes: int32(size), Cells: int32(width)}) + } + ascii = r < utf8.RuneSelf + cells += width + } + return label, runs, cells +} + +func inlayCells(text string, cells int) int { + for _, r := range text { + cells += runeCells(r, cells) + } + return cells +} + +// SetPreparedInlayHints installs geometry only for the exact document snapshot. +func (v *View) SetPreparedInlayHints(prepared PreparedInlayHints) bool { + if v.revision != prepared.revision || !v.text.Same(prepared.text) { + return false + } + if len(prepared.lines) == 0 { + v.ClearInlayHints() + return true + } + v.replaceInlayHints(prepared) + v.inlayRuns = slices.Grow(v.inlayRuns[:0], prepared.maxRuns) + return true +} + +// ClearInlayHints removes virtual hints and leaves the reader at the same line. +func (v *View) ClearInlayHints() bool { + if !v.HasInlayHints() { + return false + } + v.replaceInlayHints(PreparedInlayHints{}) + return true +} + +func (v *View) replaceInlayHints(prepared PreparedInlayHints) { + if !v.wrapping() || v.lineH <= 0 { + v.inlay = inlayState{prepared: prepared} + return + } + row := int(v.scroll / v.lineH) + line, sub := v.rowLine(row) + part := v.scroll - float32(row)*v.lineH + + v.inlay = inlayState{prepared: prepared} + v.reflowInlayRows() + sub = min(sub, max(len(v.rowsOf(v.ref(line)))-1, 0)) + v.scroll = float32(v.lineRow(line)+sub)*v.lineH + part +} + +func (v *View) reflowInlayRows() { + v.inlay.wraps = nil + v.inlay.rowDeltas = v.inlay.rowDeltas[:0] + if !v.wrapping() || !v.HasInlayHints() { + return + } + v.ensureRows() + prepared := &v.inlay.prepared + v.inlay.wraps = make(map[int][]wrapRow) + total := 0 + for _, line := range prepared.order { + if v.fold.hides(line) { + continue + } + data := prepared.lines[line] + rows := oneRow + if data.cells > v.wrapCols { + rows = wrapLineWithHints(nil, v.ref(line).text, data.hints, v.wrapCols) + v.inlay.wraps[line] = rows + } + if change := len(rows) - int(v.wraps[line].rows); change != 0 { + total += change + v.inlay.rowDeltas = append(v.inlay.rowDeltas, inlayRowDelta{line: line, total: total}) + } + } +} + +func (v *View) inlayRowsBefore(line int) int { + deltas := v.inlay.rowDeltas + i := sort.Search(len(deltas), func(i int) bool { return deltas[i].line >= line }) + if i == 0 { + return 0 + } + return deltas[i-1].total +} + +// HasInlayHints reports whether the view has active inline hints. +func (v *View) HasInlayHints() bool { return len(v.inlay.prepared.lines) > 0 } + +func (v *View) lineInlayHints(line int) []preparedInlayHint { + return v.inlay.prepared.lines[line].hints +} + +// CellWidth returns the measured width of one editor cell. +func (v *View) CellWidth() float32 { return v.cellW } + +// VisibleLineRange returns the inclusive zero-based range of document lines +// at the current scroll position using the last painted viewport dimensions. +func (v *View) VisibleLineRange() (firstLine, lastLine int, ok bool) { + if !v.painted || v.lineH <= 0 { + return 0, 0, false + } + rows := v.rowCount() + if rows <= 0 { + return 0, 0, false + } + firstRow := min(max(int(v.scroll/v.lineH), 0), rows-1) + lastRow := min(max(int(math.Ceil(float64((v.scroll+v.area.Height)/v.lineH)))-1, firstRow), rows-1) + firstLine, _ = v.rowLine(firstRow) + lastLine, _ = v.rowLine(lastRow) + return firstLine, lastLine, true +} + +// InlayHintAt reports the ID and window rectangle of an interactive hint. +func (v *View) InlayHintAt(x, y float32) (int, gfx.Rect, bool) { + if !v.painted || !v.HasInlayHints() || x < v.textLeft-textPad || x >= v.textRight || y < v.area.Y || y >= v.area.Y+v.area.Height { + return 0, gfx.Rect{}, false + } + rowIndex := int((y - v.area.Y + v.scroll) / v.lineH) + if rowIndex < 0 || rowIndex >= v.rowCount() { + return 0, gfx.Rect{}, false + } + line, sub := v.rowLine(rowIndex) + hints := v.lineInlayHints(line) + if len(hints) == 0 { + return 0, gfx.Rect{}, false + } + l := v.ref(line) + rows := v.rowsOf(l) + if sub < 0 || sub >= len(rows) { + return 0, gfx.Rect{}, false + } + row := rows[sub] + start := v.textLeft - v.scrollX + y0 := v.area.Y + float32(rowIndex)*v.lineH - v.scroll + composeRow, composeAt, composeCells := v.compositionRoom() + for _, hint := range hints { + if !hint.interactive || hint.byteCol < row.at || sub+1 < len(rows) && hint.byteCol >= rows[sub+1].at { + continue + } + cell := hint.cell + if composeCells > 0 && v.text.LineOf(v.caret) == line && sub == composeRow && cell >= composeAt { + cell += composeCells + } + x0 := start + float32(cell-row.cells)*v.cellW + width := float32(hint.cells) * v.cellW + if x >= x0 && x < x0+width { + return hint.id, gfx.Rect{X: x0, Y: y0, Width: width, Height: v.lineH}, true + } + } + return 0, gfx.Rect{}, false +} + +func cellsOfWithHints(line string, hints []preparedInlayHint, col int) int { + col = min(max(col, 0), len(line)) + i := sort.Search(len(hints), func(i int) bool { return hints[i].byteCol > col }) + if i == 0 { + return cellsOf(line, col) + } + hint := &hints[i-1] + return inlayCells(line[hint.byteCol:col], hint.cell+hint.cells) +} + +func columnInWithHints(line string, hints []preparedInlayHint, from, to, startCells int, cells float32) int { + for _, hint := range hints { + if hint.byteCol < from || hint.cell < startCells { + continue + } + if hint.byteCol >= to { + break + } + if cells < float32(hint.cell) { + return columnIn(line, from, hint.byteCol, startCells, cells) + } + if cells < float32(hint.cell+hint.cells) { + return hint.byteCol + } + from, startCells = hint.byteCol, hint.cell+hint.cells + } + return columnIn(line, from, to, startCells, cells) +} + +// A hint and the following character share one byte anchor. Keep them on the +// same row even if the virtual label itself is wider than the viewport. +func wrapLineWithHints(dst []wrapRow, text string, hints []preparedInlayHint, cols int) []wrapRow { + w := wrapper{rows: append(dst, wrapRow{}), cols: cols, prev: -1} + at := 0 + for i := 0; i < len(hints); { + hintAt := hints[i].byteCol + w.feed(text[at:hintAt], at) + width := 0 + for i < len(hints) && hints[i].byteCol == hintAt { + width += hints[i].cells + i++ + } + next, size := utf8.DecodeRuneInString(text[hintAt:]) + if size > 0 { + width += runeCells(next, w.cells+width) + } + if w.cells > w.start { + pos := wrapRow{at: hintAt, cells: w.cells} + if w.cells+width-w.start > cols { + w.rows = append(w.rows, pos) + w.start, w.brk = w.cells, wrapRow{} + } else if pos.at > 0 { + w.brk = pos + } + } + w.cells += width + w.prev = next + at = hintAt + size + } + w.feed(text[at:], at) + return w.rows +} + +func (v *View) paintSingleHint(canvas *gfx.Canvas, h *preparedInlayHint, shift int, y float32, look Look) { + tint := look.Foreground + pillBg, pillBorder := tint, tint + pillBg.Alpha, pillBorder.Alpha = 0.07, 0.13 + fg := look.Subtle + fg.Alpha = 1 + + textX := v.textLeft + float32(h.cell+h.padLeft-shift)*v.cellW - v.scrollX + textWidth := float32(h.textCells) * v.cellW + height := max(min(v.cellH+2, v.lineH-2), 1) + top := y + (v.lineH-height)/2 + pill := gfx.Rect{X: textX - 2, Y: top, Width: textWidth + 4, Height: height} + canvas.Fill(pill, pillBg) + canvas.Fill(gfx.Rect{X: pill.X, Y: pill.Y, Width: pill.Width, Height: 1}, pillBorder) + canvas.Fill(gfx.Rect{X: pill.X, Y: pill.Y + pill.Height - 1, Width: pill.Width, Height: 1}, pillBorder) + + runs := v.inlayRuns[:len(h.runs)] + copy(runs, h.runs) + for i := range runs { + runs[i].Color = fg + } + style := gfx.TextStyle{Size: max(v.font.Size-1, 9), Color: fg, MonoFace: v.font.Face} + rect := gfx.Rect{X: textX, Y: y + (v.lineH-v.cellH)/2, Width: float32(math.Ceil(float64(textWidth))) + 1, Height: v.cellH} + canvas.LabelRuns(h.label, rect, style, v.cellW, runs) +} + +func (v *View) paintRowWithHints(canvas *gfx.Canvas, text string, row wrapRow, end int, lastRow bool, hints []preparedInlayHint, look Look, from, to, shift int, y float32) { + if from >= to { + return + } + for i := range hints { + hint := &hints[i] + if hint.byteCol < row.at { + continue + } + if hint.byteCol > end || hint.byteCol == end && !lastRow { + break + } + v.paintRow(canvas, text[:hint.byteCol], 0, row, from, to, shift, y) + if hint.cell+hint.cells > from && hint.cell < to { + v.paintSingleHint(canvas, hint, shift, y, look) + } + row = wrapRow{at: hint.byteCol, cells: hint.cell + hint.cells} + } + v.paintRow(canvas, text[:end], 0, row, from, to, shift, y) +} diff --git a/desktop/internal/editorview/inlayhints_test.go b/desktop/internal/editorview/inlayhints_test.go new file mode 100644 index 0000000000..71361d6e3b --- /dev/null +++ b/desktop/internal/editorview/inlayhints_test.go @@ -0,0 +1,156 @@ +package editorview + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +func prepareTestHints(t *testing.T, v *View, specs ...InlayHintSpec) PreparedInlayHints { + t.Helper() + prepared, err := PrepareInlayHints(t.Context(), v.TextSnapshot(), v.Revision(), specs) + if err != nil { + t.Fatal(err) + } + return prepared +} + +func installTestHints(t *testing.T, v *View, specs ...InlayHintSpec) { + t.Helper() + if !v.SetPreparedInlayHints(prepareTestHints(t, v, specs...)) { + t.Fatal("editor rejected hints for its current snapshot") + } +} + +func TestInlayHintOversizedAtWrapBoundaryIsPaintedAndHitOnce(t *testing.T) { + v := newTestView(t, "abcde\r\nnext") + canvas := new(gfx.Canvas) + w, _ := canvas.MonoCellSize(DefaultFont().Size, DefaultFont().Face) + area := gfx.Rect{Width: 2*gutterPad + textPad + 7*w + barWidth, Height: 180} + v.SetWrap(true) + installTestHints(t, v, + InlayHintSpec{ID: 4, Line: 0, UTF16Column: 2, Label: "typehint", Interactive: true}, + InlayHintSpec{ID: 7, Line: 0, UTF16Column: 5, Label: "EOL", Interactive: true}, + ) + v.Paint(canvas, area, Look{}) + rows := v.rowsOf(v.ref(0)) + for i := 1; i < len(rows); i++ { + if rows[i-1].at >= rows[i].at { + t.Fatalf("the same byte anchors several wrap rows: %v", rows) + } + } + seen := map[string]int{} + for _, label := range lineLabels(canvas, v) { + if label.Value != "typehint" && label.Value != "EOL" { + continue + } + seen[label.Value]++ + id, _, ok := v.InlayHintAt(label.Bounds.X+1, label.Bounds.Y+1) + if !ok || label.Value == "typehint" && id != 4 || label.Value == "EOL" && id != 7 { + t.Fatalf("hint hit on %q returned (%d, %t)", label.Value, id, ok) + } + } + if seen["typehint"] != 1 || seen["EOL"] != 1 { + t.Fatalf("each hint must draw once, drew %v", seen) + } +} + +func TestInlayHintsLeaveUnderlyingTextAndTabCoordinatesIntact(t *testing.T) { + v := newTestView(t, "😀\tab") + canvas := new(gfx.Canvas) + area := gfx.Rect{X: 31, Y: 20, Width: 600, Height: 150} + installTestHints(t, v, InlayHintSpec{ + ID: 7, Line: 0, UTF16Column: 2, Label: "T", PaddingLeft: true, Interactive: true, + }) + v.Paint(canvas, area, Look{}) + v.SetSelection(len("😀\t"), len("😀\t")) + caret, ok := v.CaretRect() + if want := v.textLeft + 8*v.CellWidth(); !ok || !near(caret.X, want) { + t.Fatalf("caret after tab = %+v, want x = %v", caret, want) + } + line, col, ok := v.PositionAt(caret.X, caret.Y+1) + if !ok || line != 0 || col != 3 { + t.Fatalf("caret position = (%d, %d, %t), want (0, 3, true)", line, col, ok) + } + id, hit, ok := v.InlayHintAt(v.textLeft+3.5*v.CellWidth(), caret.Y+1) + if !ok || id != 7 || !near(hit.Width, 2*v.CellWidth()) { + t.Fatalf("hint hit = (%d, %+v, %t)", id, hit, ok) + } + v.SetSelection(0, len("😀\ta")) + if got := v.SelectedText(); got != "😀\ta" { + t.Fatalf("copy would include virtual text: %q", got) + } + if got := v.contents(); got != "😀\tab" { + t.Fatalf("virtual text entered the document: %q", got) + } +} + +func TestInlayHintReplacementKeepsWrappedViewportAndDropsOnEdit(t *testing.T) { + v := newTestView(t, strings.Repeat("short\n", 80)) + canvas, _ := paintWrapped(t, v, gfx.Rect{Width: 130, Height: 100}) + v.scroll = 25.5 * v.lineH + first, _, _ := v.VisibleLineRange() + spec := InlayHintSpec{Line: 20, UTF16Column: 0, Label: "extra-wide-hint"} + installTestHints(t, v, spec) + if got, _, _ := v.VisibleLineRange(); got != first { + t.Fatalf("a hint before the viewport shifted first line from %v to %v", first, got) + } + late := prepareTestHints(t, v, spec) + v.typeText("x") + if v.SetPreparedInlayHints(late) || v.HasInlayHints() { + t.Fatal("the editor retained geometry prepared for an old document revision") + } + canvas.Reset() + v.Paint(canvas, v.area, Look{}) + if got := v.rowCount(); got != v.text.LineCount() { + t.Fatalf("stale hints left %d rows in a %d-line document", got, v.text.LineCount()) + } +} + +func TestInlayHintsHorizontalExtentClearsAndLongLinesStayPaged(t *testing.T) { + area := gfx.Rect{Width: 160, Height: 120} + canvas := new(gfx.Canvas) + v := newTestView(t, "short") + v.Paint(canvas, area, Look{}) + before := v.maxScrollX() + installTestHints(t, v, InlayHintSpec{Label: "long inlay label expands scroll range", UTF16Column: 5}) + if got := v.maxScrollX(); got <= before { + t.Fatalf("hint did not extend horizontal scrolling: %v <= %v", got, before) + } + if !v.ClearInlayHints() || v.maxScrollX() != before { + t.Fatalf("horizontal range after clearing hints = %v, want %v", v.maxScrollX(), before) + } + v = newTestView(t, strings.Repeat("x", longLine+1)+"\nshort") + installTestHints(t, v, InlayHintSpec{Label: "too long"}, InlayHintSpec{Line: 1, Label: "normal"}) + canvas.Reset() + v.Paint(canvas, area, Look{}) + seen := false + for _, label := range lineLabels(canvas, v) { + if label.Value == "too long" { + t.Fatal("virtual hint was inserted into a paged line") + } + seen = seen || label.Value == "normal" + } + if !seen { + t.Fatal("a paged line suppressed hints on neighboring lines") + } +} + +func TestInlayHintPaintingAllocatesNothingAfterWarmup(t *testing.T) { + v := newTestView(t, "let result = run(参数)\nreturn result\n") + installTestHints(t, v, InlayHintSpec{Line: 0, UTF16Column: 17, Label: "value:"}) + canvas := new(gfx.Canvas) + area := gfx.Rect{Width: 640, Height: 120} + paint := func() { + canvas.Reset() + v.Paint(canvas, area, Look{}) + } + for _, wrap := range []bool{false, true} { + v.SetWrap(wrap) + paint() + if allocs := testing.AllocsPerRun(25, paint); allocs != 0 { + t.Fatalf("painting inline hints with wrap=%t allocates %v times per frame", wrap, allocs) + } + } +} diff --git a/desktop/internal/editorview/lineicons.go b/desktop/internal/editorview/lineicons.go index cceff2b20a..cb6247f708 100644 --- a/desktop/internal/editorview/lineicons.go +++ b/desktop/internal/editorview/lineicons.go @@ -19,9 +19,10 @@ const ( // LineIcon is an icon drawn in the gutter of one zero-based line, in the zero-based slot (column) // of the icon area. A slot should be used densely: slots 0 to n-1 with no gap. type LineIcon struct { - Line int - Slot int - Icon gfx.Icon + Line int + Slot int + Icon gfx.Icon + Color gfx.Color } // SetLineIcons replaces the icons of the gutter. The first icon of a line and slot wins; the slice is @@ -54,12 +55,15 @@ func (v *View) lineIconColumn() float32 { // paintLineIcons draws the icons of the lines firstLine to lastLine, centered in their rows. func (v *View) paintLineIcons(canvas *gfx.Canvas, area gfx.Rect, look Look, firstLine, lastLine int) { - color := look.Subtle side := min(v.lineH-2, lineIconSize) for _, icon := range v.gutter.icons { if icon.Line < firstLine || icon.Line > lastLine || icon.Line >= v.text.LineCount() { continue } + color := icon.Color + if color.Alpha == 0 { + color = look.Subtle + } top := area.Y + float32(v.lineRow(icon.Line))*v.lineH - v.scroll x := v.iconX + float32(icon.Slot)*lineIconWidth canvas.DrawIcon(icon.Icon, gfx.Rect{X: x, Y: top + (v.lineH-side)/2, Width: side, Height: side}, color) diff --git a/desktop/internal/editorview/longline.go b/desktop/internal/editorview/longline.go index 05f0512c82..073b5b0ad8 100644 --- a/desktop/internal/editorview/longline.go +++ b/desktop/internal/editorview/longline.go @@ -76,6 +76,9 @@ func (v *View) ref(line int) lineRef { // cellsAt is how many cells the bytes of l take up to byte column col, as cellsOf counts them. func (v *View) cellsAt(l lineRef, col int) int { if !l.long { + if hints := v.lineInlayHints(l.line); len(hints) > 0 { + return cellsOfWithHints(l.text, hints, col) + } return cellsOf(l.text, col) } col = min(max(col, 0), l.size) @@ -87,6 +90,9 @@ func (v *View) cellsAt(l lineRef, col int) int { // startCells columns in, whose cell holds cells, counted from the line's start. func (v *View) columnFrom(l lineRef, from, to, startCells int, cells float32) int { if !l.long { + if hints := v.lineInlayHints(l.line); len(hints) > 0 { + return columnInWithHints(l.text, hints, from, to, startCells, cells) + } return columnIn(l.text, from, to, startCells, cells) } at, sum := from, startCells diff --git a/desktop/internal/editorview/markers.go b/desktop/internal/editorview/markers.go index 87e3b8359f..7bb736ec1a 100644 --- a/desktop/internal/editorview/markers.go +++ b/desktop/internal/editorview/markers.go @@ -36,8 +36,9 @@ func ProjectMarkers(ctx context.Context, text rope.Rope, markers []Marker) (Proj } slices.Sort(positions) positions = slices.Compact(positions) - cellsAt := make(map[int]int, len(positions)) - index, units, cells := 0, 0, 0 + type point struct{ cell, byteColumn int } + pointAt := make(map[int]point, len(positions)) + index, units, cells, bytes := 0, 0, 0, 0 text.Chunks(text.LineStart(line), text.LineEnd(line), func(chunk string) bool { if ctx.Err() != nil { return false @@ -51,7 +52,7 @@ func ProjectMarkers(ctx context.Context, text rope.Rope, markers []Marker) (Proj // A malformed UTF-16 endpoint inside a surrogate pair rounds down, // matching ByteOffset. Out-of-line endpoints clamp to the line end. for index < len(positions) && positions[index] < units+width { - cellsAt[positions[index]] = cells + pointAt[positions[index]] = point{cells, bytes} index++ } if index == len(positions) { @@ -59,6 +60,7 @@ func ProjectMarkers(ctx context.Context, text rope.Rope, markers []Marker) (Proj } units += width cells += runeCells(r, cells) + bytes += size chunk = chunk[size:] } return index < len(positions) @@ -66,12 +68,15 @@ func ProjectMarkers(ctx context.Context, text rope.Rope, markers []Marker) (Proj if err := ctx.Err(); err != nil { return ProjectedMarkers{}, err } + lineLen := text.LineEnd(line) - text.LineStart(line) for ; index < len(positions); index++ { - cellsAt[positions[index]] = cells + pointAt[positions[index]] = point{cells, lineLen} } projected := items[:0] for _, item := range items { - item.Start, item.End = cellsAt[item.Start], cellsAt[item.End] + start, end := pointAt[item.Start], pointAt[item.End] + item.Start, item.End = start.cell, end.cell + item.byteStart, item.byteEnd = start.byteColumn, end.byteColumn if item.End > item.Start { projected = append(projected, item) } diff --git a/desktop/internal/editorview/paint.go b/desktop/internal/editorview/paint.go index 5b5c6fa6f5..420bc854b3 100644 --- a/desktop/internal/editorview/paint.go +++ b/desktop/internal/editorview/paint.go @@ -134,6 +134,7 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { v.extraCells = v.extraSelectionCells(l, v.extraCells) } v.tokens = v.hl.Line(v.tokens[:0], line) + lineHints := v.lineInlayHints(line) for k, row := range wraps { y := top + float32(k)*v.lineH if y+v.lineH <= area.Y { @@ -178,7 +179,14 @@ func (v *View) Paint(canvas *gfx.Canvas, area gfx.Rect, look Look) { } p := v.part(l, row, end, from, to) v.paintSearchMatches(canvas, l, p, from, to, shift, y, look.Selection) - if line == caretLine && k == composeRow && composeCells > 0 { + if len(lineHints) > 0 { + if line == caretLine && k == composeRow && composeCells > 0 { + v.paintRowWithHints(canvas, p.text, p.row, end, k == len(wraps)-1, lineHints, look, from, min(to, composeAt), shift, y) + v.paintRowWithHints(canvas, p.text, p.row, end, k == len(wraps)-1, lineHints, look, max(from, composeAt), to, shift-composeCells, y) + } else { + v.paintRowWithHints(canvas, p.text, p.row, end, k == len(wraps)-1, lineHints, look, from, to, shift, y) + } + } else if line == caretLine && k == composeRow && composeCells > 0 { // The input method draws the text being composed at the caret, over the // editor. The rest of the row moves right to make room for it, so no glyph // of the line shows through the composition. @@ -564,11 +572,22 @@ const markerThickness = 2 // A marker is laid out on the cell grid like the text above it, so the underline // stays under the characters it belongs to when the row is scrolled or wrapped. func (v *View) paintMarkers(canvas *gfx.Canvas, line, from, to, shift int, y float32) { - if len(v.markers) == 0 { + markers := v.markers[line] + if len(markers) == 0 { return } - for _, marker := range v.markers[line] { - start, end := max(marker.Start, from), min(marker.End, to) + hasHints := len(v.lineInlayHints(line)) > 0 + var l lineRef + if hasHints { + l = v.ref(line) + } + for _, marker := range markers { + mStart, mEnd := marker.Start, marker.End + if hasHints && marker.byteEnd > marker.byteStart { + mStart = v.cellsAt(l, marker.byteStart) + mEnd = v.cellsAt(l, marker.byteEnd) + } + start, end := max(mStart, from), min(mEnd, to) if end <= start { continue } @@ -709,12 +728,27 @@ func (v *View) paintHoveredLink(canvas *gfx.Canvas, line, from, to, shift int, y if link == nil || line < link.StartLine || line > link.EndLine { return } + hasHints := len(v.lineInlayHints(line)) > 0 + var l lineRef + if hasHints { + l = v.ref(line) + } start, end := 0, linkOpenEnd if line == link.StartLine { start = link.StartColumn + if hasHints { + if bOff, ok := v.ByteOffset(line, link.StartColumn); ok { + start = v.cellsAt(l, bOff-l.start) + } + } } if line == link.EndLine { end = link.EndColumn + if hasHints { + if bOff, ok := v.ByteOffset(line, link.EndColumn); ok { + end = v.cellsAt(l, bOff-l.start) + } + } } start, end = max(start, from), min(end, to) if end <= start { diff --git a/desktop/internal/editorview/prepared_edit.go b/desktop/internal/editorview/prepared_edit.go index 38504ff7b0..d75415584b 100644 --- a/desktop/internal/editorview/prepared_edit.go +++ b/desktop/internal/editorview/prepared_edit.go @@ -70,6 +70,7 @@ func (v *View) ApplyPreparedEdit(prepared PreparedEdit) bool { } v.redo = v.redo[:0] v.extra = nil + v.ClearInlayHints() v.text = prepared.after v.widest = prepared.widest v.revision++ diff --git a/desktop/internal/editorview/scrollbar.go b/desktop/internal/editorview/scrollbar.go index 3bf539c9b1..8fdb31acb0 100644 --- a/desktop/internal/editorview/scrollbar.go +++ b/desktop/internal/editorview/scrollbar.go @@ -81,7 +81,8 @@ func (v *View) maxScrollX() float32 { if v.wrapping() { return 0 } - return max(float32(v.widest+4)*v.cellW-(v.textRight-v.textLeft), 0) + widest := max(v.widest, v.inlay.prepared.widest) + return max(float32(widest+4)*v.cellW-(v.textRight-v.textLeft), 0) } // verticalThumb is the thumb of the vertical bar, with the scroll its far end stands for. It is diff --git a/desktop/internal/editorview/view.go b/desktop/internal/editorview/view.go index db46808079..62183d0ced 100644 --- a/desktop/internal/editorview/view.go +++ b/desktop/internal/editorview/view.go @@ -195,6 +195,10 @@ type View struct { // over while the link modifier is held, or nil. links []Link hovered *Link + // Inline hints are prepared from one revision. Runs are styled into + // scratch space before each draw without mutating worker results. + inlay inlayState + inlayRuns []gfx.TextRun hl *syntax.Highlighter theme *syntax.Theme @@ -360,10 +364,11 @@ const ( // Line, Start and End are zero-based, and End counts UTF-16 code units within the // line, which is the unit the language protocol reports. type Marker struct { - Line int - Start int - End int - Severity MarkerSeverity + Line int + Start int + End int + Severity MarkerSeverity + byteStart, byteEnd int } // SetMarkers replaces the diagnostics the view underlines. @@ -500,6 +505,7 @@ func (v *View) replaceFromDisk(content Content) bool { v.undo = v.undo[len(v.undo)-undoLimit:] } v.redo = v.redo[:0] + v.ClearInlayHints() v.text = content.text v.saved = v.text v.revision++ @@ -886,6 +892,7 @@ func (v *View) edit(start, end int, text string, kind editKind) { column = v.caretUTF16Column - v.utf16Units(start, v.caretUTF16Offset) + utf16Length(text) } adjustedCells, adjusted := v.adjustCaretLine(firstLine, start, end, text) + v.ClearInlayHints() v.text = v.text.Replace(start, end, []byte(text)) if len(v.vim.marks) > 0 { v.vimShiftMarks(start, end, len(text)) @@ -985,6 +992,7 @@ func (v *View) restore(s snapshot) { change = v.editBetween(start, oldEnd, text) } firstLine, oldLast, oldCount := v.text.LineOf(start), v.text.LineOf(oldEnd), v.text.LineCount() + v.ClearInlayHints() v.text = s.text v.revision++ v.clearCursorHistory() diff --git a/desktop/internal/editorview/wrap.go b/desktop/internal/editorview/wrap.go index ba5d431efb..f02e19236e 100644 --- a/desktop/internal/editorview/wrap.go +++ b/desktop/internal/editorview/wrap.go @@ -140,7 +140,16 @@ func (v *View) rowsOf(l lineRef) []wrapRow { if v.fold.hides(l.line) { return nil } - if !v.wrapping() || l.size*tabSize <= v.wrapCols { + if !v.wrapping() { + return oneRow + } + if len(v.lineInlayHints(l.line)) > 0 { + if rows := v.inlay.wraps[l.line]; len(rows) != 0 { + return rows + } + return oneRow + } + if l.size*tabSize <= v.wrapCols { return oneRow } if rows, ok := v.rowCache[l.line]; ok { @@ -189,6 +198,7 @@ func (v *View) setWrapCols(cols int, wasLineH float32) { } v.rowsDirty = true } + v.reflowInlayRows() v.scroll = float32(v.lineRow(top))*v.lineH + part } @@ -314,7 +324,14 @@ func (v *View) rowCount() int { return v.text.LineCount() } v.ensureRows() - return int(v.rowStart[len(v.rowStart)-1]) + return v.rowStartForLine(len(v.wraps)) +} + +func (v *View) rowStartForLine(line int) int { + if len(v.inlay.rowDeltas) == 0 { + return int(v.rowStart[line]) + } + return int(v.rowStart[line]) + v.inlayRowsBefore(line) } // lineRow is the first row of line. @@ -323,7 +340,7 @@ func (v *View) lineRow(line int) int { return line } v.ensureRows() - return int(v.rowStart[min(max(line, 0), len(v.wraps)-1)]) + return v.rowStartForLine(min(max(line, 0), len(v.wraps)-1)) } // rowLine is the line row is on and which of the line's rows it is. A row past the last is the @@ -335,8 +352,13 @@ func (v *View) rowLine(row int) (int, int) { } v.ensureRows() lines := len(v.wraps) - line := min(sort.Search(lines, func(i int) bool { return int(v.rowStart[i+1]) > row }), lines-1) - return line, min(max(row-int(v.rowStart[line]), 0), int(v.wraps[line].rows)-1) + if len(v.inlay.rowDeltas) == 0 { + line := min(sort.Search(lines, func(i int) bool { return int(v.rowStart[i+1]) > row }), lines-1) + return line, min(max(row-int(v.rowStart[line]), 0), int(v.wraps[line].rows)-1) + } + line := min(sort.Search(lines, func(i int) bool { return v.rowStartForLine(i+1) > row }), lines-1) + start := v.rowStartForLine(line) + return line, min(max(row-start, 0), v.rowStartForLine(line+1)-start-1) } // caretPlace is the caret's line, the line's rows, and which row the caret is on. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 8bdfcbb4aa..453026fbf1 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -452,6 +452,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorFind.tooMany": "More than 10,000 matches. Narrow the scope before replacing all.", "desktop.editorFind.word": "Whole words", "desktop.editorMenu.back": "Back", + "desktop.editorMenu.codeActions": "Code Actions...", "desktop.editorMenu.deleteLine": "Delete Line", "desktop.editorMenu.duplicateLine": "Duplicate Line", "desktop.editorMenu.findUsages": "Find Usages", @@ -463,6 +464,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorMenu.moveLineUp": "Move Line Up", "desktop.editorMenu.openInBrowser": "Open in Browser", "desktop.editorMenu.openInBrowserFailed": "Could not open the file in the browser: {reason}", + "desktop.editorMenu.parameterInfo": "Parameter Info", "desktop.editorMenu.reformat": "Reformat Code", "desktop.editorMenu.rename": "Rename Symbol", "desktop.editorMenu.toggleComment": "Toggle Line Comment", @@ -470,6 +472,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorPrefs.cursorBlink": "Blink caret", "desktop.editorPrefs.cursorStyle": "Caret style", "desktop.editorPrefs.failed": "Could not update editor settings.", + "desktop.editorPrefs.inlayHints": "Show inlay hints", + "desktop.editorPrefs.inlayHintsHelp": "Show parameter names, inferred types, and other inline hints reported by language servers. Turning this off hides hints immediately and stops requesting them.", "desktop.editorPrefs.line": "Line", "desktop.editorPrefs.lineNumbers": "Show line numbers", "desktop.editorPrefs.saveDelay": "Auto-save delay (ms)", @@ -1522,16 +1526,30 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.search.replaceSummary": "{occurrences} occurrences in {files} files", "desktop.search.replaceToggle": "Toggle Replace", "desktop.search.watchUnavailable": "Could not monitor project changes. Refresh search results to check for changes.", + "desktop.semantics.codeActionFailed": "The code action could not be applied.", + "desktop.semantics.codeActionOther": "Action", + "desktop.semantics.codeActionPartial": "Some open documents changed while applying the code action and were not updated.", + "desktop.semantics.codeActionPreferred": "Preferred", + "desktop.semantics.codeActionQuickFix": "Quick Fix", + "desktop.semantics.codeActionRefactor": "Refactor", + "desktop.semantics.codeActionRejected": "The code action touches files outside the project or read-only documents, so nothing was changed.", + "desktop.semantics.codeActionSource": "Source", + "desktop.semantics.codeActions": "Code Actions", "desktop.semantics.completion": "Completion suggestions", "desktop.semantics.completionFailed": "The completion could not be applied.", "desktop.semantics.definitions": "Definitions", "desktop.semantics.formatFailed": "The document could not be formatted.", "desktop.semantics.formatNothing": "Nothing to format.", "desktop.semantics.hover": "Hover information", + "desktop.semantics.inlayHintApply": "Insert Hint", + "desktop.semantics.inlayHintTooltip": "Inlay hint details", + "desktop.semantics.noCodeActions": "No code actions available here.", "desktop.semantics.noDefinition": "No definition found.", "desktop.semantics.noReferences": "No references found.", "desktop.semantics.noServer": "No language server is available for this file.", + "desktop.semantics.noSignatureHelp": "No parameter information available here.", "desktop.semantics.operationFailed": "The language server could not complete the request.", + "desktop.semantics.quickFixButton": "Quick Fix…", "desktop.semantics.references": "References", "desktop.semantics.renameApplied": "Renamed in {count} files.", "desktop.semantics.renameButton": "Rename", @@ -1543,6 +1561,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.semantics.renamePartial": "Some open documents changed during the rename and were not updated.", "desktop.semantics.renameRejected": "The rename touches files outside the project or read-only documents, so nothing was changed.", "desktop.semantics.renameTitle": "Rename Symbol", + "desktop.semantics.signatureHelp": "Parameter Info", + "desktop.semantics.signatureNext": "Next signature", + "desktop.semantics.signatureOverload": "{current}/{total}", + "desktop.semantics.signaturePrevious": "Previous signature", "desktop.semantics.targetUnavailable": "The target is not a local file and cannot be opened yet.", "desktop.settings.about": "About", "desktop.settings.about.build": "Build", @@ -3441,6 +3463,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorFind.tooMany": "匹配超过 10000 处;请缩小范围后再全部替换。", "desktop.editorFind.word": "整词匹配", "desktop.editorMenu.back": "后退", + "desktop.editorMenu.codeActions": "代码操作…", "desktop.editorMenu.deleteLine": "删除行", "desktop.editorMenu.duplicateLine": "复制行", "desktop.editorMenu.findUsages": "查找用法", @@ -3452,6 +3475,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorMenu.moveLineUp": "上移行", "desktop.editorMenu.openInBrowser": "在浏览器中打开", "desktop.editorMenu.openInBrowserFailed": "无法在浏览器中打开文件:{reason}", + "desktop.editorMenu.parameterInfo": "参数信息", "desktop.editorMenu.reformat": "格式化代码", "desktop.editorMenu.rename": "重命名符号", "desktop.editorMenu.toggleComment": "切换行注释", @@ -3459,6 +3483,8 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.editorPrefs.cursorBlink": "光标闪烁", "desktop.editorPrefs.cursorStyle": "光标样式", "desktop.editorPrefs.failed": "无法更新编辑器设置。", + "desktop.editorPrefs.inlayHints": "显示内联提示", + "desktop.editorPrefs.inlayHintsHelp": "显示语言服务器提供的参数名、推导类型等行内提示。关闭后会立即移除已有提示并停止请求。", "desktop.editorPrefs.line": "竖线", "desktop.editorPrefs.lineNumbers": "显示行号", "desktop.editorPrefs.saveDelay": "自动保存延迟(毫秒)", @@ -4511,16 +4537,30 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.search.replaceSummary": "{files} 个文件中的 {occurrences} 处", "desktop.search.replaceToggle": "切换替换", "desktop.search.watchUnavailable": "无法监听项目变化。请刷新搜索结果以检查更新。", + "desktop.semantics.codeActionFailed": "无法应用该代码操作。", + "desktop.semantics.codeActionOther": "操作", + "desktop.semantics.codeActionPartial": "部分已打开的文档在应用代码操作期间发生了变化,未更新。", + "desktop.semantics.codeActionPreferred": "首选", + "desktop.semantics.codeActionQuickFix": "快速修复", + "desktop.semantics.codeActionRefactor": "重构", + "desktop.semantics.codeActionRejected": "该代码操作涉及项目之外的文件或只读文档,未做任何更改。", + "desktop.semantics.codeActionSource": "源码", + "desktop.semantics.codeActions": "代码操作", "desktop.semantics.completion": "补全建议", "desktop.semantics.completionFailed": "无法应用补全。", "desktop.semantics.definitions": "定义", "desktop.semantics.formatFailed": "无法格式化文档。", "desktop.semantics.formatNothing": "没有需要格式化的内容。", "desktop.semantics.hover": "悬浮信息", + "desktop.semantics.inlayHintApply": "插入提示文本", + "desktop.semantics.inlayHintTooltip": "内联提示详情", + "desktop.semantics.noCodeActions": "此处没有可用的代码操作。", "desktop.semantics.noDefinition": "未找到定义。", "desktop.semantics.noReferences": "未找到引用。", "desktop.semantics.noServer": "此文件没有可用的语言服务器。", + "desktop.semantics.noSignatureHelp": "此处没有可用的参数信息。", "desktop.semantics.operationFailed": "语言服务器无法完成该请求。", + "desktop.semantics.quickFixButton": "快速修复…", "desktop.semantics.references": "引用", "desktop.semantics.renameApplied": "已在 {count} 个文件中重命名。", "desktop.semantics.renameButton": "重命名", @@ -4532,6 +4572,10 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.semantics.renamePartial": "部分已打开的文档在重命名期间发生了变化,未更新。", "desktop.semantics.renameRejected": "重命名涉及项目之外的文件或只读文档,未做任何更改。", "desktop.semantics.renameTitle": "重命名符号", + "desktop.semantics.signatureHelp": "参数信息", + "desktop.semantics.signatureNext": "下一个重载签名", + "desktop.semantics.signatureOverload": "{current}/{total}", + "desktop.semantics.signaturePrevious": "上一个重载签名", "desktop.semantics.targetUnavailable": "目标不是本地文件,暂时无法打开。", "desktop.settings.about": "关于", "desktop.settings.about.build": "构建", diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index f0190dcc37..5ca43e5c42 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -74,8 +74,9 @@ type Capabilities map[string][]int // toolchain layers select for the workspace, or the command line the plugin // backend answers), starts the process and keeps the session's documents in // step with the editor. The editor presents its diagnostics, completion, -// hover, definition, references, rename, formatting, document symbols, -// document links and semantic tokens. Plugin-owned sessions are wired: the +// hover, signature help, code actions, inlay hints, definition, references, +// rename, formatting, document symbols, document links and semantic tokens, +// and applies validated server-initiated workspace edits. Plugin-owned sessions are wired: the // backend's languageServer/request and notify reach the server under Core's // session policy, and didReceiveNotification and didChangeState reach the // backend. @@ -132,8 +133,8 @@ type Capabilities map[string][]int // // Not presented yet (the plugin installs, the part has no surface): // -// - a language server's code actions, signature help and inlay hints, and a -// plugin's foldingRange provider, which is not routed. +// - a plugin's foldingRange provider, which is not routed (language-server +// foldingRange is served). // - tool discovery for system commands reads PATH and the plugin's installed // command directories only; a plan that depends on a project toolchain or a // user override must use a tool launch. diff --git a/desktop/internal/settingswindow/editor_preferences_view.go b/desktop/internal/settingswindow/editor_preferences_view.go index a4b80afa3b..bd8912277d 100644 --- a/desktop/internal/settingswindow/editor_preferences_view.go +++ b/desktop/internal/settingswindow/editor_preferences_view.go @@ -35,6 +35,12 @@ func (w *window) editorPresentationCard(c ui.C) { if ui.Switch(c.Part("whitespace"), ¤t.Whitespace, i18n.Shared(lang, "desktop.editorPrefs.whitespace")).Changed() { w.setEditorPresentation(current) } + ui.Row(c).FillWidth().Items(ui.Center).Gap(6).Children(func() { + if ui.Switch(c.Part("inlay-hints"), ¤t.InlayHints, i18n.Shared(lang, "desktop.editorPrefs.inlayHints")).Changed() { + w.setEditorPresentation(current) + } + w.infoButton(c.Part("inlay-hints-info"), i18n.Shared(lang, "desktop.editorPrefs.inlayHintsHelp")) + }) w.settingsRow(c, i18n.Shared(lang, "desktop.editorPrefs.cursorStyle"), "", func() { if ui.Select(c.Part("caret-style"), ¤t.CursorStyle, []string{"line", "block", "underline"}, func(style string) string { switch style { @@ -72,7 +78,14 @@ func (w *window) editorPresentationCard(c ui.C) { } func (w *window) setEditorPresentation(value core.EditorPreferences) { - stored := core.EditorStoredPreferences{LineNumbers: &value.LineNumbers, Whitespace: &value.Whitespace, CursorStyle: value.CursorStyle, CursorBlink: &value.CursorBlink, AutoSaveDelayMilliseconds: &value.AutoSaveDelayMilliseconds} + stored := core.EditorStoredPreferences{ + LineNumbers: &value.LineNumbers, + Whitespace: &value.Whitespace, + InlayHints: &value.InlayHints, + CursorStyle: value.CursorStyle, + CursorBlink: &value.CursorBlink, + AutoSaveDelayMilliseconds: &value.AutoSaveDelayMilliseconds, + } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() resolved, err := core.NewClient().ResolveEditorPreferences(ctx, stored) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 59288b8c8d..985968e743 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -686,7 +686,8 @@ type App struct { // pluginDiagnostics holds what each running language server published for // the files of the open project, keyed by plugin so stopping one server // withdraws only its own diagnostics. - pluginDiagnostics map[string]*plugindiag.Set + pluginDiagnostics map[string]*plugindiag.Set + rawPluginDiagnostics map[string]map[string][]core.PluginDiagnostic // semantics is the editor's pending and presented language answers. semantics pluginSemantics contentOpen *contentOpenRequest diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 67a99c3b46..5272e8b479 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -56,6 +56,8 @@ type document struct { recoveredConflict bool recoveryTimer *time.Timer autoSaveTimer *time.Timer + inlay documentInlayHints + lastArea gfx.Rect // folds is the document's code folding requests (folding.go). folds documentFolds // serverLinks are the links the language server reported for the text, and pluginLinks the @@ -843,6 +845,7 @@ func (a *App) removeDocument(p *project, d *document) { // A document without a tab is released with nothing to close, once it is saved. if d.tabless && !d.dirty() { a.semanticTokensDropped(d) + a.clearDocumentInlayHints(d) d.closeEditorView() p.docs.list = slices.DeleteFunc(p.docs.list, func(x *document) bool { return x.id == d.id }) // The preview's language features may have opened it in a server. @@ -855,6 +858,7 @@ func (a *App) removeDocument(p *project, d *document) { return } a.semanticTokensDropped(d) + a.clearDocumentInlayHints(d) d.closeEditorView() p.docs.list = slices.DeleteFunc(p.docs.list, func(x *document) bool { return x.id == d.id }) a.unwatchDocument(p, d) @@ -945,6 +949,7 @@ func (a *App) closeDocuments(p *project) { a.flushCheckpoint(p, d, false) d.find.dispose() d.cancelAutoSave() + a.clearDocumentInlayHints(d) d.closeEditorView() } p.docs = documentSet{} diff --git a/desktop/internal/workbench/editor_menu.go b/desktop/internal/workbench/editor_menu.go index 22037ac29b..2c26ba6dc0 100644 --- a/desktop/internal/workbench/editor_menu.go +++ b/desktop/internal/workbench/editor_menu.go @@ -45,6 +45,17 @@ func (a *App) editorMenuItems(c ui.C, p *project, d *document) func(*ui.MenuItem if menu.Item(i18n.Shared(language, "desktop.editorMenu.reformat")).Disabled(readOnly).Clicked() { c.After(func() { a.startPluginFormattingAtSelection(p, d) }) } + _, codeActions := a.editorServer(d, featureCodeActions) + if menu.Item(i18n.Shared(language, "desktop.editorMenu.codeActions")).Keys(gfx.ModifierAlt, "enter").Disabled(readOnly || !codeActions).Clicked() { + c.After(func() { a.startPluginCodeActions(p, d, nil, surfaceContextMenu) }) + } + _, parameterInfo := a.editorServer(d, featureSignatureHelp) + if menu.Item(i18n.Shared(language, "desktop.semantics.signatureHelp")).Keys(primary, "p").Disabled(!parameterInfo).Clicked() { + c.After(func() { + line, column := d.view.CaretUTF16() + a.startPluginSignatureHelp(p, d, line, column, surfaceContextMenu) + }) + } if browserPreviewable(d) { if menu.Item(i18n.Shared(language, "desktop.editorMenu.openInBrowser")).Clicked() { c.After(func() { a.openInBrowser(p, d, surfaceContextMenu) }) diff --git a/desktop/internal/workbench/editor_requests.go b/desktop/internal/workbench/editor_requests.go index 876b1261eb..8e8b33bf31 100644 --- a/desktop/internal/workbench/editor_requests.go +++ b/desktop/internal/workbench/editor_requests.go @@ -4,6 +4,7 @@ import ( "context" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" ) // The editor's own language requests: the outline's document symbols and the semantic @@ -89,6 +90,32 @@ func (a *App) applyEditorEvent(pending *semanticPending, event core.BackendEvent a.applyServerDocumentLinks(pending, event, failed) case pluginSemanticWorkspaceSymbols: a.applyWorkspaceSymbols(pending, event, failed) + case pluginSemanticInlayHints: + a.applyServerInlayHints(pending, event, failed) + case pluginSemanticResolveInlayHint: + a.applyResolvedInlayHint(pending, event, failed) + case pluginSemanticSignatureHelp: + if !failed { + a.applySemanticSignatureHelp(pending, event) + } + case pluginSemanticCodeActions: + if failed { + a.closeSemanticCodeActions() + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + } else { + a.applySemanticCodeActions(pending, event) + } + case pluginSemanticResolveCodeAction: + if failed { + a.closeSemanticCodeActions() + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + } else { + a.applySemanticResolveCodeAction(pending, event) + } + case pluginSemanticExecuteCommand: + if failed { + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + } default: return false } diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index 5cd13e7a5c..96405ccf70 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -179,6 +179,7 @@ func (a *App) documentView(c ui.C, group string, d *document) { if p := a.project; p != nil { a.foldSync(c, p, d) a.linkSync(c, p, d) + a.inlayHintsSync(c, p, d) } if p := a.project; p != nil && !d.virtual { items, shown := a.editorMenuItems(c, p, d), false @@ -235,7 +236,18 @@ func (a *App) documentInput(p *project, d *document) { // belongs to the line the frame draws. a.applyInlineBlame(p, d) a.applyDebugGutter(p, d) + // Inlay requests depend on the geometry published by paint. Resize and + // the first paint queue a single follow-up with the new viewport. + first, last, measured := v.VisibleLineRange() + previousArea := d.lastArea + d.lastArea = dc.Rect v.Paint(dc.Canvas, dc.Rect, a.editorLook()) + if prefs.InlayHints && previousArea != dc.Rect { + nextFirst, nextLast, ok := v.VisibleLineRange() + if ok && (!measured || first != nextFirst || last != nextLast) { + a.invalidator.Invalidate() + } + } if dc.State.Focused { p.docs.group = d.group } @@ -258,6 +270,9 @@ func (a *App) documentViewKey(p *project, d *document, view *editorview.View, ev if result := a.pluginSemanticsKey(event); result.Handled { return result } + if result := a.codeActionsShortcut(event); result.Handled { + return result + } if result, handled := a.pluginSemanticsTrigger(event, p, d); handled { return result } @@ -287,6 +302,9 @@ func (a *App) documentPointer(p *project, d *document, event gfx.PointerEvent) g // A semantic popup or request belongs to the caret and symbol it was opened at; any // pointer work that moved either closes it before the frame paints. defer a.pluginSemanticsCaretSync() + if result, handled := a.inlayHintPointer(event, p, d, d.view); handled { + return result + } if result, handled := a.documentLinkPointer(event, d); handled { return result } @@ -545,6 +563,7 @@ func verticalWheel(event *gfx.ScrollEvent) { // closes the hover popup of the editor, which no control sees leave. func (a *App) onPointer(event gfx.PointerEvent) gfx.EventResult { if event.Kind == gfx.PointerExit { + a.semantics.inlayHover = inlayHintHoverState{} a.leaveSemanticHover() } return gfx.EventResult{} diff --git a/desktop/internal/workbench/inlay_hints.go b/desktop/internal/workbench/inlay_hints.go new file mode 100644 index 0000000000..bd0aad84eb --- /dev/null +++ b/desktop/internal/workbench/inlay_hints.go @@ -0,0 +1,488 @@ +package workbench + +import ( + "context" + "strings" + "time" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "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" +) + +const ( + pluginSemanticInlayHints semanticKind = "inlayHints" + pluginSemanticResolveInlayHint semanticKind = "resolveInlayHint" + + pluginMethodInlayHints = "textDocument/inlayHint" + pluginMethodResolveInlayHint = "inlayHint/resolve" + + pluginInlayHintsRefresh = "inlayHintsRefresh" + + featureInlayHints = "inlayHints" + featureInlayHintResolve = "inlayHintResolve" + + inlayHintsPrefetchMargin = 40 + inlayHintsDelay = 120 * time.Millisecond +) + +type documentInlayHints struct { + initialized bool + revision int + coveredStart int + coveredEnd int + reqStart int + reqEnd int + dirty bool + changedAt time.Time + seenRevision int + seenFirst int + seenLast int + pending *semanticPending + resolve *semanticPending + resolveIndex int + prepareCancel context.CancelFunc + prepareGen uint64 + hints []core.PluginSemanticInlayHint + resolved map[int]bool +} + +type inlayHintHoverState struct { + open bool + documentID int + revision int + hintIndex int + anchor gfx.Rect + rect gfx.Rect +} + +func (a *App) clearDocumentInlayHints(d *document) { + if d == nil { + return + } + ih := &d.inlay + if ih.pending != nil { + a.cancelSemantic(ih.pending) + ih.pending = nil + } + if ih.resolve != nil { + a.cancelSemantic(ih.resolve) + ih.resolve = nil + } + if ih.prepareCancel != nil { + ih.prepareCancel() + ih.prepareCancel = nil + } + ih.prepareGen++ + ih.hints = nil + ih.resolved = nil + ih.revision = -1 + ih.coveredStart, ih.coveredEnd = 0, -1 + ih.dirty = false + if d.view != nil && d.view.ClearInlayHints() { + a.invalidator.Invalidate() + } + if a.semantics.inlayHover.open && a.semantics.inlayHover.documentID == d.id { + a.semantics.inlayHover = inlayHintHoverState{} + } +} + +func (a *App) applyInlayHintsPreference(enabled bool) { + p := a.project + if p == nil { + return + } + if !enabled { + a.semantics.inlayHover = inlayHintHoverState{} + for _, d := range p.docs.list { + a.clearDocumentInlayHints(d) + } + return + } + for _, d := range p.docs.list { + d.inlay.dirty = true + } + a.invalidator.Invalidate() +} + +func (a *App) inlayHintsRefresh(server *pluginServer) { + if server == nil || server.session == nil || !a.isCurrentPluginServer(server.session.PluginID, server) { + return + } + p := a.project + if p == nil || p != server.project { + return + } + changed := false + for _, d := range p.docs.list { + if srv, _ := a.documentSyncServer(d); srv == server { + d.inlay.dirty = true + d.inlay.changedAt = a.now() + changed = true + } + } + if changed && a.editorPreferences.InlayHints { + a.invalidator.Invalidate() + } +} + +// inlayHintsSync requests visible-viewport (+ bounded margin) inlay hints when enabled, +// coalescing scroll and edit bursts without idle polling or idle repaints. +func (a *App) inlayHintsSync(c ui.C, p *project, d *document) { + if p == nil || d == nil { + return + } + if !a.editorPreferences.InlayHints { + if d.view.HasInlayHints() || d.inlay.pending != nil || d.inlay.prepareCancel != nil { + a.clearDocumentInlayHints(d) + } + return + } + ih := &d.inlay + if !ih.initialized { + ih.initialized = true + ih.revision = -1 + ih.seenRevision = -1 + ih.coveredEnd = -1 + } + server, offered := a.editorServer(d, featureInlayHints) + if server == nil || !offered || d.virtual { + if d.view.HasInlayHints() || ih.pending != nil { + a.clearDocumentInlayHints(d) + } + return + } + visFirst, visLast, ok := d.view.VisibleLineRange() + if !ok { + return + } + revision := d.view.Revision() + if !ih.dirty && ih.revision == revision && visFirst >= ih.coveredStart && visLast <= ih.coveredEnd { + return + } + if a.editorRequestWaiting(ih.pending) { + if ih.pending.revision == revision && !ih.dirty && visFirst >= ih.reqStart && visLast <= ih.reqEnd { + return + } + a.cancelSemantic(ih.pending) + ih.pending = nil + } else { + ih.pending = nil + } + if !a.semanticDocumentReady(d) { + return + } + now := a.now() + if ih.seenRevision != revision || ih.seenFirst != visFirst || ih.seenLast != visLast { + ih.seenRevision = revision + ih.seenFirst = visFirst + ih.seenLast = visLast + ih.changedAt = now + } + delay := a.semantics.inlayDelay + if delay == 0 { + delay = inlayHintsDelay + } + if ih.revision >= 0 && delay > 0 { + if wait := ih.changedAt.Add(delay).Sub(now); wait > 0 { + c.Canvas().RequestFrameIn(wait) + return + } + } + snapshot := d.view.TextSnapshot() + lineCount := max(snapshot.LineCount(), 1) + reqStart := max(visFirst-inlayHintsPrefetchMargin, 0) + reqEnd := min(visLast+inlayHintsPrefetchMargin, lineCount-1) + end := core.PluginDocumentPosition{Line: reqEnd + 1} + if end.Line == lineCount { + lastStart, lastEnd := snapshot.LineStart(reqEnd), snapshot.LineEnd(reqEnd) + if lastEnd-lastStart <= 64*1024 { + end = core.PluginDocumentPosition{Line: reqEnd, UTF16Column: utf16CountString(snapshot.Line(reqEnd))} + } else { + // The editor skips annotations on long-line mode's last line. + end = core.PluginDocumentPosition{Line: reqEnd} + } + } + + ih.dirty = false + ih.reqStart = reqStart + ih.reqEnd = reqEnd + ih.pending = a.submitEditorRequest(pluginSemanticInlayHints, p, d, server, core.PluginSemanticRequest{ + Range: &core.PluginDocumentRange{ + Start: core.PluginDocumentPosition{Line: reqStart, UTF16Column: 0}, + End: end, + }, + }) +} + +func utf16CountString(s string) int { + n := 0 + for _, r := range s { + n++ + if r > 0xffff { + n++ + } + } + return n +} + +func (a *App) applyServerInlayHints(pending *semanticPending, event core.BackendEvent, failed bool) { + p, d := a.currentSemanticDocument(pending.documentID) + if p != pending.project || d == nil || d.inlay.pending != pending { + return + } + ih := &d.inlay + ih.pending = nil + if !a.editorPreferences.InlayHints { + a.clearDocumentInlayHints(d) + return + } + if d.view.Revision() != pending.revision { + return + } + // Settle this range on a failed request too. A visible error should + // not turn unrelated repaints into repeated requests to the server. + d.inlay.revision = pending.revision + d.inlay.coveredStart, d.inlay.coveredEnd = d.inlay.reqStart, d.inlay.reqEnd + if failed { + return + } + hints, err := core.PluginSemanticInlayHints(event) + if err != nil { + a.backgroundFailed("plugin_inlay_hints", err) + return + } + if ih.prepareCancel != nil { + ih.prepareCancel() + ih.prepareCancel = nil + } + if ih.resolve != nil { + a.cancelSemantic(ih.resolve) + ih.resolve = nil + } + if a.semantics.inlayHover.documentID == d.id { + a.semantics.inlayHover = inlayHintHoverState{} + } + d.view.ClearInlayHints() + ih.hints = hints + ih.resolved = nil + ih.revision = pending.revision + ih.coveredStart = ih.reqStart + ih.coveredEnd = ih.reqEnd + if len(hints) == 0 { + a.invalidator.Invalidate() + return + } + specs := make([]editorview.InlayHintSpec, len(hints)) + for i, h := range hints { + specs[i] = editorview.InlayHintSpec{ + ID: i, + Line: h.Position.Line, + UTF16Column: h.Position.UTF16Column, + Label: h.Label, + PaddingLeft: h.PaddingLeft, + PaddingRight: h.PaddingRight, + Interactive: (h.Tooltip != nil && *h.Tooltip != "") || len(h.TextEdits) > 0 || len(h.ResolvePayload) > 0, + } + } + snapshot := d.view.TextSnapshot() + revision := pending.revision + docID := d.id + ih.prepareGen++ + gen := ih.prepareGen + ctx, cancel := context.WithCancel(p.ctx) + ih.prepareCancel = cancel + a.background(p, 10*time.Second, func(workCtx context.Context) func(*App) { + defer cancel() + prepared, prepErr := editorview.PrepareInlayHints(ctx, snapshot, revision, specs) + if prepErr != nil { + // log-exempt: 用户取消:滚动、编辑或关闭开关会取消旧的内联提示排版计算。 + return nil + } + return func(a *App) { + curProj, curDoc := a.currentSemanticDocument(docID) + if curProj != p || curDoc == nil || !a.editorPreferences.InlayHints || curDoc.inlay.prepareGen != gen { + return + } + curDoc.inlay.prepareCancel = nil + if curDoc.view.SetPreparedInlayHints(prepared) { + a.invalidator.Invalidate() + } + } + }) +} + +func (a *App) applyResolvedInlayHint(pending *semanticPending, event core.BackendEvent, failed bool) { + p, d := a.currentSemanticDocument(pending.documentID) + if p != pending.project || d == nil || d.inlay.resolve != pending { + return + } + ih := &d.inlay + idx := ih.resolveIndex + ih.resolve = nil + if failed || d.view.Revision() != pending.revision || idx < 0 || idx >= len(ih.hints) { + return + } + resolved, err := core.PluginSemanticResolvedInlayHint(event) + if err != nil || resolved == nil { + if err != nil { + a.backgroundFailed("plugin_inlay_hint_resolve", err) + } + return + } + ih.hints[idx] = *resolved + if ih.resolved == nil { + ih.resolved = make(map[int]bool) + } + ih.resolved[idx] = true + a.invalidator.Invalidate() +} + +func (a *App) inlayHintPointer(event gfx.PointerEvent, p *project, d *document, view *editorview.View) (gfx.EventResult, bool) { + if p == nil || d == nil || view == nil || !a.editorPreferences.InlayHints { + return gfx.EventResult{}, false + } + switch event.Kind { + case gfx.PointerMove: + if pointInRect(a.semantics.inlayHover.rect, event.X, event.Y) { + return gfx.EventResult{}, false + } + id, rect, ok := view.InlayHintAt(event.X, event.Y) + if !ok || id < 0 || id >= len(d.inlay.hints) { + if a.semantics.inlayHover.open { + a.semantics.inlayHover = inlayHintHoverState{} + a.invalidator.Invalidate() + } + return gfx.EventResult{}, false + } + hint := d.inlay.hints[id] + server, _ := a.editorServer(d, featureInlayHintResolve) + canResolve := server != nil && server.features[featureInlayHintResolve] && len(hint.ResolvePayload) > 0 && !d.inlay.resolved[id] + hasTooltip := hint.Tooltip != nil && strings.TrimSpace(*hint.Tooltip) != "" + hasEdits := len(hint.TextEdits) > 0 && !d.view.ReadOnly() + if !hasTooltip && !hasEdits && !canResolve { + return gfx.EventResult{}, false + } + if canResolve && !hasTooltip && !hasEdits && d.inlay.resolve == nil { + d.inlay.resolveIndex = id + d.inlay.resolve = a.submitEditorRequest(pluginSemanticResolveInlayHint, p, d, server, core.PluginSemanticRequest{ + InlayHint: hint.Raw, + }) + } + if !a.semantics.inlayHover.open || a.semantics.inlayHover.documentID != d.id || a.semantics.inlayHover.hintIndex != id { + a.semantics.project = p + a.semantics.inlayHover = inlayHintHoverState{ + open: true, + documentID: d.id, + revision: d.view.Revision(), + hintIndex: id, + anchor: rect, + } + a.invalidator.Invalidate() + } + return gfx.EventResult{}, false + case gfx.PointerDown: + if event.Button == gfx.PointerButtonPrimary && event.ClickCount >= 2 && !d.view.ReadOnly() && !d.caretView().IsComposing() { + id, _, ok := view.InlayHintAt(event.X, event.Y) + if ok && id >= 0 && id < len(d.inlay.hints) && len(d.inlay.hints[id].TextEdits) > 0 { + a.applyInlayHintEdits(p, d, id) + return gfx.EventResult{Handled: true, Repaint: true}, true + } + } + if a.semantics.inlayHover.open && !pointInRect(a.semantics.inlayHover.rect, event.X, event.Y) { + a.semantics.inlayHover = inlayHintHoverState{} + } + case gfx.PointerExit: + if a.semantics.inlayHover.open { + a.semantics.inlayHover = inlayHintHoverState{} + a.invalidator.Invalidate() + } + } + return gfx.EventResult{}, false +} + +func (a *App) applyInlayHintEdits(p *project, d *document, hintIndex int) { + if p == nil || d == nil || p != a.project || d.view.ReadOnly() || d.caretView().IsComposing() { + return + } + if hintIndex < 0 || hintIndex >= len(d.inlay.hints) || d.inlay.revision != d.view.Revision() { + return + } + edits := d.inlay.hints[hintIndex].TextEdits + if len(edits) == 0 { + return + } + a.semantics.inlayHover = inlayHintHoverState{} + a.performed("editor.inlayHint.apply", surfaceButton) + a.applyEditsToDocument(p, d, edits, "plugin_inlay_hint_apply") +} + +func (a *App) inlayHintHoverPopup(c ui.C) { + st := &a.semantics.inlayHover + if !st.open || !a.editorPreferences.InlayHints { + return + } + p, d := a.currentSemanticDocument(st.documentID) + if d == nil || p != a.project || d.view.Revision() != st.revision || st.hintIndex < 0 || st.hintIndex >= len(d.inlay.hints) { + *st = inlayHintHoverState{} + return + } + hint := d.inlay.hints[st.hintIndex] + tooltip := "" + if hint.Tooltip != nil { + tooltip = truncateDisplayText(*hint.Tooltip, 260) + } + hasEdits := len(hint.TextEdits) > 0 && !d.view.ReadOnly() + if tooltip == "" && !hasEdits { + return + } + bounds := c.Bounds() + width := float32(300) + if tooltip == "" { + width = 180 + } + height := float32(40) + if tooltip != "" && hasEdits { + height = 68 + } else if tooltip != "" && utf8.RuneCountInString(tooltip) > 42 { + height = 56 + } + x, y := popupOrigin(st.anchor.X, st.anchor.Y+st.anchor.Height+2, width, bounds) + st.rect = gfx.Rect{X: x, Y: y, Width: width, Height: height} + lang := a.language() + label := i18n.Shared(lang, "desktop.semantics.inlayHintTooltip") + applyClicked := false + ui.Stack(c.Part("inlay-hover-layer")).Fill().Children(func() { + hc := c.Part("inlay-hover-card") + ui.Column(hc).Absolute().Left(x).Top(y).Width(width).Pad(8).Gap(6). + Background(a.theme.Popover).Border(1, a.theme.Border). + Radius(a.theme.Metrics.RadiusPopup()).Shadow(gfx.ShadowMD). + HitWith(ui.ID(hc), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}). + Children(func() { + if tooltip != "" { + ui.Wrap(hc, tooltip).FontSize(11.5).Color(a.colors.Text) + } + if hasEdits { + btnLabel := i18n.Shared(lang, "desktop.semantics.inlayHintApply") + bc := hc.Part("apply-inlay-edit") + btn := ui.Row(bc).Height(22).PadX(8).Center().Radius(4). + Background(a.colors.Active). + HitWith(ui.ID(bc), btnLabel, gfx.HitOptions{Role: gfx.RoleButton, SkipFocus: true, Cursor: gfx.PointerCursorHand}). + Hover(ui.Look{}.Background(a.colors.Hover)) + btn.Children(func() { + ui.Text(bc, btnLabel).FontSize(11.5).Color(a.colors.Text) + }) + if btn.Clicked() { + applyClicked = true + } + } + }) + }) + if applyClicked { + idx := st.hintIndex + c.After(func() { a.applyInlayHintEdits(p, d, idx) }) + } +} diff --git a/desktop/internal/workbench/lsp_actions_test.go b/desktop/internal/workbench/lsp_actions_test.go new file mode 100644 index 0000000000..26cb5525ad --- /dev/null +++ b/desktop/internal/workbench/lsp_actions_test.go @@ -0,0 +1,152 @@ +package workbench + +import ( + "context" + "encoding/json" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/vivaui/viva/gfx" +) + +func TestLSPCodeActionsUseTheActiveServerDiagnosticsAndApplyEdit(t *testing.T) { + f := newSemanticFixture(t) + f.server.features = map[string]bool{featureCodeActions: true} + f.d.view.GoToNavigation(0, 1, false) + f.h.app.storeRawPluginDiagnostics("test", f.d.path, []core.PluginDiagnostic{{Message: "active diagnostic"}}) + f.h.app.storeRawPluginDiagnostics("dev.lithe.test.other", f.d.path, []core.PluginDiagnostic{{Message: "other diagnostic"}}) + if err := f.h.driver.Key(gfx.KeyEnter, gfx.ModifierAlt); err != nil { + t.Fatal(err) + } + f.waitForRequests(t, 1) + request := f.kernel.request(0) + if request.Operation != string(pluginSemanticCodeActions) || request.Range == nil || request.Range.Start.UTF16Column != 1 { + t.Fatalf("code action request = %+v", request) + } + if len(request.Diagnostics) != 1 || request.Diagnostics[0].Message != "active diagnostic" { + t.Fatalf("diagnostic context = %+v", request.Diagnostics) + } + + version, ok := f.server.session.Documents.Version(f.d.sync.uri) + if !ok { + t.Fatal("fixture lacks a synchronized document version") + } + response, err := json.Marshal(map[string]any{"actions": []core.PluginSemanticCodeAction{{ + Title: "Replace one with two", + Group: "quickfix", + Edit: &core.PluginSemanticWorkspaceEdit{ + Changes: map[string][]core.PluginTextEdit{f.d.path: wordEdit(0, 0, 3, "two")}, + DocumentVersions: map[string]int64{f.d.path: version}, + }, + }}}) + if err != nil { + t.Fatal(err) + } + f.deliver(t, "op-1", pluginMethodCodeActions, response) + if !f.h.app.semantics.codeActions.open { + t.Fatal("code action list did not open") + } + if err := f.h.driver.Key(gfx.KeyEnter, 0); err != nil { + t.Fatal(err) + } + f.h.await("code action edit", func() bool { return f.d.view.TextSnapshot().String() == "two\n" }) + if got := f.d.view.TextSnapshot().String(); got != "two\n" { + t.Fatalf("code action produced %q", got) + } + if _, err := f.h.driver.ShortcutChord(primaryModifier(), 'z'); err != nil { + t.Fatal(err) + } + if got := f.d.view.TextSnapshot().String(); got != "one\n" { + t.Fatalf("undo produced %q", got) + } +} + +func TestLSPSignatureHelpShortcutPresentsAndDismisses(t *testing.T) { + f := newSemanticFixture(t) + f.server.features = map[string]bool{featureSignatureHelp: true} + key := gfx.KeyEvent{Text: "p", Modifiers: primaryModifier(), Target: f.d.hit} + if !f.h.app.pluginSemanticsShortcut(key).Handled { + t.Fatal("signature help shortcut was not handled") + } + f.waitForRequests(t, 1) + if request := f.kernel.request(0); request.Operation != string(pluginSemanticSignatureHelp) || request.Position == nil { + t.Fatalf("signature request = %+v", request) + } + f.deliver(t, "op-1", pluginMethodSignatureHelp, json.RawMessage(`{"signatureHelp":{"signatures":[{"label":"greet(name: string)"}],"activeSignature":0}}`)) + if state := f.h.app.semantics.signatureHelp; !state.open || state.help.Signatures[0].Label != "greet(name: string)" { + t.Fatalf("signature help state = %+v", state) + } + if err := f.h.driver.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + if f.h.app.semantics.signatureHelp.open { + t.Fatal("Escape left the signature popup open") + } +} + +func TestLSPInlayHintsReleaseWhenDisabled(t *testing.T) { + f := newSemanticFixture(t) + f.h.app.editorPreferences.InlayHints = true + f.server.features = map[string]bool{featureInlayHints: true} + f.h.app.invalidator.Invalidate() + if err := f.h.driver.Pump(); err != nil { + t.Fatal(err) + } + f.waitForRequests(t, 1) + request := f.kernel.request(0) + if request.Operation != string(pluginSemanticInlayHints) || request.Range == nil || request.Range.Start.Line != 0 { + t.Fatalf("inlay request = %+v", request) + } + f.deliver(t, "op-1", pluginMethodInlayHints, json.RawMessage(`{"hints":[{"position":{"line":0,"utf16Column":1},"label":": string"}]}`)) + f.h.settleChain() + if !f.d.view.HasInlayHints() { + t.Fatal("inlay result did not reach the editor") + } + f.h.app.editorPreferences.InlayHints = false + f.h.app.applyInlayHintsPreference(false) + if f.d.view.HasInlayHints() || f.d.inlay.prepareCancel != nil { + t.Fatal("disabling inlay hints kept decorations or background preparation") + } +} + +func TestLSPWorkspaceEditWriteRestoresFilesOnCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + first := filepath.Join(t.TempDir(), "first.txt") + second := filepath.Join(t.TempDir(), "second.txt") + contents := map[string]string{first: "old first", second: "old second"} + writes := []renameClosedWrite{ + {path: first, before: []byte("old first"), after: []byte("new first")}, + {path: second, before: []byte("old second"), after: []byte("new second")}, + } + if err := writeWorkspaceEdit(ctx, writes, func(path string, next, expected []byte) error { + if contents[path] != string(expected) { + t.Fatalf("write to %s expected %q, got %q", path, expected, contents[path]) + } + contents[path] = string(next) + cancel() + return nil + }); err == nil { + t.Fatal("workspace edit completed despite cancellation") + } + if contents[first] != "old first" || contents[second] != "old second" { + t.Fatalf("cancellation left edits behind: %v", contents) + } +} + +func TestLSPCodeActionsMatchEarlyResultsByOperationID(t *testing.T) { + f := newSemanticFixture(t) + a := f.h.app + pending := a.newSemanticPending(pluginSemanticCodeActions, f.p, f.d, f.server, 0, 0, false, false) + a.semantics.pending = append(a.semantics.pending, pending) + f.deliver(t, "replaced", pluginMethodCodeActions, json.RawMessage(`{"actions":[{"title":"Old edits","group":"quickfix"}]}`)) + if a.semantics.codeActions.open || !a.hasPending(pending) { + t.Fatal("a late result was consumed by the new operation before acknowledgement") + } + f.deliver(t, "current", pluginMethodCodeActions, json.RawMessage(`{"actions":[{"title":"Current edits","group":"quickfix"}]}`)) + a.semanticRequestStarted(pending, "current", nil, nil) + if state := a.semantics.codeActions; !state.open || len(state.actions) != 1 || state.actions[0].Title != "Current edits" { + t.Fatalf("wrong code action opened: %+v", state) + } +} diff --git a/desktop/internal/workbench/lsp_actions_visual_test.go b/desktop/internal/workbench/lsp_actions_visual_test.go new file mode 100644 index 0000000000..59f57cbd5f --- /dev/null +++ b/desktop/internal/workbench/lsp_actions_visual_test.go @@ -0,0 +1,243 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginlsp" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" +) + +func TestVisualLSPActions(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"en", "zh-Hans"} { + t.Run(theme+"-"+language, func(t *testing.T) { + visualLSPActions(t, out, theme, language) + }) + } + } +} + +func visualLSPActions(t *testing.T, out, theme, language string) { + t.Helper() + const source = `package main + +import "fmt" + +func greet(name string, count int) string { + return fmt.Sprintf("%s (%d)", name, count) +} + +func main() { + message := greet("Lithe", 3) + fmt.Println(message) +} +` + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + root := filepath.Join(t.TempDir(), "Greeting") + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatal(err) + } + path := filepath.Join(root, "main.go") + if err := os.WriteFile(path, []byte(source), 0o600); err != nil { + t.Fatal(err) + } + var session *headless.Session + kernel := &semanticTestKernel{testKernel: &testKernel{Client: core.NewClient()}} + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1440, 900 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.settleChain() + d := p.docs.byPath(path) + if d == nil { + t.Fatal("expected the synthetic editor document to open") + } + h.app.focusDocument(d.id) + nameAt := strings.Index(source, `"Lithe", 3`) + countAt := nameAt + len(`"Lithe", `) + d.view.SetSelection(countAt, countAt) + line, column := d.view.CaretUTF16() + picture := func(scene string, labels ...string) { + t.Helper() + for _, label := range labels { + if !h.shows(label) { + t.Fatalf("%s did not paint %q", scene, label) + } + } + if err := session.Screenshot(filepath.Join(out, scene+"-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + } + paint := func() { + h.app.invalidator.Invalidate() + h.settleChain() + } + + paint() + picture("editor-before", "main.go") + + // Register a ready synthetic session without a server process. These + // captures use canned Core results; protocol behavior is tested separately. + service, err := pluginservice.Open(kernel, prefs, t.TempDir()) + if err != nil { + t.Fatal(err) + } + h.app.plugins = service + const pluginID = "dev.lithe.test.visual-lsp" + tracker := pluginlsp.New(&closeRecordKernel{}, "visual-lsp") + uri := "file://" + filepath.ToSlash(path) + if _, err := tracker.Open(t.Context(), pluginlsp.Document{URI: uri, LanguageID: "visual-lsp", Text: source}); err != nil { + t.Fatal(err) + } + h.app.pluginServerMu.Lock() + h.app.pluginServers = map[string]*pluginServer{pluginID: { + session: &pluginservice.LanguageSession{ + PluginID: pluginID, Session: pluginbackend.Session{ID: "visual-lsp"}, Documents: tracker, + }, + project: p, buildReady: true, cancel: func() {}, + features: map[string]bool{featureCodeActions: true, featureInlayHints: true}, + }} + h.app.pluginServerLanguages = map[string]string{"visual-lsp": pluginID} + h.app.pluginServerMu.Unlock() + d.languageID = "visual-lsp" + d.sync.opened, d.sync.pluginID, d.sync.uri = true, pluginID, uri + d.inlay.initialized = true + d.inlay.revision = d.view.Revision() + d.inlay.coveredEnd = d.view.TextSnapshot().LineCount() - 1 + h.app.semantics.project = p + + h.app.storeRawPluginDiagnostics(pluginID, path, []core.PluginDiagnostic{{ + Message: "Choose an intention for this call", + Range: core.PluginDiagnosticRange{ + Start: core.PluginDiagnosticPosition{Line: line, UTF16Column: column}, + End: core.PluginDiagnosticPosition{Line: line, UTF16Column: column + 1}, + }, + }}) + h.app.semantics.codeActions = codeActionsState{ + open: true, documentID: d.id, revision: d.view.Revision(), + actions: []core.PluginSemanticCodeAction{ + {Title: "Extract greeting count to a constant", Group: "quickfix", IsPreferred: true}, + {Title: "Inline the message variable", Group: "refactor"}, + {Title: "Extract a greeting helper", Group: "refactor"}, + {Title: "Move greeting to a separate file", Group: "refactor"}, + {Title: "Convert to a named return value", Group: "refactor"}, + {Title: "Organize imports", Group: "source"}, + {Title: "Add a documentation comment", Group: "source"}, + {Title: "Add a test for the greeting", Group: "source"}, + {Title: "Update related call sites", Group: "other"}, + {Title: "Sort declarations", Group: "source"}, + {Title: "Inline greeting formatting", Group: "refactor"}, + {Title: "Replace string formatting with a helper", Group: "refactor"}, + }, + } + paint() + caret, ok := d.view.CaretRect() + if !ok { + t.Fatal("missing caret geometry for code actions") + } + actionLabel := h.shared("desktop.semantics.codeActions") + foundGutterAction := false + for _, hit := range h.driver.Snapshot().Hits { + if hit.Role != gfx.RoleButton || hit.Label != actionLabel { + continue + } + center := hit.Bounds.Y + hit.Bounds.Height/2 + if center < caret.Y || center >= caret.Y+caret.Height || hit.Bounds.X >= caret.X { + t.Fatalf("code action button is outside the caret row's gutter: button %+v, caret %+v", hit.Bounds, caret) + } + foundGutterAction = true + } + if !foundGutterAction { + t.Fatal("missing code action button in the editor gutter") + } + picture("code-actions", "Extract greeting count to a constant", h.shared("desktop.semantics.codeActionPreferred")) + + h.app.semantics.codeActions = codeActionsState{} + const signature = "greet(name string, count int) string" + const parameter = "count int" + start := strings.Index(signature, parameter) + end := start + len(parameter) + active := 0 + paramDoc := "How many greetings to format." + sigDoc := "Formats a greeting and its repetition count." + h.app.semantics.signatureHelp = signatureHelpState{ + open: true, documentID: d.id, revision: d.view.Revision(), line: line, column: column, + help: &core.PluginSemanticSignatureHelp{ + ActiveParameter: &active, + Signatures: []core.PluginSemanticSignatureInfo{ + {Label: signature, Documentation: &sigDoc, Parameters: []core.PluginSemanticParameterInfo{ + {Label: parameter, ByteStart: &start, ByteEnd: &end, Documentation: ¶mDoc}, + }}, + {Label: "greet(name string) string"}, + }, + }, + } + paint() + picture("signature-help", parameter, paramDoc) + + h.app.semantics.signatureHelp = signatureHelpState{} + h.app.editorPreferences.InlayHints = true + _, nameColumn := d.view.PositionOf(nameAt) + const nameHint = "name:" + const countHint = "count:" + tip := "The name to include in the greeting." + position := core.PluginDocumentPosition{Line: line, UTF16Column: nameColumn} + d.inlay.hints = []core.PluginSemanticInlayHint{ + {Position: position, Label: nameHint, Tooltip: &tip, PaddingRight: true, TextEdits: []core.PluginTextEdit{ + {Range: core.PluginDocumentRange{Start: position, End: position}, NewText: "/* name */ "}, + }}, + {Position: core.PluginDocumentPosition{Line: line, UTF16Column: column}, Label: countHint, PaddingRight: true}, + } + prepared, err := editorview.PrepareInlayHints(t.Context(), d.view.TextSnapshot(), d.view.Revision(), []editorview.InlayHintSpec{ + {ID: 0, Line: line, UTF16Column: nameColumn, Label: nameHint, PaddingRight: true, Interactive: true}, + {ID: 1, Line: line, UTF16Column: column, Label: countHint, PaddingRight: true}, + }) + if err != nil { + t.Fatal(err) + } + if !d.view.SetPreparedInlayHints(prepared) { + t.Fatal("the visual editor did not accept its hints") + } + paint() + for _, label := range session.Snapshot().Texts { + if label.Value != nameHint { + continue + } + x, y := label.Bounds.X+1, label.Bounds.Y+1 + if err := h.driver.Move(x, y); err != nil { + t.Fatal(err) + } + break + } + picture("inlay-hints", nameHint, countHint, tip, h.shared("desktop.semantics.inlayHintApply")) +} diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index aed7dd857f..b205ff769c 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -81,7 +81,10 @@ type pluginServer struct { // completionTriggers are the characters the server declared to open completion, from // Core's featuresChanged event. Only the window thread reads or writes them; nil // means the server declared none. - completionTriggers []string + completionTriggers []string + signatureHelpTriggers []string + signatureHelpRetriggers []string + workspaceEdits map[string]context.CancelFunc // features are the features the server offers, from Core's featuresChanged event // (documentSymbols, semanticTokens and so on). Only the window thread reads or writes it. features map[string]bool @@ -382,6 +385,12 @@ func (a *App) servePluginServer(server *pluginServer, ctx context.Context) { a.post(func(a *App) { a.applyServerFeatures(server, event) }) case pluginSemanticTokensRefresh: a.post(func(a *App) { a.semanticTokensRefresh(server) }) + case pluginInlayHintsRefresh: + a.post(func(a *App) { a.inlayHintsRefresh(server) }) + case pluginWorkspaceApplyEdit: + a.post(func(a *App) { a.applyServerWorkspaceEdit(server, event) }) + case pluginWorkspaceApplyEditCancelled: + a.post(func(a *App) { a.cancelServerWorkspaceEdit(server, event) }) case pluginSemanticCompleted: // The answer is handed to the window thread with the session it // belongs to, so a retired server cannot reopen a popup. diff --git a/desktop/internal/workbench/plugindiagnostics.go b/desktop/internal/workbench/plugindiagnostics.go index ba868fca1d..e4d808e48e 100644 --- a/desktop/internal/workbench/plugindiagnostics.go +++ b/desktop/internal/workbench/plugindiagnostics.go @@ -72,6 +72,7 @@ func (a *App) applyPluginDiagnostics(pluginID string, event core.PluginDiagnosti a.backgroundFailed("plugin_diagnostics", err) return } + a.storeRawPluginDiagnostics(pluginID, fileKey, event.Diagnostics) a.refreshDocumentMarkers(fileKey) a.markProblemsChanged() } @@ -137,6 +138,7 @@ func markerSeverity(severity plugindiag.Severity) editorview.MarkerSeverity { // clearPluginDiagnostics withdraws everything one plugin's server published. // Other plugins' diagnostics for the same files stay. func (a *App) clearPluginDiagnostics(pluginID string) { + a.clearRawPluginDiagnostics(pluginID) if a.pluginDiagnostics == nil { return } @@ -154,6 +156,7 @@ func (a *App) clearPluginDiagnostics(pluginID string) { // clearPluginFileDiagnostics withdraws one plugin's diagnostics for one file, // which is what closing the document in its session means for the Problems list. func (a *App) clearPluginFileDiagnostics(pluginID, fileKey string) { + a.clearRawPluginFileDiagnostics(pluginID, fileKey) if a.pluginDiagnostics == nil || fileKey == "" { return } @@ -169,6 +172,7 @@ func (a *App) clearPluginFileDiagnostics(pluginID, fileKey string) { // clearAllPluginDiagnostics drops every server's diagnostics, for a project // switch or close. func (a *App) clearAllPluginDiagnostics() { + a.clearAllRawPluginDiagnostics() if a.pluginDiagnostics == nil { return } diff --git a/desktop/internal/workbench/pluginrename.go b/desktop/internal/workbench/pluginrename.go index 0d533a6b66..6189957aa8 100644 --- a/desktop/internal/workbench/pluginrename.go +++ b/desktop/internal/workbench/pluginrename.go @@ -44,10 +44,12 @@ type renameState struct { // renameOpenDocument is one open editor document captured on the window thread // for a workspace edit. type renameOpenDocument struct { - id int - revision int - text rope.Rope - caret int + id int + revision int + text rope.Rope + caret int + isReadOnly bool + isComposing bool } // renameClosedWrite is one closed file's before and after bytes. @@ -199,7 +201,7 @@ func (a *App) applyWorkspaceChanges(p *project, changes map[string][]core.Plugin for _, d := range p.docs.list { line, column := d.view.CaretUTF16() caret, _ := d.view.ByteOffset(line, column) - open[d.path] = renameOpenDocument{id: d.id, revision: d.view.Revision(), text: d.view.TextSnapshot(), caret: caret} + open[d.path] = renameOpenDocument{id: d.id, revision: d.view.Revision(), text: d.view.TextSnapshot(), caret: caret, isReadOnly: d.view.ReadOnly(), isComposing: d.caretView().IsComposing()} } write := a.documentWriter root := p.root @@ -240,6 +242,17 @@ func (a *App) applyWorkspaceChanges(p *project, changes map[string][]core.Plugin // order. A failed write restores the files already written in reverse order and // returns the failure, leaving open documents untouched. func (a *App) commitWorkspaceEdit(ctx context.Context, root string, changes map[string][]core.PluginTextEdit, openByPath map[string]renameOpenDocument, write func(string, []byte, []byte) error) (int, []renameDocumentUpdate, error) { + writes, updates, err := a.prepareWorkspaceEdit(ctx, root, changes, openByPath) + if err != nil { + return 0, nil, err + } + if err := writeWorkspaceEdit(ctx, writes, write); err != nil { + return 0, nil, err + } + return len(writes), updates, nil +} + +func (a *App) prepareWorkspaceEdit(ctx context.Context, root string, changes map[string][]core.PluginTextEdit, openByPath map[string]renameOpenDocument) ([]renameClosedWrite, []renameDocumentUpdate, error) { // A language server may name a file by its real path or by the path it was // given, so the workspace root, the open documents and the targets are all // compared by real path; otherwise a project opened through a symbolic link @@ -265,10 +278,10 @@ func (a *App) commitWorkspaceEdit(ctx context.Context, root string, changes map[ } plan, err := a.kernel.PlanPluginWorkspaceEdit(ctx, root, resolved, list) if err != nil { - return 0, nil, err + return nil, nil, err } if plan.Rejection != nil { - return 0, nil, fmt.Errorf("%w: %s", errRenameRejected, plan.Rejection.Code) + return nil, nil, fmt.Errorf("%w: %s", errRenameRejected, plan.Rejection.Code) } var writes []renameClosedWrite var updates []renameDocumentUpdate @@ -277,40 +290,58 @@ func (a *App) commitWorkspaceEdit(ctx context.Context, root string, changes map[ case "writeFile": data, err := readDocument(target.Path) if err != nil { - return 0, nil, err + return nil, nil, err } text, err := a.kernel.ApplyPluginTextEdits(ctx, string(data), target.Edits) if err != nil { - return 0, nil, err + return nil, nil, err } writes = append(writes, renameClosedWrite{path: target.Path, before: data, after: []byte(text)}) case "updateDocument": snapshot, ok := open[target.Path] if !ok { - return 0, nil, errors.New("workspace edit names an open document the editor does not hold") + return nil, nil, errors.New("workspace edit names an open document the editor does not hold") + } + if snapshot.isReadOnly || snapshot.isComposing { + return nil, nil, errRenameRejected } text, err := a.kernel.ApplyPluginTextEdits(ctx, snapshot.text.String(), target.Edits) if err != nil { - return 0, nil, err + return nil, nil, err } updates = append(updates, renameDocumentUpdate{ id: snapshot.id, revision: snapshot.revision, change: preparedTextChange(snapshot.text, text, snapshot.caret), }) default: - return 0, nil, errors.New("workspace edit plan has an unknown effect") + return nil, nil, errors.New("workspace edit plan has an unknown effect") } } + return writes, updates, nil +} + +func writeWorkspaceEdit(ctx context.Context, writes []renameClosedWrite, write func(string, []byte, []byte) error) error { for i, w := range writes { + if err := ctx.Err(); err != nil { + return errors.Join(err, restoreWorkspaceEdit(writes[:i], write)) + } if err := write(w.path, w.after, w.before); err != nil { - failure := err - for j := i - 1; j >= 0; j-- { - if restoreErr := write(writes[j].path, writes[j].before, writes[j].after); restoreErr != nil { - failure = errors.Join(failure, restoreErr) - } - } - return 0, nil, failure + return errors.Join(err, restoreWorkspaceEdit(writes[:i], write)) } } - return len(writes), updates, nil + if err := ctx.Err(); err != nil { + return errors.Join(err, restoreWorkspaceEdit(writes, write)) + } + return nil +} + +func restoreWorkspaceEdit(writes []renameClosedWrite, write func(string, []byte, []byte) error) error { + var failure error + for i := len(writes) - 1; i >= 0; i-- { + w := writes[i] + if err := write(w.path, w.before, w.after); err != nil { + failure = errors.Join(failure, err) + } + } + return failure } diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index 6ca2d7f1ad..97b62378ba 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -7,6 +7,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strconv" "strings" "time" @@ -98,6 +99,18 @@ type semanticKind string func (k semanticKind) method() string { switch k { + case pluginSemanticCodeActions: + return pluginMethodCodeActions + case pluginSemanticResolveCodeAction: + return pluginMethodResolveCodeAction + case pluginSemanticExecuteCommand: + return pluginMethodExecuteCommand + case pluginSemanticSignatureHelp: + return pluginMethodSignatureHelp + case pluginSemanticInlayHints: + return pluginMethodInlayHints + case pluginSemanticResolveInlayHint: + return pluginMethodResolveInlayHint case pluginSemanticDefinition: return pluginMethodDefinition case pluginSemanticHover: @@ -156,6 +169,13 @@ type semanticPending struct { usages bool } +type earlySemanticResult struct { + server *pluginServer + event core.BackendEvent +} + +const maxEarlySemanticResults = 32 + // completionState is the explicit completion popup. type completionState struct { open bool @@ -197,6 +217,7 @@ type hoverState struct { // the symbol and the popup. fromPointer bool page *hoverPage + quickFix *core.PluginDocumentRange } // hoverCandidate is the symbol under the resting pointer. It stays after its hover was asked for, @@ -219,17 +240,28 @@ type pluginSemantics struct { documentID int generation uint64 pending []*semanticPending + // A result may reach the window before the submission acknowledgement. + // IDs keep those answers apart from requests for the same document and method. + early []earlySemanticResult // deferred starts the user's request once the document's pending changes // have reached Core, so a definition never asks about stale text. deferred func(*App) completion completionState // merge is the explicit completion whose language-server and provider answers are pending. - merge *completionMergeJoin - definition definitionState - hover hoverState - rename renameState - candidate hoverCandidate - hoverDelay time.Duration + merge *completionMergeJoin + definition definitionState + hover hoverState + codeActions codeActionsState + signatureHelp signatureHelpState + sigCancel context.CancelFunc + sigDelay time.Duration + sigGeneration uint64 + sigDeferred func(*App) + inlayHover inlayHintHoverState + inlayDelay time.Duration + rename renameState + candidate hoverCandidate + hoverDelay time.Duration // hoverHideDelay overrides semanticHoverHideDelay; hideCancel ends the pending close of a // pointer hover and hideToken names the newest one, so an older wait that fired is ignored. hoverHideDelay time.Duration @@ -276,12 +308,22 @@ func (a *App) pluginSemanticsKey(event gfx.KeyEvent) gfx.EventResult { if event.Release { return gfx.EventResult{} } + if a.semantics.codeActions.open { + return a.codeActionsKey(event) + } if a.semantics.completion.open { return a.completionKey(event) } if a.semantics.definition.open { return a.definitionKey(event) } + if result := a.signatureHelpKey(event); result.Handled { + return result + } + if a.semantics.inlayHover.open && event.Key == gfx.KeyEscape { + a.semantics.inlayHover = inlayHintHoverState{} + return gfx.EventResult{Handled: true, Repaint: true} + } if a.semantics.hover.open && event.Key == gfx.KeyEscape { a.leaveSemanticHover() return gfx.EventResult{Handled: true, Repaint: true} @@ -407,6 +449,12 @@ func (a *App) pluginSemanticsTrigger(event gfx.KeyEvent, p *project, d *document // trigger. A platform may deliver it as a shortcut text without the key code, // so the space text is accepted as well as KeySpace. func (a *App) pluginSemanticsShortcut(event gfx.KeyEvent) gfx.EventResult { + if result := a.codeActionsShortcut(event); result.Handled { + return result + } + if result := a.signatureHelpShortcut(event); result.Handled { + return result + } if result := a.pluginEditShortcut(event); result.Handled { return result } @@ -449,7 +497,7 @@ func (a *App) declarationShortcut(event gfx.KeyEvent) gfx.EventResult { func (a *App) pluginSemanticsPointer(event gfx.PointerEvent, p *project, d *document, view *editorview.View) (gfx.EventResult, bool) { switch event.Kind { case gfx.PointerDown: - if a.semantics.completion.open || a.semantics.definition.open || a.semantics.hover.open { + if a.semantics.codeActions.open || a.semantics.completion.open || a.semantics.definition.open || a.semantics.hover.open { a.closePluginSemantics() } if d == nil || event.Button != gfx.PointerButtonPrimary { @@ -469,7 +517,7 @@ func (a *App) pluginSemanticsPointer(event gfx.PointerEvent, p *project, d *docu a.startPluginDefinition(p, d, line, column, false) return gfx.EventResult{Handled: true, Repaint: true}, true case gfx.PointerMove: - if a.semantics.completion.open || a.semantics.definition.open { + if a.semantics.codeActions.open || a.semantics.completion.open || a.semantics.definition.open { return gfx.EventResult{}, false } if d == nil { @@ -592,6 +640,17 @@ func (a *App) startPluginHover(p *project, d *document, line, column int, anchor } a.closeSemanticCompletion() a.closeSemanticDefinition() + if diag, ok := a.diagnosticAt(d, line, column); ok && !d.view.ReadOnly() { + span := core.PluginDocumentRange{ + Start: core.PluginDocumentPosition{Line: diag.Range.Start.Line, UTF16Column: diag.Range.Start.UTF16Column}, + End: core.PluginDocumentPosition{Line: diag.Range.End.Line, UTF16Column: diag.Range.End.UTF16Column}, + } + a.cancelSemanticKind(pluginSemanticHover) + a.semantics.project, a.semantics.documentID = p, d.id + a.showSemanticHover(p, d, diag.Message, false, line, column, &span, anchor, fromPointer) + a.semantics.hover.quickFix = &span + return + } if !a.semanticDocumentReady(d) { a.deferSemantic(p, d, func(a *App) { a.startPluginHover(p, d, line, column, anchor, fromPointer, requireCaret) @@ -755,6 +814,12 @@ func (a *App) applyServerFeatures(server *pluginServer, event core.BackendEvent) if event.CompletionOptions != nil { server.completionTriggers = event.CompletionOptions.TriggerCharacters } + server.signatureHelpTriggers = nil + server.signatureHelpRetriggers = nil + if options := event.SignatureHelpOptions; options != nil { + server.signatureHelpTriggers = options.TriggerCharacters + server.signatureHelpRetriggers = options.RetriggerCharacters + } // The features arrive after the documents opened: ask for the colors now. a.semanticTokensResume() } @@ -865,10 +930,10 @@ func (a *App) submitSemantic(pending *semanticPending, request core.PluginSemant }) } -// semanticRequestStarted records Core's operation ID. An answer may have -// arrived before this hand-off; that answer settled the pending request and the -// late ID is cancelled instead of leaving a pending server operation. +// semanticRequestStarted binds Core's operation ID to the submitted request. +// If an answer arrived first, only this ID's result can settle the request. func (a *App) semanticRequestStarted(pending *semanticPending, operation string, err, ctxErr error) { + result, received := a.takeEarlySemanticResult(pending.server, operation) if !a.hasPending(pending) { if operation != "" { a.cancelSemanticOperation(pending, operation) @@ -889,10 +954,19 @@ func (a *App) semanticRequestStarted(pending *semanticPending, operation string, // tell the user, the others go without. if pending.kind.toldToUser() { a.operationFailed("plugin_semantics", err) - a.semanticOperationFailed(pending.kind) + if !a.applyEditorEvent(pending, core.BackendEvent{}, true) { + a.semanticOperationFailed(pending.kind) + } } else { a.backgroundFailed("plugin_semantics", err) + if pending.kind == pluginSemanticInlayHints || pending.kind == pluginSemanticResolveInlayHint { + a.applyEditorEvent(pending, core.BackendEvent{}, true) + } } + return + } + if received { + a.applyPluginSemanticEvent(pending.server, result) } } @@ -903,8 +977,7 @@ func (a *App) applyPluginSemanticEvent(server *pluginServer, event core.BackendE } pending := a.matchPending(server, event) if pending == nil { - // A late answer from a cancelled or replaced request. Core already - // dropped operations it timed out; nothing may reopen a popup. + a.queueEarlySemanticResult(server, event) return } a.removePending(pending) @@ -938,22 +1011,43 @@ func (a *App) applyPluginSemanticEvent(server *pluginServer, event core.BackendE } func (a *App) matchPending(server *pluginServer, event core.BackendEvent) *semanticPending { - if event.OperationID != "" { - for _, pending := range a.semantics.pending { - if pending.server == server && pending.operation == event.OperationID { - return pending - } - } - } for _, pending := range a.semantics.pending { - if pending.server == server && pending.kind.method() == event.Method && - (pending.operation == "" || pending.operation == event.OperationID) { + if pending.server == server && pending.operation != "" && pending.operation == event.OperationID { return pending } } return nil } +func (a *App) queueEarlySemanticResult(server *pluginServer, event core.BackendEvent) { + if event.OperationID == "" { + return + } + for _, pending := range a.semantics.pending { + if pending.server != server || pending.operation != "" || pending.kind.method() != event.Method || + (event.URI != "" && event.URI != pending.uri) { + continue + } + early := &a.semantics.early + if len(*early) == maxEarlySemanticResults { + *early = slices.Delete(*early, 0, 1) + } + *early = append(*early, earlySemanticResult{server: server, event: event}) + return + } +} + +func (a *App) takeEarlySemanticResult(server *pluginServer, operation string) (core.BackendEvent, bool) { + early := &a.semantics.early + for i, result := range *early { + if result.server == server && result.event.OperationID == operation { + *early = slices.Delete(*early, i, i+1) + return result.event, true + } + } + return core.BackendEvent{}, false +} + func (a *App) applySemanticDefinition(pending *semanticPending, event core.BackendEvent) { p, d := a.currentSemanticDocument(pending.documentID) if p != pending.project || d == nil || d.view.Revision() != pending.revision || !a.semanticPositionCurrent(pending, d) { @@ -1458,8 +1552,7 @@ func (a *App) resumeDeferredSemantics() { // The outline waits for the synchronization too, and asks again on the next frame. a.invalidator.Invalidate() a.semanticTokensResume() - run := a.semantics.deferred - if run == nil { + if a.semantics.deferred == nil && a.semantics.sigDeferred == nil { return } p, d := a.currentSemanticDocument(a.semantics.documentID) @@ -1470,8 +1563,14 @@ func (a *App) resumeDeferredSemantics() { if !ok || !server.isReady() { return } - a.semantics.deferred = nil - run(a) + run, sigRun := a.semantics.deferred, a.semantics.sigDeferred + a.semantics.deferred, a.semantics.sigDeferred = nil, nil + if run != nil { + run(a) + } + if sigRun != nil { + sigRun(a) + } } func (a *App) pointPluginHover(p *project, d *document, line, column int, anchor gfx.Rect) { @@ -1524,6 +1623,14 @@ func (a *App) pluginSemanticsCaretSync() { if state.project == nil || a.project != state.project { return } + a.syncSignatureHelpCaret() + if state.codeActions.open { + p, d := a.currentSemanticDocument(state.codeActions.documentID) + if d == nil || p != a.project || d.view.Revision() != state.codeActions.revision || d.caretView().IsComposing() { + a.closeSemanticCodeActions() + a.cancelSemanticKind(pluginSemanticResolveCodeAction) + } + } if state.completion.open { p, d := a.currentSemanticDocument(state.completion.documentID) if d == nil || p != a.project { @@ -1559,6 +1666,9 @@ func (a *App) pluginSemanticsCaretSync() { // pluginSemanticsScrolled closes popups whose screen position the scroll moved. A hover still // waiting would open at the place its character scrolled away from. func (a *App) pluginSemanticsScrolled(_ *document) { + a.semantics.inlayHover = inlayHintHoverState{} + a.closeSemanticCodeActions() + a.cancelSemanticKind(pluginSemanticResolveCodeAction) a.leaveSemanticHover() a.closeSemanticCompletion() a.closeSemanticDefinition() @@ -1569,11 +1679,13 @@ func (a *App) pluginSemanticsScrolled(_ *document) { func (a *App) pluginSemanticsEdited(d *document) { if p := a.project; p != nil && d != nil { a.semanticTokensEdited(p, d) + a.clearDocumentInlayHints(d) } if d == nil || a.semantics.documentID != d.id { return } - a.closePluginSemantics() + // Keep the previous signature answer while the typing hook refreshes it. + a.closePositionSemantics() } // pluginSemanticsDocumentClosed drops state that belonged to a closed tab. @@ -1593,6 +1705,7 @@ func (a *App) pluginSemanticsReset() { a.closePluginSemantics() a.cancelSemanticKind(pluginSemanticRename) a.semantics.rename = renameState{} + a.semantics.early = nil a.semantics.deferred = nil a.semantics.project = nil a.semantics.documentID = 0 @@ -1602,6 +1715,16 @@ func (a *App) pluginSemanticsReset() { } func (a *App) closePluginSemantics() { + a.closeSemanticSignatureHelp() + a.cancelSemanticKind(pluginSemanticExecuteCommand) + a.closePositionSemantics() +} + +func (a *App) closePositionSemantics() { + a.closeSemanticCodeActions() + a.semantics.inlayHover = inlayHintHoverState{} + a.cancelSemanticKind(pluginSemanticCodeActions) + a.cancelSemanticKind(pluginSemanticResolveCodeAction) a.cancelContentOpen() a.closeSemanticCompletion() a.closeSemanticDefinition() @@ -1723,7 +1846,8 @@ func (a *App) logSemanticError(kind semanticKind, raw json.RawMessage) { // hover, completion or location, and the failure is a background one. func (k semanticKind) toldToUser() bool { switch k { - case pluginSemanticFormatting, pluginSemanticRangeFormatting, pluginSemanticRename: + case pluginSemanticFormatting, pluginSemanticRangeFormatting, pluginSemanticRename, + pluginSemanticCodeActions, pluginSemanticResolveCodeAction, pluginSemanticExecuteCommand: return true } return false diff --git a/desktop/internal/workbench/pluginsemantics_codeactions.go b/desktop/internal/workbench/pluginsemantics_codeactions.go new file mode 100644 index 0000000000..dcd7def74b --- /dev/null +++ b/desktop/internal/workbench/pluginsemantics_codeactions.go @@ -0,0 +1,822 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync/atomic" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +const ( + pluginSemanticCodeActions semanticKind = "codeActions" + pluginSemanticResolveCodeAction semanticKind = "resolveCodeAction" + pluginSemanticExecuteCommand semanticKind = "executeCommand" + + pluginMethodCodeActions = "textDocument/codeAction" + pluginMethodResolveCodeAction = "codeAction/resolve" + pluginMethodExecuteCommand = "workspace/executeCommand" + + pluginWorkspaceApplyEdit = "workspaceApplyEdit" + pluginWorkspaceApplyEditCancelled = "workspaceApplyEditCancelled" + + featureCodeActions = "codeActions" + featureCodeActionResolve = "codeActionResolve" + + codeActionPopupWidth = float32(420) + codeActionRowHeight = float32(28) +) + +type workspaceApplyEditKernel interface { + RespondWorkspaceApplyEdit(ctx context.Context, session, applyEditID string, applied bool, failureReason string) error +} + +// codeActionsState holds the open Code Actions popup and its virtualized list state. +type codeActionsState struct { + open bool + resolving bool + actions []core.PluginSemanticCodeAction + selected int + list ui.ListState + documentID int + revision int + anchor gfx.Rect +} + +// storeRawPluginDiagnostics retains Core's normalized LSP diagnostics per plugin and file +// so codeAction requests forward nullable severity, tags and relatedInformation intact. +func (a *App) storeRawPluginDiagnostics(pluginID, fileKey string, diagnostics []core.PluginDiagnostic) { + if pluginID == "" || fileKey == "" { + return + } + if len(diagnostics) == 0 { + if byFile := a.rawPluginDiagnostics[pluginID]; byFile != nil { + delete(byFile, fileKey) + if len(byFile) == 0 { + delete(a.rawPluginDiagnostics, pluginID) + } + } + return + } + if a.rawPluginDiagnostics == nil { + a.rawPluginDiagnostics = make(map[string]map[string][]core.PluginDiagnostic) + } + byFile := a.rawPluginDiagnostics[pluginID] + if byFile == nil { + byFile = make(map[string][]core.PluginDiagnostic) + a.rawPluginDiagnostics[pluginID] = byFile + } + copied := make([]core.PluginDiagnostic, len(diagnostics)) + copy(copied, diagnostics) + byFile[fileKey] = copied +} + +func (a *App) clearRawPluginDiagnostics(pluginID string) { + if a.rawPluginDiagnostics != nil { + delete(a.rawPluginDiagnostics, pluginID) + if len(a.rawPluginDiagnostics) == 0 { + a.rawPluginDiagnostics = nil + } + } +} + +func (a *App) clearRawPluginFileDiagnostics(pluginID, fileKey string) { + if byFile := a.rawPluginDiagnostics[pluginID]; byFile != nil { + delete(byFile, fileKey) + if len(byFile) == 0 { + delete(a.rawPluginDiagnostics, pluginID) + } + } +} + +func (a *App) clearAllRawPluginDiagnostics() { + a.rawPluginDiagnostics = nil +} + +// diagnosticsOverlapping forwards only diagnostics from the server +// receiving the request, keeping the server's original publication order. +func (a *App) diagnosticsOverlapping(owner, path string, target core.PluginDocumentRange) []core.PluginDiagnostic { + var out []core.PluginDiagnostic + for _, diag := range a.rawPluginDiagnostics[owner][path] { + if diagnosticOverlapsRange(diag.Range, target) { + out = append(out, diag) + } + } + return out +} + +func (a *App) diagnosticsOnLine(owner, path string, line int) []core.PluginDiagnostic { + var out []core.PluginDiagnostic + for _, diag := range a.rawPluginDiagnostics[owner][path] { + if diag.Range.Start.Line <= line && line <= diag.Range.End.Line { + out = append(out, diag) + } + } + return out +} + +func diagnosticOverlapsRange(d core.PluginDiagnosticRange, r core.PluginDocumentRange) bool { + if comparePos(d.End.Line, d.End.UTF16Column, r.Start.Line, r.Start.UTF16Column) < 0 { + return false + } + if comparePos(r.End.Line, r.End.UTF16Column, d.Start.Line, d.Start.UTF16Column) < 0 { + return false + } + return true +} + +func comparePos(lineA, colA, lineB, colB int) int { + if lineA != lineB { + if lineA < lineB { + return -1 + } + return 1 + } + if colA < colB { + return -1 + } + if colA > colB { + return 1 + } + return 0 +} + +func (a *App) diagnosticAt(d *document, line, column int) (core.PluginDiagnostic, bool) { + server, offered := a.editorServer(d, featureCodeActions) + if !offered { + return core.PluginDiagnostic{}, false + } + pos := core.PluginDocumentPosition{Line: line, UTF16Column: column} + target := core.PluginDocumentRange{Start: pos, End: pos} + for _, diag := range a.rawPluginDiagnostics[server.session.PluginID][d.path] { + if diag.Message != "" && diagnosticOverlapsRange(diag.Range, target) { + return diag, true + } + } + return core.PluginDiagnostic{}, false +} + +// codeActionsShortcut handles Option+Enter on macOS and Alt+Enter on Windows/Linux. +func (a *App) codeActionsShortcut(event gfx.KeyEvent) gfx.EventResult { + if event.Release || event.Modifiers != gfx.ModifierAlt { + return gfx.EventResult{} + } + if event.Key != gfx.KeyEnter && event.Text != "\r" && event.Text != "\n" { + return gfx.EventResult{} + } + p, d := a.pluginSemanticHit(event.Target) + if d == nil || d.caretView().IsComposing() || d.view.ReadOnly() { + return gfx.EventResult{} + } + if _, offered := a.editorServer(d, featureCodeActions); !offered { + return gfx.EventResult{} + } + a.startPluginCodeActions(p, d, nil, surfaceShortcut) + return gfx.EventResult{Handled: true, Repaint: true} +} + +// startPluginCodeActions requests code actions for the current selection or caret position. +func (a *App) startPluginCodeActions(p *project, d *document, only []string, surface actionSurface) { + if a.plugins == nil || p == nil || d == nil || a.project != p || d.caretView().IsComposing() || d.view.ReadOnly() { + return + } + var target core.PluginDocumentRange + if sLine, sCol, eLine, eCol, ok := d.caretView().SelectionUTF16(); ok { + target = core.PluginDocumentRange{ + Start: core.PluginDocumentPosition{Line: sLine, UTF16Column: sCol}, + End: core.PluginDocumentPosition{Line: eLine, UTF16Column: eCol}, + } + } else { + line, col := d.caretView().CaretUTF16() + pos := core.PluginDocumentPosition{Line: line, UTF16Column: col} + target = core.PluginDocumentRange{Start: pos, End: pos} + } + anchor, _ := d.caretView().CaretRect() + a.startPluginCodeActionsAtRange(p, d, target, anchor, only, surface) +} + +// startPluginCodeActionsAtRange requests code actions over an explicit UTF-16 range and anchor. +func (a *App) startPluginCodeActionsAtRange(p *project, d *document, target core.PluginDocumentRange, anchor gfx.Rect, only []string, surface actionSurface) { + if a.plugins == nil || p == nil || d == nil || a.project != p || d.caretView().IsComposing() || d.view.ReadOnly() { + return + } + a.closeSemanticHover() + a.closeSemanticCompletion() + a.closeSemanticDefinition() + a.closeSemanticCodeActions() + revision := d.view.Revision() + retry := func(a *App) { + if p.docs.find(d.id) == d && d.view.Revision() == revision { + a.startPluginCodeActionsAtRange(p, d, target, anchor, only, surface) + } + } + if !a.semanticDocumentReady(d) { + a.deferSemantic(p, d, retry) + a.startDocumentSync(p, d) + return + } + server, ok := a.semanticServer(d) + if !ok { + a.notify(i18n.Shared(a.language(), "desktop.semantics.noServer")) + return + } + if !server.isReady() { + a.deferSemantic(p, d, retry) + return + } + if !server.features[featureCodeActions] { + a.notifyInfo(i18n.Shared(a.language(), "desktop.semantics.noCodeActions")) + return + } + diags := a.diagnosticsOverlapping(server.session.PluginID, d.path, target) + if len(diags) == 0 && target.Start == target.End { + diags = a.diagnosticsOnLine(server.session.PluginID, d.path, target.Start.Line) + } + ctxPayload := map[string]any{"triggerKind": 1} + if len(only) > 0 { + ctxPayload["only"] = only + } + rawCtx, _ := json.Marshal(ctxPayload) + + a.cancelSemanticKind(pluginSemanticCodeActions) + a.cancelSemanticKind(pluginSemanticResolveCodeAction) + pending := a.newSemanticPending(pluginSemanticCodeActions, p, d, server, target.Start.Line, target.Start.UTF16Column, false, false) + pending.anchor = anchor + a.semantics.pending = append(a.semantics.pending, pending) + if surface != "" { + a.performed("editor.semantics.codeActions", surface) + } + request := core.PluginSemanticRequest{ + Operation: string(pluginSemanticCodeActions), + URI: d.sync.uri, + Range: &target, + Diagnostics: diags, + CodeActionContext: rawCtx, + } + a.background(pending.project, semanticStartTimeout, func(ctx context.Context) func(*App) { + operation, err := a.plugins.RequestLanguageSession(ctx, pending.server.session, request) + return func(a *App) { a.semanticRequestStarted(pending, operation, err, ctx.Err()) } + }) +} + +func (a *App) applySemanticCodeActions(pending *semanticPending, event core.BackendEvent) { + p, d := a.currentSemanticDocument(pending.documentID) + if p != pending.project || d == nil || d.view.Revision() != pending.revision || d.caretView().IsComposing() { + return + } + actions, err := core.PluginSemanticCodeActions(event) + if err != nil { + a.operationFailed("plugin_code_actions", err) + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.operationFailed")) + return + } + if len(actions) == 0 { + a.closeSemanticCodeActions() + a.notifyInfo(i18n.Shared(a.language(), "desktop.semantics.noCodeActions")) + return + } + anchor := pending.anchor + if anchor.Height <= 0 { + anchor, _ = d.caretView().CaretRect() + } + state := &a.semantics.codeActions + *state = codeActionsState{ + open: true, + actions: actions, + selected: 0, + documentID: d.id, + revision: pending.revision, + anchor: anchor, + } + state.list.Select(0) +} + +func (a *App) closeSemanticCodeActions() { + a.semantics.codeActions = codeActionsState{} +} + +func (a *App) codeActionsKey(event gfx.KeyEvent) gfx.EventResult { + state := &a.semantics.codeActions + if state.resolving { + if event.Key == gfx.KeyEscape { + a.cancelSemanticKind(pluginSemanticResolveCodeAction) + a.closeSemanticCodeActions() + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{Handled: true} + } + switch event.Key { + case gfx.KeyEscape: + a.closeSemanticCodeActions() + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyUp: + if state.selected > 0 { + state.selected-- + state.list.Select(state.selected) + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyDown: + if state.selected+1 < len(state.actions) { + state.selected++ + state.list.Select(state.selected) + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyPageUp: + state.selected = max(state.selected-visibleSemanticRows, 0) + state.list.Select(state.selected) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyPageDown: + state.selected = min(state.selected+visibleSemanticRows, max(len(state.actions)-1, 0)) + state.list.Select(state.selected) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEnter: + if len(state.actions) > 0 { + a.choosePluginCodeAction(state.selected) + return gfx.EventResult{Handled: true, Repaint: true} + } + a.closeSemanticCodeActions() + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +func (a *App) choosePluginCodeAction(index int) { + state := &a.semantics.codeActions + if index < 0 || index >= len(state.actions) || state.resolving { + a.closeSemanticCodeActions() + return + } + p, d := a.currentSemanticDocument(state.documentID) + if d == nil || p != a.project || d.view.Revision() != state.revision || d.caretView().IsComposing() || d.view.ReadOnly() { + a.closeSemanticCodeActions() + return + } + action := state.actions[index] + revision := state.revision + server, ok := a.semanticServer(d) + if !ok || !server.isReady() { + a.closeSemanticCodeActions() + a.notify(i18n.Shared(a.language(), "desktop.semantics.noServer")) + return + } + if action.Edit == nil && action.Command == nil && len(action.Raw) > 0 && server.features[featureCodeActionResolve] { + state.resolving = true + a.cancelSemanticKind(pluginSemanticResolveCodeAction) + pending := a.newSemanticPending(pluginSemanticResolveCodeAction, p, d, server, 0, 0, false, false) + a.semantics.pending = append(a.semantics.pending, pending) + request := core.PluginSemanticRequest{ + Operation: string(pluginSemanticResolveCodeAction), + URI: d.sync.uri, + CodeAction: action.Raw, + } + a.background(p, semanticStartTimeout, func(ctx context.Context) func(*App) { + operation, err := a.plugins.RequestLanguageSession(ctx, server.session, request) + return func(a *App) { a.semanticRequestStarted(pending, operation, err, ctx.Err()) } + }) + return + } + a.closeSemanticCodeActions() + a.executeResolvedCodeAction(p, d, server, revision, action) +} + +func (a *App) applySemanticResolveCodeAction(pending *semanticPending, event core.BackendEvent) { + p, d := a.currentSemanticDocument(pending.documentID) + a.closeSemanticCodeActions() + if p != pending.project || d == nil || d.view.Revision() != pending.revision || d.caretView().IsComposing() || d.view.ReadOnly() { + return + } + resolved, err := core.PluginSemanticResolvedCodeAction(event) + if err != nil || resolved == nil { + if err != nil { + a.operationFailed("plugin_code_action_resolve", err) + } + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + return + } + a.executeResolvedCodeAction(p, d, pending.server, pending.revision, *resolved) +} + +func (a *App) executeResolvedCodeAction(p *project, d *document, server *pluginServer, revision int, action core.PluginSemanticCodeAction) { + if p != a.project || d == nil || d.view.Revision() != revision || d.caretView().IsComposing() || d.view.ReadOnly() { + return + } + a.performed("editor.codeAction.apply", surfaceButton) + runCommand := func() { + if action.Command == nil || action.Command.Command == "" { + return + } + if server == nil || !server.isReady() || !server.features[featureExecuteCommand] { + return + } + cmdBytes, err := json.Marshal(action.Command) + if err != nil { + return + } + pending := a.newSemanticPending(pluginSemanticExecuteCommand, p, d, server, 0, 0, false, false) + a.semantics.pending = append(a.semantics.pending, pending) + request := core.PluginSemanticRequest{ + Operation: string(pluginSemanticExecuteCommand), + Command: cmdBytes, + } + a.background(p, semanticStartTimeout, func(ctx context.Context) func(*App) { + operation, reqErr := a.plugins.RequestLanguageSession(ctx, server.session, request) + return func(a *App) { a.semanticRequestStarted(pending, operation, reqErr, ctx.Err()) } + }) + } + if action.Edit != nil && len(action.Edit.Changes) > 0 { + if !a.workspaceEditVersionsCurrent(p, server, action.Edit.DocumentVersions) { + a.operationRejected("plugin_code_action", "stale_document_revision") + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + return + } + a.applyLanguageWorkspaceEdit(p, server, p.ctx, action.Edit.Changes, func(err error) { + if err == nil { + runCommand() + return + } + if errors.Is(err, context.Canceled) || a.project != p { + return + } + if errors.Is(err, errRenameRejected) { + a.operationRejected("plugin_code_action", "outside_or_readonly") + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionRejected")) + } else { + a.operationFailed("plugin_code_action", err) + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + } + }) + return + } + runCommand() +} + +func (a *App) captureWorkspaceOpenDocuments(p *project) map[string]renameOpenDocument { + open := make(map[string]renameOpenDocument, len(p.docs.list)) + for _, d := range p.docs.list { + line, column := d.view.CaretUTF16() + caret, _ := d.view.ByteOffset(line, column) + open[d.path] = renameOpenDocument{ + id: d.id, revision: d.view.Revision(), + text: d.view.TextSnapshot(), caret: caret, + isReadOnly: d.view.ReadOnly(), isComposing: d.caretView().IsComposing(), + } + } + return open +} + +func (a *App) workspaceEditVersionsCurrent(p *project, server *pluginServer, versions map[string]int64) bool { + if len(versions) == 0 { + return true + } + if server.session.Documents == nil { + return false + } + for path, version := range versions { + d := p.docs.byPath(path) + if d == nil || !a.semanticDocumentReady(d) { + return false + } + owner, _ := a.documentSyncServer(d) + current, tracked := server.session.Documents.Version(d.sync.uri) + if owner != server || !tracked || current != version { + return false + } + } + return true +} + +var errStaleWorkspaceEdit = errors.New("open document changed before workspace edit could be applied") + +// applyLanguageWorkspaceEdit keeps disk I/O off the window thread. If a target +// changes before the open-document edits are installed, it restores any disk +// edits using the exact bytes written, preserving concurrent external edits. +func (a *App) applyLanguageWorkspaceEdit(p *project, server *pluginServer, parent context.Context, changes map[string][]core.PluginTextEdit, done func(error)) { + open := a.captureWorkspaceOpenDocuments(p) + write := a.documentWriter + session := server.session + // The final callback also runs if the project closes, so it can restore disk writes. + ctx, cancel := context.WithTimeout(parent, semanticApplyTimeout) + a.background(nil, 0, func(context.Context) func(*App) { + defer cancel() + writes, updates, err := a.prepareWorkspaceEdit(ctx, p.root, changes, open) + if err == nil { + err = writeWorkspaceEdit(ctx, writes, write) + } + if err != nil { + return func(*App) { done(err) } + } + + // The worker owns the disk transaction until the window claims + // the result. Closing the window may prevent a queued callback + // from ever running, so cleanup cannot rely on that callback. + var claimed atomic.Bool + settled := make(chan struct{}) + var reject error + a.post(func(a *App) { + if !claimed.CompareAndSwap(false, true) { + return + } + defer close(settled) + reject = ctx.Err() + if reject == nil && (a.project != p || !a.isCurrentPluginServer(session.PluginID, server)) { + reject = context.Canceled + } + if reject != nil { + return + } + for path := range changes { + if d := p.docs.byPath(path); d != nil && open[path].id != d.id { + reject = errStaleWorkspaceEdit + return + } + } + for _, update := range updates { + d := p.docs.find(update.id) + if d == nil || d.view.ReadOnly() || d.caretView().IsComposing() || d.view.Revision() != update.revision { + reject = errStaleWorkspaceEdit + return + } + } + for _, update := range updates { + p.docs.find(update.id).view.ApplyTextChange(update.change) + } + }) + select { + case <-settled: + case <-ctx.Done(): + if claimed.CompareAndSwap(false, true) { + reject = ctx.Err() + } else { + // The window owns the result. This callback only checks + // snapshots and applies already prepared editor changes. + <-settled + } + } + var rollbackErr error + if reject != nil { + rollbackErr = restoreWorkspaceEdit(writes, write) + } + return func(a *App) { + if rollbackErr != nil { + a.operationFailed("plugin_workspace_apply_edit_rollback", rollbackErr) + } + done(errors.Join(reject, rollbackErr)) + } + }) +} + +// applyServerWorkspaceEdit validates a server request and returns the final +// result through Core's bounded, session-scoped request lifecycle. +func (a *App) applyServerWorkspaceEdit(server *pluginServer, event core.BackendEvent) { + if server == nil || server.session == nil { + return + } + req, err := core.PluginWorkspaceApplyEditFromEvent(event) + if err != nil { + a.backgroundFailed("plugin_workspace_apply_edit", err) + return + } + responder, ok := a.kernel.(workspaceApplyEditKernel) + if !ok { + return + } + respond := func(applied bool, reason string) { + sessionID := server.session.Session.ID + a.background(nil, semanticStartTimeout, func(ctx context.Context) func(*App) { + if err := responder.RespondWorkspaceApplyEdit(ctx, sessionID, req.ApplyEditID, applied, reason); err != nil && !errors.Is(err, context.Canceled) { + return func(a *App) { a.backgroundFailed("plugin_workspace_apply_edit_response", err) } + } + return nil + }) + } + p := a.project + if p == nil || p != server.project || !a.isCurrentPluginServer(server.session.PluginID, server) { + respond(false, "Workspace session is no longer active.") + return + } + if !a.workspaceEditVersionsCurrent(p, server, req.DocumentVersions) { + a.operationRejected("plugin_workspace_apply_edit", "stale_document_revision") + respond(false, "Open document changed before workspace edit could be applied.") + return + } + if len(req.Changes) == 0 { + respond(true, "") + return + } + if server.workspaceEdits == nil { + server.workspaceEdits = make(map[string]context.CancelFunc) + } + ctx, cancel := context.WithCancel(p.ctx) + server.workspaceEdits[req.ApplyEditID] = cancel + a.applyLanguageWorkspaceEdit(p, server, ctx, req.Changes, func(err error) { + delete(server.workspaceEdits, req.ApplyEditID) + defer cancel() + switch { + case ctx.Err() != nil: + // log-exempt: 用户取消:Core 已结束这条工作区编辑请求。 + case err == nil: + respond(true, "") + case errors.Is(err, errStaleWorkspaceEdit): + a.operationRejected("plugin_workspace_apply_edit", "stale_document_revision") + respond(false, "Open document changed before workspace edit could be applied.") + case errors.Is(err, errRenameRejected): + a.operationRejected("plugin_workspace_apply_edit", "outside_or_readonly") + respond(false, "Workspace edit touches outside-workspace or read-only documents.") + default: + a.operationFailed("plugin_workspace_apply_edit", err) + respond(false, "Workspace edit validation or disk write failed.") + } + }) +} + +func (a *App) cancelServerWorkspaceEdit(server *pluginServer, event core.BackendEvent) { + if server == nil { + return + } + var req struct { + ID string `json:"applyEditId"` + } + if err := json.Unmarshal(event.Result, &req); err != nil { + a.backgroundFailed("plugin_workspace_apply_edit_cancel", err) + return + } + if cancel := server.workspaceEdits[req.ID]; cancel != nil { + cancel() + } +} + +func (a *App) codeActionGroupLabel(group string) string { + lang := a.language() + switch group { + case "quickfix": + return i18n.Shared(lang, "desktop.semantics.codeActionQuickFix") + case "refactor": + return i18n.Shared(lang, "desktop.semantics.codeActionRefactor") + case "source": + return i18n.Shared(lang, "desktop.semantics.codeActionSource") + default: + return i18n.Shared(lang, "desktop.semantics.codeActionOther") + } +} + +func (a *App) codeActionsPopup(c ui.C) { + state := &a.semantics.codeActions + p, d := a.currentSemanticDocument(state.documentID) + if d == nil || p != a.project || d.view.Revision() != state.revision || len(state.actions) == 0 { + a.closeSemanticCodeActions() + return + } + anchor := state.anchor + if anchor.Height <= 0 { + var ok bool + anchor, ok = d.caretView().CaretRect() + if !ok { + a.closeSemanticCodeActions() + return + } + } + bounds := c.Bounds() + rows := min(len(state.actions), visibleSemanticRows) + listHeight := float32(rows) * codeActionRowHeight + totalHeight := listHeight + 2*semanticPopupPad + y := anchor.Y + anchor.Height + 2 + if y+totalHeight > bounds.Y+bounds.Height-4 && anchor.Y-totalHeight-2 >= bounds.Y+4 { + y = anchor.Y - totalHeight - 2 + } + x, y := popupOrigin(anchor.X, y, codeActionPopupWidth, bounds) + title := i18n.Shared(a.language(), "desktop.semantics.codeActions") + state.list.Label = func(i int) string { + if i >= 0 && i < len(state.actions) { + return state.actions[i].Title + } + return "" + } + if state.selected >= 0 && state.selected < len(state.actions) && state.list.Selected() != state.selected { + state.list.Select(state.selected) + } + chosen := -1 + a.semanticPopup(c, x, y, codeActionPopupWidth, totalHeight, title, semanticPopupPad, func() { + ui.List(c.Part("code-actions-list"), &state.list, len(state.actions), func(row ui.ListRow) { + action := state.actions[row.Index] + selected := row.Index == state.selected + el := row.Element.FillWidth().Height(codeActionRowHeight).PadX(8).Gap(8).Items(ui.Center). + Radius(a.theme.Metrics.RadiusItem()). + HitWith(ui.ID(row.C), action.Title, gfx.HitOptions{Role: gfx.RoleOption, SkipFocus: true, Cursor: gfx.PointerCursorHand}). + Hover(ui.Look{}.Background(a.colors.Hover)). + Pressed(ui.Look{}.Background(a.colors.Active)) + if selected { + el = el.Background(a.colors.Active) + } + iconColor := a.colors.Subtle + if action.Group == "quickfix" || action.IsPreferred { + iconColor = gfx.RGB24(0xD99B26) + } + el.Children(func() { + ui.Icon(row.C, icons.Sparkles).Size(13, 13).Color(iconColor).Shrink(0) + ui.Text(row.C, action.Title).FontSize(12).Color(a.colors.Text).Grow(1).Shrink(1).Ellipsis() + if action.IsPreferred { + ui.Text(row.C, i18n.Shared(a.language(), "desktop.semantics.codeActionPreferred")). + FontSize(10.5).Color(a.theme.Primary).Shrink(0) + } + ui.Text(row.C, a.codeActionGroupLabel(action.Group)). + FontSize(10.5).Color(a.colors.Subtle).Shrink(0) + }) + if el.Clicked() { + chosen = row.Index + } + }).Scrollbars().Label(title).FillWidth().Height(listHeight) + }) + if chosen >= 0 { + state.selected = chosen + c.After(func() { a.choosePluginCodeAction(chosen) }) + } +} + +// codeActionLightbulb renders a non-focus-stealing clickable lightbulb indicator on the +// active line's left gutter margin without shifting textLeft horizontally. +func (a *App) codeActionLightbulb(c ui.C, p *project, d *document) { + if p == nil || d == nil || d.virtual || d.view.ReadOnly() || d.caretView().IsComposing() { + return + } + server, offered := a.editorServer(d, featureCodeActions) + if server == nil || !offered || d.lastArea.Width <= 0 { + return + } + caretRect, ok := d.caretView().CaretRect() + if !ok || caretRect.Y < d.lastArea.Y || caretRect.Y+caretRect.Height > d.lastArea.Y+d.lastArea.Height { + return + } + caretLine, _ := d.caretView().CaretUTF16() + hasDiagnostics := false + for _, diag := range a.rawPluginDiagnostics[server.session.PluginID][d.path] { + if diag.Range.Start.Line <= caretLine && caretLine <= diag.Range.End.Line { + hasDiagnostics = true + break + } + } + start, end := d.caretView().Selection() + if !hasDiagnostics && start == end { + return + } + bulbColor := a.colors.Subtle + if hasDiagnostics { + bulbColor = gfx.RGB24(0xD99B26) + } + label := i18n.Shared(a.language(), "desktop.semantics.codeActions") + bx := d.lastArea.X + 2 + by := caretRect.Y + (caretRect.Height-16)/2 + ui.Stack(c.Part("lightbulb-layer")).Fill().Children(func() { + kc := c.Part("code-action-bulb") + btn := ui.Row(kc).Absolute().Left(bx).Top(by).Size(16, 16).Center(). + Radius(4). + HitWith(ui.ID(kc), label, gfx.HitOptions{Role: gfx.RoleButton, SkipFocus: true, Cursor: gfx.PointerCursorHand}). + Hover(ui.Look{}.Background(a.colors.Hover)). + Pressed(ui.Look{}.Background(a.colors.Active)). + Tooltip(label) + btn.Children(func() { + ui.Icon(kc, icons.Sparkles).Size(12, 12).Color(bulbColor) + }) + if btn.Clicked() { + anchor := gfx.Rect{X: max(caretRect.X, d.lastArea.X+28), Y: caretRect.Y, Width: 16, Height: caretRect.Height} + c.After(func() { + var target core.PluginDocumentRange + if sLine, sCol, eLine, eCol, selOK := d.caretView().SelectionUTF16(); selOK { + target = core.PluginDocumentRange{ + Start: core.PluginDocumentPosition{Line: sLine, UTF16Column: sCol}, + End: core.PluginDocumentPosition{Line: eLine, UTF16Column: eCol}, + } + } else { + l, col := d.caretView().CaretUTF16() + pos := core.PluginDocumentPosition{Line: l, UTF16Column: col} + target = core.PluginDocumentRange{Start: pos, End: pos} + } + a.startPluginCodeActionsAtRange(p, d, target, anchor, nil, surfaceButton) + }) + } + }) +} + +func truncateDisplayText(s string, maxRunes int) string { + s = strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", " "), "\n", " ")) + if utf8.RuneCountInString(s) <= maxRunes { + return s + } + var b strings.Builder + count := 0 + for _, r := range s { + if count >= maxRunes-1 { + break + } + b.WriteRune(r) + count++ + } + b.WriteRune('…') + return b.String() +} diff --git a/desktop/internal/workbench/pluginsemantics_hover.go b/desktop/internal/workbench/pluginsemantics_hover.go index b75d536a73..1f456d8dcf 100644 --- a/desktop/internal/workbench/pluginsemantics_hover.go +++ b/desktop/internal/workbench/pluginsemantics_hover.go @@ -412,6 +412,10 @@ func (a *App) hoverPopup(c ui.C) { a.layoutHover(canvas, page, maxWidth) width := page.width + 2*semanticHoverPadX height := min(page.height+2*semanticHoverPadY, semanticHoverMaxHeight) + if state.quickFix != nil { + width = max(width, 124) + height += 28 + } anchor := state.anchor below := bounds.Y + bounds.Height - semanticHoverMargin - (anchor.Y + anchor.Height) above := anchor.Y - bounds.Y - semanticHoverMargin @@ -439,6 +443,21 @@ func (a *App) hoverPopup(c ui.C) { id := ui.ID(c.Part(name)) ui.Control(c.Part(name), page.label, &page.input).Fill().Draw(page.draw). HitWith(id, page.label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + if state.quickFix != nil { + label := i18n.Shared(a.language(), "desktop.semantics.codeActionQuickFix") + key := c.Part("diagnostic-quick-fix") + button := ui.Row(key).FillWidth().Height(28).PadX(8).Items(ui.Center). + HitWith(ui.ID(key), label, gfx.HitOptions{Role: gfx.RoleButton, SkipFocus: true, Cursor: gfx.PointerCursorHand}). + Hover(ui.Look{}.Background(a.colors.Hover)) + button.Children(func() { ui.Text(key, label).FontSize(12) }) + if button.Clicked() { + docID, span, anchor := state.documentID, *state.quickFix, state.anchor + c.After(func() { + p, d := a.currentSemanticDocument(docID) + a.startPluginCodeActionsAtRange(p, d, span, anchor, []string{"quickfix"}, surfaceButton) + }) + } + } }) }) } diff --git a/desktop/internal/workbench/pluginsemantics_view.go b/desktop/internal/workbench/pluginsemantics_view.go index 74398e8bce..0cd78b44f9 100644 --- a/desktop/internal/workbench/pluginsemantics_view.go +++ b/desktop/internal/workbench/pluginsemantics_view.go @@ -13,12 +13,17 @@ import ( // constant number of views. func (a *App) semanticPopups(c ui.C) { state := &a.semantics + if p := a.project; p != nil { + a.codeActionLightbulb(c, p, p.selectedDocument(p.docs.group)) + } if a.project == nil || state.project != a.project { return } switch { case state.rename.open: a.renameDialog(c) + case state.codeActions.open: + a.codeActionsPopup(c) case state.definition.open: a.definitionPopup(c) case state.completion.open: @@ -26,6 +31,10 @@ func (a *App) semanticPopups(c ui.C) { case state.hover.open: a.hoverPopup(c) } + if !state.rename.open && !state.codeActions.open && !state.definition.open { + a.signatureHelpPopup(c) + a.inlayHintHoverPopup(c) + } } // semanticPopup declares a popup panel at x, y over the window. The panel is diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index 1eeebbb8c1..3857a488ca 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -91,6 +91,7 @@ func (a *App) documentEdited(p *project, d *document, edit editorview.Edit) { // Keeping it after an edit would apply or jump from stale positions. a.pluginSemanticsEdited(d) a.scheduleAutoCompletion(p, d, edit) + a.scheduleAutoSignatureHelp(p, d, edit) s := &d.sync if s.full || len(s.pending) >= maxPendingDocumentChanges { s.full, s.pending = true, nil @@ -314,6 +315,7 @@ func (a *App) releasePluginDocuments(pluginID string) { a.semanticTokensReleased(pluginID) for _, d := range a.project.docs.list { if d.sync.pluginID == pluginID { + a.clearDocumentInlayHints(d) d.sync.reset() } } @@ -328,6 +330,7 @@ func (a *App) releaseAllPluginDocuments() { a.pluginSemanticsReset() a.semanticTokensReleased("") for _, d := range a.project.docs.list { + a.clearDocumentInlayHints(d) d.sync.reset() } } diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index a6e75b4f8f..0b6803b301 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -292,7 +292,11 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { SetEditorPreferences: func(stored core.EditorStoredPreferences, resolved core.EditorPreferences) { a.post(func(a *App) { a.settings.EditorPreferences = stored + inlayChanged := a.editorPreferences.InlayHints != resolved.InlayHints a.editorPreferences = resolved + if inlayChanged { + a.applyInlayHintsPreference(resolved.InlayHints) + } a.saveSettings() a.invalidator.Invalidate() }) diff --git a/desktop/internal/workbench/signature_help.go b/desktop/internal/workbench/signature_help.go new file mode 100644 index 0000000000..5bf5e8236f --- /dev/null +++ b/desktop/internal/workbench/signature_help.go @@ -0,0 +1,567 @@ +package workbench + +import ( + "context" + "encoding/json" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +const ( + pluginSemanticSignatureHelp semanticKind = "signatureHelp" + pluginMethodSignatureHelp = "textDocument/signatureHelp" + featureSignatureHelp = "signatureHelp" + + semanticAutoSignatureDelay = 60 * time.Millisecond + signatureHelpMaxWidth = float32(520) + signatureHelpMinWidth = float32(220) + maxCallScanBytes = 2048 +) + +type signatureHelpState struct { + open bool + help *core.PluginSemanticSignatureHelp + activeSignature int + documentID int + revision int + line, column int + callOpenOffset int + rect gfx.Rect +} + +// signatureHelpShortcut handles explicit Parameter Info (Command+P on macOS, Control+P elsewhere). +func (a *App) signatureHelpShortcut(event gfx.KeyEvent) gfx.EventResult { + if event.Release || event.Modifiers != primaryModifier() || !strings.EqualFold(event.Text, "p") { + return gfx.EventResult{} + } + p, d := a.pluginSemanticHit(event.Target) + if d == nil || d.caretView().IsComposing() { + return gfx.EventResult{} + } + if _, offered := a.editorServer(d, featureSignatureHelp); !offered { + return gfx.EventResult{} + } + line, column := d.caretView().CaretUTF16() + a.startPluginSignatureHelp(p, d, line, column, surfaceShortcut) + return gfx.EventResult{Handled: true, Repaint: true} +} + +// startPluginSignatureHelp explicitly invokes textDocument/signatureHelp at (line, column). +func (a *App) startPluginSignatureHelp(p *project, d *document, line, column int, surface actionSurface) { + ctx := a.buildSignatureHelpContext(1, "", a.semantics.signatureHelp.open, a.activeSignatureHelpRaw(d)) + if surface != "" { + a.performed("editor.semantics.signatureHelp", surface) + } + a.requestPluginSignatureHelp(p, d, line, column, ctx, false) +} + +func (a *App) activeSignatureHelpRaw(d *document) json.RawMessage { + st := &a.semantics.signatureHelp + if !st.open || st.help == nil || d == nil || st.documentID != d.id { + return nil + } + return st.help.Raw +} + +func (a *App) buildSignatureHelpContext(triggerKind int, triggerChar string, isRetrigger bool, activeRaw json.RawMessage) json.RawMessage { + payload := map[string]any{ + "triggerKind": triggerKind, + "isRetrigger": isRetrigger, + } + if triggerKind == 2 && triggerChar != "" { + payload["triggerCharacter"] = triggerChar + } + if isRetrigger && len(activeRaw) > 0 { + payload["activeSignatureHelp"] = activeRaw + } + raw, _ := json.Marshal(payload) + return raw +} + +func (a *App) requestPluginSignatureHelp(p *project, d *document, line, column int, sigCtx json.RawMessage, automatic bool) { + if a.plugins == nil || p == nil || d == nil || a.project != p || d.caretView().IsComposing() { + return + } + if automatic { + if caretLine, caretCol := d.caretView().CaretUTF16(); caretLine != line || caretCol != column { + return + } + } + retry := func(a *App) { + a.requestPluginSignatureHelp(p, d, line, column, sigCtx, automatic) + } + if !a.semanticDocumentReady(d) { + if automatic { + // Coalesce automatic signature help behind document sync without clobbering explicit deferred actions. + a.semantics.sigDeferred = retry + a.semantics.project = p + a.semantics.documentID = d.id + } else { + a.deferSemantic(p, d, retry) + } + a.startDocumentSync(p, d) + return + } + server, ok := a.semanticServer(d) + if !ok { + if !automatic { + a.notify(i18n.Shared(a.language(), "desktop.semantics.noServer")) + } + return + } + if !server.isReady() { + if !automatic { + a.deferSemantic(p, d, retry) + } + return + } + if !server.features[featureSignatureHelp] { + if !automatic { + a.notifyInfo(i18n.Shared(a.language(), "desktop.semantics.noSignatureHelp")) + } + return + } + position := core.PluginDocumentPosition{Line: line, UTF16Column: column} + a.cancelSemanticKind(pluginSemanticSignatureHelp) + pending := a.newSemanticPending(pluginSemanticSignatureHelp, p, d, server, line, column, true, false) + pending.automatic = automatic + a.semantics.pending = append(a.semantics.pending, pending) + request := core.PluginSemanticRequest{ + Operation: string(pluginSemanticSignatureHelp), + URI: d.sync.uri, + Position: &position, + SignatureHelpContext: sigCtx, + } + a.background(pending.project, semanticStartTimeout, func(ctx context.Context) func(*App) { + operation, err := a.plugins.RequestLanguageSession(ctx, pending.server.session, request) + return func(a *App) { a.semanticRequestStarted(pending, operation, err, ctx.Err()) } + }) +} + +func (a *App) scheduleAutoSignatureHelp(p *project, d *document, edit editorview.Edit) { + if a.semantics.sigCancel != nil { + a.semantics.sigCancel() + a.semantics.sigCancel = nil + } + if a.plugins == nil || a.project != p || d == nil || d.caretView().IsComposing() { + return + } + server, ok := a.semanticServer(d) + if !ok || !server.isReady() || !server.features[featureSignatureHelp] { + a.closeSemanticSignatureHelp() + return + } + line, column := d.caretView().CaretUTF16() + caretByte, okByte := d.view.ByteOffset(line, column) + snapshot := d.view.TextSnapshot() + openParen := -1 + if okByte { + openParen = enclosingCallOffset(snapshot, caretByte) + } + wasOpen := a.semantics.signatureHelp.open && a.semantics.signatureHelp.documentID == d.id + var sigCtx json.RawMessage + triggered := false + if edit.StartLine == edit.EndLine && edit.StartColumn == edit.EndColumn && len([]rune(edit.Text)) == 1 { + ch := edit.Text + for _, trig := range server.signatureHelpTriggers { + if trig == ch { + sigCtx = a.buildSignatureHelpContext(2, ch, wasOpen, a.activeSignatureHelpRaw(d)) + triggered = true + break + } + } + if !triggered && (wasOpen || openParen >= 0) { + for _, retrig := range server.signatureHelpRetriggers { + if retrig == ch { + sigCtx = a.buildSignatureHelpContext(2, ch, wasOpen, a.activeSignatureHelpRaw(d)) + triggered = true + break + } + } + } + } + if !triggered { + if !wasOpen { + return + } + if openParen < 0 { + a.closeSemanticSignatureHelp() + return + } + sigCtx = a.buildSignatureHelpContext(3, "", true, a.activeSignatureHelpRaw(d)) + } + // Preserve open signature help across typing inside the call while the update is in flight. + if wasOpen && openParen >= 0 { + a.semantics.signatureHelp.revision = d.view.Revision() + a.semantics.signatureHelp.line = line + a.semantics.signatureHelp.column = column + a.semantics.signatureHelp.callOpenOffset = openParen + } + a.queueDebouncedSignatureHelp(p, d, line, column, sigCtx) +} + +func (a *App) queueDebouncedSignatureHelp(p *project, d *document, line, column int, sigCtx json.RawMessage) { + if a.semantics.sigCancel != nil { + a.semantics.sigCancel() + a.semantics.sigCancel = nil + } + delay := a.semantics.sigDelay + if delay == 0 { + delay = semanticAutoSignatureDelay + } + ctx, cancel := context.WithCancel(p.ctx) + a.semantics.sigCancel = cancel + a.semantics.sigGeneration++ + generation := a.semantics.sigGeneration + if delay < 0 { + cancel() + a.semantics.sigCancel = nil + a.requestPluginSignatureHelp(p, d, line, column, sigCtx, true) + return + } + a.background(p, 0, func(context.Context) func(*App) { + defer cancel() + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + // log-exempt: 用户取消:继续输入、移动光标或关闭项目会取消签名提示防抖等待。 + return nil + } + return func(a *App) { + if a.semantics.sigGeneration != generation { + return + } + a.requestPluginSignatureHelp(p, d, line, column, sigCtx, true) + } + }) +} + +func (a *App) syncSignatureHelpCaret() { + st := &a.semantics.signatureHelp + if !st.open { + return + } + p, d := a.currentSemanticDocument(st.documentID) + if d == nil || p != a.project { + a.closeSemanticSignatureHelp() + return + } + line, column := d.caretView().CaretUTF16() + if d.view.Revision() != st.revision { + // Handled by scheduleAutoSignatureHelp on edit; if changed externally, check call parens. + caretByte, ok := d.view.ByteOffset(line, column) + if !ok || enclosingCallOffset(d.view.TextSnapshot(), caretByte) < 0 { + a.closeSemanticSignatureHelp() + } + return + } + if line == st.line && column == st.column { + return + } + caretByte, ok := d.view.ByteOffset(line, column) + if !ok { + a.closeSemanticSignatureHelp() + return + } + openParen := enclosingCallOffset(d.view.TextSnapshot(), caretByte) + if openParen < 0 || (st.callOpenOffset >= 0 && openParen != st.callOpenOffset) { + a.closeSemanticSignatureHelp() + return + } + st.line, st.column = line, column + sigCtx := a.buildSignatureHelpContext(3, "", true, st.help.Raw) + a.queueDebouncedSignatureHelp(p, d, line, column, sigCtx) +} + +func (a *App) applySemanticSignatureHelp(pending *semanticPending, event core.BackendEvent) { + p, d := a.currentSemanticDocument(pending.documentID) + if p != pending.project || d == nil || d.view.Revision() != pending.revision || !a.semanticPositionCurrent(pending, d) { + return + } + help, err := core.PluginSemanticSignatureHelpFromEvent(event) + if err != nil { + a.backgroundFailed("plugin_signature_help", err) + return + } + if help == nil || len(help.Signatures) == 0 { + a.closeSemanticSignatureHelp() + if !pending.automatic { + a.notifyInfo(i18n.Shared(a.language(), "desktop.semantics.noSignatureHelp")) + } + return + } + openParen := -1 + if caretByte, ok := d.view.ByteOffset(pending.line, pending.column); ok { + openParen = enclosingCallOffset(d.view.TextSnapshot(), caretByte) + } + active := min(max(help.ActiveSignature, 0), len(help.Signatures)-1) + a.semantics.signatureHelp = signatureHelpState{ + open: true, + help: help, + activeSignature: active, + documentID: d.id, + revision: pending.revision, + line: pending.line, + column: pending.column, + callOpenOffset: openParen, + } +} + +func (a *App) closeSemanticSignatureHelp() { + if a.semantics.sigCancel != nil { + a.semantics.sigCancel() + a.semantics.sigCancel = nil + } + a.semantics.sigGeneration++ + a.semantics.sigDeferred = nil + a.semantics.signatureHelp = signatureHelpState{} + a.cancelSemanticKind(pluginSemanticSignatureHelp) +} + +func (a *App) stepSignatureOverload(delta int) { + st := &a.semantics.signatureHelp + if !st.open || st.help == nil || len(st.help.Signatures) <= 1 { + return + } + n := len(st.help.Signatures) + st.activeSignature = (st.activeSignature + delta + n) % n +} + +func (a *App) signatureHelpKey(event gfx.KeyEvent) gfx.EventResult { + st := &a.semantics.signatureHelp + if !st.open || st.help == nil { + return gfx.EventResult{} + } + if event.Key == gfx.KeyEscape && !a.semantics.completion.open && !a.semantics.codeActions.open && !a.semantics.definition.open { + a.closeSemanticSignatureHelp() + return gfx.EventResult{Handled: true, Repaint: true} + } + if len(st.help.Signatures) > 1 { + noOtherList := !a.semantics.completion.open && !a.semantics.codeActions.open && !a.semantics.definition.open + if (event.Modifiers == gfx.ModifierAlt || (event.Modifiers == 0 && noOtherList)) && event.Key == gfx.KeyUp { + a.stepSignatureOverload(-1) + return gfx.EventResult{Handled: true, Repaint: true} + } + if (event.Modifiers == gfx.ModifierAlt || (event.Modifiers == 0 && noOtherList)) && event.Key == gfx.KeyDown { + a.stepSignatureOverload(1) + return gfx.EventResult{Handled: true, Repaint: true} + } + } + return gfx.EventResult{} +} + +// enclosingCallOffset scans up to maxCallScanBytes backwards from caretOffset to find the +// byte offset of the unclosed '(' (or '<' when on the same line) enclosing the caret, or -1. +func enclosingCallOffset(text rope.Rope, caretOffset int) int { + caretOffset = min(max(caretOffset, 0), text.Len()) + start := max(caretOffset-maxCallScanBytes, 0) + window, _ := text.Substring(start, caretOffset) + depthParen, depthBracket, depthBrace := 0, 0, 0 + var inQuote byte + for i := len(window) - 1; i >= 0; i-- { + b := window[i] + if inQuote != 0 { + if b == inQuote && (i == 0 || window[i-1] != '\\') { + inQuote = 0 + } + continue + } + switch b { + case '"', '\'', '`': + inQuote = b + case ')': + depthParen++ + case '(': + if depthParen == 0 { + return start + i + } + depthParen-- + case ']': + depthBracket++ + case '[': + if depthBracket > 0 { + depthBracket-- + } + case '}': + depthBrace++ + case '{': + if depthBrace > 0 { + depthBrace-- + } else { + return -1 + } + case ';': + if depthParen == 0 && depthBracket == 0 && depthBrace == 0 { + return -1 + } + } + } + return -1 +} + +func (a *App) signatureHelpPopup(c ui.C) { + st := &a.semantics.signatureHelp + if !st.open || st.help == nil || len(st.help.Signatures) == 0 { + return + } + p, d := a.currentSemanticDocument(st.documentID) + if d == nil || p != a.project { + a.closeSemanticSignatureHelp() + return + } + anchor, ok := d.caretView().CaretRect() + if !ok { + a.closeSemanticSignatureHelp() + return + } + sigIdx := min(max(st.activeSignature, 0), len(st.help.Signatures)-1) + sig := st.help.Signatures[sigIdx] + activeParam := st.help.ActiveParameter + if sig.ActiveParameter != nil { + activeParam = sig.ActiveParameter + } + + var prefix, highlighted, suffix string + var paramDoc string + prefix = sig.Label + if activeParam != nil && *activeParam >= 0 && *activeParam < len(sig.Parameters) { + param := sig.Parameters[*activeParam] + if param.Documentation != nil { + paramDoc = truncateDisplayText(*param.Documentation, 180) + } + if param.ByteStart != nil && param.ByteEnd != nil { + bs, be := *param.ByteStart, *param.ByteEnd + if bs >= 0 && bs <= be && be <= len(sig.Label) { + prefix = sig.Label[:bs] + highlighted = sig.Label[bs:be] + suffix = sig.Label[be:] + } + } + } + sigDoc := "" + if sig.Documentation != nil { + sigDoc = truncateDisplayText(*sig.Documentation, 200) + } + + hasDocs := paramDoc != "" || sigDoc != "" + estimatedHeight := float32(34) + if hasDocs { + estimatedHeight += 26 + if paramDoc != "" && sigDoc != "" { + estimatedHeight += 18 + } + } + bounds := c.Bounds() + charWidth := max(d.view.CellWidth(), 7.5) + labelRunes := float32(len([]rune(sig.Label))) + overloadRoom := float32(28) + if len(st.help.Signatures) > 1 { + overloadRoom = 96 + } + width := min(max(labelRunes*charWidth+overloadRoom, signatureHelpMinWidth), min(signatureHelpMaxWidth, bounds.Width-8)) + + // Prefer above the caret so completion (placed below the caret) is never occluded. + y := anchor.Y - estimatedHeight - 4 + x := min(max(anchor.X, bounds.X+4), max(bounds.X+bounds.Width-width-4, bounds.X+4)) + if y < bounds.Y+4 { + if a.semantics.completion.open { + compX, compY := popupOrigin(anchor.X, anchor.Y+anchor.Height+2, semanticPopupWidth, bounds) + compRows := min(len(a.semantics.completion.items), visibleSemanticRows) + compH := float32(compRows)*semanticRowHeight + 2*semanticPopupPad + // Place beside completion if there is horizontal room, else below completion. + if compX+semanticPopupWidth+8+width <= bounds.X+bounds.Width-4 { + x = compX + semanticPopupWidth + 8 + y = max(anchor.Y+anchor.Height+2, bounds.Y+4) + } else { + y = min(compY+compH+4, max(bounds.Y+bounds.Height-estimatedHeight-4, bounds.Y+4)) + } + } else { + y = min(anchor.Y+anchor.Height+4, max(bounds.Y+bounds.Height-estimatedHeight-4, bounds.Y+4)) + } + } + st.rect = gfx.Rect{X: x, Y: y, Width: width, Height: estimatedHeight} + lang := a.language() + title := i18n.Shared(lang, "desktop.semantics.signatureHelp") + stepDelta := 0 + + ui.Stack(c.Part("signature-help-layer")).Fill().Children(func() { + sc := c.Part("signature-help-card") + ui.Column(sc).Absolute().Left(x).Top(y).Width(width).PadX(10).PadY(6).Gap(4). + Background(a.theme.Popover).Border(1, a.theme.Border). + Radius(a.theme.Metrics.RadiusPopup()).Shadow(gfx.ShadowMD). + HitWith(ui.ID(sc), title, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}). + Children(func() { + ui.Row(sc).FillWidth().Items(ui.Center).Gap(6).Children(func() { + ui.Row(sc).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Gap(0).Clip().Children(func() { + if prefix != "" { + ui.Text(sc, prefix).Mono().FontSize(12).Color(a.colors.Subtle).Shrink(1).Ellipsis() + } + if highlighted != "" { + ui.Row(sc.Part("active-param")).PadX(3).PadY(1).Radius(3). + Background(a.colors.Active).Shrink(0).Children(func() { + ui.Text(sc.Part("active-param-text"), highlighted).Mono().FontSize(12). + Weight(gfx.WeightBold).Color(a.colors.Text) + }) + } + if suffix != "" { + ui.Text(sc, suffix).Mono().FontSize(12).Color(a.colors.Subtle).Shrink(1).Ellipsis() + } + }) + if len(st.help.Signatures) > 1 { + counter := i18n.SharedFormat(lang, "desktop.semantics.signatureOverload", map[string]string{ + "current": strconv.Itoa(sigIdx + 1), + "total": strconv.Itoa(len(st.help.Signatures)), + }) + prevLabel := i18n.Shared(lang, "desktop.semantics.signaturePrevious") + nextLabel := i18n.Shared(lang, "desktop.semantics.signatureNext") + ui.Row(sc.Part("overloads")).Shrink(0).Items(ui.Center).Gap(2).Children(func() { + prevC := sc.Part("sig-prev") + prevBtn := ui.Row(prevC).Size(16, 16).Center().Radius(3). + HitWith(ui.ID(prevC), prevLabel, gfx.HitOptions{Role: gfx.RoleButton, SkipFocus: true, Cursor: gfx.PointerCursorHand}). + Hover(ui.Look{}.Background(a.colors.Hover)) + prevBtn.Children(func() { + ui.Icon(prevC, icons.ChevronUp).Size(11, 11).Color(a.colors.Subtle) + }) + if prevBtn.Clicked() { + stepDelta = -1 + } + ui.Text(sc, counter).FontSize(11).Color(a.colors.Subtle) + nextC := sc.Part("sig-next") + nextBtn := ui.Row(nextC).Size(16, 16).Center().Radius(3). + HitWith(ui.ID(nextC), nextLabel, gfx.HitOptions{Role: gfx.RoleButton, SkipFocus: true, Cursor: gfx.PointerCursorHand}). + Hover(ui.Look{}.Background(a.colors.Hover)) + nextBtn.Children(func() { + ui.Icon(nextC, icons.ChevronDown).Size(11, 11).Color(a.colors.Subtle) + }) + if nextBtn.Clicked() { + stepDelta = 1 + } + }) + } + }) + if hasDocs { + ui.Row(sc).FillWidth().Height(1).Background(a.theme.Border) + if paramDoc != "" { + ui.Wrap(sc, paramDoc).FontSize(11.5).Color(a.colors.Text) + } + if sigDoc != "" { + ui.Wrap(sc, sigDoc).FontSize(11).Color(a.colors.Subtle) + } + } + }) + }) + if stepDelta != 0 { + c.After(func() { a.stepSignatureOverload(stepDelta) }) + } +} diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 7c41ae4f04..1480756e4f 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,7 @@ native_path() { fi } +# Lithe-core-rust for #2128: code actions, signature help, inlay hints, and guarded workspace edits. # Lithe-core-rust main at e56dbb650 (#93): project tool environments use Core's discovery # plan, native path validation and machine-local workspace trust catalog (#2122). # Lithe-core-rust main at 661ef0f: #94, squash-merged into main on top of 8b91b32: a plugin's @@ -245,7 +246,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="7f1fc4becd0b4b415aa463abd0ea5e2810b3e964" +PINNED_CORE_REVISION="23164e82f774873c734a02647b129a1daaa9aab4" 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 7e4e192367..124f24a38d 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11330,6 +11330,28 @@ "desktop.editorPrefs.title": "Editor display", "desktop.editorPrefs.lineNumbers": "Show line numbers", "desktop.editorPrefs.whitespace": "Show whitespace", + "desktop.editorPrefs.inlayHints": "Show inlay hints", + "desktop.editorPrefs.inlayHintsHelp": "Show parameter names, inferred types, and other inline hints reported by language servers. Turning this off hides hints immediately and stops requesting them.", + "desktop.editorMenu.codeActions": "Code Actions...", + "desktop.editorMenu.parameterInfo": "Parameter Info", + "desktop.semantics.codeActions": "Code Actions", + "desktop.semantics.noCodeActions": "No code actions available here.", + "desktop.semantics.codeActionQuickFix": "Quick Fix", + "desktop.semantics.codeActionRefactor": "Refactor", + "desktop.semantics.codeActionSource": "Source", + "desktop.semantics.codeActionOther": "Action", + "desktop.semantics.codeActionPreferred": "Preferred", + "desktop.semantics.codeActionFailed": "The code action could not be applied.", + "desktop.semantics.codeActionRejected": "The code action touches files outside the project or read-only documents, so nothing was changed.", + "desktop.semantics.codeActionPartial": "Some open documents changed while applying the code action and were not updated.", + "desktop.semantics.quickFixButton": "Quick Fix…", + "desktop.semantics.signatureHelp": "Parameter Info", + "desktop.semantics.noSignatureHelp": "No parameter information available here.", + "desktop.semantics.signatureOverload": "{current}/{total}", + "desktop.semantics.signaturePrevious": "Previous signature", + "desktop.semantics.signatureNext": "Next signature", + "desktop.semantics.inlayHintApply": "Insert Hint", + "desktop.semantics.inlayHintTooltip": "Inlay hint details", "desktop.editorPrefs.cursorStyle": "Caret style", "desktop.editorPrefs.cursorBlink": "Blink caret", "desktop.editorPrefs.line": "Line", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 36300c1475..17adfd028a 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11330,6 +11330,28 @@ "desktop.editorPrefs.title": "编辑器显示", "desktop.editorPrefs.lineNumbers": "显示行号", "desktop.editorPrefs.whitespace": "显示空白字符", + "desktop.editorPrefs.inlayHints": "显示内联提示", + "desktop.editorPrefs.inlayHintsHelp": "显示语言服务器提供的参数名、推导类型等行内提示。关闭后会立即移除已有提示并停止请求。", + "desktop.editorMenu.codeActions": "代码操作…", + "desktop.editorMenu.parameterInfo": "参数信息", + "desktop.semantics.codeActions": "代码操作", + "desktop.semantics.noCodeActions": "此处没有可用的代码操作。", + "desktop.semantics.codeActionQuickFix": "快速修复", + "desktop.semantics.codeActionRefactor": "重构", + "desktop.semantics.codeActionSource": "源码", + "desktop.semantics.codeActionOther": "操作", + "desktop.semantics.codeActionPreferred": "首选", + "desktop.semantics.codeActionFailed": "无法应用该代码操作。", + "desktop.semantics.codeActionRejected": "该代码操作涉及项目之外的文件或只读文档,未做任何更改。", + "desktop.semantics.codeActionPartial": "部分已打开的文档在应用代码操作期间发生了变化,未更新。", + "desktop.semantics.quickFixButton": "快速修复…", + "desktop.semantics.signatureHelp": "参数信息", + "desktop.semantics.noSignatureHelp": "此处没有可用的参数信息。", + "desktop.semantics.signatureOverload": "{current}/{total}", + "desktop.semantics.signaturePrevious": "上一个重载签名", + "desktop.semantics.signatureNext": "下一个重载签名", + "desktop.semantics.inlayHintApply": "插入提示文本", + "desktop.semantics.inlayHintTooltip": "内联提示详情", "desktop.editorPrefs.cursorStyle": "光标样式", "desktop.editorPrefs.cursorBlink": "光标闪烁", "desktop.editorPrefs.line": "竖线", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index f93e303532..0a9aa7c4cd 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -108491,6 +108491,164 @@ "desktop" ] }, + { + "id": "desktop.editorPrefs.inlayHints", + "description": "IDE editor essentials: editorPrefs.inlayHints", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorPrefs.inlayHintsHelp", + "description": "IDE editor essentials: editorPrefs.inlayHintsHelp", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorMenu.codeActions", + "description": "Editor context menu: open code actions popup", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.editorMenu.parameterInfo", + "description": "Editor context menu: invoke parameter signature help", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActions", + "description": "Code actions popup accessibility label and title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.noCodeActions", + "description": "Shown when the language server returns no code actions at the caret", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionQuickFix", + "description": "Group badge for quickfix code actions", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionRefactor", + "description": "Group badge for refactor code actions", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionSource", + "description": "Group badge for source code actions", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionOther", + "description": "Group badge for uncategorized code actions", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionPreferred", + "description": "Badge marking a preferred code action", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionFailed", + "description": "Error shown when applying a code action fails", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionRejected", + "description": "Error shown when a code action workspace edit targets outside or read-only files", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.codeActionPartial", + "description": "Error shown when open documents changed before a code action finished applying", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.quickFixButton", + "description": "Diagnostic hover quick fix button label", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.signatureHelp", + "description": "Signature help floating card accessibility label", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.noSignatureHelp", + "description": "Shown when explicit signature help finds no active call signature", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.signatureOverload", + "description": "Overload counter in signature help", + "platforms": [ + "desktop" + ], + "parameters": { + "current": "string", + "total": "string" + } + }, + { + "id": "desktop.semantics.signaturePrevious", + "description": "Previous signature overload button label", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.signatureNext", + "description": "Next signature overload button label", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.inlayHintApply", + "description": "Button label to apply an inlay hint's attached text edits", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.semantics.inlayHintTooltip", + "description": "Inlay hint tooltip popover accessibility label", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.editorPrefs.cursorStyle", "description": "IDE editor essentials: editorPrefs.cursorStyle", diff --git a/shared/platform-feature-matrix/features/lsp-code-actions.json b/shared/platform-feature-matrix/features/lsp-code-actions.json new file mode 100644 index 0000000000..9995036567 --- /dev/null +++ b/shared/platform-feature-matrix/features/lsp-code-actions.json @@ -0,0 +1,27 @@ +{ + "id": "lsp-code-actions", + "area": "编辑器", + "group": "语言服务", + "capability": "代码操作与快速修复", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/pluginsemantics_codeactions.go", + "desktop/internal/workbench/lsp_actions_test.go", + "desktop/internal/core/plugin_semantics.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/pluginsemantics_codeactions.go", + "desktop/internal/workbench/lsp_actions_test.go", + "desktop/internal/core/plugin_semantics.go" + ] + }, + "owner": "Editor / Language Tooling", + "verification": "以声明该能力的合成语言服务器验证 Alt/Option+Enter、编辑器菜单、诊断快速修复、动作列表、撤销,以及工作区编辑的文件边界、文档版本和取消。", + "notes": "Viva 在 macOS 和 Windows 共享实现。原生平台验证待补。" +} diff --git a/shared/platform-feature-matrix/features/lsp-inlay-hints.json b/shared/platform-feature-matrix/features/lsp-inlay-hints.json new file mode 100644 index 0000000000..42f2e35baa --- /dev/null +++ b/shared/platform-feature-matrix/features/lsp-inlay-hints.json @@ -0,0 +1,29 @@ +{ + "id": "lsp-inlay-hints", + "area": "编辑器", + "group": "语言服务", + "capability": "内联提示", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/inlay_hints.go", + "desktop/internal/workbench/lsp_actions_test.go", + "desktop/internal/core/plugin_semantics.go", + "desktop/internal/editorview/inlayhints.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/inlay_hints.go", + "desktop/internal/workbench/lsp_actions_test.go", + "desktop/internal/core/plugin_semantics.go", + "desktop/internal/editorview/inlayhints.go" + ] + }, + "owner": "Editor / Language Tooling", + "verification": "以声明该能力的合成语言服务器验证可见行请求、编辑与服务刷新、折行和选区几何、设置禁用后清理。", + "notes": "Viva 在 macOS 和 Windows 共享实现。原生平台验证待补。" +} diff --git a/shared/platform-feature-matrix/features/lsp-signature-help.json b/shared/platform-feature-matrix/features/lsp-signature-help.json new file mode 100644 index 0000000000..81ea8bfab2 --- /dev/null +++ b/shared/platform-feature-matrix/features/lsp-signature-help.json @@ -0,0 +1,27 @@ +{ + "id": "lsp-signature-help", + "area": "编辑器", + "group": "语言服务", + "capability": "参数信息", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/signature_help.go", + "desktop/internal/workbench/lsp_actions_test.go", + "desktop/internal/core/plugin_semantics.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/workbench/signature_help.go", + "desktop/internal/workbench/lsp_actions_test.go", + "desktop/internal/core/plugin_semantics.go" + ] + }, + "owner": "Editor / Language Tooling", + "verification": "以声明该能力的合成语言服务器验证参数信息快捷键、触发字符、当前参数高亮、重载切换、离开调用和 Esc 关闭。", + "notes": "Viva 在 macOS 和 Windows 共享实现。原生平台验证待补。" +} From 8c7e623c2976aa8199114e1dfbe3663a477ffbe1 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 22:35:37 +0800 Subject: [PATCH 2/8] fix(editor): guard LSP action lifecycle and folded hint ranges --- ...11-18-viva-lsp-editor-actions-and-hints.md | 39 +++++ desktop/internal/editorview/inlayhints.go | 68 ++++++++- .../internal/editorview/inlayhints_test.go | 61 ++++++++ desktop/internal/editorview/longline_test.go | 2 +- desktop/internal/editorview/minimap.go | 25 +++- desktop/internal/editorview/minimap_test.go | 4 +- desktop/internal/workbench/documents.go | 1 + desktop/internal/workbench/inlay_hints.go | 125 ++++++++-------- .../internal/workbench/lsp_actions_test.go | 25 ++++ .../workbench/lsp_actions_visual_test.go | 2 +- desktop/internal/workbench/pluginbackends.go | 1 + .../workbench/pluginsemantics_codeactions.go | 105 ++++++++++++-- desktop/internal/workbench/pluginsync.go | 3 + desktop/internal/workbench/signature_help.go | 137 +++--------------- docs/development/macos-plugin-api-plan.md | 2 +- 15 files changed, 399 insertions(+), 201 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-18-viva-lsp-editor-actions-and-hints.md diff --git a/.agents/notes/implemented/architecture/2026-11-18-viva-lsp-editor-actions-and-hints.md b/.agents/notes/implemented/architecture/2026-11-18-viva-lsp-editor-actions-and-hints.md new file mode 100644 index 0000000000..495632ac55 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-18-viva-lsp-editor-actions-and-hints.md @@ -0,0 +1,39 @@ +# Agent 笔记:Viva 编辑器的代码操作、参数信息与内联提示 + +状态:已实现 + +## 先说结论 + +代码操作、参数信息和内联提示由标准语言服务器协议提供。Rust Core 校验请求、响应及文档版本,Viva 负责编辑器交互和文件写入。对于折叠的文档,编辑器把可见行拆成多个连续区间,分别请求提示。 + +## 问题 + +语言服务器的回复和正在编辑的文本可能属于不同版本。代码操作还可能先编辑几个文件,再要求语言服务器执行命令。滚动和折叠则会不断改变需要显示提示的行。 + +## 决策 + +- 按 Core 返回的操作 ID 接收结果。对于先到的完成事件,等同 ID 的提交确认后再处理。请求期间替换文档或更改版本时,丢弃旧结果。 +- Core 校验服务器给出的文档版本。Viva 再核对当前同步状态和视图修订,在后台准备编辑。关闭工作区、取消或目标变化时,后台任务负责按旧内容恢复本次已经写入的文件。恢复时核对写入后的字节,保留同时发生的外部改动。 +- 代码操作附带的命令在相关编辑内容同步到语言服务器后发送。参数信息使用服务端能力声明触发,并根据服务端返回的结果更新,避免用宿主的括号规则猜测不同语言的参数范围。 +- 折叠块两侧的可见行分别请求。提示排版依赖不可变文本快照,并在视图修订匹配时安装。涉及超长单行时,继续分页绘制源码,该行省略内联提示。 + +## 考虑过的备选方案 + +- 按方法名匹配提前到达的完成事件。同一文档的前后两次操作会共用方法名,导致旧编辑误用新请求的修订。 +- 从首个到最后一个可见逻辑行发出单次请求。折叠一千行后,这个区间仍包含一千行,隐藏结果可能先耗尽提示额度。 +- 在字符表面叠放浮层或向文本插入空格。折行、选区和鼠标命中依赖同一几何,覆盖层不能可靠匹配,插入空格还会污染实际文档。 + +## 后果 + +编辑缓冲区和磁盘上的文件都可以参与代码操作。外部进程同时改写目标文件时,保护写入可能拒绝编辑或回滚,并记录对应失败。多段可见提示减少折叠区的工作量,语言服务器需要分段返回。 + +## 验证 + +运行 `scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/editorview`,覆盖快捷键、编辑撤销、取消恢复、请求身份、提示生命周期及布局。使用 `TestVisualLSPActions` 生成中英文与明暗主题的无头截图,用 `scripts/desktop/perf/editor-bench.sh` 对比编辑器基准。 + +## 适用范围 + +- `desktop/internal/workbench/pluginsemantics_codeactions.go` +- `desktop/internal/workbench/signature_help.go` +- `desktop/internal/workbench/inlay_hints.go` +- `desktop/internal/editorview/inlayhints.go` diff --git a/desktop/internal/editorview/inlayhints.go b/desktop/internal/editorview/inlayhints.go index a31beefd45..23929974a0 100644 --- a/desktop/internal/editorview/inlayhints.go +++ b/desktop/internal/editorview/inlayhints.go @@ -206,6 +206,7 @@ func (v *View) ClearInlayHints() bool { } func (v *View) replaceInlayHints(prepared PreparedInlayHints) { + v.mm.key.valid = false if !v.wrapping() || v.lineH <= 0 { v.inlay = inlayState{prepared: prepared} return @@ -226,6 +227,7 @@ func (v *View) reflowInlayRows() { if !v.wrapping() || !v.HasInlayHints() { return } + v.mm.key.valid = false v.ensureRows() prepared := &v.inlay.prepared v.inlay.wraps = make(map[int][]wrapRow) @@ -269,6 +271,49 @@ func (v *View) CellWidth() float32 { return v.cellW } // VisibleLineRange returns the inclusive zero-based range of document lines // at the current scroll position using the last painted viewport dimensions. func (v *View) VisibleLineRange() (firstLine, lastLine int, ok bool) { + firstRow, lastRow, ok := v.viewportRows(0) + if !ok { + return 0, 0, false + } + firstLine, _ = v.rowLine(firstRow) + lastLine, _ = v.rowLine(lastRow) + return firstLine, lastLine, true +} + +// LineSpan is a contiguous range of zero-based document lines, both inclusive. +type LineSpan struct{ First, Last int } + +// ViewportLineRanges appends contiguous spans of visible lines to dst. The +// margin extends the viewport in screen rows before mapping to document lines, +// so neither the viewport nor the margin includes any lines hidden by folding. +func (v *View) ViewportLineRanges(dst []LineSpan, marginRows int) []LineSpan { + firstRow, lastRow, ok := v.viewportRows(marginRows) + if !ok { + return dst + } + first, _ := v.rowLine(firstRow) + last, _ := v.rowLine(lastRow) + if len(v.fold.collapsed) == 0 || first == last { + return append(dst, LineSpan{first, last}) + } + + span := LineSpan{first, first} + for line := first; line < last; { + next := line + 1 + if v.fold.hides(next) { + // Hidden lines share the next visible line's first row. Map that row + // back once, regardless of how many logical lines the fold hides. + next, _ = v.rowLine(v.rowStartForLine(next)) + dst = append(dst, span) + span.First = next + } + span.Last = next + line = next + } + return append(dst, span) +} + +func (v *View) viewportRows(marginRows int) (firstRow, lastRow int, ok bool) { if !v.painted || v.lineH <= 0 { return 0, 0, false } @@ -276,11 +321,24 @@ func (v *View) VisibleLineRange() (firstLine, lastLine int, ok bool) { if rows <= 0 { return 0, 0, false } - firstRow := min(max(int(v.scroll/v.lineH), 0), rows-1) - lastRow := min(max(int(math.Ceil(float64((v.scroll+v.area.Height)/v.lineH)))-1, firstRow), rows-1) - firstLine, _ = v.rowLine(firstRow) - lastLine, _ = v.rowLine(lastRow) - return firstLine, lastLine, true + firstRow = min(max(int(v.scroll/v.lineH), 0), rows-1) + lastRow = min(max(int(math.Ceil(float64((v.scroll+v.area.Height)/v.lineH)))-1, firstRow), rows-1) + marginRows = max(marginRows, 0) + return max(firstRow-marginRows, 0), lastRow + min(marginRows, rows-1-lastRow), true +} + +// InlayHintRequestEnd returns the exclusive LSP position after lastLine. +// Only the document's final line needs a UTF-16 measurement. A final line +// using long-line mode is excluded as the editor cannot annotate it. +func (v *View) InlayHintRequestEnd(lastLine int) (line, utf16Column int) { + if lastLine+1 < v.text.LineCount() { + return lastLine + 1, 0 + } + start, end := v.text.LineStart(lastLine), v.text.LineEnd(lastLine) + if end-start > longLine { + return lastLine, 0 + } + return lastLine, v.utf16Units(start, end) } // InlayHintAt reports the ID and window rectangle of an interactive hint. diff --git a/desktop/internal/editorview/inlayhints_test.go b/desktop/internal/editorview/inlayhints_test.go index 71361d6e3b..14abb4e6f0 100644 --- a/desktop/internal/editorview/inlayhints_test.go +++ b/desktop/internal/editorview/inlayhints_test.go @@ -1,6 +1,7 @@ package editorview import ( + "slices" "strings" "testing" @@ -154,3 +155,63 @@ func TestInlayHintPaintingAllocatesNothingAfterWarmup(t *testing.T) { } } } + +func TestInlayHintViewportSkipsFoldedLinesAndMeasuresMarginInRows(t *testing.T) { + v := newTestView(t, strings.Repeat("short\n", 4006)) + canvas := new(gfx.Canvas) + v.Paint(canvas, gfx.Rect{Width: 500, Height: 150}, Look{}) + v.SetFoldRanges([]FoldRange{{2, 3999}, {4001, 4002}}) + if !v.ToggleFold(2) || !v.ToggleFold(4001) { + t.Fatal("the fixture's folders could not be collapsed") + } + canvas.Reset() + v.Paint(canvas, gfx.Rect{Width: 500, Height: v.LineHeight() * 3}, Look{}) + v.Scroll(gfx.ScrollEvent{Target: v.cfg.HitID, DeltaY: 2.5 * v.LineHeight(), Precise: true}) + + var buffer [4]LineSpan + visible := v.ViewportLineRanges(buffer[:0], 0) + if want := []LineSpan{{2, 2}, {4000, 4001}, {4003, 4003}}; !slices.Equal(visible, want) { + t.Fatalf("scrolled viewport = %v, want %v", visible, want) + } + prefetch := v.ViewportLineRanges(buffer[:0], 2) + if want := []LineSpan{{0, 2}, {4000, 4001}, {4003, 4005}}; !slices.Equal(prefetch, want) { + t.Fatalf("rows with prefetch = %v, want %v", prefetch, want) + } + if allocs := testing.AllocsPerRun(20, func() { v.ViewportLineRanges(buffer[:0], 2) }); allocs != 0 { + t.Fatalf("viewport query allocates %v times with a warmed buffer", allocs) + } +} + +func TestInlayHintRequestEndUsesTheDocumentEndOnlyAtEOF(t *testing.T) { + v := newTestView(t, "text\r\n😀好") + if line, column := v.InlayHintRequestEnd(0); line != 1 || column != 0 { + t.Fatalf("position after first line = (%v, %v), want beginning of next line", line, column) + } + if line, column := v.InlayHintRequestEnd(1); line != 1 || column != 3 { + t.Fatalf("position after last line = (%v, %v), want (1, 3)", line, column) + } + v = newTestView(t, strings.Repeat("x", longLine+1)) + if line, column := v.InlayHintRequestEnd(0); line != 0 || column != 0 { + t.Fatalf("position at final paged line = (%v, %v), want (0, 0)", line, column) + } +} + +func TestInlayHintWrappedRowsStayAlignedInTheMinimap(t *testing.T) { + v := newTestView(t, "before\nshort\nnext") + v.SetMinimap(true) + area := gfx.Rect{Width: 170, Height: 110} + canvas, _ := paintWrapped(t, v, area) + installTestHints(t, v, InlayHintSpec{Line: 1, UTF16Column: 2, Label: "long-enough-to-wrap"}) + canvas.Reset() + v.Paint(canvas, area, Look{}) + rows := v.rowsOf(v.ref(1)) + if len(rows) <= 1 { + t.Fatal("the test hint did not wrap") + } + if mapRows := v.minimapRows(v.ref(1)); !slices.Equal(mapRows, rows) { + t.Fatalf("minimap rows = %v, editor rows = %v", mapRows, rows) + } + if end, next := v.lineRowEnd(1), v.lineRow(2); end != next { + t.Fatalf("minimap selection end row %v differs from the next editor row %v", end, next) + } +} diff --git a/desktop/internal/editorview/longline_test.go b/desktop/internal/editorview/longline_test.go index 89b5a9edab..eb3af7e676 100644 --- a/desktop/internal/editorview/longline_test.go +++ b/desktop/internal/editorview/longline_test.go @@ -247,7 +247,7 @@ func TestLongLineMinimapBarsMatchTheWholeLine(t *testing.T) { if k+1 < len(rows) { end = rows[k+1].at } - v.markRow(line, 0, rows[k], end, int32(k), cols) + v.markRow(line, 0, rows[k], end, int32(k), cols, nil) } if !slices.Equal(got, v.mm.marks) { t.Fatalf("wrap %v: %d bars, want %d as the whole line gives", wrap, len(got), len(v.mm.marks)) diff --git a/desktop/internal/editorview/minimap.go b/desktop/internal/editorview/minimap.go index 0c92189570..4fc11dd8bd 100644 --- a/desktop/internal/editorview/minimap.go +++ b/desktop/internal/editorview/minimap.go @@ -214,7 +214,7 @@ func (v *View) lineRowEnd(line int) int { return line + 1 } v.ensureRows() - return int(v.rowStart[min(max(line, 0), len(v.wraps)-1)+1]) + return v.rowStartForLine(min(max(line, 0), len(v.wraps)-1) + 1) } // buildMinimap makes the bars of rows first to last at cols columns, unless the ones kept are @@ -261,8 +261,12 @@ func (v *View) markRows(first, last, cols int) { line, sub := v.rowLine(first) row := first for row <= last && line < v.text.LineCount() { + if v.fold.hides(line) { + line, _ = v.rowLine(row) + } l := v.ref(line) rows := v.minimapRows(l) + hints := v.lineInlayHints(line) v.mm.tokens = v.hl.Line(v.mm.tokens[:0], line) for k := sub; k < len(rows) && row <= last; k++ { end := l.size @@ -271,7 +275,7 @@ func (v *View) markRows(first, last, cols int) { } // A row shows its first cols columns, so of a long line only those are read. p := v.part(l, rows[k], end, rows[k].cells, rows[k].cells+cols) - v.markRow(p.text, p.base, p.row, end, int32(row), cols) + v.markRow(p.text, p.base, p.row, end, int32(row), cols, hints) row++ } line, sub = line+1, 0 @@ -285,7 +289,13 @@ func (v *View) minimapRows(l lineRef) []wrapRow { if v.fold.hides(l.line) { return nil } - if !v.wrapping() || l.size*tabSize <= v.wrapCols { + if !v.wrapping() { + return oneRow + } + if len(v.lineInlayHints(l.line)) > 0 { + return v.rowsOf(l) + } + if l.size*tabSize <= v.wrapCols { return oneRow } if rows, ok := v.rowCache[l.line]; ok { @@ -304,7 +314,7 @@ func (v *View) minimapRows(l lineRef) []wrapRow { // at or after base, the same number of columns into the line as the row the view lays out. A run of characters of one color is one bar, and spaces, tabs and // control characters leave gaps. A wrapped row starts at the minimap's left edge, as it does in // the view; columns past cols are left out. The tokens of the line are in v.mm.tokens. -func (v *View) markRow(text string, base int, row wrapRow, end int, at int32, cols int) { +func (v *View) markRow(text string, base int, row wrapRow, end int, at int32, cols int, hints []preparedInlayHint) { tokens := v.mm.tokens token := max(sort.Search(len(tokens), func(i int) bool { return int(tokens[i].Start) > row.at })-1, 0) colored := -1 @@ -312,8 +322,15 @@ func (v *View) markRow(text string, base int, row wrapRow, end int, at int32, co // mark is the bar being made longer, -1 after a gap. mark := -1 cells := row.cells + for len(hints) > 0 && hints[0].byteCol < row.at { + hints = hints[1:] + } for i, r := range text[row.at-base : min(end-base, len(text))] { i += row.at + for len(hints) > 0 && hints[0].byteCol == i { + cells = hints[0].cell + hints[0].cells + hints = hints[1:] + } w := runeCells(r, cells) col := cells - row.cells cells += w diff --git a/desktop/internal/editorview/minimap_test.go b/desktop/internal/editorview/minimap_test.go index cd1be40d66..eb5bd2130f 100644 --- a/desktop/internal/editorview/minimap_test.go +++ b/desktop/internal/editorview/minimap_test.go @@ -343,7 +343,7 @@ func TestMinimapBarsAreRunsOfOneColor(t *testing.T) { text := "func ab\tcd//x" v.mm.tokens = []syntax.Token{{Start: 0, Name: keyword}, {Start: 5, Name: comment}, {Start: 6, Name: comment}, {Start: 10, Name: keyword}} v.mm.marks = v.mm.marks[:0] - v.markRow(text, 0, wrapRow{}, len(text), 7, 100) + v.markRow(text, 0, wrapRow{}, len(text), 7, 100, nil) want := []minimapMark{ {row: 7, col: 0, cells: 4, color: color(keyword)}, // "ab" is two tokens of one color, one bar; the tab leaves the gap to column 8. @@ -356,7 +356,7 @@ func TestMinimapBarsAreRunsOfOneColor(t *testing.T) { } v.mm.marks = v.mm.marks[:0] - v.markRow(text, 0, wrapRow{}, len(text), 0, 6) + v.markRow(text, 0, wrapRow{}, len(text), 0, 6, nil) if got := v.mm.marks; len(got) != 2 || got[1].col+got[1].cells != 6 { t.Fatalf("at 6 columns marks = %+v, want the bars cut at column 6", got) } diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 5272e8b479..a6948d65c5 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -58,6 +58,7 @@ type document struct { autoSaveTimer *time.Timer inlay documentInlayHints lastArea gfx.Rect + codeActionGutter codeActionGutterState // folds is the document's code folding requests (folding.go). folds documentFolds // serverLinks are the links the language server reported for the text, and pluginLinks the diff --git a/desktop/internal/workbench/inlay_hints.go b/desktop/internal/workbench/inlay_hints.go index bd0aad84eb..2711457d10 100644 --- a/desktop/internal/workbench/inlay_hints.go +++ b/desktop/internal/workbench/inlay_hints.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "slices" "strings" "time" "unicode/utf8" @@ -27,20 +28,21 @@ const ( inlayHintsPrefetchMargin = 40 inlayHintsDelay = 120 * time.Millisecond + maxInlayHintsPerViewport = 512 ) type documentInlayHints struct { initialized bool revision int - coveredStart int - coveredEnd int - reqStart int - reqEnd int + visible []editorview.LineSpan + seen []editorview.LineSpan + covered []editorview.LineSpan + requested []editorview.LineSpan + next int + collected []core.PluginSemanticInlayHint dirty bool changedAt time.Time seenRevision int - seenFirst int - seenLast int pending *semanticPending resolve *semanticPending resolveIndex int @@ -80,7 +82,7 @@ func (a *App) clearDocumentInlayHints(d *document) { ih.hints = nil ih.resolved = nil ih.revision = -1 - ih.coveredStart, ih.coveredEnd = 0, -1 + ih.covered, ih.requested, ih.collected = nil, nil, nil ih.dirty = false if d.view != nil && d.view.ClearInlayHints() { a.invalidator.Invalidate() @@ -146,7 +148,6 @@ func (a *App) inlayHintsSync(c ui.C, p *project, d *document) { ih.initialized = true ih.revision = -1 ih.seenRevision = -1 - ih.coveredEnd = -1 } server, offered := a.editorServer(d, featureInlayHints) if server == nil || !offered || d.virtual { @@ -155,31 +156,28 @@ func (a *App) inlayHintsSync(c ui.C, p *project, d *document) { } return } - visFirst, visLast, ok := d.view.VisibleLineRange() - if !ok { + ih.visible = d.view.ViewportLineRanges(ih.visible[:0], 0) + if len(ih.visible) == 0 { return } revision := d.view.Revision() - if !ih.dirty && ih.revision == revision && visFirst >= ih.coveredStart && visLast <= ih.coveredEnd { + if !ih.dirty && ih.revision == revision && inlaySpansCover(ih.covered, ih.visible) { return } if a.editorRequestWaiting(ih.pending) { - if ih.pending.revision == revision && !ih.dirty && visFirst >= ih.reqStart && visLast <= ih.reqEnd { + if ih.pending.revision == revision && !ih.dirty && inlaySpansCover(ih.requested, ih.visible) { return } a.cancelSemantic(ih.pending) - ih.pending = nil - } else { - ih.pending = nil + ih.pending, ih.collected = nil, nil } if !a.semanticDocumentReady(d) { return } now := a.now() - if ih.seenRevision != revision || ih.seenFirst != visFirst || ih.seenLast != visLast { + if ih.seenRevision != revision || !slices.Equal(ih.seen, ih.visible) { ih.seenRevision = revision - ih.seenFirst = visFirst - ih.seenLast = visLast + ih.seen = append(ih.seen[:0], ih.visible...) ih.changedAt = now } delay := a.semantics.inlayDelay @@ -192,43 +190,45 @@ func (a *App) inlayHintsSync(c ui.C, p *project, d *document) { return } } - snapshot := d.view.TextSnapshot() - lineCount := max(snapshot.LineCount(), 1) - reqStart := max(visFirst-inlayHintsPrefetchMargin, 0) - reqEnd := min(visLast+inlayHintsPrefetchMargin, lineCount-1) - end := core.PluginDocumentPosition{Line: reqEnd + 1} - if end.Line == lineCount { - lastStart, lastEnd := snapshot.LineStart(reqEnd), snapshot.LineEnd(reqEnd) - if lastEnd-lastStart <= 64*1024 { - end = core.PluginDocumentPosition{Line: reqEnd, UTF16Column: utf16CountString(snapshot.Line(reqEnd))} - } else { - // The editor skips annotations on long-line mode's last line. - end = core.PluginDocumentPosition{Line: reqEnd} + ih.dirty = false + margin := inlayHintsPrefetchMargin + if len(ih.visible) > 1 { + // Give visible spans on both sides of folds priority over prefetch. + margin = 0 + } + ih.requested = d.view.ViewportLineRanges(ih.requested[:0], margin) + ih.next = 0 + ih.collected = nil + a.requestNextInlaySpan(p, d, server) +} + +// inlaySpansCover compares ordered, disjoint logical line ranges. A newly +// unfolded interval is missing even when both of its endpoints were visible. +func inlaySpansCover(available, visible []editorview.LineSpan) bool { + for _, span := range visible { + for len(available) > 0 && available[0].Last < span.First { + available = available[1:] + } + if len(available) == 0 || available[0].First > span.First || available[0].Last < span.Last { + return false } } + return true +} - ih.dirty = false - ih.reqStart = reqStart - ih.reqEnd = reqEnd +func (a *App) requestNextInlaySpan(p *project, d *document, server *pluginServer) { + ih := &d.inlay + span := ih.requested[ih.next] + ih.next++ + line, column := d.view.InlayHintRequestEnd(span.Last) ih.pending = a.submitEditorRequest(pluginSemanticInlayHints, p, d, server, core.PluginSemanticRequest{ Range: &core.PluginDocumentRange{ - Start: core.PluginDocumentPosition{Line: reqStart, UTF16Column: 0}, - End: end, + Start: core.PluginDocumentPosition{Line: span.First}, + End: core.PluginDocumentPosition{Line: line, UTF16Column: column}, }, }) } -func utf16CountString(s string) int { - n := 0 - for _, r := range s { - n++ - if r > 0xffff { - n++ - } - } - return n -} - func (a *App) applyServerInlayHints(pending *semanticPending, event core.BackendEvent, failed bool) { p, d := a.currentSemanticDocument(pending.documentID) if p != pending.project || d == nil || d.inlay.pending != pending { @@ -243,18 +243,30 @@ func (a *App) applyServerInlayHints(pending *semanticPending, event core.Backend if d.view.Revision() != pending.revision { return } - // Settle this range on a failed request too. A visible error should - // not turn unrelated repaints into repeated requests to the server. - d.inlay.revision = pending.revision - d.inlay.coveredStart, d.inlay.coveredEnd = d.inlay.reqStart, d.inlay.reqEnd - if failed { - return + if !failed { + hints, err := core.PluginSemanticInlayHints(event) + if err != nil { + a.backgroundFailed("plugin_inlay_hints", err) + } else { + span := ih.requested[ih.next-1] + for _, hint := range hints { + if len(ih.collected) == maxInlayHintsPerViewport { + break + } + if hint.Position.Line >= span.First && hint.Position.Line <= span.Last { + ih.collected = append(ih.collected, hint) + } + } + } } - hints, err := core.PluginSemanticInlayHints(event) - if err != nil { - a.backgroundFailed("plugin_inlay_hints", err) + if !ih.dirty && ih.next < len(ih.requested) && len(ih.collected) < maxInlayHintsPerViewport { + a.requestNextInlaySpan(p, d, pending.server) return } + hints := ih.collected + ih.collected = nil + ih.revision = pending.revision + ih.covered = append(ih.covered[:0], ih.requested...) if ih.prepareCancel != nil { ih.prepareCancel() ih.prepareCancel = nil @@ -269,9 +281,6 @@ func (a *App) applyServerInlayHints(pending *semanticPending, event core.Backend d.view.ClearInlayHints() ih.hints = hints ih.resolved = nil - ih.revision = pending.revision - ih.coveredStart = ih.reqStart - ih.coveredEnd = ih.reqEnd if len(hints) == 0 { a.invalidator.Invalidate() return diff --git a/desktop/internal/workbench/lsp_actions_test.go b/desktop/internal/workbench/lsp_actions_test.go index 26cb5525ad..8bcbc4fb4c 100644 --- a/desktop/internal/workbench/lsp_actions_test.go +++ b/desktop/internal/workbench/lsp_actions_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/vivaui/viva/gfx" ) @@ -150,3 +151,27 @@ func TestLSPCodeActionsMatchEarlyResultsByOperationID(t *testing.T) { t.Fatalf("wrong code action opened: %+v", state) } } + +func TestLSPCodeActionCommandWaitsForDocumentSynchronization(t *testing.T) { + f := newSemanticFixture(t) + f.d.sync.running = true + called := false + f.h.app.deferCodeActionCommand(f.p, f.server, []renameDocumentUpdate{{id: f.d.id}}, func() { called = true }) + if called { + t.Fatal("command ran while the text edit was still synchronizing") + } + f.h.app.finishDocumentChange(f.p, f.d, f.d.sync.generation, f.d.view.Revision(), nil, nil) + if !called || f.server.codeActionCommand != nil { + t.Fatal("command did not run once synchronization completed") + } +} + +func TestLSPInlayCoverageRejectsNewlyUnfoldedInterior(t *testing.T) { + covered := []editorview.LineSpan{{First: 1, Last: 2}, {First: 5000, Last: 5010}} + if !inlaySpansCover(covered, []editorview.LineSpan{{First: 2, Last: 2}, {First: 5000, Last: 5002}}) { + t.Fatal("a viewport split by a fold was not covered by its two requests") + } + if inlaySpansCover(covered, []editorview.LineSpan{{First: 1, Last: 8}}) { + t.Fatal("unfolded lines were treated as already requested") + } +} diff --git a/desktop/internal/workbench/lsp_actions_visual_test.go b/desktop/internal/workbench/lsp_actions_visual_test.go index 59f57cbd5f..9d51283804 100644 --- a/desktop/internal/workbench/lsp_actions_visual_test.go +++ b/desktop/internal/workbench/lsp_actions_visual_test.go @@ -133,7 +133,7 @@ func main() { d.sync.opened, d.sync.pluginID, d.sync.uri = true, pluginID, uri d.inlay.initialized = true d.inlay.revision = d.view.Revision() - d.inlay.coveredEnd = d.view.TextSnapshot().LineCount() - 1 + d.inlay.covered = []editorview.LineSpan{{First: 0, Last: d.view.TextSnapshot().LineCount() - 1}} h.app.semantics.project = p h.app.storeRawPluginDiagnostics(pluginID, path, []core.PluginDiagnostic{{ diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go index b205ff769c..fc674a8553 100644 --- a/desktop/internal/workbench/pluginbackends.go +++ b/desktop/internal/workbench/pluginbackends.go @@ -85,6 +85,7 @@ type pluginServer struct { signatureHelpTriggers []string signatureHelpRetriggers []string workspaceEdits map[string]context.CancelFunc + codeActionCommand *deferredCodeActionCommand // features are the features the server offers, from Core's featuresChanged event // (documentSymbols, semanticTokens and so on). Only the window thread reads or writes it. features map[string]bool diff --git a/desktop/internal/workbench/pluginsemantics_codeactions.go b/desktop/internal/workbench/pluginsemantics_codeactions.go index dcd7def74b..f4b8bb7763 100644 --- a/desktop/internal/workbench/pluginsemantics_codeactions.go +++ b/desktop/internal/workbench/pluginsemantics_codeactions.go @@ -50,12 +50,23 @@ type codeActionsState struct { anchor gfx.Rect } +type codeActionGutterState struct { + server *pluginServer + line int + hasDiagnostic bool +} + // storeRawPluginDiagnostics retains Core's normalized LSP diagnostics per plugin and file // so codeAction requests forward nullable severity, tags and relatedInformation intact. func (a *App) storeRawPluginDiagnostics(pluginID, fileKey string, diagnostics []core.PluginDiagnostic) { if pluginID == "" || fileKey == "" { return } + if a.project != nil { + if d := a.project.docs.byPath(fileKey); d != nil { + d.codeActionGutter = codeActionGutterState{} + } + } if len(diagnostics) == 0 { if byFile := a.rawPluginDiagnostics[pluginID]; byFile != nil { delete(byFile, fileKey) @@ -88,6 +99,11 @@ func (a *App) clearRawPluginDiagnostics(pluginID string) { } func (a *App) clearRawPluginFileDiagnostics(pluginID, fileKey string) { + if a.project != nil { + if d := a.project.docs.byPath(fileKey); d != nil { + d.codeActionGutter = codeActionGutterState{} + } + } if byFile := a.rawPluginDiagnostics[pluginID]; byFile != nil { delete(byFile, fileKey) if len(byFile) == 0 { @@ -98,6 +114,11 @@ func (a *App) clearRawPluginFileDiagnostics(pluginID, fileKey string) { func (a *App) clearAllRawPluginDiagnostics() { a.rawPluginDiagnostics = nil + if p := a.project; p != nil { + for _, d := range p.docs.list { + d.codeActionGutter = codeActionGutterState{} + } + } } // diagnosticsOverlapping forwards only diagnostics from the server @@ -412,11 +433,13 @@ func (a *App) executeResolvedCodeAction(p *project, d *document, server *pluginS if action.Command == nil || action.Command.Command == "" { return } - if server == nil || !server.isReady() || !server.features[featureExecuteCommand] { + if server == nil || !server.isReady() || !server.features[featureExecuteCommand] || p.docs.find(d.id) != d { return } cmdBytes, err := json.Marshal(action.Command) if err != nil { + a.operationFailed("plugin_code_action_command", err) + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) return } pending := a.newSemanticPending(pluginSemanticExecuteCommand, p, d, server, 0, 0, false, false) @@ -436,9 +459,11 @@ func (a *App) executeResolvedCodeAction(p *project, d *document, server *pluginS a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) return } - a.applyLanguageWorkspaceEdit(p, server, p.ctx, action.Edit.Changes, func(err error) { + a.applyLanguageWorkspaceEdit(p, server, p.ctx, action.Edit.Changes, func(updates []renameDocumentUpdate, err error) { if err == nil { - runCommand() + if action.Command != nil { + a.deferCodeActionCommand(p, server, updates, runCommand) + } return } if errors.Is(err, context.Canceled) || a.project != p { @@ -457,6 +482,54 @@ func (a *App) executeResolvedCodeAction(p *project, d *document, server *pluginS runCommand() } +// deferredCodeActionCommand holds the command until the server has received +// the code action's edits to every document it tracks. +type deferredCodeActionCommand struct { + project *project + documents []int + run func() +} + +func (a *App) deferCodeActionCommand(p *project, server *pluginServer, updates []renameDocumentUpdate, run func()) { + command := &deferredCodeActionCommand{project: p, run: run} + for _, update := range updates { + if d := p.docs.find(update.id); d != nil { + if owner, _ := a.documentSyncServer(d); owner == server { + command.documents = append(command.documents, d.id) + } + } + } + // Only one edit-and-command action may be waiting for this session. + // Replacing it is equivalent to closing the previous action's popup. + server.codeActionCommand = command + a.resumeCodeActionCommand(server) +} + +func (a *App) resumeCodeActionCommand(server *pluginServer) { + if server == nil || server.codeActionCommand == nil { + return + } + command := server.codeActionCommand + if a.project != command.project || a.closingProject || !a.isCurrentPluginServer(server.session.PluginID, server) { + server.codeActionCommand = nil + return + } + for _, id := range command.documents { + d := command.project.docs.find(id) + if d == nil || !d.sync.opened { + server.codeActionCommand = nil + a.operationRejected("plugin_code_action_command", "document_sync_unavailable") + a.notifyError(i18n.Shared(a.language(), "desktop.semantics.codeActionFailed")) + return + } + if !a.semanticDocumentReady(d) { + return + } + } + server.codeActionCommand = nil + command.run() +} + func (a *App) captureWorkspaceOpenDocuments(p *project) map[string]renameOpenDocument { open := make(map[string]renameOpenDocument, len(p.docs.list)) for _, d := range p.docs.list { @@ -497,7 +570,7 @@ var errStaleWorkspaceEdit = errors.New("open document changed before workspace e // applyLanguageWorkspaceEdit keeps disk I/O off the window thread. If a target // changes before the open-document edits are installed, it restores any disk // edits using the exact bytes written, preserving concurrent external edits. -func (a *App) applyLanguageWorkspaceEdit(p *project, server *pluginServer, parent context.Context, changes map[string][]core.PluginTextEdit, done func(error)) { +func (a *App) applyLanguageWorkspaceEdit(p *project, server *pluginServer, parent context.Context, changes map[string][]core.PluginTextEdit, done func([]renameDocumentUpdate, error)) { open := a.captureWorkspaceOpenDocuments(p) write := a.documentWriter session := server.session @@ -510,7 +583,7 @@ func (a *App) applyLanguageWorkspaceEdit(p *project, server *pluginServer, paren err = writeWorkspaceEdit(ctx, writes, write) } if err != nil { - return func(*App) { done(err) } + return func(*App) { done(nil, err) } } // The worker owns the disk transaction until the window claims @@ -525,7 +598,7 @@ func (a *App) applyLanguageWorkspaceEdit(p *project, server *pluginServer, paren } defer close(settled) reject = ctx.Err() - if reject == nil && (a.project != p || !a.isCurrentPluginServer(session.PluginID, server)) { + if reject == nil && (a.project != p || a.closingProject || !a.isCurrentPluginServer(session.PluginID, server)) { reject = context.Canceled } if reject != nil { @@ -567,7 +640,7 @@ func (a *App) applyLanguageWorkspaceEdit(p *project, server *pluginServer, paren if rollbackErr != nil { a.operationFailed("plugin_workspace_apply_edit_rollback", rollbackErr) } - done(errors.Join(reject, rollbackErr)) + done(updates, errors.Join(reject, rollbackErr)) } }) } @@ -597,7 +670,7 @@ func (a *App) applyServerWorkspaceEdit(server *pluginServer, event core.BackendE }) } p := a.project - if p == nil || p != server.project || !a.isCurrentPluginServer(server.session.PluginID, server) { + if p == nil || p != server.project || a.closingProject || !a.isCurrentPluginServer(server.session.PluginID, server) { respond(false, "Workspace session is no longer active.") return } @@ -615,7 +688,7 @@ func (a *App) applyServerWorkspaceEdit(server *pluginServer, event core.BackendE } ctx, cancel := context.WithCancel(p.ctx) server.workspaceEdits[req.ApplyEditID] = cancel - a.applyLanguageWorkspaceEdit(p, server, ctx, req.Changes, func(err error) { + a.applyLanguageWorkspaceEdit(p, server, ctx, req.Changes, func(_ []renameDocumentUpdate, err error) { delete(server.workspaceEdits, req.ApplyEditID) defer cancel() switch { @@ -754,13 +827,17 @@ func (a *App) codeActionLightbulb(c ui.C, p *project, d *document) { return } caretLine, _ := d.caretView().CaretUTF16() - hasDiagnostics := false - for _, diag := range a.rawPluginDiagnostics[server.session.PluginID][d.path] { - if diag.Range.Start.Line <= caretLine && caretLine <= diag.Range.End.Line { - hasDiagnostics = true - break + cached := &d.codeActionGutter + if cached.server != server || cached.line != caretLine { + *cached = codeActionGutterState{server: server, line: caretLine} + for _, diag := range a.rawPluginDiagnostics[server.session.PluginID][d.path] { + if diag.Range.Start.Line <= caretLine && caretLine <= diag.Range.End.Line { + cached.hasDiagnostic = true + break + } } } + hasDiagnostics := cached.hasDiagnostic start, end := d.caretView().Selection() if !hasDiagnostics && start == end { return diff --git a/desktop/internal/workbench/pluginsync.go b/desktop/internal/workbench/pluginsync.go index 3857a488ca..e9c690ba92 100644 --- a/desktop/internal/workbench/pluginsync.go +++ b/desktop/internal/workbench/pluginsync.go @@ -227,6 +227,8 @@ func (a *App) finishDocumentChange(p *project, d *document, generation uint64, r if a.project != p || p.docs.byPath(d.path) != d || s.generation != generation { return } + server, _ := a.documentSyncServer(d) + defer a.resumeCodeActionCommand(server) s.running = false if err != nil { a.reportDocumentSyncFailure("plugin_document_change", ctxErr, err) @@ -291,6 +293,7 @@ func (a *App) closeDocumentInSession(p *project, d *document) { server, pluginID := a.documentSyncServer(d) uri, opened := s.uri, s.opened && s.pluginID == pluginID s.reset() + a.resumeCodeActionCommand(server) if !opened || server == nil || uri == "" { return } diff --git a/desktop/internal/workbench/signature_help.go b/desktop/internal/workbench/signature_help.go index 5bf5e8236f..4688891a54 100644 --- a/desktop/internal/workbench/signature_help.go +++ b/desktop/internal/workbench/signature_help.go @@ -3,12 +3,13 @@ package workbench import ( "context" "encoding/json" + "slices" "strconv" "strings" "time" + "unicode/utf8" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" @@ -24,7 +25,6 @@ const ( semanticAutoSignatureDelay = 60 * time.Millisecond signatureHelpMaxWidth = float32(520) signatureHelpMinWidth = float32(220) - maxCallScanBytes = 2048 ) type signatureHelpState struct { @@ -34,7 +34,6 @@ type signatureHelpState struct { documentID int revision int line, column int - callOpenOffset int rect gfx.Rect } @@ -161,50 +160,26 @@ func (a *App) scheduleAutoSignatureHelp(p *project, d *document, edit editorview return } line, column := d.caretView().CaretUTF16() - caretByte, okByte := d.view.ByteOffset(line, column) - snapshot := d.view.TextSnapshot() - openParen := -1 - if okByte { - openParen = enclosingCallOffset(snapshot, caretByte) - } - wasOpen := a.semantics.signatureHelp.open && a.semantics.signatureHelp.documentID == d.id - var sigCtx json.RawMessage - triggered := false - if edit.StartLine == edit.EndLine && edit.StartColumn == edit.EndColumn && len([]rune(edit.Text)) == 1 { - ch := edit.Text - for _, trig := range server.signatureHelpTriggers { - if trig == ch { - sigCtx = a.buildSignatureHelpContext(2, ch, wasOpen, a.activeSignatureHelpRaw(d)) - triggered = true - break - } - } - if !triggered && (wasOpen || openParen >= 0) { - for _, retrig := range server.signatureHelpRetriggers { - if retrig == ch { - sigCtx = a.buildSignatureHelpContext(2, ch, wasOpen, a.activeSignatureHelpRaw(d)) - triggered = true - break - } - } - } + previous := &a.semantics.signatureHelp + wasOpen := previous.open && previous.documentID == d.id + trigger := "" + if edit.StartLine == edit.EndLine && edit.StartColumn == edit.EndColumn && + utf8.RuneCountInString(edit.Text) == 1 && + (slices.Contains(server.signatureHelpTriggers, edit.Text) || + wasOpen && slices.Contains(server.signatureHelpRetriggers, edit.Text)) { + trigger = edit.Text + } + if trigger == "" && !wasOpen { + return } - if !triggered { - if !wasOpen { - return - } - if openParen < 0 { - a.closeSemanticSignatureHelp() - return - } - sigCtx = a.buildSignatureHelpContext(3, "", true, a.activeSignatureHelpRaw(d)) + kind := 3 // ContentChange + if trigger != "" { + kind = 2 // TriggerCharacter } - // Preserve open signature help across typing inside the call while the update is in flight. - if wasOpen && openParen >= 0 { - a.semantics.signatureHelp.revision = d.view.Revision() - a.semantics.signatureHelp.line = line - a.semantics.signatureHelp.column = column - a.semantics.signatureHelp.callOpenOffset = openParen + sigCtx := a.buildSignatureHelpContext(kind, trigger, wasOpen, a.activeSignatureHelpRaw(d)) + if wasOpen { + previous.revision = d.view.Revision() + previous.line, previous.column = line, column } a.queueDebouncedSignatureHelp(p, d, line, column, sigCtx) } @@ -258,25 +233,11 @@ func (a *App) syncSignatureHelpCaret() { return } line, column := d.caretView().CaretUTF16() - if d.view.Revision() != st.revision { - // Handled by scheduleAutoSignatureHelp on edit; if changed externally, check call parens. - caretByte, ok := d.view.ByteOffset(line, column) - if !ok || enclosingCallOffset(d.view.TextSnapshot(), caretByte) < 0 { - a.closeSemanticSignatureHelp() - } - return - } - if line == st.line && column == st.column { - return - } - caretByte, ok := d.view.ByteOffset(line, column) - if !ok { + if d.view.Revision() != st.revision || d.caretView().IsComposing() { a.closeSemanticSignatureHelp() return } - openParen := enclosingCallOffset(d.view.TextSnapshot(), caretByte) - if openParen < 0 || (st.callOpenOffset >= 0 && openParen != st.callOpenOffset) { - a.closeSemanticSignatureHelp() + if line == st.line && column == st.column { return } st.line, st.column = line, column @@ -301,10 +262,6 @@ func (a *App) applySemanticSignatureHelp(pending *semanticPending, event core.Ba } return } - openParen := -1 - if caretByte, ok := d.view.ByteOffset(pending.line, pending.column); ok { - openParen = enclosingCallOffset(d.view.TextSnapshot(), caretByte) - } active := min(max(help.ActiveSignature, 0), len(help.Signatures)-1) a.semantics.signatureHelp = signatureHelpState{ open: true, @@ -314,7 +271,6 @@ func (a *App) applySemanticSignatureHelp(pending *semanticPending, event core.Ba revision: pending.revision, line: pending.line, column: pending.column, - callOpenOffset: openParen, } } @@ -361,55 +317,6 @@ func (a *App) signatureHelpKey(event gfx.KeyEvent) gfx.EventResult { return gfx.EventResult{} } -// enclosingCallOffset scans up to maxCallScanBytes backwards from caretOffset to find the -// byte offset of the unclosed '(' (or '<' when on the same line) enclosing the caret, or -1. -func enclosingCallOffset(text rope.Rope, caretOffset int) int { - caretOffset = min(max(caretOffset, 0), text.Len()) - start := max(caretOffset-maxCallScanBytes, 0) - window, _ := text.Substring(start, caretOffset) - depthParen, depthBracket, depthBrace := 0, 0, 0 - var inQuote byte - for i := len(window) - 1; i >= 0; i-- { - b := window[i] - if inQuote != 0 { - if b == inQuote && (i == 0 || window[i-1] != '\\') { - inQuote = 0 - } - continue - } - switch b { - case '"', '\'', '`': - inQuote = b - case ')': - depthParen++ - case '(': - if depthParen == 0 { - return start + i - } - depthParen-- - case ']': - depthBracket++ - case '[': - if depthBracket > 0 { - depthBracket-- - } - case '}': - depthBrace++ - case '{': - if depthBrace > 0 { - depthBrace-- - } else { - return -1 - } - case ';': - if depthParen == 0 && depthBracket == 0 && depthBrace == 0 { - return -1 - } - } - } - return -1 -} - func (a *App) signatureHelpPopup(c ui.C) { st := &a.semantics.signatureHelp if !st.open || st.help == nil || len(st.help.Signatures) == 0 { diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 9019e614f6..89058948fc 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -47,7 +47,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-22 | 部分完成 | 既有函数进度与取消;语言服务器准备状态 `languageServer/setStatus`(仅百分比,无 actions,仅 macOS);新增 `outputLinkMatchers:1`,插件声明的匹配器让 Run 与测试控制台出现链接(macOS);独立 output channel、通用 log/progress API 未做 | | API-23 | 部分完成 | 已有进程声明与运行时解析;新增 `serverProcess:4` 的工具 ID 引用(清单 `requiresTools`)与后端发起的 `run/start`、`run/stop`、`run/didExit`(macOS,工具 ID 未找到或不可用时返回 -32025);新增 `commandInstallers:0`:插件声明用哪个已注入工具安装 `systemCommand` 启动缺的命令,Core 校验并展开(`plugins.commandInstallers.requirements/plan/defaultDirectory`),宿主在能力卡片显示缺失与安装按钮,用户选择 Lithe 管理的目录或工具默认位置后运行并记录(权限 `commands.install`,Viva 桌面端);通用 toolchains/process 服务未开放 | | API-24 | 部分完成 | 已公开插件自有原生终端 create/show/close/reopen/dispose/onExit(macOS、本机);不开放 sendText/输出读取,Windows 待接入 | -| API-25 | 部分完成 | 既有语言/LSP 贡献;`languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;新增 `languageServers:3` 与 `serverProcess:3`:后端经 `languageServer/request\|notify\|setStatus` 使用自己的服务器、后端启动(`launch.kind:"backend"`),会话策略由 Core 执行(仅 macOS,远程后端启动未支持,见 Agent Note 2026-11-04-plugin-owned-language-server-sessions);新增宿主方法 `lithe/host/editor/registerProviders`(权限 `editor.providers`,macOS,待运行验收)把 definition/hover/completion/codeLens/foldingRange/semanticTokens/documentLink 绑定到普通插件函数,语言服务器优先、插件只补充;符号、格式化、重命名、Code Action、签名帮助、内联提示和运行期传入 JSON 动态注册高亮未做,详见下方范围说明;Java 拆分计划(C-EDIT):Spring、MyBatis 只补上游缺失的 Provider | +| API-25 | 部分完成 | 既有语言/LSP 贡献;`languages:2` 的清单与包内 JSON 语法/编辑配置,仅支持 Monarch;新增 `languageServers:3` 与 `serverProcess:3`:后端经 `languageServer/request\|notify\|setStatus` 使用自己的服务器、后端启动(`launch.kind:"backend"`),会话策略由 Core 执行(仅 macOS,远程后端启动未支持,见 Agent Note 2026-11-04-plugin-owned-language-server-sessions);新增宿主方法 `lithe/host/editor/registerProviders`(权限 `editor.providers`,macOS,待运行验收)把 definition/hover/completion/codeLens/foldingRange/semanticTokens/documentLink 绑定到普通插件函数,语言服务器优先、插件只补充;标准 LSP 的 Code Actions、签名帮助和内联提示由 Viva 编辑器呈现(#2128)。自定义插件 Provider 的符号、格式化、重命名、Code Action、签名帮助、内联提示及运行期 JSON 动态注册高亮仍待补齐;Java 拆分计划(C-EDIT):Spring、MyBatis 只补上游缺失的 Provider | | API-26 | 未做 | 公共诊断 collection/events API 未开放;既有 LSP 诊断不等于该 API;`registerProviders` 不接受 `diagnostics` 类型(返回 unsupportedOption),推送式诊断集合另行设计;Java 拆分计划(C-EDIT):推送式 collection,带文档版本 | | API-27 | 部分完成 | 独立 `editor/registerActions` 绑定普通函数与文档范围,不依赖 LSP/Build/Run;版本 2 增加行首多图标(run/run-all/debug/test 与 test-passed/test-failed/test-skipped 结果态、navigate-super/navigate-implementations 导航)、同一标记的 `alternatives`(至多 4 个)和点击结果的 `reveal`(宿主展示位置);通用主题、片段、其他装饰未做;Java 拆分计划(C-EDIT):图标、alternatives、reveal、CodeLens、运行与测试标记 | | API-28 | 未做 | 公共 custom editor 文档 owner/保存/撤销/恢复未开放 | From b7f2bb9b3b9688f56befcc412ff176bc126f51e1 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 22:42:53 +0800 Subject: [PATCH 3/8] build(desktop): pin the verified API-25 Core revision --- scripts/desktop/build-desktop-core.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 1480756e4f..c921c36a4f 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -246,7 +246,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="23164e82f774873c734a02647b129a1daaa9aab4" +PINNED_CORE_REVISION="dfa44f45c07a2f6df6e38a87985eabc759fc4094" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in From dc510f1fd059e62ae216cccdda9ee3a51f475cd7 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 22:59:58 +0800 Subject: [PATCH 4/8] perf(editor): keep unannotated and long lines on the fast path --- desktop/internal/editorview/inlayhints.go | 3 +++ desktop/internal/editorview/wrap.go | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/desktop/internal/editorview/inlayhints.go b/desktop/internal/editorview/inlayhints.go index 23929974a0..7384cc0339 100644 --- a/desktop/internal/editorview/inlayhints.go +++ b/desktop/internal/editorview/inlayhints.go @@ -262,6 +262,9 @@ func (v *View) inlayRowsBefore(line int) int { func (v *View) HasInlayHints() bool { return len(v.inlay.prepared.lines) > 0 } func (v *View) lineInlayHints(line int) []preparedInlayHint { + if !v.HasInlayHints() { + return nil + } return v.inlay.prepared.lines[line].hints } diff --git a/desktop/internal/editorview/wrap.go b/desktop/internal/editorview/wrap.go index f02e19236e..d1fddbd8f9 100644 --- a/desktop/internal/editorview/wrap.go +++ b/desktop/internal/editorview/wrap.go @@ -143,7 +143,7 @@ func (v *View) rowsOf(l lineRef) []wrapRow { if !v.wrapping() { return oneRow } - if len(v.lineInlayHints(l.line)) > 0 { + if !l.long && len(v.lineInlayHints(l.line)) > 0 { if rows := v.inlay.wraps[l.line]; len(rows) != 0 { return rows } From dffaec794f2c701b886365f767c1fc9143f3da90 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 00:09:25 +0800 Subject: [PATCH 5/8] fix(editor): retry failed viewport inlay hints once --- ...26-11-19-viva-inlay-hint-viewport-retry.md | 35 ++++++ desktop/internal/workbench/inlay_hints.go | 108 ++++++++++++------ .../internal/workbench/lsp_actions_test.go | 73 ++++++++++++ .../workbench/lsp_actions_visual_test.go | 45 +++++--- .../features/lsp-inlay-hints.json | 2 +- 5 files changed, 210 insertions(+), 53 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-19-viva-inlay-hint-viewport-retry.md diff --git a/.agents/notes/implemented/bug-fix/2026-11-19-viva-inlay-hint-viewport-retry.md b/.agents/notes/implemented/bug-fix/2026-11-19-viva-inlay-hint-viewport-retry.md new file mode 100644 index 0000000000..9a10230436 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-19-viva-inlay-hint-viewport-retry.md @@ -0,0 +1,35 @@ +# Agent 笔记:Viva 内联提示请求失败后的视口重试 + +状态:已实现 + +## 先说结论 + +编辑器请求内联提示遇到临时错误时,会对同一视口自动重试一次。服务连续失败后,编辑器等到视口、文档版本或服务刷新事件变化时再请求。等待期间保留当前文档已有的提示。 + +## 问题 + +语言服务器可能在编辑过程中撤回请求,响应也可能无法解码。原来这两种情况都会把整个视口登记为已取回。停留在相同位置等服务恢复时,编辑器会一直跳过该视口的请求。 + +## 决策 + +- 每个可见范围批次成功返回后才缓存覆盖范围。一个分段失败时,丢弃这次批次收集到的结果,保留上一份已绘制的提示。 +- 首次失败后通过画布调度一次延迟帧。重试仍失败便等待输入、文档版本或服务刷新事件。刷新从新批次开始,过期批次的结果直接丢弃。 + +## 考虑过的备选方案 + +- 把失败当作空结果缓存,编辑器将失去自动恢复机会。 +- 失败后立即重新请求,服务持续失败时,每次响应都会引出新的请求和帧。 + +## 后果 + +短暂失败会增加一次视口请求。服务器恢复较慢时,旧提示会一直保留到下次成功刷新、文档版本变化或编辑器关闭。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test ./internal/workbench -run '^TestLSPInlayHints'` 使用合成服务和虚拟时钟验证自动恢复、连续失败后停止,以及收到服务刷新后的恢复。 +- `TestVisualLSPActions` 检查同一视口中一次失败前后的绘制,覆盖深浅主题与中英文。 + +## 适用范围 + +- `desktop/internal/workbench/inlay_hints.go` +- [Viva 编辑器的代码操作、参数信息与内联提示](../architecture/2026-11-18-viva-lsp-editor-actions-and-hints.md) diff --git a/desktop/internal/workbench/inlay_hints.go b/desktop/internal/workbench/inlay_hints.go index 2711457d10..5d67f28046 100644 --- a/desktop/internal/workbench/inlay_hints.go +++ b/desktop/internal/workbench/inlay_hints.go @@ -28,28 +28,32 @@ const ( inlayHintsPrefetchMargin = 40 inlayHintsDelay = 120 * time.Millisecond + inlayHintsRetryDelay = 250 * time.Millisecond + maxInlayHintAttempts = 2 maxInlayHintsPerViewport = 512 ) type documentInlayHints struct { - initialized bool - revision int - visible []editorview.LineSpan - seen []editorview.LineSpan - covered []editorview.LineSpan - requested []editorview.LineSpan - next int - collected []core.PluginSemanticInlayHint - dirty bool - changedAt time.Time - seenRevision int - pending *semanticPending - resolve *semanticPending - resolveIndex int - prepareCancel context.CancelFunc - prepareGen uint64 - hints []core.PluginSemanticInlayHint - resolved map[int]bool + initialized bool + revision int + visible []editorview.LineSpan + seen []editorview.LineSpan + covered []editorview.LineSpan + requested []editorview.LineSpan + next int + collected []core.PluginSemanticInlayHint + dirty bool + changedAt time.Time + retryAt time.Time + failedAttempts int + seenRevision int + pending *semanticPending + resolve *semanticPending + resolveIndex int + prepareCancel context.CancelFunc + prepareGen uint64 + hints []core.PluginSemanticInlayHint + resolved map[int]bool } type inlayHintHoverState struct { @@ -84,6 +88,7 @@ func (a *App) clearDocumentInlayHints(d *document) { ih.revision = -1 ih.covered, ih.requested, ih.collected = nil, nil, nil ih.dirty = false + ih.failedAttempts = 0 if d.view != nil && d.view.ClearInlayHints() { a.invalidator.Invalidate() } @@ -175,10 +180,22 @@ func (a *App) inlayHintsSync(c ui.C, p *project, d *document) { return } now := a.now() - if ih.seenRevision != revision || !slices.Equal(ih.seen, ih.visible) { + if ih.dirty || ih.seenRevision != revision || !slices.Equal(ih.seen, ih.visible) { ih.seenRevision = revision ih.seen = append(ih.seen[:0], ih.visible...) - ih.changedAt = now + if !ih.dirty { + ih.changedAt = now + } + ih.failedAttempts = 0 + } + if ih.failedAttempts >= maxInlayHintAttempts { + return + } + if ih.failedAttempts > 0 { + if wait := ih.retryAt.Sub(now); wait > 0 { + c.Canvas().RequestFrameIn(wait) + return + } } delay := a.semantics.inlayDelay if delay == 0 { @@ -229,6 +246,18 @@ func (a *App) requestNextInlaySpan(p *project, d *document, server *pluginServer }) } +func (a *App) retryInlayHints(ih *documentInlayHints) { + // Keep the last rendered hints until a new batch succeeds. A failed batch + // can't establish coverage, and a persistent failure must leave the editor idle. + ih.covered = ih.covered[:0] + ih.collected = nil + ih.failedAttempts++ + if ih.failedAttempts < maxInlayHintAttempts { + ih.retryAt = a.now().Add(inlayHintsRetryDelay) + a.invalidator.Invalidate() + } +} + func (a *App) applyServerInlayHints(pending *semanticPending, event core.BackendEvent, failed bool) { p, d := a.currentSemanticDocument(pending.documentID) if p != pending.project || d == nil || d.inlay.pending != pending { @@ -240,31 +269,36 @@ func (a *App) applyServerInlayHints(pending *semanticPending, event core.Backend a.clearDocumentInlayHints(d) return } - if d.view.Revision() != pending.revision { + if ih.dirty || d.view.Revision() != pending.revision { + ih.collected = nil return } - if !failed { - hints, err := core.PluginSemanticInlayHints(event) - if err != nil { - a.backgroundFailed("plugin_inlay_hints", err) - } else { - span := ih.requested[ih.next-1] - for _, hint := range hints { - if len(ih.collected) == maxInlayHintsPerViewport { - break - } - if hint.Position.Line >= span.First && hint.Position.Line <= span.Last { - ih.collected = append(ih.collected, hint) - } - } + if failed { + a.retryInlayHints(ih) + return + } + hints, err := core.PluginSemanticInlayHints(event) + if err != nil { + a.backgroundFailed("plugin_inlay_hints", err) + a.retryInlayHints(ih) + return + } + span := ih.requested[ih.next-1] + for _, hint := range hints { + if len(ih.collected) == maxInlayHintsPerViewport { + break + } + if hint.Position.Line >= span.First && hint.Position.Line <= span.Last { + ih.collected = append(ih.collected, hint) } } - if !ih.dirty && ih.next < len(ih.requested) && len(ih.collected) < maxInlayHintsPerViewport { + if ih.next < len(ih.requested) && len(ih.collected) < maxInlayHintsPerViewport { a.requestNextInlaySpan(p, d, pending.server) return } - hints := ih.collected + hints = ih.collected ih.collected = nil + ih.failedAttempts = 0 ih.revision = pending.revision ih.covered = append(ih.covered[:0], ih.requested...) if ih.prepareCancel != nil { diff --git a/desktop/internal/workbench/lsp_actions_test.go b/desktop/internal/workbench/lsp_actions_test.go index 8bcbc4fb4c..ab757070a3 100644 --- a/desktop/internal/workbench/lsp_actions_test.go +++ b/desktop/internal/workbench/lsp_actions_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "path/filepath" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" @@ -111,6 +112,78 @@ func TestLSPInlayHintsReleaseWhenDisabled(t *testing.T) { } } +func TestLSPInlayHintsRetryAndStopAfterFailure(t *testing.T) { + f := newSemanticFixture(t) + a := f.h.app + clock := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + a.now = func() time.Time { return clock } + a.editorPreferences.InlayHints = true + f.server.features = map[string]bool{featureInlayHints: true} + a.invalidator.Invalidate() + f.h.settle() + f.waitForRequests(t, 1) + + advance := func() { + t.Helper() + clock = clock.Add(time.Second) + if err := f.h.driver.Advance(time.Second); err != nil { + t.Fatal(err) + } + } + serverError := func(operation string) { + t.Helper() + f.h.settle() + a.applyPluginSemanticEvent(f.server, core.BackendEvent{ + Type: pluginSemanticCompleted, OperationID: operation, Method: pluginMethodInlayHints, + Error: json.RawMessage(`{"code":-32801,"message":"Content modified"}`), + }) + // Directly injected events bypass App.post's wakeup. + a.invalidator.Invalidate() + f.h.settle() + } + + serverError("op-1") + if got := f.kernel.requestCount(); got != 1 { + t.Fatalf("requests before retry delay = %d, want 1", got) + } + advance() + f.waitForRequests(t, 2) + f.deliver(t, "op-2", pluginMethodInlayHints, json.RawMessage(`{"hints":[{"position":{"line":0,"utf16Column":1},"label":": string"}]}`)) + f.h.settleChain() + if !f.d.view.HasInlayHints() { + t.Fatal("the retry did not paint hints in the same viewport") + } + + a.inlayHintsRefresh(f.server) + f.h.settle() + advance() + f.waitForRequests(t, 3) + serverError("op-3") + advance() + f.waitForRequests(t, 4) + f.deliver(t, "op-4", pluginMethodInlayHints, json.RawMessage(`{"hints":true}`)) + f.h.settle() + if !f.d.view.HasInlayHints() { + t.Fatal("a failed refresh discarded the last successful hints") + } + advance() + a.invalidator.Invalidate() + f.h.settleChain() + if got := f.kernel.requestCount(); got != 4 { + t.Fatalf("requests after the retry failed = %d, want 4", got) + } + + a.inlayHintsRefresh(f.server) + f.h.settle() + advance() + f.waitForRequests(t, 5) + f.deliver(t, "op-5", pluginMethodInlayHints, json.RawMessage(`{"hints":[]}`)) + f.h.settleChain() + if f.d.view.HasInlayHints() { + t.Fatal("a successful empty refresh left stale hints visible") + } +} + func TestLSPWorkspaceEditWriteRestoresFilesOnCancellation(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) defer cancel() diff --git a/desktop/internal/workbench/lsp_actions_visual_test.go b/desktop/internal/workbench/lsp_actions_visual_test.go index 9d51283804..dd526f997c 100644 --- a/desktop/internal/workbench/lsp_actions_visual_test.go +++ b/desktop/internal/workbench/lsp_actions_visual_test.go @@ -3,13 +3,14 @@ package workbench import ( + "encoding/json" "os" "path/filepath" "strings" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginlsp" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" @@ -119,21 +120,20 @@ func main() { if _, err := tracker.Open(t.Context(), pluginlsp.Document{URI: uri, LanguageID: "visual-lsp", Text: source}); err != nil { t.Fatal(err) } - h.app.pluginServerMu.Lock() - h.app.pluginServers = map[string]*pluginServer{pluginID: { + server := &pluginServer{ session: &pluginservice.LanguageSession{ PluginID: pluginID, Session: pluginbackend.Session{ID: "visual-lsp"}, Documents: tracker, }, project: p, buildReady: true, cancel: func() {}, features: map[string]bool{featureCodeActions: true, featureInlayHints: true}, - }} + } + h.app.pluginServerMu.Lock() + h.app.pluginServers = map[string]*pluginServer{pluginID: server} h.app.pluginServerLanguages = map[string]string{"visual-lsp": pluginID} h.app.pluginServerMu.Unlock() d.languageID = "visual-lsp" d.sync.opened, d.sync.pluginID, d.sync.uri = true, pluginID, uri - d.inlay.initialized = true - d.inlay.revision = d.view.Revision() - d.inlay.covered = []editorview.LineSpan{{First: 0, Last: d.view.TextSnapshot().LineCount() - 1}} + h.app.editorPreferences.InlayHints = false h.app.semantics.project = p h.app.storeRawPluginDiagnostics(pluginID, path, []core.PluginDiagnostic{{ @@ -206,28 +206,43 @@ func main() { picture("signature-help", parameter, paramDoc) h.app.semantics.signatureHelp = signatureHelpState{} + clock := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + h.app.now = func() time.Time { return clock } h.app.editorPreferences.InlayHints = true + paint() + h.await("initial inlay hint request", func() bool { return kernel.requestCount() == 1 }) + h.settle() + h.app.applyPluginSemanticEvent(server, core.BackendEvent{ + Type: pluginSemanticCompleted, OperationID: "op-1", Method: pluginMethodInlayHints, + Error: json.RawMessage(`{"code":-32801,"message":"Content modified"}`), + }) + paint() + picture("inlay-retry-pending", "main.go") + clock = clock.Add(time.Second) + if err := session.Advance(time.Second); err != nil { + t.Fatal(err) + } + h.await("inlay hint retry", func() bool { return kernel.requestCount() == 2 }) + _, nameColumn := d.view.PositionOf(nameAt) const nameHint = "name:" const countHint = "count:" tip := "The name to include in the greeting." position := core.PluginDocumentPosition{Line: line, UTF16Column: nameColumn} - d.inlay.hints = []core.PluginSemanticInlayHint{ + hints := []core.PluginSemanticInlayHint{ {Position: position, Label: nameHint, Tooltip: &tip, PaddingRight: true, TextEdits: []core.PluginTextEdit{ {Range: core.PluginDocumentRange{Start: position, End: position}, NewText: "/* name */ "}, }}, {Position: core.PluginDocumentPosition{Line: line, UTF16Column: column}, Label: countHint, PaddingRight: true}, } - prepared, err := editorview.PrepareInlayHints(t.Context(), d.view.TextSnapshot(), d.view.Revision(), []editorview.InlayHintSpec{ - {ID: 0, Line: line, UTF16Column: nameColumn, Label: nameHint, PaddingRight: true, Interactive: true}, - {ID: 1, Line: line, UTF16Column: column, Label: countHint, PaddingRight: true}, - }) + result, err := json.Marshal(map[string]any{"hints": hints}) if err != nil { t.Fatal(err) } - if !d.view.SetPreparedInlayHints(prepared) { - t.Fatal("the visual editor did not accept its hints") - } + h.settle() + h.app.applyPluginSemanticEvent(server, core.BackendEvent{ + Type: pluginSemanticCompleted, OperationID: "op-2", Method: pluginMethodInlayHints, Result: result, + }) paint() for _, label := range session.Snapshot().Texts { if label.Value != nameHint { diff --git a/shared/platform-feature-matrix/features/lsp-inlay-hints.json b/shared/platform-feature-matrix/features/lsp-inlay-hints.json index 42f2e35baa..8601f92bb7 100644 --- a/shared/platform-feature-matrix/features/lsp-inlay-hints.json +++ b/shared/platform-feature-matrix/features/lsp-inlay-hints.json @@ -24,6 +24,6 @@ ] }, "owner": "Editor / Language Tooling", - "verification": "以声明该能力的合成语言服务器验证可见行请求、编辑与服务刷新、折行和选区几何、设置禁用后清理。", + "verification": "以声明该能力的合成语言服务器验证可见行请求、编辑与服务刷新、失败后的单次重试及恢复、折行和选区几何、设置禁用后清理。", "notes": "Viva 在 macOS 和 Windows 共享实现。原生平台验证待补。" } From e475341823229aadc12a00d9751be62560601f0f Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 08:36:01 +0800 Subject: [PATCH 6/8] test(editor): verify LSP edit flow and add headless CI --- .github/workflows/desktop-ci.yml | 20 ++ .../internal/workbench/lsp_actions_test.go | 204 ++++++++++++++++-- docs/ci-builds.md | 3 + .../features/lsp-code-actions.json | 2 +- 4 files changed, 205 insertions(+), 24 deletions(-) diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 67258ef288..504753d0ee 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -169,6 +169,26 @@ jobs: - name: Vet and test run: ./scripts/desktop/check.sh + - name: Run LSP editor headless tests + id: lsp-visual + # Capture evidence even when an unrelated test in the full suite fails. + if: ${{ !cancelled() && steps.rust.outcome == 'success' }} + timeout-minutes: 5 + env: + LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/lsp-editor-visual + run: | + ./scripts/desktop/desktop-go.sh test -v -tags 'vivahead lithevisual' ./internal/workbench \ + -run '^(TestLSP|TestVisualLSPActions$)' -count=1 -timeout=120s + + - name: Upload LSP editor screenshots + if: ${{ !cancelled() && steps.lsp-visual.outcome != 'skipped' }} + uses: actions/upload-artifact@v7 + with: + name: lsp-editor-visual-${{ runner.os }}-${{ runner.arch }} + path: .artifacts/lsp-editor-visual/*.png + if-no-files-found: error + retention-days: 14 + - name: Upload native verification reports if: always() uses: actions/upload-artifact@v7 diff --git a/desktop/internal/workbench/lsp_actions_test.go b/desktop/internal/workbench/lsp_actions_test.go index ab757070a3..1b3f30dd1c 100644 --- a/desktop/internal/workbench/lsp_actions_test.go +++ b/desktop/internal/workbench/lsp_actions_test.go @@ -3,18 +3,57 @@ package workbench import ( "context" "encoding/json" + "errors" + "os" "path/filepath" + "sync" "testing" "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginlsp" "github.com/vivaui/viva/gfx" ) -func TestLSPCodeActionsUseTheActiveServerDiagnosticsAndApplyEdit(t *testing.T) { +type codeActionSyncKernel struct { + closeRecordKernel + changeStarted chan core.PluginDocumentSyncRequest + releaseChange <-chan struct{} + version int64 +} + +func (k *codeActionSyncKernel) SyncPluginDocument(ctx context.Context, request core.PluginDocumentSyncRequest) (core.PluginDocumentSync, error) { + if len(request.ContentChanges) == 0 { + return k.closeRecordKernel.SyncPluginDocument(ctx, request) + } + select { + case k.changeStarted <- request: + case <-ctx.Done(): + return core.PluginDocumentSync{}, ctx.Err() + } + select { + case <-k.releaseChange: + k.version++ + return core.PluginDocumentSync{URI: request.URI, DocumentVersion: k.version, Changed: true}, nil + case <-ctx.Done(): + return core.PluginDocumentSync{}, ctx.Err() + } +} + +func TestLSPCodeActionsApplyEditAndWaitForSynchronizationBeforeCommand(t *testing.T) { f := newSemanticFixture(t) - f.server.features = map[string]bool{featureCodeActions: true} + release := make(chan struct{}) + releaseChange := sync.OnceFunc(func() { close(release) }) + defer releaseChange() + syncKernel := &codeActionSyncKernel{changeStarted: make(chan core.PluginDocumentSyncRequest, 2), releaseChange: release, version: 1} + tracker := pluginlsp.New(syncKernel, f.server.session.Session.ID) + if _, err := tracker.Open(t.Context(), pluginlsp.Document{URI: f.d.sync.uri, LanguageID: f.d.languageID, Text: "one\n"}); err != nil { + t.Fatal(err) + } + f.server.session.Documents = tracker + f.server.features = map[string]bool{featureCodeActions: true, featureExecuteCommand: true} f.d.view.GoToNavigation(0, 1, false) f.h.app.storeRawPluginDiagnostics("test", f.d.path, []core.PluginDiagnostic{{Message: "active diagnostic"}}) f.h.app.storeRawPluginDiagnostics("dev.lithe.test.other", f.d.path, []core.PluginDiagnostic{{Message: "other diagnostic"}}) @@ -41,6 +80,7 @@ func TestLSPCodeActionsUseTheActiveServerDiagnosticsAndApplyEdit(t *testing.T) { Changes: map[string][]core.PluginTextEdit{f.d.path: wordEdit(0, 0, 3, "two")}, DocumentVersions: map[string]int64{f.d.path: version}, }, + Command: &core.PluginSemanticCommand{Title: "Finish edit", Command: "test.finishEdit"}, }}}) if err != nil { t.Fatal(err) @@ -52,10 +92,33 @@ func TestLSPCodeActionsUseTheActiveServerDiagnosticsAndApplyEdit(t *testing.T) { if err := f.h.driver.Key(gfx.KeyEnter, 0); err != nil { t.Fatal(err) } - f.h.await("code action edit", func() bool { return f.d.view.TextSnapshot().String() == "two\n" }) + f.h.await("code action edit and deferred command", func() bool { + return f.server.codeActionCommand != nil || f.kernel.requestCount() > 1 + }) if got := f.d.view.TextSnapshot().String(); got != "two\n" { t.Fatalf("code action produced %q", got) } + syncDeadline, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + select { + case change := <-syncKernel.changeStarted: + if change.URI != f.d.sync.uri || len(change.ContentChanges) != 1 || change.ContentChanges[0].Text != "two" { + t.Fatalf("wrong code action didChange: %+v", change) + } + case <-syncDeadline.Done(): + t.Fatal("the code action did not send its edit to the server") + } + if f.server.codeActionCommand == nil || f.kernel.requestCount() != 1 { + t.Fatal("the command was submitted before the didChange acknowledgement") + } + releaseChange() + f.waitForRequests(t, 2) + request = f.kernel.request(1) + var command core.PluginSemanticCommand + if err := json.Unmarshal(request.Command, &command); err != nil || request.Operation != string(pluginSemanticExecuteCommand) || command.Command != "test.finishEdit" { + t.Fatalf("execute command request = %+v (%v)", request, err) + } + f.deliver(t, "op-2", pluginMethodExecuteCommand, json.RawMessage(`{}`)) if _, err := f.h.driver.ShortcutChord(primaryModifier(), 'z'); err != nil { t.Fatal(err) } @@ -184,28 +247,123 @@ func TestLSPInlayHintsRetryAndStopAfterFailure(t *testing.T) { } } -func TestLSPWorkspaceEditWriteRestoresFilesOnCancellation(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - first := filepath.Join(t.TempDir(), "first.txt") - second := filepath.Join(t.TempDir(), "second.txt") - contents := map[string]string{first: "old first", second: "old second"} - writes := []renameClosedWrite{ - {path: first, before: []byte("old first"), after: []byte("new first")}, - {path: second, before: []byte("old second"), after: []byte("new second")}, - } - if err := writeWorkspaceEdit(ctx, writes, func(path string, next, expected []byte) error { - if contents[path] != string(expected) { - t.Fatalf("write to %s expected %q, got %q", path, expected, contents[path]) - } - contents[path] = string(next) - cancel() +func TestLSPWorkspaceEditWriteRollsBackGuardedDiskWrites(t *testing.T) { + for _, scenario := range []struct { + name string + cancel bool + externalTarget string + }{ + {name: "cancel after first write", cancel: true}, + {name: "second file changed externally", externalTarget: "second.txt"}, + {name: "first file changed before rollback", cancel: true, externalTarget: "first.txt"}, + } { + t.Run(scenario.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + dir := t.TempDir() + writes := []renameClosedWrite{ + {path: filepath.Join(dir, "first.txt"), before: []byte("old first"), after: []byte("new first")}, + {path: filepath.Join(dir, "second.txt"), before: []byte("old second"), after: []byte("new second")}, + } + for _, write := range writes { + if err := os.WriteFile(write.path, write.before, 0o600); err != nil { + t.Fatal(err) + } + } + external := []byte("external edit") + err := writeWorkspaceEdit(ctx, writes, func(path string, next, expected []byte) error { + if err := documentio.WriteGuarded(path, next, expected); err != nil { + return err + } + if path == writes[0].path && string(next) == string(writes[0].after) { + if scenario.externalTarget != "" { + if err := os.WriteFile(filepath.Join(dir, scenario.externalTarget), external, 0o600); err != nil { + t.Fatal(err) + } + } + if scenario.cancel { + cancel() + } + } + return nil + }) + if scenario.cancel && !errors.Is(err, context.Canceled) { + t.Fatalf("workspace edit error = %v, want cancellation", err) + } + if scenario.externalTarget != "" && !errors.Is(err, documentio.ErrConflict) { + t.Fatalf("workspace edit error = %v, want the writer to detect changed bytes", err) + } + for _, write := range writes { + want := write.before + if filepath.Base(write.path) == scenario.externalTarget { + want = external + } + data, err := os.ReadFile(write.path) + if err != nil || string(data) != string(want) { + t.Fatalf("%s = %q, %v, want %q", write.path, data, err, want) + } + } + }) + } +} + +type workspaceEditResponse struct { + session, id string + applied bool + reason string +} + +type workspaceEditResponseKernel struct { + *semanticTestKernel + reply chan workspaceEditResponse +} + +func (k *workspaceEditResponseKernel) RespondWorkspaceApplyEdit(ctx context.Context, session, id string, applied bool, reason string) error { + select { + case k.reply <- workspaceEditResponse{session: session, id: id, applied: applied, reason: reason}: return nil - }); err == nil { - t.Fatal("workspace edit completed despite cancellation") + case <-ctx.Done(): + return ctx.Err() + } +} + +func TestLSPServerWorkspaceEditAppliesDiskAndEditorChangesBeforeResponding(t *testing.T) { + f := newSemanticFixture(t) + a := f.h.app + responder := &workspaceEditResponseKernel{semanticTestKernel: f.kernel, reply: make(chan workspaceEditResponse, 1)} + a.kernel = responder + closed := filepath.Join(f.p.root, "B.java") + if err := os.WriteFile(closed, []byte("one\n"), 0o600); err != nil { + t.Fatal(err) + } + version, ok := f.server.session.Documents.Version(f.d.sync.uri) + if !ok { + t.Fatal("fixture lacks a synchronized document version") + } + const requestID = "apply-1" + result, err := json.Marshal(core.PluginWorkspaceApplyEdit{ + ApplyEditID: requestID, + Changes: map[string][]core.PluginTextEdit{ + f.d.path: wordEdit(0, 0, 3, "two"), + closed: wordEdit(0, 0, 3, "two"), + }, + DocumentVersions: map[string]int64{f.d.path: version}, + }) + if err != nil { + t.Fatal(err) + } + a.applyServerWorkspaceEdit(f.server, core.BackendEvent{Type: pluginWorkspaceApplyEdit, Result: result}) + awaitDocumentState(t, f.h, func() bool { return len(responder.reply) > 0 }) + response := <-responder.reply + if response.session != f.server.session.Session.ID || response.id != requestID || !response.applied || response.reason != "" { + t.Fatalf("workspace edit response = %+v", response) + } + if got := f.d.view.TextSnapshot().String(); got != "two\n" { + t.Fatalf("editor text at acknowledgement = %q, want two", got) } - if contents[first] != "old first" || contents[second] != "old second" { - t.Fatalf("cancellation left edits behind: %v", contents) + data, err := os.ReadFile(closed) + if err != nil || string(data) != "two\n" { + t.Fatalf("disk text at acknowledgement = %q, %v, want two", data, err) } } diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 0359d00703..26227cfd7d 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -15,6 +15,7 @@ CI 构建缓存、架构并行、测试产物和 artifact 保留策略见 - Draft PR 只运行 Linux 检查:macOS 和 Windows 作业带有 `draft == false` 条件。标记为 ready 后,才运行完整的 Desktop CI。 - `Desktop CI gate` 汇总固定版本、Linux 格式与脚本、Linux 测试、macOS 测试和 Windows 测试;普通 PR 必须全部成功,Draft 只允许跳过 macOS 和 Windows。更换已有 PR 的目标分支后,保留 Draft 状态;需要评审时标记为 ready 以针对新基线重新运行完整检查。单纯修改标题或正文不触发平台 runner。 - Desktop CI 通过 `scripts/desktop/check.sh` 执行 Go 检查,Rust 内核由 `scripts/desktop/build-desktop-core.sh` 按 `PINNED_CORE_REVISION` 固定的 Lithe-core-rust 修订构建。 +- Linux 测试作业也运行 `TestVisualLSPActions`,覆盖中英文与明暗主题的代码操作、签名帮助和内联提示失败重试。全量测试失败时仍采集截图。结果作为 `lsp-editor-visual-<系统>-<架构>` artifact 保留 14 天。 - Desktop Release 的打包脚本是 `scripts/ci/desktop-release/package-release.sh`,AutoBuild 的打包和发布脚本位于 `scripts/ci/desktop-autobuild/`。 - 两条发布入口共用 `scripts/desktop/package-desktop.sh`,通过 Viva 的 `--cgo` 选项保留 Rust Core 原生桥接;`desktop-go.sh` 提供目标编译器、静态库及头文件。Linux 发布包由 Ubuntu 22.04 构建,其系统库兼容性需要单独验证,不能按 Viva 的默认纯 Go 包假设没有 glibc 依赖。 - 本地复现与 CI 相同的检查见 [`desktop-getting-started.md`](development/desktop-getting-started.md) 的“提交前检查”。 @@ -67,6 +68,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 ### 独立工作树的本地编译 +Desktop CI 的 LSP 无头截图由 `TestVisualLSPActions` 写入当前工作树的 `.artifacts/lsp-editor-visual/`。截图是当前提交与当前渲染环境的验证产物,绑定源码、平台、Go 工具链和固定的 Viva 与 Core 版本,不跨工作树复用。CI 上传后由运行器清理工作树,截图不进入安装包。 + Viva 编辑器性能基线 `scripts/desktop/perf/editor-bench.sh` 把每次运行的原始输出和 Markdown 预算报告写入当前工作树的 `.artifacts/editor-perf/`(`run-.txt`、`record-.txt` 及同名 `.md`,以及开发者用 `--out` 指定在该目录下的文件)。它们只属于这一次运行,受源码修订、机器、CPU、运行时负载、Go 工具链和大文档大小(默认 10 MiB,可用 `LITHE_EDITOR_PERF_LARGE_BYTES` 或 `--large-bytes` 修改)影响;没有可验证的跨树身份 stamp,不跨工作树复制,由开发者在本地清理;该基线不是 CI 必跑项,CI 不运行基准,也没有 artifact。随仓库提交的历史记录 `desktop/benchmarks/history/*.jsonl` 由 Git 跟踪,属于源码而不是下载或生成资源,各工作树从 Git 检出。这些文件都不进入安装包,也不会改变代码签名或增量更新。 Viva 的 Core 源码检出、Cargo 目标目录和暂存静态库位于当前工作树的 diff --git a/shared/platform-feature-matrix/features/lsp-code-actions.json b/shared/platform-feature-matrix/features/lsp-code-actions.json index 9995036567..79cee3e6b5 100644 --- a/shared/platform-feature-matrix/features/lsp-code-actions.json +++ b/shared/platform-feature-matrix/features/lsp-code-actions.json @@ -22,6 +22,6 @@ ] }, "owner": "Editor / Language Tooling", - "verification": "以声明该能力的合成语言服务器验证 Alt/Option+Enter、编辑器菜单、诊断快速修复、动作列表、撤销,以及工作区编辑的文件边界、文档版本和取消。", + "verification": "以合成语言服务器验证 Alt/Option+Enter、编辑器菜单、诊断快速修复、动作列表、撤销、编辑同步后的命令提交,以及工作区编辑的文件边界、文档版本、磁盘回滚和外部编辑保护。", "notes": "Viva 在 macOS 和 Windows 共享实现。原生平台验证待补。" } From 48b1e0415f99cc71327f19b85908eab4c28873e0 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 09:17:42 +0800 Subject: [PATCH 7/8] fix(toolchain): resolve Windows directory junctions before probing --- ...-11-19-windows-toolchain-junction-paths.md | 34 +++++++++++ .../internal/toolchain/native_path_other.go | 9 +++ .../internal/toolchain/native_path_windows.go | 60 +++++++++++++++++++ desktop/internal/toolchain/scan.go | 33 ++++------ .../features/plugin-injected-toolchains.json | 5 +- 5 files changed, 118 insertions(+), 23 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-19-windows-toolchain-junction-paths.md create mode 100644 desktop/internal/toolchain/native_path_other.go create mode 100644 desktop/internal/toolchain/native_path_windows.go diff --git a/.agents/notes/implemented/bug-fix/2026-11-19-windows-toolchain-junction-paths.md b/.agents/notes/implemented/bug-fix/2026-11-19-windows-toolchain-junction-paths.md new file mode 100644 index 0000000000..e7e799674f --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-19-windows-toolchain-junction-paths.md @@ -0,0 +1,34 @@ +# Agent 笔记:Windows 工具链发现使用文件句柄读取最终路径 + +状态:已实现 + +## 先说结论 + +Windows 工具链发现通过文件句柄读取最终路径。目录联接点(junction,Windows 上把一个目录指向另一位置的重定向)也会被解析,Core 因此能在版本探测前检查实际目录是否仍在工作区内。 + +## 问题 + +PR #2175 和桌面主线的 Windows CI 都发现,指向工作区外的环境目录被当作工作区内的环境接受。Go 的 `filepath.EvalSymlinks` 无法完整解析经过联接点的路径。宿主遇到解析失败时,仍可能把原路径作为最终路径交给 Core。[Go #82447](https://github.com/golang/go/issues/82447) + +## 决策 + +- Windows 使用 `GetFinalPathNameByHandleW` 读取系统解析出的路径,再以 Core 已支持的盘符或 UNC 共享路径形式上报。句柄仅用于读取元数据,候选读取结束即关闭。[Windows API 文档](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew) +- 文件或目录候选必须同时有最终路径与匹配的文件类型证据。解析失败时,该路径不能作为文件或目录候选上报。是否允许探测和选择仍由 Core 判定。 + +## 考虑过的备选方案 + +- 逐段解析联接点需要维护 Windows 重定向类型、循环和长路径规则。通过已打开的句柄读取最终路径可以复用系统已完成的解析。 + +## 后果 + +Core 能区分项目内环境目录和指向外部的目录联接点。无法取得最终路径的候选会被排除。读取发生在工具链发现期间,无需修改工具配置或安装文件。 + +## 验证 + +`scripts/desktop/desktop-go.sh test ./internal/toolchain -run '^TestTrustedWorkspaceResolvesSubdirectoryEnvironmentAndRejectsEscapingDirectories$'`。用例同时检查合法的子目录环境可选,以及外部目录联接点返回 `unsafePath` 且没有启动任何探测。macOS 使用目录符号链接执行对应断言。 + +## 适用范围 + +- `desktop/internal/toolchain/native_path_windows.go` +- `desktop/internal/toolchain/scan.go` +- `desktop/internal/toolchain/project_trust_test.go` diff --git a/desktop/internal/toolchain/native_path_other.go b/desktop/internal/toolchain/native_path_other.go new file mode 100644 index 0000000000..cac8541d7d --- /dev/null +++ b/desktop/internal/toolchain/native_path_other.go @@ -0,0 +1,9 @@ +//go:build !windows + +package toolchain + +import "path/filepath" + +func resolveNativePath(absolute string) (string, error) { + return filepath.EvalSymlinks(absolute) +} diff --git a/desktop/internal/toolchain/native_path_windows.go b/desktop/internal/toolchain/native_path_windows.go new file mode 100644 index 0000000000..ced9639336 --- /dev/null +++ b/desktop/internal/toolchain/native_path_windows.go @@ -0,0 +1,60 @@ +package toolchain + +import ( + "errors" + "path/filepath" + "strings" + + "golang.org/x/sys/windows" +) + +// Note: .agents/notes/implemented/bug-fix/2026-11-19-windows-toolchain-junction-paths.md +// Go's EvalSymlinks walks symbolic links but does not resolve Windows directory +// junctions. Ask the filesystem for the final path of the opened target. +func resolveNativePath(absolute string) (resolved string, err error) { + native := absolute + if !strings.HasPrefix(native, `\\?\`) { + if tail, unc := strings.CutPrefix(native, `\\`); unc { + native = `\\?\UNC\` + tail + } else { + native = `\\?\` + native + } + } + name, err := windows.UTF16PtrFromString(native) + if err != nil { + return "", err + } + handle, err := windows.CreateFile(name, 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return "", err + } + defer func() { + if closeErr := windows.CloseHandle(handle); closeErr != nil { + err = errors.Join(err, closeErr) + } + }() + + var initial [windows.MAX_PATH]uint16 + buffer := initial[:] + for { + // Zero requests FILE_NAME_NORMALIZED and VOLUME_NAME_DOS. + length, err := windows.GetFinalPathNameByHandle(handle, &buffer[0], uint32(len(buffer)), 0) + if err != nil { + return "", err + } + if length >= uint32(len(buffer)) { + buffer = make([]uint16, length+1) + continue + } + path := windows.UTF16ToString(buffer[:length]) + if share, ok := strings.CutPrefix(path, `\\?\UNC\`); ok { + return `\\` + share, nil + } + path = strings.TrimPrefix(path, `\\?\`) + if filepath.IsAbs(path) && len(filepath.VolumeName(path)) == 2 { + return path, nil + } + return "", windows.ERROR_BAD_PATHNAME + } +} diff --git a/desktop/internal/toolchain/scan.go b/desktop/internal/toolchain/scan.go index 9e04596198..d56e38ba41 100644 --- a/desktop/internal/toolchain/scan.go +++ b/desktop/internal/toolchain/scan.go @@ -126,21 +126,13 @@ func executableMode(info os.FileInfo) bool { return runtime.GOOS == "windows" || info.Mode().Perm()&0o111 != 0 } -// canonicalPath resolves every symbolic link. Missing paths keep the cleaned -// absolute spelling, which is still enough evidence for Core to see "missing". +// canonicalPath resolves an existing path through filesystem redirects. func canonicalPath(name string) (string, error) { absolute, err := filepath.Abs(name) if err != nil { return "", err } - resolved, err := filepath.EvalSymlinks(absolute) - if err == nil { - return resolved, nil - } - if errors.Is(err, os.ErrNotExist) { - return filepath.Clean(absolute), nil - } - return "", err + return resolveNativePath(absolute) } func (w *workspace) insideRoot(name string) bool { @@ -196,20 +188,19 @@ func (w *workspace) observe(name string) core.ToolchainFileFact { return fact } fact := core.ToolchainFileFact{Path: cleaned, CanonicalPath: cleaned, Kind: "missing"} - if info, statErr := os.Lstat(cleaned); statErr == nil { - if resolved, linkErr := filepath.EvalSymlinks(cleaned); linkErr == nil { + // Only publish a file or directory fact with a resolved path. Core uses it + // to check containment before authorizing an executable probe. + if resolved, err := resolveNativePath(cleaned); err == nil { + if info, err := os.Stat(resolved); err == nil { fact.CanonicalPath = resolved - if target, targetErr := os.Stat(resolved); targetErr == nil { - info = target + switch { + case info.Mode().IsRegular(): + fact.Kind = "file" + fact.Executable = executableMode(info) + case info.IsDir(): + fact.Kind = "directory" } } - switch { - case info.Mode().IsRegular(): - fact.Kind = "file" - fact.Executable = executableMode(info) - case info.IsDir(): - fact.Kind = "directory" - } } w.facts[key] = fact w.order = append(w.order, key) diff --git a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json index ff57d72dcb..97507832f3 100644 --- a/shared/platform-feature-matrix/features/plugin-injected-toolchains.json +++ b/shared/platform-feature-matrix/features/plugin-injected-toolchains.json @@ -57,11 +57,12 @@ "desktop/internal/settingswindow/visual_capture_test.go", ".github/workflows/desktop-ci.yml", "desktop/internal/toolchain/load.go", - "desktop/internal/toolchain/path_windows_test.go" + "desktop/internal/toolchain/path_windows_test.go", + "desktop/internal/toolchain/native_path_windows.go" ] }, "owner": "Plugin Platform", - "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib toolchain,核对定义独占与官方短 ID、第二种通用工具、旧候选边界、答案身份/代次、Windows 路径大小写、工作区排除、固定值失效不回落、最近项目要求、冲突选择、最低版本、环境隔离和纯声明扫描;按逐项计时工具生成 HTML/JUnit。macOS 继续补齐下列消费者与保存验收,Windows 须先实现对应 adapter:启动提供方并协商、取消/超时和过期结果隔离、输入新建/删除后整体重查、目录固定保存/取消/冲突回读、插件停用撤回、真实 Build/LSP/Run 消费者取得同一选择、发行目录哈希不变与子进程清理。未完成原生流程前保持 pending,不以 Core 测试代替实机验证。 提供方查询:cargo test -p lithe-core --lib toolchain(含 lsp 引擎脚本后端:只有插件后端被提供 litheToolchains、未协商的提供方不写请求、错误回复原样返回;别名链接只有链接路径事实时仍选中规范 home);MacToolchainDiscoveryTests 用真实临时目录与注入的查询验证全局与目录查询各带独立 operationID/代次、链接 home 规范化、工作区内 home 整份拒绝;ToolchainSettingsFeatureTests 验证监视文件连续变化只重载一次、外部输入观察随关闭释放。真实 mise 插件端到端尚未在应用内验证。 原生布局回归 ToolchainSettingsLayoutTests:同一设置宿主按900/1180/1400/900重复缩放,真实分隔条拖动;来源页按500/666/946/500缩放,检查AX控件边界、卡片不重叠、选择和快照不改变。此几何验证不代表提供方查询或保存功能已完成。 声明式扫描 MacToolchainDiscoveryTests:真实临时目录、注入的用户目录与探测,覆盖 homeLayouts 首个匹配、隐藏与未匹配条目、链接到工作区的条目不探测、只探测 Core 返回的可执行文件、同版本冲突、被拒声明不扫描,以及隔离预览样例清单通过 Core 准入;不运行本机安装的工具。 固定集成新增 MacToolchainDiscoveryTests 的运行前解析回归和 MacBuildToolResolverTests,验证两个目录使用各自 pin、最低版本、独立环境与失败不回落;RunLaunchEnvironmentTests 证明操作返回值不会留下共享执行许可槽。该测试不是完整应用 UI 验收。 生产准入回归 installedToolDeclarationsPassTheProductionHostAdmission 经 RustDeclarativePluginOperations 验证工具定义和提供者。Build PATH 保留声明的附加目录,拒绝空目录项。 Windows 原生解析基础:lithe-project::defined_toolchain 逐项计时覆盖两个工具、声明式扫描、固定目录、最近继承、同版本冲突、最低版本、显式 Wrapper、输入撤销及宿主秘密不进入 RPC。真实 Windows 命令包装和进程清理继续由现有 CI 验证;准入仍关闭。 本次回归另核对同目录两个 Run 独立选择、团队/本机逐项合并和显式清空、私有环境隔离、失效固定值不回落、工作区启动器被动零探测,以及未知默认值迁移失败保留源文件。 本批显式 LITHE_TEST_NODE 驱动真实 Core/Node 会话,逐项计时覆盖单次协商、多次查询、原始错误、无协商拒绝、静默超时、后端意外退出与撤销清理;原生解析验证查询与当前事实、来源在探测中变化及稳定模型摘要。安装状态按 plugin/operation/workspace 隔离且不可跨工作树复制。 #1581 最终合入回归包含固定值与未扫描目录、同轮次/上下文、冲突及提供方超时和不可用的来源展示。 通用默认增量:更改工作区工具 home 后,消费者继承读取新值,按 Run 固定值保持独立;失效明确路径不回落,来源在探测期间改变或越出工作区时拒绝。旧编辑保存保留通用偏好,显式空 v1 文档清除。矩阵保持 pending,未把手写测试文档当成设置页或旧配置迁移验收。 macOS Build 偏好编辑:ToolchainPreferencesTests 验证打开/草稿/取消/空重置不建文件、明确保存/回读与权限保留、外部冲突保留原始草稿基线、仅偏好文档不阻断旧默认迁移、缺失子目录的父链接/最终链接/只读安装目录拒绝及主动取消;原生 Save/Reset 按钮在深浅主题通过实际存储执行。ToolchainSettingsLoaderTests 验证使用方来自当前 Core invocation 并随停用撤回。运行全量 Core 与相关 macOS 逐项计时;完整产品、全局默认、旧消费者和 Windows 设置页仍待验收。 tool 引用验证:共享 fixture/Core 覆盖最近通用目录、根目录、跳过父消费者、目录与工作区默认变化、显式 Run 优先和禁止通用工具反向引用;MacToolchainDiscoveryTests 与 lithe-project::defined_toolchain 的真实临时安装/注入探测验证运行前重读,不冻结安装路径。 本机目录/重载回归覆盖仅消费者偏好、父目录连接、重置撤回、链接/非法层级拒绝、单次重试与可刷新错误、未修改表单更新、冲突草稿保留及自身保存通知不等待/撤销保存。该集成不代替完整 GUI。 运行前来源审计 missingPreferenceLeafBehindAParentAliasIsRejectedBeforeToolWork 覆盖两级父目录及存在/悬空链接,四种情况均在工具探测前拒绝。 ToolchainPluginAdmissionTests 使用正式契约 fixture 与真实 Core 验证市场可安装、完整安装审查、清单加载,以及无后端纯工具定义插件的启用模块和工厂登记;本地编译验证不代替真实 mise 与 Windows 工作流验收。 2026-11-02 本机 Swift 6.4.2:准入、后端、发现和加载器 42 项通过,新增两个准入用例分别 4/6 ms;Swift 6.3.3 在本机 Xcode 27.2 SDK 下编译依赖清单崩溃,不能作为固定工具链通过。真实 mise 0.2.1 发布包 SHA-256 与市场一致,Core 证明修复前 unsupported、修复后 available;真实后端完成协商、查询并停止销毁,当前环境未安装 mise,查询真实返回 miseNotFound,未验证安装列表和应用内工作流。 增补来源保存验收:不存在的 pin 重置不创建状态;拒绝逃出工作区的符号链接/junction;有界 UTF-8 与重复键、未知字段和 dormant pin 校验;Git 后续否定规则、换行/评论/权限保留;公开字节基线不可替代私有快照;已提交但回读失败必须重新加载后才能重试。 Viva 全局 SDK 页:运行 TestVisualSettings/33-settings-toolchains,使用 en、zh-Hans 和 dark/light 的生产无头窗口,核对无项目模式、自动实际值、多版本登记与全局默认选择。通过 run-go-tests-with-timing.mjs 记录单测试 HTML/JUnit;desktop-ci 的 macOS/Windows 每次上传四张图和计时报告。2026-11-15 本机 macOS 与 Windows 11 ARM64 来宾的 GNU x64 系统仿真均通过两个语言各 3 个计时结果,Windows 49 个 SDK/来源/诊断/资源定向用例通过;该证据不替代工具提供方与完整产品工作流验收,整体保持 partial/pending。 Windows #2042:TestToolchainCandidatesUseNativeShellPathsInUserProfiles 以真实 PATH 查找、真实有界版本进程和 Core 候选规则,覆盖 PATH-only/环境变量-only 及空格/中文用户目录;合成工具位于扫描目录之外,全局登记使用私有根。 通过现有 Windows CI 的 scripts/desktop/check.sh 运行;本机逐项计时报告覆盖这些合成场景,完整原生界面验收仍保持 pending。 2026-11-18(#2122):使用 dev.lithe.test.* 合成工具清单运行 TestUntrustedProjectEnvironmentNeverProbesWorkspaceExecutables、TestTrustedWorkspacePersistsInLocalSettingsOnlyAndResolvesSymlinkedVenv、TestTrustedWorkspaceResolvesSubdirectoryEnvironmentAndRejectsEscapingDirectories、TestProjectToolchainTrustSwitchGrantsAndRevokesImmediately 与 TestWorkbenchToolchainTrustPersistsLocallyLogsActionAndEnablesRuntimeResolution,验证未授权零探测、两跳符号链接虚拟环境字面路径保留、目录软链逃逸在探测前拒绝、本机 toolchains/global.json 原子保存与撤销(绝不写工作区 .lithe/)、performedIn 操作轨迹以及中英明暗无头截图 m47/m48;Windows 实机与完整原生 GUI 工作流保持 pending。", + "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib toolchain,核对定义独占与官方短 ID、第二种通用工具、旧候选边界、答案身份/代次、Windows 路径大小写、工作区排除、固定值失效不回落、最近项目要求、冲突选择、最低版本、环境隔离和纯声明扫描;按逐项计时工具生成 HTML/JUnit。macOS 继续补齐下列消费者与保存验收,Windows 须先实现对应 adapter:启动提供方并协商、取消/超时和过期结果隔离、输入新建/删除后整体重查、目录固定保存/取消/冲突回读、插件停用撤回、真实 Build/LSP/Run 消费者取得同一选择、发行目录哈希不变与子进程清理。未完成原生流程前保持 pending,不以 Core 测试代替实机验证。 提供方查询:cargo test -p lithe-core --lib toolchain(含 lsp 引擎脚本后端:只有插件后端被提供 litheToolchains、未协商的提供方不写请求、错误回复原样返回;别名链接只有链接路径事实时仍选中规范 home);MacToolchainDiscoveryTests 用真实临时目录与注入的查询验证全局与目录查询各带独立 operationID/代次、链接 home 规范化、工作区内 home 整份拒绝;ToolchainSettingsFeatureTests 验证监视文件连续变化只重载一次、外部输入观察随关闭释放。真实 mise 插件端到端尚未在应用内验证。 原生布局回归 ToolchainSettingsLayoutTests:同一设置宿主按900/1180/1400/900重复缩放,真实分隔条拖动;来源页按500/666/946/500缩放,检查AX控件边界、卡片不重叠、选择和快照不改变。此几何验证不代表提供方查询或保存功能已完成。 声明式扫描 MacToolchainDiscoveryTests:真实临时目录、注入的用户目录与探测,覆盖 homeLayouts 首个匹配、隐藏与未匹配条目、链接到工作区的条目不探测、只探测 Core 返回的可执行文件、同版本冲突、被拒声明不扫描,以及隔离预览样例清单通过 Core 准入;不运行本机安装的工具。 固定集成新增 MacToolchainDiscoveryTests 的运行前解析回归和 MacBuildToolResolverTests,验证两个目录使用各自 pin、最低版本、独立环境与失败不回落;RunLaunchEnvironmentTests 证明操作返回值不会留下共享执行许可槽。该测试不是完整应用 UI 验收。 生产准入回归 installedToolDeclarationsPassTheProductionHostAdmission 经 RustDeclarativePluginOperations 验证工具定义和提供者。Build PATH 保留声明的附加目录,拒绝空目录项。 Windows 原生解析基础:lithe-project::defined_toolchain 逐项计时覆盖两个工具、声明式扫描、固定目录、最近继承、同版本冲突、最低版本、显式 Wrapper、输入撤销及宿主秘密不进入 RPC。真实 Windows 命令包装和进程清理继续由现有 CI 验证;准入仍关闭。 本次回归另核对同目录两个 Run 独立选择、团队/本机逐项合并和显式清空、私有环境隔离、失效固定值不回落、工作区启动器被动零探测,以及未知默认值迁移失败保留源文件。 本批显式 LITHE_TEST_NODE 驱动真实 Core/Node 会话,逐项计时覆盖单次协商、多次查询、原始错误、无协商拒绝、静默超时、后端意外退出与撤销清理;原生解析验证查询与当前事实、来源在探测中变化及稳定模型摘要。安装状态按 plugin/operation/workspace 隔离且不可跨工作树复制。 #1581 最终合入回归包含固定值与未扫描目录、同轮次/上下文、冲突及提供方超时和不可用的来源展示。 通用默认增量:更改工作区工具 home 后,消费者继承读取新值,按 Run 固定值保持独立;失效明确路径不回落,来源在探测期间改变或越出工作区时拒绝。旧编辑保存保留通用偏好,显式空 v1 文档清除。矩阵保持 pending,未把手写测试文档当成设置页或旧配置迁移验收。 macOS Build 偏好编辑:ToolchainPreferencesTests 验证打开/草稿/取消/空重置不建文件、明确保存/回读与权限保留、外部冲突保留原始草稿基线、仅偏好文档不阻断旧默认迁移、缺失子目录的父链接/最终链接/只读安装目录拒绝及主动取消;原生 Save/Reset 按钮在深浅主题通过实际存储执行。ToolchainSettingsLoaderTests 验证使用方来自当前 Core invocation 并随停用撤回。运行全量 Core 与相关 macOS 逐项计时;完整产品、全局默认、旧消费者和 Windows 设置页仍待验收。 tool 引用验证:共享 fixture/Core 覆盖最近通用目录、根目录、跳过父消费者、目录与工作区默认变化、显式 Run 优先和禁止通用工具反向引用;MacToolchainDiscoveryTests 与 lithe-project::defined_toolchain 的真实临时安装/注入探测验证运行前重读,不冻结安装路径。 本机目录/重载回归覆盖仅消费者偏好、父目录连接、重置撤回、链接/非法层级拒绝、单次重试与可刷新错误、未修改表单更新、冲突草稿保留及自身保存通知不等待/撤销保存。该集成不代替完整 GUI。 运行前来源审计 missingPreferenceLeafBehindAParentAliasIsRejectedBeforeToolWork 覆盖两级父目录及存在/悬空链接,四种情况均在工具探测前拒绝。 ToolchainPluginAdmissionTests 使用正式契约 fixture 与真实 Core 验证市场可安装、完整安装审查、清单加载,以及无后端纯工具定义插件的启用模块和工厂登记;本地编译验证不代替真实 mise 与 Windows 工作流验收。 2026-11-02 本机 Swift 6.4.2:准入、后端、发现和加载器 42 项通过,新增两个准入用例分别 4/6 ms;Swift 6.3.3 在本机 Xcode 27.2 SDK 下编译依赖清单崩溃,不能作为固定工具链通过。真实 mise 0.2.1 发布包 SHA-256 与市场一致,Core 证明修复前 unsupported、修复后 available;真实后端完成协商、查询并停止销毁,当前环境未安装 mise,查询真实返回 miseNotFound,未验证安装列表和应用内工作流。 增补来源保存验收:不存在的 pin 重置不创建状态;拒绝逃出工作区的符号链接/junction;有界 UTF-8 与重复键、未知字段和 dormant pin 校验;Git 后续否定规则、换行/评论/权限保留;公开字节基线不可替代私有快照;已提交但回读失败必须重新加载后才能重试。 Viva 全局 SDK 页:运行 TestVisualSettings/33-settings-toolchains,使用 en、zh-Hans 和 dark/light 的生产无头窗口,核对无项目模式、自动实际值、多版本登记与全局默认选择。通过 run-go-tests-with-timing.mjs 记录单测试 HTML/JUnit;desktop-ci 的 macOS/Windows 每次上传四张图和计时报告。2026-11-15 本机 macOS 与 Windows 11 ARM64 来宾的 GNU x64 系统仿真均通过两个语言各 3 个计时结果,Windows 49 个 SDK/来源/诊断/资源定向用例通过;该证据不替代工具提供方与完整产品工作流验收,整体保持 partial/pending。 Windows #2042:TestToolchainCandidatesUseNativeShellPathsInUserProfiles 以真实 PATH 查找、真实有界版本进程和 Core 候选规则,覆盖 PATH-only/环境变量-only 及空格/中文用户目录;合成工具位于扫描目录之外,全局登记使用私有根。 通过现有 Windows CI 的 scripts/desktop/check.sh 运行;本机逐项计时报告覆盖这些合成场景,完整原生界面验收仍保持 pending。 2026-11-18(#2122):使用 dev.lithe.test.* 合成工具清单运行 TestUntrustedProjectEnvironmentNeverProbesWorkspaceExecutables、TestTrustedWorkspacePersistsInLocalSettingsOnlyAndResolvesSymlinkedVenv、TestTrustedWorkspaceResolvesSubdirectoryEnvironmentAndRejectsEscapingDirectories、TestProjectToolchainTrustSwitchGrantsAndRevokesImmediately 与 TestWorkbenchToolchainTrustPersistsLocallyLogsActionAndEnablesRuntimeResolution,验证未授权零探测、两跳符号链接虚拟环境字面路径保留、macOS 目录符号链接与 Windows 目录联接点指向外部时在探测前拒绝、本机 toolchains/global.json 原子保存与撤销(绝不写工作区 .lithe/)、performedIn 操作轨迹以及中英明暗无头截图 m47/m48;Windows 实机与完整原生 GUI 工作流保持 pending。", "notes": "Viva:共享 Core toolchain 命令已接入 desktop/internal/core/toolchain.go;声明式扫描、文件事实、有界版本探测、toolchains.candidates/resolve 与目录 pin 保存位于 desktop/internal/toolchain/ 并有真实 Core 测试;设置窗口 Build 页可按插件声明展示工具、生效值与来源,显式 Save/Reset 写 .lithe/toolchains/local.json,Cancel 不写;Build 命令和 Provider Run 的 toolchain 候选使用 Core 解析出的可执行文件、环境导出和 PATH。提供方后端查询(toolchainProviders)未接入,因此未声明该能力;Windows 与完整 GUI/原生工作流未验收,状态保持 pending,legacy 证据不代表 Viva。 本轮通过外部 Core Draft PR #3 的精确提交接入 toolchains.editPins:平台不再编辑 pin schema;Core/Go 共用 fixture、批量保存和取消/外部并发修改回归通过。命令型 Tests 同样消费解析后的工具链环境。原生 Windows、提供方工具查询、完整 GUI 与发行验收仍 pending。 Windows 原生回归确认保存前后的文件模式以及真实访问控制描述符(所有者、组、DACL/继承保护)保留;元数据先准备到临时文件,再核对取消/冲突并原子发布。此证据不代表提供方查询或 GUI 已验收。 Viva 设置保存前核对读取项目的原生目录身份;项目关闭或切换后旧草稿拒绝写入,已确认保存的发布与回读固定捕获来源。冲突通过共享 i18n 显示并保留草稿,加载/保存失败进入目录日志;macOS 先失败后通过的回归已有计时,新增作用域行为的 Windows 验收尚未执行。 Windows 原生探测统一 Core 正斜杠路径与本机反斜杠/大小写别名,防止重复事实使目录 pin 解析遭拒绝;选择与校验规则仍由原有 Core 决定。 全局 SDK 登记与默认值可在未打开项目时编辑;项目范围保留独立覆盖,读取不创建文件,确认保存后按实际探测回显。新增合成工具原生与无头测试,不改变历史完整验收状态。 Viva 2026-11-16:Build 页每个工具改为一个下拉框,默认回显当前选择(未固定时为“自动(实际目录)”),列出识别到的其他安装、已保存固定值和已校验目录;选“自定义…”才显示目录输入、浏览和“使用此目录”,校验通过后该目录成为列表项并被选中。无版本的安装不可选,在列表下以说明文字列出。自动化:TestToolchainListShowsAutomaticAndHidesTheDirectoryUntilCustom 及原有草稿/保存/冲突用例;截图 TestVisualSettings/33-settings-toolchains、m44-toolchain-directory-menu、m45-toolchain-custom-directory。原生验收仍 pending。 Viva 2026-11-16(#2032):toolchains.candidates 改为同时接收宿主找到的 PATH 命令所在目录(commandHomes),JAVA_HOME 等声明变量和 PATH 上的安装校验通过后以 host:shell 并入安装列表并按规范目录去重,新建项目的工具选择、设置页和运行配置因此能选到只配置在 PATH 或环境变量上的 JDK;自动层的选择不变。Core 回归 toolchain_candidates_offer_shell_homes_that_no_discovery_scan_covers(Lithe-core-rust#67),宿主回归 TestShellHomesAreInstallationsWithoutADiscoveryScan;两者都确认修复前失败。Windows 0.8.0 实机复现了缺陷,修复后的完整 Windows 客户端尚未实机验收,状态保持 pending。 Viva 2026-11-18(#2122):prepareTool 沿工作区祖先链观测 discoveryPlan 返回的 projectFiles、requires、home、中间父目录、pathPrepend 及软链目标;probeAll 在 ProjectCodeAllowed 为 false 时拒绝探测任何工作区内可执行文件;本机信任记录经 Core catalogState/editCatalog 保存在应用用户设置目录 toolchains/global.json,设置页项目作用域提供带 ⓘ 说明的显式信任开关并立即回读生效值,工作台 resolveToolchainSelection 同步读取同一本机信任状态。 Viva 2026-11-18(构建设置重构):工具链页按 docs/design/build-execution-settings.html 重做为“全局默认 / 当前项目”两个作用域、按类别或插件分组、需处理与已手动指定过滤,列表与详情两栏;详情显示当前生效的程序、版本与来源标签和安装列表(自动、发现的安装、手动目录),项目作用域在未信任时显示信任提示。筛选、分组和计数由 Core 设置投影(Lithe-core-rust#99)给出,一个插件可以注册多个 SDK。固定值本身不再算一个来源标签,只有其目录不在其他来源中时才标出提供方。自动化:toolchains_view_test.go、TestVisualSettings 的 33、m44–m49 场景。原生与 Windows 验收仍 pending。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", From 25d1401845481c83cd271508af069c922f55be7c Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 12:21:38 +0800 Subject: [PATCH 8/8] test(pluginhost): expect managed runtime mirror capability --- desktop/internal/pluginhost/pluginhost_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 4e0b95e17a..b43c8c2647 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -83,6 +83,10 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { if name == "toolDefinitions" { wanted = []int{0, 1} } + // Managed runtime artifacts can use the mirror URLs version 1 adds. + if name == "managedRuntimes" { + wanted = []int{0, 1} + } if versions := declared[name]; !slices.Equal(versions, wanted) { t.Fatalf("%s = %v, want %v", name, versions, wanted) }