diff --git a/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md b/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md index 64cd3cb03..c8e88172c 100644 --- a/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md +++ b/.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md @@ -2,7 +2,7 @@ 状态:已实现 -> Viva 迁移状态:下文的编辑器接线(动作、Provider 与语法注册)原先属于旧的 Web 编辑器宿主,现已不再适用。当前锁定的 Core 契约使用 `languages:3` TextMate;Viva 只有静态语法解码桥接和共享样例验证,插件安装、编辑器注册及动作/Provider 宿主均未接入。下文的契约、权限隔离、版本检查与不透明链接限制仍是 Viva 的验收要求。 +> Viva 迁移状态:当前 Viva 宿主已接通插件静态语法、编辑器动作,以及跳转、悬浮、补全、CodeLens、语义着色、文档链接和前景着色提供者。折叠提供者尚未路由。前景着色随 Core #188 合入,宿主通过固定修订声明该能力。下文旧 Web 编辑器的具体呈现方式仅供历史对照。公共参数、版本和能力以 Core 仓库当前契约为准。 ## 先说结论 @@ -73,13 +73,32 @@ Core 校验资源大小、状态和规则,并拒绝 include 环及展开后超 正确做法:一个“资源 key 在模板和 `.properties` 之间跳转”的插件注册 `definition`、`hover`、`completion` 三个函数,选择器写 `html` 和 `properties`;语言服务器照常提供模板的普通跳转,插件补上 key 的跳转。 不要这样做:在宿主里按语言名加分支,或让插件返回 `command:` 链接让界面去执行。 + +### 独立前景颜色范围与语言服务共存 + +颜色范围使用独立的 `colorDecorations` 提供者。它描述“这段文字使用哪个主题颜色”,不冒充变量、类或其他语言语义类别。插件通过现有 `editor/registerProviders` 注册,同一个文件可以接受多个颜色来源;语法和语言服务器仍独立回答原有的语义着色。 + +Core 校验颜色表、单行 UTF-16 范围(列以 Unicode 的 UTF-16 编码单元计数)和结果上限,并按稳定的来源标识决定重叠优先级。较早的来源保留前景色,后面的范围只覆盖尚未着色的部分。宿主只在后台把这些位置转换成绘制需要的 UTF-8 字节偏移,不再实现第二份排序、裁切或预算规则。调用期限读取 Core 校验后返回的预算;宿主另外限制同时进行的原生调用数量。 + +绘制时先保留语法与语义着色的字体样式,再用独立范围替换前景色。选区背景、诊断下划线、内联提示、光标和背景主题保留各自的层级。每个颜色同时提供明、暗主题值,切换主题无需重新调用插件。正确做法:两个语义无关的插件都返回同一种范围和颜色标识,由 Core 合并。不要这样做:为了得到多种颜色,把范围伪装成不同的内置语义 token 类型,或在宿主判断某个插件名后改变样式。 + +每个打开文档只保留当前颜色结果、一次缓存的提供者查询和一个可取消请求。颜色范围以文档绝对字节偏移和颜色表下标保存,同一对明暗颜色只解析一次,所以彩虹括号这类少量颜色循环覆盖上万个括号的结果,每个范围只占 12 字节。 + +编辑、撤销、重做和后台准备的批量编辑会把编辑点之后的范围整体平移,删除被编辑切开或替换的范围,编辑点之前的范围原样保留。这样在括号前打字时,括号颜色跟着文字走,直到插件对新文本给出答案再整体替换,而不是每次按键都先清空、再在停顿后闪回。平移只遍历编辑点之后的范围,上限是 Core 的 10,000 个。磁盘重新加载替换整个文本,会直接清空。 + +按键只重新开始一次 250 ms 的停顿计时:不查询提供者,不创建后台任务,也不清空颜色。停顿结束后才创建可取消请求。提供者是否服务该文档按路径、语言和颜色提供者注册变化缓存;提供者注册或撤回、文档改名或换语言时,会重新查询并立即清空旧颜色。每次计划、撤销请求都会递增代数,过期计时器和过期答案直接丢弃;答案应用前还会核对文档版本。提供者撤回、插件停止和文档关闭会取消请求并清空颜色;旧会话释放前,重启的后端可以重新注册相同标识。 + +绘制时,每个可见行用二分查找取出本行范围,再按语法片段和颜色边界分段解析样式,不逐字符查找,不逐帧解析颜色,也不复制文档。 + +工作区打开早于后端初始化时,首次上下文通知可能没有接收者。因此宿主在按需启动的后端准备好后补发当前上下文修订,并与后续通知按会话和修订去重、串行发送。初始化期间出现的工作区变化会体现在这次最新修订中;不增加后台轮询。 + ## 考虑过的备选方案 - 要求工具插件提供 LSP:标准化但无必要地强加语言服务生命周期,拒绝。 - 专用 `runMarkers` 和 `didRun.runMarker`:把展示和执行耦合,新增一种动作就扩张执行通知,拒绝。 - 函数名约定或插件名分支:宿主猜私有协议且无法安全撤回,拒绝。 - 让工具插件把 Provider 注册成一个语言服务器:强加服务器生命周期和文档同步,而且无法表达“只补充”,拒绝。 -- 让插件的答案覆盖语言服务器:会让一个补充性的小插件破坏上游语言能力,拒绝。 +- 让插件的语言功能答案覆盖语言服务器:会破坏上游语言能力,拒绝;前景颜色覆盖则是明确授权的独立呈现层,不替换语义身份或样式。 - 把插件返回的 URL 或命令直接交给编辑器:`command:` 链接会被执行,拒绝;页面只持有不透明键。 - 为测试标记新增测试专用契约:测试发现和运行已经是既有契约的职责,编辑器只需要多种图标,拒绝。 - 允许插件提供自己的图标 SVG 或 CSS:等于向编辑器注入界面,拒绝;改为宿主声明图标表。 @@ -93,13 +112,17 @@ Provider 通道额外增加一个权限(`editor.providers`)、每次触发 ## 验证 +- `scripts/desktop/desktop-go.sh test -tags vivahead ./internal/pluginservice ./internal/workbench ./internal/editorview -run 'TestColor|TestWorkspaceBackendReceives'`:合成提供者注册、Core 合并、撤回、后端重启、首次上下文通知、过期结果、主题与零分配绘制。 +- `scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualColorDecorations$'`:设置 `LITHE_VISUAL_OUTPUT_DIR` 后生成明暗主题、中英文的实际工作台前后 PNG;这个合成来源场景不替代插件仓库的真实安装和日志验收。 +- `scripts/desktop/perf/editor-bench.sh`:相同机器与规模的改动前后对比,不通过放宽预算掩盖回归。 + - `scripts/desktop/desktop-go.sh test ./internal/core -run '^TestPluginTextMateGrammarUsesPinnedCore$'`:共享语法样例经锁定 Core 解码;不证明插件安装和编辑器注册。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:发行路径只读静态边界。 - `scripts/platform-feature-matrix/verify-platform-feature-matrix.sh`:功能矩阵 `plugin-editor-providers.json`、`plugin-editor-grammars.json` 记录待验收项。 ## 适用范围 -- Core 实现的语法、编辑器动作与语言功能([锁定修订](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/0ffd327b4329261e393b08ed76fbd134b4dd17e9/rust/lithe-core/src/plugins)) +- Core 实现的编辑器动作与语言功能([锁定修订](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/c6cef0b9f63024f99cfc447dbf205e05893f7597/rust/crates/plugin-editor)) - `desktop/internal/core/plugin_session.go` - `desktop/internal/core/plugin_session_test.go` - `https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md` diff --git a/desktop/internal/core/editor_providers_test.go b/desktop/internal/core/editor_providers_test.go index 1c88b4942..0a83bd449 100644 --- a/desktop/internal/core/editor_providers_test.go +++ b/desktop/internal/core/editor_providers_test.go @@ -2,6 +2,7 @@ package core import ( "encoding/json" + "slices" "testing" ) @@ -11,9 +12,13 @@ import ( // refuse it under the same list. func TestEditorHostProviderTypesPassCoreRegistration(t *testing.T) { client, ctx := NewClient(), testContext(t) + if !slices.Contains(EditorHost.ProviderTypes, "colorDecorations") { + t.Fatal("the host must advertise colorDecorations with the pinned Core") + } options := map[string]map[string]any{ - "completion": {"function": "keys.completion", "triggerCharacters": []string{"."}}, - "semanticTokens": {"function": "keys.semanticTokens", "legend": map[string]any{"tokenTypes": []string{"property"}, "tokenModifiers": []string{}}}, + "colorDecorations": {"function": "keys.colors", "colorLegend": []map[string]string{{"id": "accent", "light": "#000000", "dark": "#FFFFFF"}}}, + "completion": {"function": "keys.completion", "triggerCharacters": []string{"."}}, + "semanticTokens": {"function": "keys.semanticTokens", "legend": map[string]any{"tokenTypes": []string{"property"}, "tokenModifiers": []string{}}}, } for _, kind := range EditorHost.ProviderTypes { provider, ok := options[kind] diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index 2f0885388..d80e50241 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -64,7 +64,7 @@ var EditorHost = EditorHostOptions{ "navigate-implemented", "navigate-implementing", "navigate-overridden", "navigate-overriding", }, ActionSourceBytes: 1024 * 1024, - ProviderTypes: []string{"definition", "hover", "completion", "codeLens", "semanticTokens", "documentLink"}, + ProviderTypes: []string{"definition", "hover", "completion", "codeLens", "semanticTokens", "colorDecorations", "documentLink"}, } // EditorActionDecodeVersion is the plugins.editorActions.decode request version EditorHost is diff --git a/desktop/internal/core/plugin_symbols.go b/desktop/internal/core/plugin_symbols.go index 5f7ff8175..39ce609a4 100644 --- a/desktop/internal/core/plugin_symbols.go +++ b/desktop/internal/core/plugin_symbols.go @@ -45,6 +45,35 @@ type SemanticTokens struct { Tokens []SemanticToken `json:"tokens"` } +// PluginColorLegendEntry is a stable color ID with its light- and dark-theme colors. +// Core validates each color against the provider's legend before returning it. +type PluginColorLegendEntry struct { + ID string `json:"id"` + Light string `json:"light"` + Dark string `json:"dark"` +} + +// PluginColorPosition is a zero-based LSP position with a UTF-16 character column. +type PluginColorPosition struct { + Line int `json:"line"` + Character int `json:"character"` +} + +// PluginColorRange is a half-open range in LSP UTF-16 coordinates. +type PluginColorRange struct { + Start PluginColorPosition `json:"start"` + End PluginColorPosition `json:"end"` +} + +// PluginColorDecoration is a Core-normalized foreground color for one document range. +type PluginColorDecoration struct { + SourceID string `json:"sourceId"` + ColorID string `json:"colorId"` + Light string `json:"light"` + Dark string `json:"dark"` + Range PluginColorRange `json:"range"` +} + // PluginSemanticTokens decodes a completed semanticTokens event. func PluginSemanticTokens(event BackendEvent) (SemanticTokens, error) { var tokens SemanticTokens diff --git a/desktop/internal/editorview/color_decorations.go b/desktop/internal/editorview/color_decorations.go new file mode 100644 index 000000000..6c538cda2 --- /dev/null +++ b/desktop/internal/editorview/color_decorations.go @@ -0,0 +1,192 @@ +package editorview + +import ( + "math" + "slices" + "sort" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" + "github.com/vivaui/viva/gfx" +) + +// ColorDecoration is a provider's foreground override for a half-open LSP range. +// The range is in zero-based lines and UTF-16 columns; colors are #RRGGBB strings. +type ColorDecoration struct { + StartLine, StartCharacter int + EndLine, EndCharacter int + SourceID string + Light, Dark string +} + +// colorDecorationSpan is one provider color over the bytes [start, end) of the text. The offsets +// are absolute, so an edit moves every span after it by one addition and no line has to be found +// again, and the colors are an index into the palette, so the 10,000 brackets of a rainbow cycling +// through a few colors keep a few pairs of colors and 12 bytes per bracket. +type colorDecorationSpan struct { + start, end uint32 + color uint32 +} + +// colorPair is a provider color as the light and as the dark theme draw it. +type colorPair struct{ light, dark gfx.Color } + +// PreparedColorDecorations is a bounded foreground overlay tied to the immutable text it names. +type PreparedColorDecorations struct { + text rope.Rope + spans []colorDecorationSpan + palette []colorPair +} + +// PrepareColorDecorations converts UTF-16 ranges to byte offsets and parses each distinct pair of +// colors once, away from the window thread. Core sorts the ranges and makes them disjoint; ranges +// that break that order, malformed colors and stale coordinates are ignored defensively, so the +// spans the view paints from are always sorted and disjoint. +func PrepareColorDecorations(text rope.Rope, decorations []ColorDecoration) PreparedColorDecorations { + prepared := PreparedColorDecorations{text: text} + if len(decorations) == 0 || text.Len() > math.MaxUint32 { + return prepared + } + type colorKey struct{ light, dark string } + const invalid = math.MaxUint32 + palette := make(map[colorKey]uint32) + prepared.spans = make([]colorDecorationSpan, 0, len(decorations)) + line, lineStart := -1, 0 + lineText := "" + byteColumn, utf16Column := 0, 0 + for _, decoration := range decorations { + if decoration.StartLine != decoration.EndLine || decoration.StartLine < max(line, 0) || decoration.StartLine >= text.LineCount() { + continue + } + if line != decoration.StartLine { + line = decoration.StartLine + lineStart = text.LineStart(line) + end := text.LineEnd(line) + if end > lineStart && text.ByteAt(end-1) == '\r' { + end-- + } + lineText, _ = text.Substring(lineStart, end) + byteColumn, utf16Column = 0, 0 + } + start, startOK := colorDecorationByteColumn(lineText, decoration.StartCharacter, &byteColumn, &utf16Column) + end, endOK := colorDecorationByteColumn(lineText, decoration.EndCharacter, &byteColumn, &utf16Column) + if !startOK || !endOK || end <= start { + continue + } + key := colorKey{decoration.Light, decoration.Dark} + color, seen := palette[key] + if !seen { + light, lightOK := syntax.ParseColor(decoration.Light) + dark, darkOK := syntax.ParseColor(decoration.Dark) + color = invalid + if lightOK && darkOK { + color = uint32(len(prepared.palette)) + prepared.palette = append(prepared.palette, colorPair{light: uiColor(light), dark: uiColor(dark)}) + } + palette[key] = color + } + if color == invalid { + continue + } + prepared.spans = append(prepared.spans, colorDecorationSpan{ + start: uint32(lineStart + start), end: uint32(lineStart + end), color: color, + }) + } + return prepared +} + +// colorDecorationByteColumn advances across one line once for Core's ordered disjoint ranges. +func colorDecorationByteColumn(text string, target int, byteColumn, utf16Column *int) (int, bool) { + if target < *utf16Column { + return 0, false + } + for *utf16Column < target && *byteColumn < len(text) { + r, size := utf8.DecodeRuneInString(text[*byteColumn:]) + units := 1 + if r > 0xffff { + units = 2 + } + if *utf16Column+units > target { + return 0, false + } + *byteColumn += size + *utf16Column += units + } + return *byteColumn, *utf16Column == target +} + +// SetPreparedColorDecorations applies ranges only when they were prepared for the live text, and +// the view owns them from then on. Painting reads the sorted byte spans of the visible lines and +// performs no color conversion. +func (v *View) SetPreparedColorDecorations(prepared PreparedColorDecorations) bool { + if !v.text.Same(prepared.text) { + return false + } + v.decor.colors, v.decor.colorPalette = prepared.spans, prepared.palette + v.decor.colorLine = nil + if v.cfg.Notify != nil { + v.cfg.Notify() + } + return true +} + +// ClearColorDecorations removes foreground overrides when their provider is withdrawn. +func (v *View) ClearColorDecorations() { + if len(v.decor.colors) == 0 { + return + } + v.clearColors() + if v.cfg.Notify != nil { + v.cfg.Notify() + } +} + +// clearColors forgets the provider colors, as a replacement of the whole text does. +func (v *View) clearColors() { + v.decor.colors, v.decor.colorPalette, v.decor.colorLine = nil, nil, nil +} + +// shiftColors keeps the provider colors on the characters they colored when the bytes +// [start, oldEnd) are replaced by newEnd-start bytes, until the provider answers for the new +// text: a span before the edit stays, a span after it moves by the edit's length, and a span the +// edit cuts or replaces goes, because what it colored changed. Typing in front of a bracket thus +// carries the bracket's color along instead of showing every bracket uncolored until the answer. +// It costs the spans after the edit, which Core bounds at 10,000. +func (v *View) shiftColors(start, oldEnd, newEnd int) { + colors := v.decor.colors + if len(colors) == 0 { + return + } + v.decor.colorLine = nil + if v.text.Len() > math.MaxUint32 { + v.clearColors() + return + } + // The spans are sorted and disjoint, so their ends are sorted too: first is the first span + // that reaches past start and last the first that starts at or after the replaced bytes. An + // insertion strictly inside a span cuts it, and one at a span's start moves it. + first := sort.Search(len(colors), func(i int) bool { return int(colors[i].end) > start }) + last := first + sort.Search(len(colors)-first, func(i int) bool { return int(colors[first+i].start) >= oldEnd }) + colors = slices.Delete(colors, first, last) + if delta := newEnd - oldEnd; delta != 0 { + for i := first; i < len(colors); i++ { + colors[i].start = uint32(int(colors[i].start) + delta) + colors[i].end = uint32(int(colors[i].end) + delta) + } + } + if len(colors) == 0 { + v.clearColors() + return + } + v.decor.colors = colors +} + +// lineColors is the provider colors of the line whose bytes are [start, end), found by binary +// search so that a frame's cost does not grow with the colors of lines it does not show. +func (v *View) lineColors(start, end int) []colorDecorationSpan { + colors := v.decor.colors + first := sort.Search(len(colors), func(i int) bool { return int(colors[i].start) >= start }) + last := first + sort.Search(len(colors)-first, func(i int) bool { return int(colors[first+i].start) >= end }) + return colors[first:last] +} diff --git a/desktop/internal/editorview/color_decorations_test.go b/desktop/internal/editorview/color_decorations_test.go new file mode 100644 index 000000000..0ddcfb0ca --- /dev/null +++ b/desktop/internal/editorview/color_decorations_test.go @@ -0,0 +1,195 @@ +package editorview + +import ( + "slices" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" + "github.com/vivaui/viva/gfx" +) + +func textInColor(canvas *gfx.Canvas, color gfx.Color) string { + var out strings.Builder + for _, label := range canvas.Texts() { + at := 0 + for _, run := range canvas.TextRuns(label) { + end := at + int(run.Bytes) + if run.Color == color { + out.WriteString(label.Value[at:end]) + } + at = end + } + } + return out.String() +} + +// Color ranges override foreground only. LSP token identity, style, selection backgrounds, +// another line's colors, and theme changes keep their independent rendering behavior. +func TestColorDecorationsComposeWithSemanticTokensAndThemes(t *testing.T) { + v := newTestView(t, "header\nfirst second") + text := v.TextSnapshot() + legend := syntax.NewSemanticLegend([]string{"class"}, []string{"deprecated"}) + v.SetSemantic(text, legend, []syntax.SemanticToken{{Line: 1, StartChar: 0, Length: 12, Modifiers: 1}}) + prepared := PrepareColorDecorations(text, []ColorDecoration{{StartLine: 1, StartCharacter: 0, EndLine: 1, EndCharacter: 5, Light: "#C00050", Dark: "#FF80B0"}}) + if !v.SetPreparedColorDecorations(prepared) { + t.Fatal("current text was rejected") + } + v.SetSelection(len("header\n"), len("header\nfirst")) + canvas := new(gfx.Canvas) + area := gfx.Rect{Width: 600, Height: 220} + for _, dark := range []bool{false, true} { + canvas.Reset() + selection := gfx.RGB24(0xABCDEF) + v.Paint(canvas, area, Look{Dark: dark, Selection: selection}) + wantColor := gfx.RGB24(0xC00050) + if dark { + wantColor = gfx.RGB24(0xFF80B0) + } + if got := textInColor(canvas, wantColor); got != "first" { + t.Fatalf("dark=%t decorated text=%q, want first on line 1", dark, got) + } + if len(fills(canvas, selection)) != 1 { + t.Fatal("foreground decoration changed the selection background") + } + for _, label := range canvas.Texts() { + for _, run := range canvas.TextRuns(label) { + if run.Color == wantColor && !run.Strike { + t.Fatal("foreground decoration removed the semantic strikethrough") + } + } + } + } + if got := v.SyntaxLine(nil, 1); len(got) == 0 || got[0].Name.String() != "class.deprecated" { + t.Fatalf("decoration replaced LSP semantic identity: %v", got) + } + v.ClearColorDecorations() + canvas.Reset() + v.Paint(canvas, area, Look{}) + if textInColor(canvas, gfx.RGB24(0xC00050)) != "" { + t.Fatal("cleared provider colors remained visible") + } +} + +// colorSpans is the view's provider colors as byte ranges of its text, in order. +func colorSpans(v *View) [][2]int { + var spans [][2]int + for _, span := range v.decor.colors { + spans = append(spans, [2]int{int(span.start), int(span.end)}) + } + return spans +} + +func requireColorSpans(t *testing.T, v *View, what string, want ...[2]int) { + t.Helper() + if got := colorSpans(v); !slices.Equal(got, want) { + t.Fatalf("%s: colors cover %v, want %v", what, got, want) + } +} + +func TestColorDecorationsConvertUTF16OnceAndShareColors(t *testing.T) { + v := newTestView(t, "😀a\r\n界b") + decorations := []ColorDecoration{ + {StartLine: 0, StartCharacter: 2, EndLine: 0, EndCharacter: 3, Light: "#112233", Dark: "#445566"}, + {StartLine: 1, StartCharacter: 1, EndLine: 1, EndCharacter: 2, Light: "#112233", Dark: "#445566"}, + } + prepared := PrepareColorDecorations(v.TextSnapshot(), decorations) + if !v.SetPreparedColorDecorations(prepared) { + t.Fatal("current text was rejected") + } + requireColorSpans(t, v, "UTF-16 columns", [2]int{len("😀"), len("😀a")}, [2]int{len("😀a\r\n界"), len("😀a\r\n界b")}) + if len(v.decor.colorPalette) != 1 { + t.Fatalf("two ranges of one color keep %d palette entries, want 1", len(v.decor.colorPalette)) + } + bad := PrepareColorDecorations(rope.FromString("😀"), []ColorDecoration{{StartLine: 0, StartCharacter: 1, EndLine: 0, EndCharacter: 2, Light: "#112233", Dark: "#445566"}}) + if len(bad.spans) != 0 { + t.Fatal("a range cut a surrogate pair") + } + unordered := PrepareColorDecorations(rope.FromString("ab\ncd"), []ColorDecoration{ + {StartLine: 1, StartCharacter: 0, EndLine: 1, EndCharacter: 1, Light: "#112233", Dark: "#445566"}, + {StartLine: 0, StartCharacter: 0, EndLine: 0, EndCharacter: 1, Light: "#112233", Dark: "#445566"}, + {StartLine: 1, StartCharacter: 1, EndLine: 1, EndCharacter: 2, Light: "not a color", Dark: "#445566"}, + }) + if len(unordered.spans) != 1 || unordered.spans[0].start != 3 { + t.Fatalf("an out-of-order range or a malformed color was kept: %+v", unordered.spans) + } +} + +// An edit moves the colors after it and drops only the ones it touches, so a rainbow keeps its +// colors while the provider computes the next answer. Undo and redo move them back and forth. +func TestColorDecorationsFollowEditsUndoAndRedo(t *testing.T) { + v := newTestView(t, "(a) [bc]") + color := func(start, end int) ColorDecoration { + return ColorDecoration{StartLine: 0, StartCharacter: start, EndLine: 0, EndCharacter: end, Light: "#112233", Dark: "#445566"} + } + prepared := PrepareColorDecorations(v.TextSnapshot(), []ColorDecoration{color(0, 1), color(2, 3), color(4, 5), color(5, 7), color(7, 8)}) + v.SetPreparedColorDecorations(prepared) + v.edit(0, 0, "xy", editOther) + requireColorSpans(t, v, "insertion before every span", [2]int{2, 3}, [2]int{4, 5}, [2]int{6, 7}, [2]int{7, 9}, [2]int{9, 10}) + if v.SetPreparedColorDecorations(prepared) { + t.Fatal("colors prepared for the old text were accepted") + } + if !v.Undo() { + t.Fatal("nothing to undo") + } + requireColorSpans(t, v, "undo", [2]int{0, 1}, [2]int{2, 3}, [2]int{4, 5}, [2]int{5, 7}, [2]int{7, 8}) + if !v.Redo() { + t.Fatal("nothing to redo") + } + requireColorSpans(t, v, "redo", [2]int{2, 3}, [2]int{4, 5}, [2]int{6, 7}, [2]int{7, 9}, [2]int{9, 10}) + // Typing at the end of a span or at the start of the next keeps both; typing inside one cuts it. + v.edit(3, 3, "z", editOther) + requireColorSpans(t, v, "insertion between two spans", [2]int{2, 3}, [2]int{5, 6}, [2]int{7, 8}, [2]int{8, 10}, [2]int{10, 11}) + v.edit(9, 9, "q", editOther) + requireColorSpans(t, v, "insertion inside a span", [2]int{2, 3}, [2]int{5, 6}, [2]int{7, 8}, [2]int{11, 12}) + // Deleting a bracket drops its color and moves the rest back. + v.edit(5, 6, "", editOther) + requireColorSpans(t, v, "deleted span", [2]int{2, 3}, [2]int{6, 7}, [2]int{10, 11}) + v.edit(0, v.text.Len(), "", editOther) + if v.decor.colors != nil || v.decor.colorPalette != nil { + t.Fatal("deleting every colored character kept the palette") + } +} + +// A prepared replacement, such as formatting, moves the colors outside what it changed; a reload +// from disk replaces the whole text and clears them until the provider answers for it. +func TestColorDecorationsFollowPreparedEditsAndClearOnReload(t *testing.T) { + v := newTestView(t, "f(x) g(y)") + color := func(start, end int) ColorDecoration { + return ColorDecoration{StartLine: 0, StartCharacter: start, EndLine: 0, EndCharacter: end, Light: "#112233", Dark: "#445566"} + } + v.SetPreparedColorDecorations(PrepareColorDecorations(v.TextSnapshot(), []ColorDecoration{color(1, 2), color(3, 4), color(6, 7), color(8, 9)})) + prepared, err := PrepareEdits(v.TextSnapshot(), v.SavedSnapshot(), []TextEdit{{Range{4, 5}, "\n\t"}}) + if err != nil { + t.Fatal(err) + } + if !v.ApplyPreparedEdit(prepared) { + t.Fatal("the prepared edit was refused") + } + requireColorSpans(t, v, "prepared edit", [2]int{1, 2}, [2]int{3, 4}, [2]int{7, 8}, [2]int{9, 10}) + clean := newTestView(t, "f(x)") + clean.SetPreparedColorDecorations(PrepareColorDecorations(clean.TextSnapshot(), []ColorDecoration{color(1, 2), color(3, 4)})) + if !clean.Reload(Prepare([]byte("other(text)"))) { + t.Fatal("reload was refused") + } + if len(clean.decor.colors) != 0 { + t.Fatal("reload kept the colors of the replaced text") + } +} + +func TestColorDecorationPaintDoesNotAllocate(t *testing.T) { + v := newTestView(t, "first second\nthird fourth") + v.hl.Close() + v.SetPreparedColorDecorations(PrepareColorDecorations(v.TextSnapshot(), []ColorDecoration{ + {StartLine: 0, StartCharacter: 0, EndLine: 0, EndCharacter: 5, Light: "#112233", Dark: "#445566"}, + {StartLine: 1, StartCharacter: 6, EndLine: 1, EndCharacter: 12, Light: "#445566", Dark: "#112233"}, + })) + canvas := new(gfx.Canvas) + area := gfx.Rect{Width: 600, Height: 220} + paint := func() { canvas.Reset(); v.Paint(canvas, area, Look{}) } + paint() + if allocs := testing.AllocsPerRun(20, paint); allocs != 0 { + t.Fatalf("warm decoration paint allocated %v times", allocs) + } +} diff --git a/desktop/internal/editorview/diffdecor.go b/desktop/internal/editorview/diffdecor.go index d6fdbafd6..a7df6b924 100644 --- a/desktop/internal/editorview/diffdecor.go +++ b/desktop/internal/editorview/diffdecor.go @@ -49,6 +49,14 @@ type decorState struct { maxEnd []int // inline is the inline highlights in cells, sorted by line. inline []inlineSpan + // colors are the provider foreground overrides, prepared off-thread, sorted and disjoint by + // absolute byte offset; colorPalette holds the light and dark colors they index. colorLine + // is the colors of the line being painted, and colorBase that line's first byte, valid only + // within Paint. + colors []colorDecorationSpan + colorPalette []colorPair + colorLine []colorDecorationSpan + colorBase int // labelled says labels replace the line numbers, and labelCells is the widest of them. labelled bool labels []string diff --git a/desktop/internal/editorview/paint.go b/desktop/internal/editorview/paint.go index 420bc854b..f22a8b566 100644 --- a/desktop/internal/editorview/paint.go +++ b/desktop/internal/editorview/paint.go @@ -134,6 +134,10 @@ 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) + v.decor.colorLine = nil + if len(v.decor.colors) > 0 { + v.decor.colorLine, v.decor.colorBase = v.lineColors(l.start, l.start+l.size), l.start + } lineHints := v.lineInlayHints(line) for k, row := range wraps { y := top + float32(k)*v.lineH @@ -439,6 +443,17 @@ func (v *View) paintRow(canvas *gfx.Canvas, text string, base int, row wrapRow, // labelEnd the column after its last character; labelAt and labelTo are the bytes of the // line it shows. label, labelEnd, labelAt, labelTo := -1, 0, base, base + // colors are the provider colors of the line, and colorAt the first that ends after the row's + // start; their offsets are the text's, base of the line's. + colors, colorBase := v.decor.colorLine, v.decor.colorBase + colorAt := 0 + if len(colors) > 0 { + colorAt = sort.Search(len(colors), func(i int) bool { return int(colors[i].end)-colorBase > row.at }) + } + // look is how the characters up to lookEnd draw: lookEnd is the next byte where a token or a + // provider color starts or ends, so the style is resolved once per span, not per character. + var look runLook + lookEnd := -1 for i := row.at; i < stop; { at := i r, size := utf8.DecodeRuneInString(text[i-base:]) @@ -468,19 +483,10 @@ func (v *View) paintRow(canvas *gfx.Canvas, text string, base int, row wrapRow, v.paintLabel(canvas, text[labelAt-base:labelTo-base], label, labelEnd, shift, y, textStyle) label, labelAt, labelTo, run = cells, at, at, -1 } - for token+1 < len(v.tokens) && int(v.tokens[token+1].Start) <= at { - token++ - } - style := defaultStyle - if token < len(v.tokens) { - style = v.theme.Style(v.tokens[token].Name) - } - color := uiColor(style.Foreground) - weight := float32(0) - if style.Font&syntax.Bold != 0 { - weight = gfx.WeightBold + if at >= lookEnd { + look, lookEnd, token, colorAt = v.runLookAt(at, token, colors, colorAt, defaultStyle) } - italic := style.Font&syntax.Italic != 0 + color, weight, italic := look.color, look.weight, look.italic ascii := r < 0x80 if ascii && runASCII && run >= 0 && v.runs[run].Color == color && v.runs[run].Weight == weight && v.runs[run].Italic == italic { @@ -497,8 +503,7 @@ func (v *View) paintRow(canvas *gfx.Canvas, text string, base int, row wrapRow, } v.runs = append(v.runs, gfx.TextRun{ Column: int32(cells - label), Bytes: int32(bytes), Cells: int32(width), - Color: color, Weight: weight, Italic: italic, Underline: style.Font&syntax.Underline != 0, - Strike: style.Font&syntax.Strikethrough != 0, + Color: color, Weight: weight, Italic: italic, Underline: look.underline, Strike: look.strike, }) run, runASCII = len(v.runs)-1, ascii } @@ -512,6 +517,54 @@ func (v *View) paintRow(canvas *gfx.Canvas, text string, base int, row wrapRow, v.paintLabel(canvas, text[labelAt-base:labelTo-base], label, labelEnd, shift, y, textStyle) } +// runLook is how one span of a row draws: its token's style with a provider's color laid over. +type runLook struct { + color gfx.Color + weight float32 + italic, underline, strike bool +} + +// runLookAt resolves the look of the character at byte at of the line and the byte where it next +// changes. token and colorAt only move forward, as the row's characters do. +func (v *View) runLookAt(at, token int, colors []colorDecorationSpan, colorAt int, defaultStyle syntax.Style) (runLook, int, int, int) { + for token+1 < len(v.tokens) && int(v.tokens[token+1].Start) <= at { + token++ + } + style := defaultStyle + if token < len(v.tokens) { + style = v.theme.Style(v.tokens[token].Name) + } + end := math.MaxInt + if token+1 < len(v.tokens) { + end = int(v.tokens[token+1].Start) + } + look := runLook{ + color: uiColor(style.Foreground), italic: style.Font&syntax.Italic != 0, + underline: style.Font&syntax.Underline != 0, strike: style.Font&syntax.Strikethrough != 0, + } + if style.Font&syntax.Bold != 0 { + look.weight = gfx.WeightBold + } + base := v.decor.colorBase + for colorAt < len(colors) && int(colors[colorAt].end)-base <= at { + colorAt++ + } + if colorAt < len(colors) { + span := colors[colorAt] + if start := int(span.start) - base; start <= at { + pair := v.decor.colorPalette[span.color] + look.color = pair.light + if v.themeDark { + look.color = pair.dark + } + end = min(end, int(span.end)-base) + } else { + end = min(end, start) + } + } + return look, end, token, colorAt +} + // replacementChar is what a byte that is not UTF-8 shows, as range over a string reads it. const replacementChar = "\uFFFD" diff --git a/desktop/internal/editorview/perf_bench_test.go b/desktop/internal/editorview/perf_bench_test.go index 5f9c65f64..718982b57 100644 --- a/desktop/internal/editorview/perf_bench_test.go +++ b/desktop/internal/editorview/perf_bench_test.go @@ -10,6 +10,7 @@ package editorview import ( "runtime" + "strings" "sync" "testing" @@ -165,6 +166,8 @@ var paintCases = []paintCase{ } v.SetMarkers(markers) }}, + // Provider colors on the brackets around the viewport, as a rainbow-bracket plugin sets them. + {name: "colors", kind: editorperf.Go, highlight: true, arrange: rainbowBrackets}, {name: "gutter", kind: editorperf.Go, highlight: true, arrange: func(v *View) { // What the Git integration sets: a change bar over every few lines of the viewport and // an annotation on each line, as a file full of blame has. The decorations and the @@ -182,6 +185,46 @@ var paintCases = []paintCase{ }}, } +// benchColorDecorations is the most provider colors Core sends for a document +// (MAX_MERGED_COLOR_DECORATIONS of its plugin-editor crate). +const benchColorDecorations = 10_000 + +// rainbowBrackets colors the brackets of the lines around the caret's, the most that Core sends, +// cycling three colors as a rainbow-bracket plugin does by nesting depth. Half of them are after +// the caret, so an edit there moves as many colors as a rainbow in a file that size moves. +func rainbowBrackets(v *View) { + palette := []string{"#C00050", "#0050C0", "#50A000"} + mid := v.text.LineOf(v.caret) + var before, after []ColorDecoration + bracketsOf := func(line int) []ColorDecoration { + var brackets []ColorDecoration + text, _ := v.text.Substring(v.text.LineStart(line), v.lineEnd(line)) + for column, r := range text { + if strings.ContainsRune("(){}[]", r) { + color := palette[(line+column)%len(palette)] + brackets = append(brackets, ColorDecoration{StartLine: line, StartCharacter: column, EndLine: line, EndCharacter: column + 1, Light: color, Dark: color}) + } + } + return brackets + } + for up, down := mid-1, mid; len(before)+len(after) < benchColorDecorations && (up >= 0 || down < v.text.LineCount()); up, down = up-1, down+1 { + if down < v.text.LineCount() { + after = append(after, bracketsOf(down)...) + } + if up >= 0 { + before = append(bracketsOf(up), before...) + } + } + decorations := append(before, after...) + if len(decorations) > benchColorDecorations { + trim := len(decorations) - benchColorDecorations + decorations = decorations[trim/2 : len(decorations)-(trim-trim/2)] + } + if !v.SetPreparedColorDecorations(PrepareColorDecorations(v.TextSnapshot(), decorations)) { + panic("colors were rejected") + } +} + // BenchmarkEditorViewPaint is one frame of a view that nothing has changed since its last, as the // window paints it for the caret to blink. It is the floor of every other benchmark here: the work // of a frame that shows the same text, at a size of file, in a language and in a mode of the view. @@ -222,6 +265,9 @@ var typeCases = []typeCase{ // A minified file with the minimap shown and soft wrap on: the minimap lays out the long line // again on every edit unless the view's rows of the line are kept. {name: "longline-wrap-minimap", kind: editorperf.JSON, layout: func(v *View) { v.SetWrap(true); v.SetMinimap(true) }}, + // Provider colors on the brackets around the caret: each keystroke moves the colors after it, + // so that they stay on their brackets until the provider answers for the new text. + {name: "colors", kind: editorperf.Go, layout: rainbowBrackets}, } // BenchmarkEditorViewType is a keystroke and the frame that shows it: a character typed at the end diff --git a/desktop/internal/editorview/prepared_edit.go b/desktop/internal/editorview/prepared_edit.go index 3f11f95b1..a6504e4a7 100644 --- a/desktop/internal/editorview/prepared_edit.go +++ b/desktop/internal/editorview/prepared_edit.go @@ -13,6 +13,9 @@ type PreparedEdit struct { dirty bool change Edit caret, widest int + // start, end and newEnd are the bytes of before the edits replace and where they end in + // after, as rope.Diff measured them on the worker. + start, end, newEnd int } // PrepareEdits must run off the UI thread. A bulk replacement builds its rope and @@ -42,6 +45,7 @@ func PrepareEdits(before, saved rope.Rope, edits []TextEdit) (PreparedEdit, erro prepared.after = before return prepared, nil } + prepared.start, prepared.end, prepared.newEnd = start, end, newEnd prepared.widest = widestLine(after, 0, after.LineCount()-1) text, _ := after.Substring(start, newEnd) prepared.change.Text = strings.Clone(text) @@ -79,6 +83,7 @@ func (v *View) ApplyPreparedEdit(prepared PreparedEdit) bool { v.revision++ v.clearCursorHistory() v.hl.SetText(v.text) + v.shiftColors(prepared.start, prepared.end, prepared.newEnd) v.forgetRows() v.anchor, v.caret = prepared.caret, prepared.caret v.lastKind, v.goal = editOther, -1 diff --git a/desktop/internal/editorview/view.go b/desktop/internal/editorview/view.go index 62183d0ce..16fb8997c 100644 --- a/desktop/internal/editorview/view.go +++ b/desktop/internal/editorview/view.go @@ -511,6 +511,7 @@ func (v *View) replaceFromDisk(content Content) bool { v.revision++ v.clearCursorHistory() v.hl.SetText(v.text) + v.clearColors() v.forgetRows() boundary := func(at int) int { at = min(max(at, 0), v.text.Len()) @@ -903,6 +904,7 @@ func (v *View) edit(start, end int, text string, kind editKind) { v.measureEdited(firstLine, newLast, adjusted, adjustedCells) v.keepStops(firstLine, oldLast, newLast, start-v.text.LineStart(firstLine)) v.hl.Edit(v.text, start, end, start+len(text)) + v.shiftColors(start, end, start+len(text)) v.spliceRows(firstLine, oldLast, newLast, oldCount) v.anchor, v.caret = start+len(text), start+len(text) if cacheEdit { @@ -999,6 +1001,7 @@ func (v *View) restore(s snapshot) { newLast := v.text.LineOf(newEnd) v.keepStops(firstLine, oldLast, newLast, start-v.text.LineStart(firstLine)) v.hl.Edit(v.text, start, oldEnd, newEnd) + v.shiftColors(start, oldEnd, newEnd) v.spliceRows(firstLine, oldLast, newLast, oldCount) v.anchor, v.caret = s.anchor, s.caret v.extra = slices.Clone(s.extra) diff --git a/desktop/internal/pluginservice/activation.go b/desktop/internal/pluginservice/activation.go index 5db39116d..e438bdc3a 100644 --- a/desktop/internal/pluginservice/activation.go +++ b/desktop/internal/pluginservice/activation.go @@ -15,6 +15,11 @@ import ( // workspace opens. const EventWorkspaceOpen = "onWorkspaceOpen" +type workspaceNotificationRevision struct { + sessionID string + revision uint64 +} + // relayDeclaration is the part of a manifest the cross-plugin relay needs. type relayDeclaration struct { PluginFunctions *struct { @@ -96,13 +101,30 @@ func (s *Service) activateWorkspace(ctx context.Context, snapshot InstalledSnaps if _, err := s.checkedWorkspaceContext(ctx, workspace); err != nil { return errors.Join(append(failures, err)...) } - if _, err := s.Host.EnsureBackend(ctx, entry.Installed.ID); err != nil { + if err := s.activateWorkspaceBackend(ctx, entry.Installed.ID, workspace); err != nil { failures = append(failures, fmt.Errorf("%s: %w", entry.Installed.ID, err)) } } return errors.Join(failures...) } +// activateWorkspaceBackend replays the current context revision after initialization. An open +// notification sent before this backend existed cannot bootstrap its workspace providers. +func (s *Service) activateWorkspaceBackend(ctx context.Context, pluginID string, workspace ContextRef) error { + if _, err := s.Host.EnsureBackend(ctx, pluginID); err != nil { + return err + } + if _, err := s.Host.Functions(ctx, pluginID); err != nil { + return err + } + if _, err := s.checkedWorkspaceContext(ctx, workspace); err != nil { + return err + } + s.contextsNotifyMu.Lock() + defer s.contextsNotifyMu.Unlock() + return s.notifyWorkspaceContextsLocked(ctx, pluginID, s.Contexts.Revision()) +} + // checkedWorkspaceContext never creates an owner on behalf of delayed work. // Closing and reopening a path invalidates the captured ID/generation even when // the new project's native root is identical. @@ -162,10 +184,58 @@ func (s *Service) contextsChanged() { go func() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() + s.contextsNotifyMu.Lock() + defer s.contextsNotifyMu.Unlock() if entries, err := s.Manager.Installed(); err == nil { _ = s.SyncFunctionRelay(ctx, entries) } - params, _ := json.Marshal(map[string]uint64{"revision": s.Contexts.Revision()}) - s.Host.NotifyAll(ctx, grantWorkspace, notifyDidChangeCtxs, params) + if err := s.notifyWorkspaceContextsLocked(ctx, "", s.Contexts.Revision()); err != nil && s.ContextIssue != nil { + s.ContextIssue(ctx, err) + } }() } + +// notifyWorkspaceContextsLocked sends the newest revision once to each ready backend session. +// Callers hold contextsNotifyMu so activation and simultaneous open/close notifications cannot +// be delivered out of order. A new backend session always starts with no delivered revision. +func (s *Service) notifyWorkspaceContextsLocked(ctx context.Context, onlyPlugin string, revision uint64) error { + if s.contextsNotified == nil { + s.contextsNotified = make(map[string]workspaceNotificationRevision) + } + params, err := json.Marshal(map[string]uint64{"revision": revision}) + if err != nil { + return err + } + ids := s.Host.RunningPlugins() + for pluginID := range s.contextsNotified { + if s.Host.Running(pluginID) == nil { + delete(s.contextsNotified, pluginID) + } + } + var failures []error + for _, pluginID := range ids { + if onlyPlugin != "" && pluginID != onlyPlugin { + continue + } + session := s.Host.Running(pluginID) + if session == nil || !session.granted(grantWorkspace) || !session.isReady() { + continue + } + last := s.contextsNotified[pluginID] + if last.sessionID == session.Session.ID && last.revision >= revision { + continue + } + delivered, err := s.Host.NotifyResult(ctx, pluginID, grantWorkspace, notifyDidChangeCtxs, params) + if err != nil { + failures = append(failures, fmt.Errorf("%s: %w", pluginID, err)) + continue + } + if !delivered { + err := fmt.Errorf("%s: workspace change notification was not delivered", pluginID) + failures = append(failures, err) + continue + } + s.contextsNotified[pluginID] = workspaceNotificationRevision{sessionID: session.Session.ID, revision: revision} + } + return errors.Join(failures...) +} diff --git a/desktop/internal/pluginservice/backendhost.go b/desktop/internal/pluginservice/backendhost.go index ece7d9421..12c64d326 100644 --- a/desktop/internal/pluginservice/backendhost.go +++ b/desktop/internal/pluginservice/backendhost.go @@ -352,16 +352,21 @@ func (h *BackendHost) DetachAll() func() { // Notify sends a host notification to a running backend that holds the grant. // A backend that is not running or not granted never sees it. func (h *BackendHost) Notify(ctx context.Context, pluginID, grant, method string, params json.RawMessage) { + _, _ = h.NotifyResult(ctx, pluginID, grant, method, params) +} + +// NotifyResult reports whether a negotiated notification reached a ready backend. +// Unlike Notify, it lets lifecycle callers retry from current state when a session started +// after the state change that normally causes the notification. +func (h *BackendHost) NotifyResult(ctx context.Context, pluginID, grant, method string, params json.RawMessage) (bool, error) { session := h.Running(pluginID) if session == nil || !session.granted(grant) { - return + return false, nil } - // A notification may arrive before initialize completes; it is dropped then, - // because a backend that starts later reads the state itself. if !session.isReady() { - return + return false, nil } - _, _ = h.service.kernel.SendPluginHostNotification(ctx, session.Session.ID, method, params) + return h.service.kernel.SendPluginHostNotification(ctx, session.Session.ID, method, params) } // NotifyAll sends a host notification to every running backend that holds the grant. @@ -618,6 +623,9 @@ func (b *BackendSession) observe(event core.BackendEvent) { } b.signal() b.mu.Unlock() + if len(change.Removed) > 0 { + b.host.service.withdrawEditorProviderFunctions(b.PluginID, b.Session.ID, change.Removed) + } } case "requestCompleted": b.mu.Lock() diff --git a/desktop/internal/pluginservice/color_decorations_test.go b/desktop/internal/pluginservice/color_decorations_test.go new file mode 100644 index 000000000..c792c419a --- /dev/null +++ b/desktop/internal/pluginservice/color_decorations_test.go @@ -0,0 +1,194 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +type colorRefreshWorkbench struct { + *fakeWorkbench + roots []string +} + +func (w *colorRefreshWorkbench) EditorColorDecorationsChanged(root string) { + w.roots = append(w.roots, root) +} + +type colorProviderKernel struct { + *realActionDecoder + service *Service + answers map[string]json.RawMessage +} + +func (k *colorProviderKernel) InvokePluginFunctionInContext(_ context.Context, session, operation, plugin, function string, params, _ json.RawMessage, _ int) (string, error) { + var argument struct { + Document struct { + ID string `json:"documentID"` + Version int `json:"version"` + } `json:"document"` + } + if err := json.Unmarshal(params, &argument); err != nil || argument.Document.ID == "" { + return "", errors.New("provider did not receive the versioned document envelope") + } + backend := k.service.Host.Running(plugin) + if backend == nil || backend.Session.ID != session { + return "", ErrBackendUnavailable + } + backend.observe(core.BackendEvent{Type: "requestCompleted", OperationID: operation, Result: mustMarshal(map[string]any{"value": k.answers[function]})}) + return operation, nil +} + +func colorSession(s *Service, plugin, sessionID string) *BackendSession { + b := &BackendSession{host: s.Host, PluginID: plugin, Session: pluginbackend.Session{ID: sessionID}, + functions: map[string]bool{"colors.collect": true}, waiters: map[string]chan core.BackendEvent{}, done: make(chan struct{}), changed: make(chan struct{}), ready: true} + s.Host.mu.Lock() + s.Host.sessions[plugin] = b + s.Host.mu.Unlock() + return b +} + +func registerColors(t *testing.T, s *Service, workspace WorkspaceContext, plugin, session string) *pluginhost.Failure { + t.Helper() + ctx := pluginhost.WithCaller(t.Context(), pluginhost.Caller{PluginID: plugin, SessionID: session}) + _, failure := s.HostServices.Respond(ctx, methodRegisterEditorProviders, json.RawMessage(`{`+contextJSONOf(workspace)+`,"id":"colors","selector":{"fileExtensions":["txt"]},"providers":{"colorDecorations":{"function":"colors.collect","colorLegend":[{"id":"accent","light":"#112233","dark":"#DDEEFF"}]}}}`)) + return failure +} + +func TestColorDecorationProvidersMergeAndWithdrawIndependently(t *testing.T) { + kernel := &colorProviderKernel{realActionDecoder: &realActionDecoder{notifyKernel: ¬ifyKernel{}}, answers: map[string]json.RawMessage{ + "colors.collect": json.RawMessage(`{"decorations":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":3}},"colorId":"accent"}]}`), + }} + window := &colorRefreshWorkbench{fakeWorkbench: &fakeWorkbench{}} + s, workspace := openEditorServiceWith(t, kernel, window) + kernel.service = s + for _, plugin := range []string{"dev.lithe.test.z-color", "dev.lithe.test.a-color"} { + session := "session-" + plugin + colorSession(s, plugin, session) + if failure := registerColors(t, s, workspace, plugin, session); failure != nil { + t.Fatal(failure) + } + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + decorations, err := s.PluginColorDecorations(ctx, workspace.Path, "sample.txt", "", "1", 7) + if err != nil || len(decorations) != 1 || decorations[0].SourceID != "dev.lithe.test.a-color/colors" || decorations[0].Light != "#112233" { + t.Fatalf("Core priority merge = %+v, %v", decorations, err) + } + s.resources.releaseSession("session-dev.lithe.test.a-color") + decorations, err = s.PluginColorDecorations(ctx, workspace.Path, "sample.txt", "", "1", 7) + if err != nil || len(decorations) != 1 || decorations[0].SourceID != "dev.lithe.test.z-color/colors" { + t.Fatalf("withdrawing one provider removed another: %+v, %v", decorations, err) + } + s.resources.releaseContext(workspace.ContextID) + if s.HasColorDecorationsProvider(workspace.Path, "sample.txt", "") || len(window.roots) != 4 { + t.Fatalf("registration/withdrawal did not refresh open documents: %v", window.roots) + } +} + +func TestColorProviderRestartCanRegisterWithoutRetainingOldSession(t *testing.T) { + s, workspace := openDecodedEditorService(t, &fakeWorkbench{}) + plugin := "dev.lithe.test.color-restart" + colorSession(s, plugin, "old") + if failure := registerColors(t, s, workspace, plugin, "old"); failure != nil { + t.Fatal(failure) + } + colorSession(s, plugin, "new") + if failure := registerColors(t, s, workspace, plugin, "new"); failure != nil { + t.Fatal(failure) + } + if len(s.providers2.list) != 1 || s.providers2.list[0].sessionID != "new" || resourcesHeldBy(s, "old") != 0 { + t.Fatalf("restart kept old registration: %+v", s.providers2.list) + } + if failure := registerColors(t, s, workspace, plugin, "new"); failure == nil { + t.Fatal("duplicate active registration accepted") + } +} + +func TestColorProviderFunctionWithdrawalReleasesOnlyItsRegistration(t *testing.T) { + window := &colorRefreshWorkbench{fakeWorkbench: &fakeWorkbench{}} + s, workspace := openDecodedEditorService(t, window) + plugin := "dev.lithe.test.color-withdrawal" + b := colorSession(s, plugin, "running") + if failure := registerColors(t, s, workspace, plugin, "running"); failure != nil { + t.Fatal(failure) + } + otherDisposed := false + s.resources.add(pluginhost.Caller{PluginID: plugin, SessionID: "running"}, workspace.ContextID, func() { otherDisposed = true }) + b.observe(core.BackendEvent{Type: "functionsChanged", Result: json.RawMessage(`{"removed":["unrelated.function"]}`)}) + if !s.HasColorDecorationsProvider(workspace.Path, "sample.txt", "") { + t.Fatal("an unrelated function withdrawal removed the provider") + } + b.observe(core.BackendEvent{Type: "functionsChanged", Result: json.RawMessage(`{"removed":["colors.collect"]}`)}) + if s.HasColorDecorationsProvider(workspace.Path, "sample.txt", "") || len(window.roots) != 2 { + t.Fatalf("function withdrawal did not release and refresh the provider: %v", window.roots) + } + if otherDisposed || resourcesHeldBy(s, "running") != 1 { + t.Fatal("function withdrawal released an unrelated session resource") + } + b.observe(core.BackendEvent{Type: "functionsChanged", Result: json.RawMessage(`{"functions":["colors.collect"]}`)}) + if s.HasColorDecorationsProvider(workspace.Path, "sample.txt", "") { + t.Fatal("function re-registration resurrected a withdrawn provider") + } + if failure := registerColors(t, s, workspace, plugin, "running"); failure != nil { + t.Fatal(failure) + } +} + +func TestWorkspaceBackendReceivesInitialAndNewestContextRevision(t *testing.T) { + kernel := ¬ifyKernel{} + s, workspace := openEditorServiceWith(t, kernel, &fakeWorkbench{}) + plugin := "dev.lithe.test.context-replay" + b := colorSession(s, plugin, "initial-session") + b.Session.Granted = []string{grantWorkspace} + b.ready = false + // Opening occurred before the backend was ready: it receives no premature callback. + s.contextsNotifyMu.Lock() + if err := s.notifyWorkspaceContextsLocked(t.Context(), "", s.Contexts.Revision()); err != nil { + t.Fatal(err) + } + s.contextsNotifyMu.Unlock() + if len(kernel.sent) != 0 { + t.Fatal("uninitialized backend received notification") + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { done <- s.activateWorkspaceBackend(ctx, plugin, workspace.ContextRef) }() + // A second context opens while initialization is pending. Replay reads the latest state. + s.Contexts.Open(t.TempDir()) + b.observe(core.BackendEvent{Type: "stateChanged", State: "ready"}) + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("backend activation did not finish") + } + for _, revision := range []uint64{s.Contexts.Revision(), 1} { + s.contextsNotifyMu.Lock() + err := s.notifyWorkspaceContextsLocked(ctx, "", revision) + s.contextsNotifyMu.Unlock() + if err != nil { + t.Fatal(err) + } + } + if len(kernel.sent) != 1 || !strings.HasSuffix(kernel.sent[0], `{"revision":2}`) { + t.Fatalf("startup replay duplicated or used old revision: %v", kernel.sent) + } + s.Contexts.Close(workspace.Path) + s.contextsNotifyMu.Lock() + err := s.notifyWorkspaceContextsLocked(ctx, "", s.Contexts.Revision()) + s.contextsNotifyMu.Unlock() + if err != nil || len(kernel.sent) != 2 || !strings.HasSuffix(kernel.sent[1], `{"revision":3}`) { + t.Fatalf("subsequent change=%v, %v", kernel.sent, err) + } +} diff --git a/desktop/internal/pluginservice/hostdocuments.go b/desktop/internal/pluginservice/hostdocuments.go index 816ce74f0..250d9a235 100644 --- a/desktop/internal/pluginservice/hostdocuments.go +++ b/desktop/internal/pluginservice/hostdocuments.go @@ -29,13 +29,13 @@ const ( methodWindowError = pluginhost.MethodPrefix + "window/showError" methodBrowserOpenExternal = pluginhost.MethodPrefix + "browser/openExternal" - // maxSnapshotBytes is what one snapshot may carry: it leaves room for + // DocumentSnapshotMaxBytes is what one snapshot may carry: it leaves room for // worst-case JSON escaping under the 1 MiB result budget. - maxSnapshotBytes = 128 * 1024 - maxEditsPerBatch = 1000 - maxMessageText = 2000 - maxMessageAction = 40 - maxMessageCount = 3 + DocumentSnapshotMaxBytes = 128 * 1024 + maxEditsPerBatch = 1000 + maxMessageText = 2000 + maxMessageAction = 40 + maxMessageCount = 3 ) // Message limits per plugin: the contract allows 5 messages in 10 seconds and 3 @@ -237,11 +237,11 @@ func (s *Service) handleDocumentsSnapshot(ctx context.Context, params json.RawMe if refusal != nil { return nil, refusal } - summary, text, err := s.workbench.Snapshot(ctx, workspace.Path, request.DocumentID, maxSnapshotBytes) + summary, text, err := s.workbench.Snapshot(ctx, workspace.Path, request.DocumentID, DocumentSnapshotMaxBytes) if err != nil { return nil, hostFailureOf(err) } - if len(text) > maxSnapshotBytes { + if len(text) > DocumentSnapshotMaxBytes { return nil, failure(CodeLimitExceeded, "The document is larger than a snapshot may be.") } return marshalResult(map[string]any{"document": summary, "text": text}) diff --git a/desktop/internal/pluginservice/hostproviders.go b/desktop/internal/pluginservice/hostproviders.go index dd6000315..6df88739e 100644 --- a/desktop/internal/pluginservice/hostproviders.go +++ b/desktop/internal/pluginservice/hostproviders.go @@ -6,6 +6,7 @@ import ( "errors" "net/url" "path/filepath" + "slices" "strings" "sync" "time" @@ -20,6 +21,7 @@ import ( // nothing is registered that the host would never call. Each routed type fills one function in the // binding (providerFunctionFields), and its answer is shown through the same presentation as a // language server's, only when no language server serves the document, since the server comes first. +// Foreground color decorations are an independent presentation layer and compose with both sources. const ( methodRegisterEditorProviders = pluginhost.MethodPrefix + "editor/registerProviders" @@ -27,6 +29,8 @@ const ( editorProviderTimeout = 15 * time.Second // maxEditorProviderBindings is the most registrations one plugin keeps across contexts. maxEditorProviderBindings = 32 + // Decorations run alongside language services; bound their process fan-out and latency. + colorProviderConcurrency = 8 ) // routedProviderTypes are the provider types this host routes, in the order Core is told them. @@ -36,12 +40,13 @@ var routedProviderTypes = core.EditorHost.ProviderTypes // routedProviderTypes: a type routed without a field would be accepted and never called, and a field // without a routed type would be refused by Core. var providerFunctionFields = map[string]func(*editorProviderBinding) *string{ - "definition": func(b *editorProviderBinding) *string { return &b.definition }, - "hover": func(b *editorProviderBinding) *string { return &b.hover }, - "completion": func(b *editorProviderBinding) *string { return &b.completion }, - "codeLens": func(b *editorProviderBinding) *string { return &b.codeLens }, - "semanticTokens": func(b *editorProviderBinding) *string { return &b.semanticTokens }, - "documentLink": func(b *editorProviderBinding) *string { return &b.documentLink }, + "definition": func(b *editorProviderBinding) *string { return &b.definition }, + "hover": func(b *editorProviderBinding) *string { return &b.hover }, + "completion": func(b *editorProviderBinding) *string { return &b.completion }, + "codeLens": func(b *editorProviderBinding) *string { return &b.codeLens }, + "semanticTokens": func(b *editorProviderBinding) *string { return &b.semanticTokens }, + "colorDecorations": func(b *editorProviderBinding) *string { return &b.colorDecorations }, + "documentLink": func(b *editorProviderBinding) *string { return &b.documentLink }, } // editorProviderDecoder is the part of Core that validates provider messages. @@ -55,14 +60,19 @@ type editorProviderBinding struct { contextID string reference json.RawMessage id string + // subscriptionID is published with the binding under editorProviderBindings.mu. + subscriptionID string // definition, hover and completion are the functions that answer those requests; empty when not declared. definition string hover string completion string // semanticTokens is the function that answers token requests, and tokenTypes/tokenModifiers its legend. - semanticTokens string - tokenTypes []string - tokenModifiers []string + semanticTokens string + tokenTypes []string + tokenModifiers []string + colorDecorations string + colorLegend []core.PluginColorLegendEntry + colorTimeout time.Duration // triggers are the characters that ask for completion as they are typed. triggers []string // codeLens is the function that answers code lens requests. @@ -101,6 +111,7 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json TokenTypes []string `json:"tokenTypes"` TokenModifiers []string `json:"tokenModifiers"` } `json:"legend"` + ColorLegend []core.PluginColorLegendEntry `json:"colorLegend"` } `json:"providers"` } if err := decodeStrict(params, &request); err != nil { @@ -110,20 +121,37 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json if refusal != nil { return nil, refusal } + session := s.Host.Running(caller.PluginID) + if session == nil || session.Session.ID != caller.SessionID { + return nil, failure(CodePreconditionFailed, "The backend session is not running.") + } if request.ID == "" || len(request.ID) > 128 { return nil, failure(codeInvalidParams, "The registration needs an ID.") } if n := len(request.Selector.Languages) + len(request.Selector.FileExtensions) + len(request.Selector.FileNames); n < 1 || n > 32 { return nil, failure(codeInvalidParams, "The selector needs one to 32 entries.") } + var colorBudget time.Duration if decoder, ok := s.kernel.(editorProviderDecoder); ok { value, err := editorRegistrationValue(params) if err != nil { return nil, invalidParams(err) } - if _, err := decoder.DecodeEditorProviders(ctx, map[string]any{"kind": "registration", "value": value, "types": routedProviderTypes}); err != nil { + decoded, err := decoder.DecodeEditorProviders(ctx, map[string]any{"kind": "registration", "value": value, "types": routedProviderTypes}) + if err != nil { return nil, failure(codeInvalidParams, err.Error()) } + var normalized struct { + Registration struct { + Providers map[string]struct { + BudgetMs int `json:"budgetMs"` + } `json:"providers"` + } `json:"registration"` + } + if err := json.Unmarshal(decoded, &normalized); err != nil { + return nil, invalidParams(err) + } + colorBudget = time.Duration(normalized.Registration.Providers["colorDecorations"].BudgetMs) * time.Millisecond } binding := &editorProviderBinding{ pluginID: caller.PluginID, sessionID: caller.SessionID, contextID: workspace.ContextID, @@ -141,7 +169,6 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json if kind == "semanticTokens" && (len(provider.Legend.TokenTypes) == 0 || len(provider.Legend.TokenTypes) > 64 || len(provider.Legend.TokenModifiers) > 64) { return nil, failure(codeInvalidParams, "The semantic tokens provider needs a legend within the limits.") } - session := s.Host.Running(caller.PluginID) if session == nil || session.Session.ID != caller.SessionID || !session.hasFunction(provider.Function) { return nil, failure(CodePreconditionFailed, "The function is not registered on this session.") } @@ -150,6 +177,12 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json case "semanticTokens": binding.tokenTypes = provider.Legend.TokenTypes binding.tokenModifiers = provider.Legend.TokenModifiers + case "colorDecorations": + if colorBudget <= 0 { + return nil, failure(CodePreconditionFailed, "Core did not provide the color decorations budget.") + } + binding.colorLegend = append([]core.PluginColorLegendEntry(nil), provider.ColorLegend...) + binding.colorTimeout = colorBudget case "completion": binding.triggers = provider.TriggerCharacters } @@ -166,29 +199,118 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json for _, name := range request.Selector.FileNames { binding.names[strings.ToLower(name)] = true } + id, retired, refusal := s.publishEditorProvider(ctx, caller, workspace, session, binding) + if refusal != nil { + return nil, refusal + } + for _, previous := range retired { + s.resources.dispose(pluginhost.Caller{PluginID: previous.pluginID, SessionID: previous.sessionID}, previous.subscriptionID) + } + if binding.colorDecorations != "" { + s.editorProvidersChanged(workspace.Path) + } + return marshalResult(map[string]string{"subscriptionID": id}) +} + +// publishEditorProvider commits both owners and the resource together. Lock order is context, +// host, session, providers, then resources; owner teardown invokes disposal after unlocking. +// A detached request cannot retire a replacement backend, and context close cannot miss a late +// lease. Only the confirmed current backend can retire its predecessors' editor registrations. +func (s *Service) publishEditorProvider(ctx context.Context, caller pluginhost.Caller, workspace WorkspaceContext, session *BackendSession, binding *editorProviderBinding) (string, []*editorProviderBinding, *pluginhost.Failure) { + s.Contexts.mu.Lock() + defer s.Contexts.mu.Unlock() + currentContext := s.Contexts.byPath[workspace.Path] + if currentContext == nil || currentContext.ContextRef != workspace.ContextRef { + return "", nil, contextFailure(ErrContextExpired) + } + s.Host.mu.Lock() + defer s.Host.mu.Unlock() + if s.Host.sessions[caller.PluginID] != session || session.Session.ID != caller.SessionID { + return "", nil, failure(CodePreconditionFailed, "The backend session is no longer current.") + } + session.mu.Lock() + defer session.mu.Unlock() + if session.ended { + return "", nil, failure(CodePreconditionFailed, "The backend session is not running.") + } + for _, field := range providerFunctionFields { + if function := *field(binding); function != "" && !session.functions[function] { + return "", nil, failure(CodePreconditionFailed, "The provider function is no longer registered.") + } + } + if ctx.Err() != nil { + return "", nil, failure(pluginhost.CodeCancelled, "The request was cancelled.") + } s.providers2.mu.Lock() + defer s.providers2.mu.Unlock() count := 0 for _, existing := range s.providers2.list { - if existing.pluginID == caller.PluginID { - count++ + if existing.pluginID != caller.PluginID || existing.sessionID != caller.SessionID { + continue } - if existing.pluginID == binding.pluginID && existing.contextID == binding.contextID && existing.id == binding.id { - s.providers2.mu.Unlock() - return nil, failure(CodePreconditionFailed, "The registration ID is already registered in this context.") + count++ + if existing.contextID == binding.contextID && existing.id == binding.id { + return "", nil, failure(CodePreconditionFailed, "The registration ID is already registered in this context.") } } if count >= maxEditorProviderBindings { - s.providers2.mu.Unlock() - return nil, failure(CodePreconditionFailed, "The plugin has too many editor provider registrations.") + return "", nil, failure(CodePreconditionFailed, "The plugin has too many editor provider registrations.") } - s.providers2.list = append(s.providers2.list, binding) - s.providers2.mu.Unlock() - id := s.resources.add(caller, workspace.ContextID, func() { + var retired []*editorProviderBinding + s.providers2.list = slices.DeleteFunc(s.providers2.list, func(existing *editorProviderBinding) bool { + if existing.pluginID == caller.PluginID && existing.sessionID != caller.SessionID { + retired = append(retired, existing) + return true + } + return false + }) + binding.subscriptionID = s.resources.add(caller, workspace.ContextID, func() { s.providers2.mu.Lock() - defer s.providers2.mu.Unlock() s.providers2.list = removeProviderBinding(s.providers2.list, binding) + s.providers2.mu.Unlock() + if binding.colorDecorations != "" { + s.editorProvidersChanged(workspace.Path) + } }) - return marshalResult(map[string]string{"subscriptionID": id}) + s.providers2.list = append(s.providers2.list, binding) + return binding.subscriptionID, retired, nil +} + +// withdrawEditorProviderFunctions releases only registrations that refer to the withdrawn +// functions. Other resources and other provider registrations of the session keep working. +func (s *Service) withdrawEditorProviderFunctions(pluginID, sessionID string, removed []string) { + if s.providers2 == nil || len(removed) == 0 { + return + } + s.providers2.mu.Lock() + var subscriptions []string + s.providers2.list = slices.DeleteFunc(s.providers2.list, func(binding *editorProviderBinding) bool { + if binding.pluginID != pluginID || binding.sessionID != sessionID { + return false + } + for _, field := range providerFunctionFields { + if function := *field(binding); function != "" && slices.Contains(removed, function) { + if binding.subscriptionID != "" { + subscriptions = append(subscriptions, binding.subscriptionID) + } + return true + } + } + return false + }) + s.providers2.mu.Unlock() + caller := pluginhost.Caller{PluginID: pluginID, SessionID: sessionID} + for _, id := range subscriptions { + s.resources.dispose(caller, id) + } +} + +// editorProvidersChanged asks the owning window to refresh decorations when a provider is +// registered or withdrawn. The service never calls the editor from this handler's thread. +func (s *Service) editorProvidersChanged(root string) { + if window, ok := s.workbench.(interface{ EditorColorDecorationsChanged(string) }); ok { + window.EditorColorDecorationsChanged(root) + } } func removeProviderBinding(list []*editorProviderBinding, target *editorProviderBinding) []*editorProviderBinding { @@ -515,6 +637,130 @@ func (s *Service) semanticTokensBinding(root, path, languageID string) *editorPr return nil } +// colorDecorationsBindings returns every registration that can decorate this document. +func (s *Service) colorDecorationsBindings(root, path, languageID string) []*editorProviderBinding { + if s == nil || s.providers2 == nil { + return nil + } + workspace, ok := s.Contexts.ByPath(root) + if !ok { + return nil + } + name := filepath.Base(path) + s.providers2.mu.Lock() + defer s.providers2.mu.Unlock() + var bindings []*editorProviderBinding + for _, binding := range s.providers2.list { + if binding.contextID == workspace.ContextID && binding.colorDecorations != "" && binding.matchesDocument(languageID, name) { + bindings = append(bindings, binding) + } + } + return bindings +} + +// HasColorDecorationsProvider reports whether any registered provider serves this document. +func (s *Service) HasColorDecorationsProvider(root, path, languageID string) bool { + return len(s.colorDecorationsBindings(root, path, languageID)) > 0 +} + +// PluginColorDecorations asks all matching providers, validates each result with Core, then lets +// Core resolve overlap precedence and attach each color legend's light/dark values. +func (s *Service) PluginColorDecorations(ctx context.Context, root, path, languageID, documentID string, version int) ([]core.PluginColorDecoration, error) { + bindings := s.colorDecorationsBindings(root, path, languageID) + if len(bindings) == 0 { + return nil, nil + } + decoder, ok := s.kernel.(editorProviderDecoder) + if !ok { + return nil, errors.New("editor providers need the Core that normalises their answers") + } + type sourceResult struct { + value map[string]any + err error + } + results := make([]sourceResult, len(bindings)) + var wait sync.WaitGroup + call := func(index int) { + binding := bindings[index] + callCtx, cancel := context.WithTimeout(ctx, binding.colorTimeout) + defer cancel() + session := s.Host.Running(binding.pluginID) + if session == nil || session.Session.ID != binding.sessionID { + results[index].err = ErrBackendUnavailable + return + } + argument := mustMarshal(map[string]any{"document": map[string]any{"documentID": documentID, "version": version}}) + answer, err := session.Call(callCtx, binding.colorDecorations, argument, binding.reference, binding.colorTimeout) + if err != nil { + results[index].err = err + return + } + normalized, err := decoder.DecodeEditorProviders(ctx, map[string]any{ + "kind": "result", "type": "colorDecorations", "value": answer, "colorLegend": binding.colorLegend, + }) + if err != nil { + results[index].err = err + return + } + var payload struct { + Result json.RawMessage `json:"result"` + } + if err := json.Unmarshal(normalized, &payload); err != nil { + results[index].err = err + return + } + if len(payload.Result) == 0 { + results[index].err = errors.New("Core returned an empty color decorations result") + return + } + results[index].value = map[string]any{ + "sourceId": binding.pluginID + "/" + binding.id, + "colorLegend": binding.colorLegend, + "value": payload.Result, + } + } + jobs := make(chan int) + for range min(colorProviderConcurrency, len(bindings)) { + wait.Add(1) + go func() { + defer wait.Done() + for index := range jobs { + call(index) + } + }() + } + for index := range bindings { + jobs <- index + } + close(jobs) + wait.Wait() + var sources []map[string]any + var failures []error + for _, result := range results { + if result.err != nil { + failures = append(failures, result.err) + continue + } + sources = append(sources, result.value) + } + if len(sources) == 0 { + return nil, errors.Join(failures...) + } + merged, err := decoder.DecodeEditorProviders(ctx, map[string]any{ + "kind": "mergeColorDecorations", "value": map[string]any{"sources": sources}, + }) + if err != nil { + return nil, errors.Join(append(failures, err)...) + } + var payload struct { + Decorations []core.PluginColorDecoration `json:"decorations"` + } + if err := json.Unmarshal(merged, &payload); err != nil { + return nil, errors.Join(append(failures, err)...) + } + return payload.Decorations, errors.Join(failures...) +} + // HasSemanticTokensProvider reports whether a plugin's semantic tokens provider serves the document. func (s *Service) HasSemanticTokensProvider(root, path, languageID string) bool { return s.semanticTokensBinding(root, path, languageID) != nil diff --git a/desktop/internal/pluginservice/hostworkbench_test.go b/desktop/internal/pluginservice/hostworkbench_test.go index 88e8dc9da..53b74e926 100644 --- a/desktop/internal/pluginservice/hostworkbench_test.go +++ b/desktop/internal/pluginservice/hostworkbench_test.go @@ -214,7 +214,7 @@ func TestEditorEditsCarryVersionAndMapFailures(t *testing.T) { func TestSnapshotRefusesWhatExceedsTheBudget(t *testing.T) { service, workbench, workspace, _ := openWorkbenchService(t) - workbench.snapshot = strings.Repeat("x", maxSnapshotBytes+1) + workbench.snapshot = strings.Repeat("x", DocumentSnapshotMaxBytes+1) _, refusal := respond(t, service, "a", "documents/getSnapshot", `{`+contextJSONOf(workspace)+`,"documentID":"d1"}`) if refusal == nil || refusal.Code != CodeLimitExceeded { t.Fatalf("oversize snapshot = %+v", refusal) diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index 0e89cbf3c..c73509fd0 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -105,6 +105,12 @@ type Service struct { Host *BackendHost // Contexts holds the workspace contexts plugin backends see. Contexts *WorkspaceContexts + // ContextIssue records a failed notification to an already running backend. + ContextIssue func(context.Context, error) + // contextsNotifyMu serializes didChangeContexts delivery with backend activation so a + // backend that starts after a workspace opens receives the latest revision once. + contextsNotifyMu sync.Mutex + contextsNotified map[string]workspaceNotificationRevision // workbench is the window the document, editor, window and terminal services drive. workbench Workbench messages *messageLimiter diff --git a/desktop/internal/pluginservice/provider_registration_lifecycle_test.go b/desktop/internal/pluginservice/provider_registration_lifecycle_test.go new file mode 100644 index 000000000..9b7a22e32 --- /dev/null +++ b/desktop/internal/pluginservice/provider_registration_lifecycle_test.go @@ -0,0 +1,124 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +// delayedProviderDecoder pauses one validation after the request has captured its owners. +// Later validations proceed independently, so a replacement backend can register first. +type delayedProviderDecoder struct { + *realActionDecoder + armed atomic.Bool + entered chan struct{} + release chan struct{} +} + +func (k *delayedProviderDecoder) DecodeEditorProviders(ctx context.Context, payload any) (json.RawMessage, error) { + if k.armed.CompareAndSwap(true, false) { + close(k.entered) + select { + case <-k.release: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return k.realActionDecoder.DecodeEditorProviders(ctx, payload) +} + +func delayedColorRegistration(t *testing.T, s *Service, k *delayedProviderDecoder, workspace WorkspaceContext, plugin, sessionID string) (<-chan struct{}, **pluginhost.Failure, func()) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + release := sync.OnceFunc(func() { close(k.release) }) + done := make(chan struct{}) + var refusal *pluginhost.Failure + k.armed.Store(true) + go func() { + defer close(done) + callerCtx := pluginhost.WithCaller(ctx, pluginhost.Caller{PluginID: plugin, SessionID: sessionID}) + _, refusal = s.HostServices.Respond(callerCtx, methodRegisterEditorProviders, json.RawMessage(`{`+contextJSONOf(workspace)+`,"id":"colors","selector":{"fileExtensions":["txt"]},"providers":{"colorDecorations":{"function":"colors.collect","colorLegend":[{"id":"accent","light":"#112233","dark":"#DDEEFF"}]}}}`)) + }() + t.Cleanup(func() { + release() + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("delayed registration did not stop after cancellation") + } + }) + select { + case <-k.entered: + case <-ctx.Done(): + t.Fatal("registration did not reach validation gate") + } + return done, &refusal, release +} + +func finishDelayedColorRegistration(t *testing.T, done <-chan struct{}, release func()) { + t.Helper() + release() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("released registration did not finish") + } +} + +func TestColorProviderDetachedRegistrationCannotReplaceNewSession(t *testing.T) { + kernel := &delayedProviderDecoder{realActionDecoder: &realActionDecoder{notifyKernel: ¬ifyKernel{}}, entered: make(chan struct{}), release: make(chan struct{})} + s, workspace := openEditorServiceWith(t, kernel, &fakeWorkbench{}) + plugin := "dev.lithe.test.color-detached-registration" + old := colorSession(s, plugin, "old") + if failure := registerColors(t, s, workspace, plugin, "old"); failure != nil { + t.Fatal(failure) + } + done, refusal, release := delayedColorRegistration(t, s, kernel, workspace, plugin, "old") + // Detach is synchronous; process teardown may still be pending when the new backend starts. + old.cancel = func() {} + stopOld := s.Host.Detach(plugin) + t.Cleanup(func() { close(old.done); stopOld() }) + colorSession(s, plugin, "new") + if failure := registerColors(t, s, workspace, plugin, "new"); failure != nil { + t.Fatalf("replacement session could not register: %+v", failure) + } + newResourceDisposed := false + s.resources.add(pluginhost.Caller{PluginID: plugin, SessionID: "new"}, workspace.ContextID, func() { newResourceDisposed = true }) + finishDelayedColorRegistration(t, done, release) + if *refusal == nil { + t.Error("detached session's delayed registration succeeded") + } + bindings := s.colorDecorationsBindings(workspace.Path, "sample.txt", "") + if len(bindings) != 1 || bindings[0].sessionID != "new" { + t.Fatalf("delayed old request replaced the current provider: %+v", bindings) + } + if newResourceDisposed || resourcesHeldBy(s, "new") != 2 { + t.Fatal("delayed old request released resources owned by the new session") + } + if resourcesHeldBy(s, "old") != 0 { + t.Fatal("detached request retained an old provider resource") + } +} + +func TestColorProviderClosedContextCannotRetainDelayedRegistration(t *testing.T) { + kernel := &delayedProviderDecoder{realActionDecoder: &realActionDecoder{notifyKernel: ¬ifyKernel{}}, entered: make(chan struct{}), release: make(chan struct{})} + s, workspace := openEditorServiceWith(t, kernel, &fakeWorkbench{}) + plugin := "dev.lithe.test.color-closed-registration" + colorSession(s, plugin, "running") + done, refusal, release := delayedColorRegistration(t, s, kernel, workspace, plugin, "running") + s.Contexts.Close(workspace.Path) + s.Contexts.Open(workspace.Path) + finishDelayedColorRegistration(t, done, release) + if *refusal == nil || (*refusal).Code != "plugin.host.contextExpired" { + t.Errorf("closed context registration was not refused: %+v", *refusal) + } + if len(s.providers2.list) != 0 || resourcesHeldBy(s, "running") != 0 { + t.Fatal("closed context retained a late provider registration") + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 0bdd6d8a9..ecf812421 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -1150,6 +1150,9 @@ func (a *App) openPlugins(options Options) { a.backgroundFailedIn(ctx, "plugin_workspace_watch", documentLogError(err)) } service.RuntimeIssue = a.recordPluginRuntimeIssue + service.ContextIssue = func(ctx context.Context, err error) { + a.backgroundFailedIn(ctx, "plugin_workspace_context_notification", err) + } service.SetRuntimeLanguage(a.language().Code()) if err := service.AttachWorkbench(pluginWorkbench{app: a}); err != nil { a.operationFailed("plugin_host_services", err) diff --git a/desktop/internal/workbench/color_decorations.go b/desktop/internal/workbench/color_decorations.go new file mode 100644 index 000000000..d575aa7b2 --- /dev/null +++ b/desktop/internal/workbench/color_decorations.go @@ -0,0 +1,177 @@ +package workbench + +import ( + "context" + "errors" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +// colorDecorationsState owns each open document's provider colors. These colors are independent +// of the language server's semantic tokens, which keep their normal lifecycle. +type colorDecorationsState struct { + docs map[int]*documentColorDecorations +} + +// documentColorDecorations is one document's color pipeline: whether a provider serves it, the +// pause after an edit and the request in flight. A keystroke only restarts the pause: it neither +// looks up providers nor starts a worker, and the view keeps the colors it moved with the edit +// until the answer for the new text replaces them. +type documentColorDecorations struct { + // provided is whether a provider serves the document at path in language. known is false + // until it is looked up and again when a color provider registers or withdraws; a new path or + // language is looked up again too. + path, language string + known, provided bool + // timer starts the request once typing pauses, and cancel ends the request in flight. + timer *time.Timer + cancel context.CancelFunc + // generation counts the requests planned and revoked, so that a timer or an answer overtaken + // by a newer edit, request or withdrawal changes nothing. + generation uint64 +} + +const ( + colorDecorationsDelay = 250 * time.Millisecond + colorDecorationsTimeout = 20 * time.Second +) + +// revoke stops the pending request and the one in flight. +func (s *documentColorDecorations) revoke() { + s.generation++ + if s.timer != nil { + s.timer.Stop() + s.timer = nil + } + if s.cancel != nil { + s.cancel() + s.cancel = nil + } +} + +// scheduleColorDecorations asks the providers for the document's colors after delay, replacing +// the request already pending or running. The colors the view moved with an edit stay until the +// answer for the new text replaces them; colors chosen under another path, language or set of +// color providers, or for a document no provider serves any longer, go at once. +func (a *App) scheduleColorDecorations(p *project, d *document, delay time.Duration) { + if p == nil || d == nil || d.view == nil || a.project != p { + return + } + docs := a.editor.colorDecorations.docs + if docs == nil { + docs = make(map[int]*documentColorDecorations) + a.editor.colorDecorations.docs = docs + } + state := docs[d.id] + if state == nil { + state = &documentColorDecorations{} + docs[d.id] = state + } + state.revoke() + if !a.colorDecorationsServed(p, d, state) { + d.view.ClearColorDecorations() + return + } + if delay <= 0 { + a.requestColorDecorations(p, d, state) + return + } + generation := state.generation + state.timer = time.AfterFunc(delay, func() { + a.post(func(a *App) { + if a.project == p && p.docs.find(d.id) == d && a.editor.colorDecorations.docs[d.id] == state && state.generation == generation { + state.timer = nil + a.requestColorDecorations(p, d, state) + } + }) + }) +} + +// colorDecorationsServed reports whether a provider serves the document as it is now. Only a +// document within the snapshot limit is sent to providers, and the providers are looked up once +// per path, language and change of the color providers, not on every keystroke. +func (a *App) colorDecorationsServed(p *project, d *document, state *documentColorDecorations) bool { + if d.virtual || d.view.TextSnapshot().Len() > pluginservice.DocumentSnapshotMaxBytes { + return false + } + if !state.known || state.path != d.path || state.language != d.languageID { + d.view.ClearColorDecorations() + state.path, state.language, state.known = d.path, d.languageID, true + state.provided = a.plugins != nil && a.plugins.HasColorDecorationsProvider(p.root, d.path, d.languageID) + } + return state.provided +} + +// requestColorDecorations asks the providers for the colors of the current text. Preparation +// reads an immutable text snapshot on the worker; the window applies only its latest answer. +func (a *App) requestColorDecorations(p *project, d *document, state *documentColorDecorations) { + ctx, cancel := context.WithTimeout(a.operationContext(p.ctx), colorDecorationsTimeout) + state.cancel = cancel + generation := state.generation + view, text, revision := d.view, d.view.TextSnapshot(), d.view.Revision() + plugins, root, path, language, id := a.plugins, p.root, d.path, d.languageID, documentPublicID(d) + a.background(p, 0, func(context.Context) func(*App) { + defer cancel() + decorations, err := plugins.PluginColorDecorations(ctx, root, path, language, id, revision) + if errors.Is(ctx.Err(), context.Canceled) { + // log-exempt: 用户取消:新的编辑、提供者撤回或关闭文档会结束过期请求,这不是失败。 + return nil + } + spans := make([]editorview.ColorDecoration, 0, len(decorations)) + for _, decoration := range decorations { + spans = append(spans, editorview.ColorDecoration{ + StartLine: decoration.Range.Start.Line, StartCharacter: decoration.Range.Start.Character, + EndLine: decoration.Range.End.Line, EndCharacter: decoration.Range.End.Character, + SourceID: decoration.SourceID, Light: decoration.Light, Dark: decoration.Dark, + }) + } + prepared := editorview.PrepareColorDecorations(text, spans) + return func(a *App) { + a.finishColorDecorations(p, d, state, generation, view, revision, prepared, err) + } + }) +} + +// finishColorDecorations applies an answer when it is still the document's latest request and +// the text is still the one it was computed for. +func (a *App) finishColorDecorations(p *project, d *document, state *documentColorDecorations, generation uint64, view *editorview.View, revision int, prepared editorview.PreparedColorDecorations, err error) { + if a.project != p || p.docs.find(d.id) != d || view != d.view || a.editor.colorDecorations.docs[d.id] != state || state.generation != generation { + return + } + state.cancel = nil + if view.Revision() != revision { + return + } + if err != nil { + a.backgroundFailed("plugin_color_decorations", err) + } + view.SetPreparedColorDecorations(prepared) +} + +// colorProvidersChanged looks up the providers of every open document again and asks for their +// colors, after a color provider registered or withdrew. +func (a *App) colorProvidersChanged(p *project) { + for _, d := range p.docs.list { + if state := a.editor.colorDecorations.docs[d.id]; state != nil { + state.known = false + } + a.scheduleColorDecorations(p, d, 0) + } +} + +// dropColorDecorations revokes the document's requests before clearing its colors, so a late +// result can never resurrect ranges from an ended document or provider registration. +func (a *App) dropColorDecorations(d *document) { + if d == nil { + return + } + if state := a.editor.colorDecorations.docs[d.id]; state != nil { + state.revoke() + delete(a.editor.colorDecorations.docs, d.id) + } + if d.view != nil { + d.view.ClearColorDecorations() + } +} diff --git a/desktop/internal/workbench/color_decorations_test.go b/desktop/internal/workbench/color_decorations_test.go new file mode 100644 index 000000000..09df529a3 --- /dev/null +++ b/desktop/internal/workbench/color_decorations_test.go @@ -0,0 +1,159 @@ +package workbench + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/vivaui/viva/gfx" +) + +func canvasHasForeground(canvas *gfx.Canvas, color gfx.Color) bool { + for _, label := range canvas.Texts() { + for _, run := range canvas.TextRuns(label) { + if run.Color == color { + return true + } + } + } + return false +} + +// viewHasForeground reports whether a painted frame of view draws text in color. +func viewHasForeground(view *editorview.View, color uint32) bool { + canvas := new(gfx.Canvas) + view.Paint(canvas, gfx.Rect{Width: 600, Height: 200}, editorview.Look{}) + return canvasHasForeground(canvas, gfx.RGB24(color)) +} + +// Typing must not make a rainbow flicker: the colors the view moved with the edit stay while the +// pause before the next request restarts, the edit looks no provider up again, and only the +// answer of the latest request replaces them. A change of the color providers looks them up again +// at once and drops what an unserved document showed. The pause is an hour, so the timer is only +// ever stopped, never fired, and the test never waits on the clock. +func TestColorDecorationEditKeepsMovedColorsUntilLatestAnswer(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + p := &project{ctx: ctx} + view := editorview.New(editorview.Config{Content: editorview.Prepare([]byte("(a) [b]"))}) + t.Cleanup(view.Close) + d := &document{id: 1, path: "/work/sample.src", languageID: "sample", view: view} + p.docs.list = []*document{d} + a := &App{project: p} + // The providers were looked up when the document opened. No plugin service is attached, so a + // second lookup would find no provider and clear the colors. + state := &documentColorDecorations{path: d.path, language: d.languageID, known: true, provided: true} + a.editor.colorDecorations.docs = map[int]*documentColorDecorations{d.id: state} + t.Cleanup(func() { a.dropColorDecorations(d) }) + view.SetPreparedColorDecorations(editorview.PrepareColorDecorations(view.TextSnapshot(), []editorview.ColorDecoration{ + {StartLine: 0, StartCharacter: 0, EndLine: 0, EndCharacter: 1, Light: "#C00050", Dark: "#C00050"}, + })) + + view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{Start: 0, End: 0}, Text: "x"}}) + a.scheduleColorDecorations(p, d, time.Hour) + first, stale := state.timer, state.generation + if first == nil || !state.provided { + t.Fatalf("the edit should restart the pause from the cached lookup: timer %v, provided %t", first, state.provided) + } + if !viewHasForeground(view, 0xC00050) { + t.Fatal("the edit cleared the colors it should have moved") + } + a.scheduleColorDecorations(p, d, time.Hour) + if first.Stop() { + t.Fatal("the next keystroke left the earlier pause running") + } + answer := editorview.PrepareColorDecorations(view.TextSnapshot(), []editorview.ColorDecoration{ + {StartLine: 0, StartCharacter: 1, EndLine: 0, EndCharacter: 2, Light: "#0050C0", Dark: "#0050C0"}, + }) + a.finishColorDecorations(p, d, state, stale, view, view.Revision(), answer, nil) + if viewHasForeground(view, 0x0050C0) || !viewHasForeground(view, 0xC00050) { + t.Fatal("an answer to an overtaken request replaced the colors") + } + a.finishColorDecorations(p, d, state, state.generation, view, view.Revision(), answer, nil) + if !viewHasForeground(view, 0x0050C0) || viewHasForeground(view, 0xC00050) { + t.Fatal("the latest answer did not replace the moved colors") + } + + a.colorProvidersChanged(p) + if !state.known || state.provided || state.timer != nil || viewHasForeground(view, 0x0050C0) { + t.Fatalf("a provider change should look the providers up again and clear an unserved document: known %t, provided %t", state.known, state.provided) + } +} + +// A valid worker result may already be queued when an edit or provider withdrawal wins the +// next window turn. Reapplying that result must never resurrect its old range positions. +func TestColorDecorationWorkerResultRejectsEditWithdrawalAndClosedDocument(t *testing.T) { + for _, transition := range []string{"current", "edit", "overtaken", "withdrawal", "replacement", "closed"} { + t.Run(transition, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + p := &project{ctx: ctx} + view := editorview.New(editorview.Config{Content: editorview.Prepare([]byte("first second"))}) + t.Cleanup(view.Close) + d := &document{id: 1, view: view} + p.docs.list = []*document{d} + a := &App{project: p} + request := &documentColorDecorations{cancel: cancel} + a.editor.colorDecorations.docs = map[int]*documentColorDecorations{1: request} + generation, revision := request.generation, view.Revision() + prepared := editorview.PrepareColorDecorations(view.TextSnapshot(), []editorview.ColorDecoration{{StartLine: 0, StartCharacter: 0, EndLine: 0, EndCharacter: 5, Light: "#C00050", Dark: "#FF80B0"}}) + switch transition { + case "edit": + view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{Start: 0, End: 0}, Text: "x"}}) + case "overtaken": + request.revoke() + case "withdrawal": + a.dropColorDecorations(d) + case "replacement": + a.editor.colorDecorations.docs[1] = &documentColorDecorations{cancel: func() {}} + case "closed": + p.docs.list = nil + } + a.finishColorDecorations(p, d, request, generation, view, revision, prepared, nil) + if got := viewHasForeground(view, 0xC00050); got != (transition == "current") { + t.Fatalf("%s: color result applied=%t", transition, got) + } + }) + } +} + +func TestMoveOpenDocumentInvalidatesColorDecorations(t *testing.T) { + root := t.TempDir() + oldPath, newPath := filepath.Join(root, "sample.src"), filepath.Join(root, "sample.txt") + if err := os.WriteFile(oldPath, []byte("sample"), 0o600); err != nil { + t.Fatal(err) + } + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.open(root) + p := h.app.project + h.app.openFile(p, oldPath) + h.await("document open", func() bool { return p.docs.byPath(oldPath) != nil }) + d := p.docs.byPath(oldPath) + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + request := &documentColorDecorations{cancel: cancel} + h.app.editor.colorDecorations.docs = map[int]*documentColorDecorations{d.id: request} + generation, revision := request.generation, d.view.Revision() + prepared := editorview.PrepareColorDecorations(d.view.TextSnapshot(), []editorview.ColorDecoration{ + {StartLine: 0, StartCharacter: 0, EndLine: 0, EndCharacter: 6, Light: "#C00050", Dark: "#FF80B0"}, + }) + d.view.SetPreparedColorDecorations(prepared) + if err := os.Rename(oldPath, newPath); err != nil { + t.Fatal(err) + } + h.app.moveOpenDocuments(p, oldPath, newPath) + if p.docs.byPath(newPath) != d { + t.Fatal("the same document should stay open at its new path") + } + if ctx.Err() != context.Canceled { + t.Error("the provider request for the old path is still running") + } + h.app.finishColorDecorations(p, d, request, generation, d.view, revision, prepared, nil) + if viewHasForeground(d.view, 0xC00050) { + t.Error("the renamed document kept colors selected for its old path") + } +} diff --git a/desktop/internal/workbench/color_decorations_visual_test.go b/desktop/internal/workbench/color_decorations_visual_test.go new file mode 100644 index 000000000..ed357e625 --- /dev/null +++ b/desktop/internal/workbench/color_decorations_visual_test.go @@ -0,0 +1,107 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// This captures the actual workbench editor with synthetic, Core-normalized sources. Concrete +// plugin installation and algorithms are verified in their owning plugin repository. +func TestVisualColorDecorations(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{"zh-Hans", "en-US"} { + t.Run(theme+"-"+language, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": theme}); err != nil { + t.Fatal(err) + } + kernel := &testKernel{Client: core.NewClient()} + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1000, 640 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + root := t.TempDir() + text := "// Foreground layers preserve semantic styles\nfunc sample(value int) int {\n return (value + (2 * 3))\n}\n" + path := filepath.Join(root, "sample.go") + if err := os.WriteFile(path, []byte(text), 0o600); err != nil { + t.Fatal(err) + } + h.open(root) + p := h.app.project + if p == nil { + t.Fatal("project did not open") + } + h.app.openFile(p, path) + h.await("source opened", func() bool { return p.docs.byPath(path) != nil }) + d := p.docs.byPath(path) + legend := syntax.NewSemanticLegend([]string{"keyword", "function", "variable", "comment"}, []string{"deprecated"}) + d.view.SetSemantic(d.view.TextSnapshot(), legend, []syntax.SemanticToken{ + {Line: 0, StartChar: 0, Length: 43, Type: 3}, {Line: 1, StartChar: 0, Length: 4, Type: 0}, + {Line: 1, StartChar: 5, Length: 6, Type: 1}, {Line: 1, StartChar: 12, Length: 5, Type: 2, Modifiers: 1}, + {Line: 2, StartChar: 4, Length: 6, Type: 0}, {Line: 2, StartChar: 12, Length: 5, Type: 2, Modifiers: 1}, + }) + selected := strings.Index(text, "value +") + d.view.SetSelection(selected, selected+len("value")) + h.settle() + base := filepath.Join(out, "color-decorations-"+theme+"-"+language) + if err := session.Screenshot(base + "-before.png"); err != nil { + t.Fatal(err) + } + rangeValue := func(line, start, end int) any { + return map[string]any{"start": map[string]int{"line": line, "character": start}, "end": map[string]int{"line": line, "character": end}} + } + colors := []map[string]string{{"id": "outer", "light": "#A34E00", "dark": "#FFB86C"}, {"id": "inner", "light": "#7A28A0", "dark": "#BD93F9"}, {"id": "name", "light": "#006E64", "dark": "#50E3C2"}} + decorations := []map[string]any{ + {"range": rangeValue(1, 11, 12), "colorId": "outer"}, {"range": rangeValue(1, 12, 17), "colorId": "name"}, + {"range": rangeValue(1, 21, 22), "colorId": "outer"}, {"range": rangeValue(2, 11, 12), "colorId": "outer"}, + {"range": rangeValue(2, 12, 17), "colorId": "name"}, {"range": rangeValue(2, 20, 21), "colorId": "inner"}, + {"range": rangeValue(2, 26, 27), "colorId": "inner"}, {"range": rangeValue(2, 27, 28), "colorId": "outer"}, + } + decoded, err := kernel.DecodeEditorProviders(t.Context(), map[string]any{"kind": "mergeColorDecorations", "value": map[string]any{"sources": []any{map[string]any{"sourceId": "dev.lithe.test.foreground/colors", "colorLegend": colors, "value": map[string]any{"decorations": decorations}}}}}) + if err != nil { + t.Fatal(err) + } + var result struct { + Decorations []core.PluginColorDecoration `json:"decorations"` + } + if err := json.Unmarshal(decoded, &result); err != nil { + t.Fatal(err) + } + spans := make([]editorview.ColorDecoration, 0, len(result.Decorations)) + for _, r := range result.Decorations { + spans = append(spans, editorview.ColorDecoration{StartLine: r.Range.Start.Line, StartCharacter: r.Range.Start.Character, EndLine: r.Range.End.Line, EndCharacter: r.Range.End.Character, Light: r.Light, Dark: r.Dark}) + } + d.view.SetPreparedColorDecorations(editorview.PrepareColorDecorations(d.view.TextSnapshot(), spans)) + h.settle() + if err := session.Screenshot(base + "-after.png"); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index fae0bc190..1ea47d556 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -587,6 +587,7 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. if !virtual { a.startDocumentSync(p, d) a.scheduleEditorActions(p, d) + a.scheduleColorDecorations(p, d, 0) } a.enforceTabLimit(p, d) if !virtual { @@ -940,6 +941,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.dropColorDecorations(d) a.clearDocumentInlayHints(d) d.closeEditorView() p.docs.list = slices.DeleteFunc(p.docs.list, func(x *document) bool { return x.id == d.id }) @@ -953,6 +955,7 @@ func (a *App) removeDocument(p *project, d *document) { return } a.semanticTokensDropped(d) + a.dropColorDecorations(d) a.clearDocumentInlayHints(d) d.closeEditorView() p.docs.list = slices.DeleteFunc(p.docs.list, func(x *document) bool { return x.id == d.id }) @@ -1046,6 +1049,7 @@ func (a *App) closeDocuments(p *project) { a.flushCheckpoint(p, d, false) d.find.dispose() d.cancelAutoSave() + a.dropColorDecorations(d) a.clearDocumentInlayHints(d) d.closeEditorView() } diff --git a/desktop/internal/workbench/editor_features.go b/desktop/internal/workbench/editor_features.go index a77265031..38182379a 100644 --- a/desktop/internal/workbench/editor_features.go +++ b/desktop/internal/workbench/editor_features.go @@ -6,11 +6,12 @@ package workbench type editorFeatures struct { nav navigationHistoryState // requests counts the editor's own language requests, which name them (editor_requests.go). - requests uint64 - outline outlineState - copyReference copyReferenceState - refs referencesState - encoding encodingState - lsp lspLogState - tokens semanticTokensState + requests uint64 + outline outlineState + copyReference copyReferenceState + refs referencesState + encoding encodingState + lsp lspLogState + tokens semanticTokensState + colorDecorations colorDecorationsState } diff --git a/desktop/internal/workbench/filetree_menu.go b/desktop/internal/workbench/filetree_menu.go index 5f8f6a8fc..ec018a3f7 100644 --- a/desktop/internal/workbench/filetree_menu.go +++ b/desktop/internal/workbench/filetree_menu.go @@ -510,6 +510,7 @@ func (a *App) moveOpenDocuments(p *project, oldPath, newPath string) { } for _, d := range docs { a.startDocumentSync(p, d) + a.scheduleColorDecorations(p, d, 0) a.refreshGitGutter(p, d) a.refreshInlineBlame(p, d) } diff --git a/desktop/internal/workbench/pluginsemantics.go b/desktop/internal/workbench/pluginsemantics.go index 2b46945fe..54975be8a 100644 --- a/desktop/internal/workbench/pluginsemantics.go +++ b/desktop/internal/workbench/pluginsemantics.go @@ -1931,6 +1931,7 @@ func (a *App) pluginSemanticsScrolled(d *document) { func (a *App) pluginSemanticsEdited(d *document) { if p := a.project; p != nil && d != nil { a.semanticTokensEdited(p, d) + a.scheduleColorDecorations(p, d, colorDecorationsDelay) a.clearDocumentInlayHints(d) } if d == nil || a.semantics.documentID != d.id { diff --git a/desktop/internal/workbench/pluginworkbench.go b/desktop/internal/workbench/pluginworkbench.go index e1bcf8494..2832a6840 100644 --- a/desktop/internal/workbench/pluginworkbench.go +++ b/desktop/internal/workbench/pluginworkbench.go @@ -37,6 +37,18 @@ func (w pluginWorkbench) EditorActionsChanged(root string) { }) } +// EditorColorDecorationsChanged refreshes the open documents when a plugin's color provider +// is registered or withdrawn. +func (w pluginWorkbench) EditorColorDecorationsChanged(root string) { + w.app.post(func(a *App) { + p, err := a.projectAt(root) + if err != nil { + return + } + a.colorProvidersChanged(p) + }) +} + // onWindow runs fn on the window thread and waits for its result. func onWindow[T any](a *App, ctx context.Context, fn func(*App) (T, error)) (T, error) { type outcome struct { diff --git a/shared/platform-feature-matrix/features/plugin-editor-providers.json b/shared/platform-feature-matrix/features/plugin-editor-providers.json index fd3bfbff0..629f24f84 100644 --- a/shared/platform-feature-matrix/features/plugin-editor-providers.json +++ b/shared/platform-feature-matrix/features/plugin-editor-providers.json @@ -2,7 +2,7 @@ "id": "plugin-editor-providers", "area": "扩展", "group": "插件与主题", - "capability": "普通工具插件的编辑器语言功能:运行期把跳转、悬浮、补全、CodeLens、折叠、语义着色、文档链接绑定到同插件函数;语言服务器先答,插件只补充;不接 LSP/Build/Run/Debug", + "capability": "普通工具插件的编辑器语言功能及可组合前景颜色范围:提供者函数由 Core 校验,独立颜色层与语法、LSP 语义着色共存,并按文档版本和注册生命周期失效", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -15,7 +15,14 @@ "desktop/internal/pluginservice/hostdocumentlinks.go", "desktop/internal/pluginservice/hostproviders_routes_test.go", "desktop/internal/workbench/editor_actions.go", - "desktop/internal/core/editor_providers_test.go" + "desktop/internal/core/editor_providers_test.go", + "desktop/internal/workbench/color_decorations.go", + "desktop/internal/workbench/color_decorations_test.go", + "desktop/internal/workbench/color_decorations_visual_test.go", + "desktop/internal/editorview/color_decorations.go", + "desktop/internal/editorview/color_decorations_test.go", + "desktop/internal/pluginservice/color_decorations_test.go", + "desktop/internal/pluginservice/activation.go" ] }, "windows": { @@ -30,12 +37,19 @@ "desktop/internal/pluginservice/hostdocumentlinks.go", "desktop/internal/pluginservice/hostproviders_routes_test.go", "desktop/internal/workbench/editor_actions.go", - "desktop/internal/core/editor_providers_test.go" + "desktop/internal/core/editor_providers_test.go", + "desktop/internal/workbench/color_decorations.go", + "desktop/internal/workbench/color_decorations_test.go", + "desktop/internal/workbench/color_decorations_visual_test.go", + "desktop/internal/editorview/color_decorations.go", + "desktop/internal/editorview/color_decorations_test.go", + "desktop/internal/pluginservice/color_decorations_test.go", + "desktop/internal/pluginservice/activation.go" ] }, "owner": "Extensions", - "verification": "用一个资源 key 在模板与 .properties 之间跳转的第二工具插件注册 definition、hover、completion、codeLens、semanticTokens;验证语言服务器的答案先出现、插件的位置只追加、重复位置只显示一次、服务器只指回自身时让位;悬浮和补全超过期限、文档已变化、注册被撤回时安静丢弃;触发字符只问声明过它的注册;点击 CodeLens 与文档链接只回传宿主生成的键,command: 链接不会被执行,工作区外的 file: 目标不会打开;只读预览不询问插件;停用、卸载、关闭项目后旧结果不再出现。", - "notes": "Viva:普通插件经 editor/registerProviders 按语言、扩展名、文件名注册跳转、悬浮、补全(含触发字符)、CodeLens、语义着色与文档链接,绑定到同插件已注册的函数;注册与答案都由 Core 校验和归一化,只在没有语言服务器服务该文档时调用插件。CodeLens 在编辑器行上显示为可点击的动作。折叠(foldingRange)未路由,Core 会拒绝该类型的注册。 2026-11-13:编辑器 Provider 注册在宿主确认工作区后,剥离路由用的 context 再交给 Core 校验声明;真实 Core 回归覆盖多个 Provider 的绑定。", + "verification": "用默认构建固定的 Core 修订验证 colorDecorations 能力声明,并用测试内联的 dev.lithe.test.* 合成提供者执行注册、版本化请求、多个来源重叠合并、撤回与后端重新注册。检查前景色叠加时保留 LSP 字体样式、选区和诊断,以及明暗主题切换直接使用对应色表。验证编辑、撤销、重做时颜色跟随文字平移、按键不重复查询提供者,关闭文档或停用提供者后旧结果不会复活。运行 TestVisualColorDecorations 生成并检查中英文、明暗主题 PNG,再运行相同规模的编辑器性能前后对比。目标平台原生安装和完整插件验收另行执行,未完成时保持 pending。", + "notes": "Viva 已路由 definition、hover、completion、codeLens、semanticTokens、documentLink 和独立 colorDecorations。foldingRange 尚未路由。语言功能保持 LSP 优先,颜色层独立组合。默认构建固定到包含 Core #188 的修订,由 Core 管理颜色图例、范围、数量、重叠和期限规则。宿主在后台准备原生坐标,按文档版本、请求代数及注册所有权应用。编辑、撤销和重做会平移已有颜色,停顿后再请求;撤回、改名与磁盘重新加载立即清空。颜色读取与绘制经局部零分配回归验证。工作区后端初始化后补发最新上下文修订,注册和撤回刷新已打开的文档。Windows 离屏检查和各平台原生验收分别记录。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {