diff --git a/.agents/notes/implemented/bug-fix/2026-11-20-console-output-encoding.md b/.agents/notes/implemented/bug-fix/2026-11-20-console-output-encoding.md new file mode 100644 index 0000000000..b69fd63a38 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-20-console-output-encoding.md @@ -0,0 +1,49 @@ +# Agent 笔记:控制台保留原始字节并逐行解码 + +状态:已实现 + +## 先说结论 + +运行、构建和测试的进程输出必须以原始字节交给 Rust Core。Core 按行选择编码,再移除终端转义并返回文字和颜色范围。应用的“构建、执行、部署 › 控制台”设置可以固定编码;自动模式的候选顺序来自同一个 Core 解析结果。 + +## 问题 + +Windows 程序向管道写入时可能使用系统 ANSI 代码页,例如简体中文系统的 GBK。Go 字符串可以保留这些字节,但直接把它作为 JSON 文本发送会先把非法 UTF-8 替换成乱码;到了 Core 已无法恢复。一次构建中的不同程序还可能分别输出 UTF-8 和 GBK,不能给整个控制台猜一次编码。 + +## 决策 + +- 平台适配器只读管道字节并报告是否为 Windows。默认在所有平台使用 UTF-8,仅 Windows 为不能按 UTF-8 读取的行增加 GBK 回退,不依赖系统语言或 ANSI 代码页;用户和插件仍可显式声明其他编码。 +- Core 使用 `encoding_rs` 的编码表逐行选择。自动候选依次是插件显式声明、UTF-8,以及仅 Windows 的 GBK,去重;显式设置只用指定编码。候选都不能无损读取时,选择替换字符最少的结果,平手按候选顺序。 +- 字节先按换行拆分,再解码;只支持换行和 ESC 不会出现在多字节字符内的兼容 ASCII 编码,因此不接受 UTF-16。跨块字符和未结束行由 Core 状态保留,桌面端不得先修正 UTF-8。 +- 每个控制台启动时保存设置快照;后续设置变更只影响新控制台。后台进程观察器通过原子快照读取偏好,不直接访问界面线程持有的可变设置。 +- 设置的自动候选由 Core 返回,编码显示名与文件编码选择器共用。加载、失败和自动候选都有明确文本;ⓘ 解释候选顺序和生效时机。解码失败沿用已有后台失败事件,每个控制台只记录一次降级。 +- 插件通过通用的 `outputEncoding` 可选字段声明输出编码。运行时或构建工具专属参数由插件决定,不在宿主按工具名添加分支。完整接口与夹具只在 Core 仓库维护。 + +正确做法:将 `B9 B9 BD A8` 原样编码为 base64 发送,Core 得到“构建”,再供复制、搜索和链接识别使用。不要先把这些字节作为 JSON 的文本字段发送,也不要在平台层另外维护编码猜测顺序。 + +## 考虑过的备选方案 + +- 统一给程序添加 UTF-8 参数:不同运行时参数不同,子进程也可能不遵守;不能解决通用宿主的字节丢失,工具专属设置仍属于插件。 +- 整个控制台只选一次编码:无法处理 UTF-8 和系统编码按行混合的输出。 +- Go 端解码后发送文本:会让平台层持有第二份编码规则,改用 Core 统一处理。 + +## 后果 + +原始字节穿过 JSON 边界后仍可恢复,现有颜色、复制、搜索、链接和输出快照沿用解码后的文本。代价是 base64 传输和未结束行预览;块大小、行长度、样式数量继续受 Core 限额约束。自动模式是候选校验,不是任意语言的可靠识别;存在字节歧义时需要插件声明或用户固定编码。已按用户指定在 SSH Windows 11 原生 x64 主机验证管道、编码、设置与竞态;完整应用窗口的 Run、Build、Tests 及复制、链接操作仍须逐项验收,无头截图不能替代它。宿主固定到 Core PR [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) 的 `604699f` 修订,包含最终 UTF-8/Windows GBK 策略与插件声明契约;本地也可用 `LITHE_CORE_RUST_DIR` 链接配套 Core 工作区。 + +## 验证 + +- macOS 定向计时记录 94 项通过,Windows 11 原生 x64(SSH 主机)记录 95 项通过;真实 stdout/stderr 子进程先写半个 GBK 字符,收到 stdin 握手后再写余下字节。两端相关工作台和设置测试均通过竞态检测,中英文明暗设置截图均已生成。未进行完整应用窗口验收。 +- Apple M4 上 release 桥接基准每批约 256 KiB、32 KiB 分块、5 次中位数:纯 UTF-8 的旧 text 通道 3.156 ms、新 bytes 通道 3.631 ms(约 +15%),99% UTF-8 行混入 1% GBK 行 3.551 ms。Go 累计分配约从 1.91 MiB/批增至 2.55 MiB/批;不代表常驻内存,不包含 Rust 分配或 UI 绘制。这是同一 Core 保留的 text 通道对照,不是旧版二进制;混合结果在波动范围内,不能据此声称零开销或更快。原始报告保存在本地 `.artifacts/console-encoding/`。 +- `scripts/desktop/desktop-go.sh test ./internal/core ./internal/workbench ./internal/pluginservice ./internal/buildprocess ./internal/settingswindow -count=1`:重放所链接 Core 的编码与样式夹具,验证声明传递、跨块字符、设置快照、设置选择与恢复。 +- `LITHE_VISUAL_OUTPUT_DIR=.artifacts/console-encoding/screenshots scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow -run '^TestVisualConsoleEncoding$' -count=1`:检查中英文、明暗主题的设置页和编码下拉。 +- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认平台生产路径保持发行目录只读。 + +## 适用范围 + +- `desktop/internal/core/output_style.go` +- `desktop/internal/workbench/output_style.go` +- `desktop/internal/workbench/console_encoding.go` +- `desktop/internal/buildprocess/` +- `desktop/internal/settingswindow/console_view.go` +- `shared/platform-feature-matrix/features/console-output-encoding.json` diff --git a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md index 32f19c2a27..c360429047 100644 --- a/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md +++ b/.agents/notes/implemented/feature/2026-10-15-macos-settings-hierarchy.md @@ -19,7 +19,7 @@ | 外观与行为 | 应用本身的外观、编辑器显示与输入、快捷键,以及应用自身网络请求的代理设置 | | 插件 | 插件的安装、启用和插件自带的选项;一级页面,不属于任何分组 | | 版本控制 | Git、SVN 等版本控制系统的配置 | -| 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)和“调试器”(单步过滤等调试设置);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 | +| 构建、执行、部署 | 分组本身是目录页;固定子页“工具链”(插件声明的全部工具,包括项目 JDK)、“调试器”(单步过滤等调试设置)和“控制台”(程序输出编码);插件声明的构建工具页、编译器页按种类排在后面,以及运行配置、服务运行和框架、构建工具注入的配置 | | 语言与框架 | 语言服务(LSP)的开关,以及 Spring Boot 等框架的配置 | | 工具 | 终端、搜索(搜索和替换文件大小预算)等通用工具;插件带来的专用工具可以放进对应工具页。日志与诊断不属于设置,它是独立的日志窗口 | | AI | 与 AI 有关的全部配置:MCP、Skill、全局指令、AI 提交信息、Agents、AI 服务商 | diff --git a/desktop/internal/buildprocess/process.go b/desktop/internal/buildprocess/process.go index e41a646317..393c22c6b6 100644 --- a/desktop/internal/buildprocess/process.go +++ b/desktop/internal/buildprocess/process.go @@ -83,9 +83,11 @@ type Process struct { stopping atomic.Bool } -// Start runs spec and reports every output chunk to observe. observe runs on a -// reader goroutine and must return promptly. The process is killed when ctx -// ends; Stop does the same explicitly. +// Start runs spec and reports every output chunk to observe. A chunk is the bytes +// the process wrote, in whatever encoding it chose, and may end inside a +// character; Core decides the characters (core.Client.DecodeOutputStyle). observe +// runs on a reader goroutine and must return promptly. The process is killed when +// ctx ends; Stop does the same explicitly. // // The host owns explicit pipes rather than exec.Cmd.StdoutPipe so root exit and // pipe EOF are independent. Wait first reaps the root, then ends descendants diff --git a/desktop/internal/core/build.go b/desktop/internal/core/build.go index ec1acbfeae..3bbab5e416 100644 --- a/desktop/internal/core/build.go +++ b/desktop/internal/core/build.go @@ -264,6 +264,7 @@ type BuildLaunch struct { Arguments []string `json:"arguments"` WorkingDirectory string `json:"workingDirectory"` Environment map[string]string `json:"environment"` + OutputEncoding string `json:"outputEncoding,omitempty"` } // BuildDecodeRunRequest validates the raw result of lithe/build/prepareRun. diff --git a/desktop/internal/core/build_test.go b/desktop/internal/core/build_test.go index 6048b2421d..74432797d5 100644 --- a/desktop/internal/core/build_test.go +++ b/desktop/internal/core/build_test.go @@ -191,6 +191,15 @@ func TestBuildDecodeRunKeepsValidatedExecutable(t *testing.T) { if err := json.Unmarshal(raw, &fixture); err != nil { t.Fatal(err) } + var result map[string]any + if err := json.Unmarshal(fixture.Result, &result); err != nil { + t.Fatal(err) + } + result["outputEncoding"] = "cp936" + fixture.Result, err = json.Marshal(result) + if err != nil { + t.Fatal(err) + } launch, err := client.DecodeBuildRun(ctx, manifest, "gradle", BuildDecodeRunRequest{ WorkspaceRoot: root, Root: ".", @@ -205,6 +214,9 @@ func TestBuildDecodeRunKeepsValidatedExecutable(t *testing.T) { if launch.WorkingDirectory != "app" || len(launch.Arguments) != 4 || launch.Environment["APP_ENV"] != "test" { t.Fatalf("launch = %+v", launch) } + if launch.OutputEncoding != "gbk" { + t.Fatalf("output encoding = %q, want normalized GBK", launch.OutputEncoding) + } } func TestBuildProviderRequestNeedsAnOpenSession(t *testing.T) { diff --git a/desktop/internal/core/output_style.go b/desktop/internal/core/output_style.go index 3cf97b9178..4b136f7345 100644 --- a/desktop/internal/core/output_style.go +++ b/desktop/internal/core/output_style.go @@ -2,6 +2,7 @@ package core import ( "context" + "encoding/base64" "encoding/json" ) @@ -46,32 +47,62 @@ type OutputStyleDecoding struct { // Lines are the lines the chunk finished, oldest first; the first one // continues the previous answer's Open line. Lines []OutputLine - // Open is the line still being written, shown after Lines. + // Open is the line still being written, shown after Lines. Core holds its + // bytes until it ends, so a later answer may show it differently. Open OutputLine // State is passed back unchanged with the console's next chunk. State json.RawMessage } -// DecodeOutputStyle turns one chunk of console output with ANSI escapes into -// plain lines and styled ranges. state is the State of the previous answer for -// the same console, or nil for its first chunk; chunks are at most 1 MiB. -func (c *Client) DecodeOutputStyle(ctx context.Context, text string, state json.RawMessage) (OutputStyleDecoding, error) { +// OutputEncodingPolicy is how Core decides the characters of a process's +// output bytes, line by line. +type OutputEncodingPolicy struct { + // Setting is the user's console encoding: empty or "auto" tries the + // candidates in order, any other id decodes every line with that encoding. + Setting string `json:"setting,omitempty"` + // Declared is the encoding whoever started the process says it writes, such + // as a plugin's run plan; empty when nobody said. + Declared string `json:"declared,omitempty"` + // Windows enables the Windows default: try GBK only after UTF-8 fails. + Windows bool `json:"windows,omitempty"` +} + +// OutputEncodings is what an output encoding policy means on this machine. +type OutputEncodings struct { + // Candidates are the encoding ids a line is tried in, in order. + Candidates []string `json:"candidates"` + // Encodings are every id a setting may choose, in menu order. + Encodings []string `json:"encodings"` +} + +// DecodeOutputStyle turns one chunk of a process's output bytes with ANSI +// escapes into plain lines and styled ranges, decoding each line with the +// encoding policy picks for it. state is the State of the previous answer for +// the same console, or nil for its first chunk; chunks are at most 1 MiB and +// may end inside a character. +func (c *Client) DecodeOutputStyle(ctx context.Context, chunk []byte, policy OutputEncodingPolicy, state json.RawMessage) (OutputStyleDecoding, error) { request := struct { - Text string `json:"text"` - State json.RawMessage `json:"state,omitempty"` - }{Text: text, State: state} + Bytes string `json:"bytes"` + Encoding OutputEncodingPolicy `json:"encoding"` + State json.RawMessage `json:"state,omitempty"` + }{Bytes: base64.StdEncoding.EncodeToString(chunk), Encoding: policy, State: state} var response struct { Lines []OutputLine `json:"lines"` + Open OutputLine `json:"open"` State json.RawMessage `json:"state"` } if err := c.Execute(ctx, "outputStyle.decode", request, &response); err != nil { return OutputStyleDecoding{}, err } - var open struct { - Line OutputLine `json:"line"` - } - if err := json.Unmarshal(response.State, &open); err != nil { - return OutputStyleDecoding{}, err + return OutputStyleDecoding{Lines: response.Lines, Open: response.Open, State: response.State}, nil +} + +// ResolveOutputEncoding asks Core which encodings policy tries, in order, and +// which encodings a setting may choose, for the console encoding setting. +func (c *Client) ResolveOutputEncoding(ctx context.Context, policy OutputEncodingPolicy) (OutputEncodings, error) { + var response OutputEncodings + if err := c.Execute(ctx, "outputEncoding.resolve", policy, &response); err != nil { + return OutputEncodings{}, err } - return OutputStyleDecoding{Lines: response.Lines, Open: open.Line, State: response.State}, nil + return response, nil } diff --git a/desktop/internal/core/output_style_bench_test.go b/desktop/internal/core/output_style_bench_test.go new file mode 100644 index 0000000000..e6163b10fb --- /dev/null +++ b/desktop/internal/core/output_style_bench_test.go @@ -0,0 +1,102 @@ +package core + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "testing" +) + +// BenchmarkOutputEncodingBridge compares the previous text request and the byte request +// through the actual C ABI, including Go JSON, base64, Rust decoding and response parsing. +// The same Core binary retains the text command, so the two paths share compiler settings. +// Mixed input has no text baseline: JSON would replace GBK before Core sees it. +func BenchmarkOutputEncodingBridge(b *testing.B) { + for _, kind := range []string{"ascii", "utf8", "mixed-1pct-gbk", "gbk"} { + for _, chunkSize := range []int{4096, 32768} { + data, expected := outputEncodingBenchmarkData(kind) + for _, mode := range []string{"text", "bytes"} { + if mode == "text" && (kind == "mixed-1pct-gbk" || kind == "gbk") { + continue + } + b.Run(fmt.Sprintf("%s/%d/%s", kind, chunkSize, mode), func(b *testing.B) { + client := NewClient() + ctx := context.Background() + // Chunk once outside the timed loop. Split both paths on the same UTF-8 + // boundary: the old caller held incomplete characters before JSON. + var chunks [][]byte + for remaining := data; len(remaining) > 0; { + end := min(len(remaining), chunkSize) + if kind == "utf8" && end < len(remaining) { + for end > 0 && remaining[end]&0xc0 == 0x80 { + end-- + } + } + chunks = append(chunks, remaining[:end]) + remaining = remaining[end:] + } + run := func(check bool) { + var state json.RawMessage + line := 0 + for _, chunk := range chunks { + var decoded OutputStyleDecoding + var err error + if mode == "bytes" { + decoded, err = client.DecodeOutputStyle(ctx, chunk, OutputEncodingPolicy{Windows: true}, state) + } else { + err = client.Execute(ctx, "outputStyle.decode", struct { + Text string `json:"text"` + State json.RawMessage `json:"state,omitempty"` + }{string(chunk), state}, &decoded) + } + if err != nil { + b.Fatal(err) + } + if check { + for _, got := range decoded.Lines { + if line >= len(expected) || got.Text != expected[line] { + b.Fatalf("line %d decoded incorrectly: %q", line, got.Text) + } + line++ + } + } + state = decoded.State + } + if check && line != len(expected) { + b.Fatalf("decoded %d lines, want %d", line, len(expected)) + } + } + run(true) + b.ReportAllocs() + b.SetBytes(int64(len(data))) + b.ResetTimer() + for b.Loop() { + run(false) + } + }) + } + } + } +} + +// Each batch is about 256 KiB, with one GBK line in every hundred in the mixed case. +func outputEncodingBenchmarkData(kind string) ([]byte, []string) { + ascii := []byte("[INFO] compile src/Example.java:42 finished successfully; module=example; duration=123ms\n") + utf8 := []byte("[INFO] 编译 src/Example.java:42 构建成功;模块=example;耗时=123ms\n") + gbk := []byte("[INFO] \xb1\xe0\xd2\xeb src/Example.java:42 \xb9\xb9\xbd\xa8\xb3\xc9\xb9\xa6; module=example; duration=123ms\n") + gbkText := "[INFO] 编译 src/Example.java:42 构建成功; module=example; duration=123ms" + var data []byte + var expected []string + for i := 0; len(data) < 256<<10; i++ { + line, text := utf8, string(bytes.TrimSuffix(utf8, []byte{'\n'})) + if kind == "ascii" { + line, text = ascii, string(bytes.TrimSuffix(ascii, []byte{'\n'})) + } else if kind == "gbk" || (kind == "mixed-1pct-gbk" && i%100 == 99) { + line, text = gbk, gbkText + } + data = append(data, line...) + expected = append(expected, text) + } + return data, expected +} diff --git a/desktop/internal/core/output_style_test.go b/desktop/internal/core/output_style_test.go index d88472ee1d..b1df4007d0 100644 --- a/desktop/internal/core/output_style_test.go +++ b/desktop/internal/core/output_style_test.go @@ -1,8 +1,11 @@ package core import ( + "bytes" "context" + "encoding/hex" "encoding/json" + "errors" "os" "reflect" "testing" @@ -12,8 +15,10 @@ import ( ) // TestDecodeOutputStyleFollowsTheCoreFixture replays every case of the shared -// fixture through the client, passing each answer's state to the next chunk: -// Core decides the text and ranges, the client only carries them. +// style fixture through the client as process output bytes, passing each +// answer's state to the next chunk: Core decides the text and ranges, the +// client only carries them. The chunks are UTF-8, so no policy decodes them +// the same as text. func TestDecodeOutputStyleFollowsTheCoreFixture(t *testing.T) { data, err := os.ReadFile(contractfixture.CoreFixture("terminal/output-style-v1.json")) if err != nil { @@ -33,35 +38,89 @@ func TestDecodeOutputStyleFollowsTheCoreFixture(t *testing.T) { if len(fixture.Cases) == 0 { t.Fatal("the fixture has no cases") } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() client := NewClient() for _, test := range fixture.Cases { t.Run(test.Name, func(t *testing.T) { - var state json.RawMessage - lines := []OutputLine{} - var open OutputLine - for _, chunk := range test.Chunks { - decoded, err := client.DecodeOutputStyle(ctx, chunk, state) + chunks := make([][]byte, len(test.Chunks)) + for index, chunk := range test.Chunks { + chunks[index] = []byte(chunk) + } + lines, open := replayOutputDecode(t, client, chunks, OutputEncodingPolicy{}) + assertOutputDecode(t, lines, open, test.Lines, test.Open) + }) + } +} + +// TestDecodeOutputStyleFollowsTheEncodingFixture replays the shared encoding +// fixture: each case's hexadecimal chunks go to Core as bytes with the case's +// policy, so the client's policy fields must be the ones Core reads. +func TestDecodeOutputStyleFollowsTheEncodingFixture(t *testing.T) { + fixture := readOutputEncodingFixture(t) + if len(fixture.Decode) == 0 { + t.Fatal("the fixture has no decode cases") + } + client := NewClient() + for _, test := range fixture.Decode { + t.Run(test.Name, func(t *testing.T) { + policy := strictOutputEncodingPolicy(t, test.Encoding) + chunks := make([][]byte, len(test.Chunks)) + for index, chunk := range test.Chunks { + decoded, err := hex.DecodeString(chunk) if err != nil { t.Fatal(err) } - lines = append(lines, decoded.Lines...) - open, state = decoded.Open, decoded.State + chunks[index] = decoded + } + lines, open := replayOutputDecode(t, client, chunks, policy) + assertOutputDecode(t, lines, open, test.Lines, test.Open) + }) + } +} + +// TestResolveOutputEncodingFollowsTheFixture checks the candidates and selectable +// encodings. Invalid policy members are sent verbatim to exercise Core's rejection. +func TestResolveOutputEncodingFollowsTheFixture(t *testing.T) { + fixture := readOutputEncodingFixture(t) + if len(fixture.Resolve) == 0 { + t.Fatal("the fixture has no resolve cases") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + client := NewClient() + for _, test := range fixture.Resolve { + t.Run(test.Name, func(t *testing.T) { + // encoding/json matches struct fields without regard to case. Send unknown + // keys verbatim so "Windows" is not silently turned into "windows". + var members map[string]json.RawMessage + if err := json.Unmarshal(test.Policy, &members); err != nil { + t.Fatal(err) + } + unknown := false + for key := range members { + unknown = unknown || (key != "setting" && key != "declared" && key != "windows") + } + var resolved OutputEncodings + var err error + if unknown { + err = client.Execute(ctx, "outputEncoding.resolve", test.Policy, &resolved) + } else { + resolved, err = client.ResolveOutputEncoding(ctx, strictOutputEncodingPolicy(t, test.Policy)) + } + if test.Error != "" { + var coreErr *Error + if !errors.As(err, &coreErr) || string(coreErr.Code) != test.Error { + t.Fatalf("err = %v, want %s", err, test.Error) + } + return } - want := test.Lines - if want == nil { - want = []OutputLine{} + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(lines, want) { - got, _ := json.Marshal(lines) - expected, _ := json.Marshal(want) - t.Fatalf("lines = %s, want %s", got, expected) + if !reflect.DeepEqual(resolved.Candidates, test.Candidates) { + t.Fatalf("candidates = %q, want %q", resolved.Candidates, test.Candidates) } - if !reflect.DeepEqual(open, test.Open) { - got, _ := json.Marshal(open) - expected, _ := json.Marshal(test.Open) - t.Fatalf("open = %s, want %s", got, expected) + if !reflect.DeepEqual(resolved.Encodings, fixture.Encodings) { + t.Fatalf("encodings = %q, want %q", resolved.Encodings, fixture.Encodings) } }) } @@ -72,7 +131,90 @@ func TestDecodeOutputStyleFollowsTheCoreFixture(t *testing.T) { func TestDecodeOutputStyleRejectsAForeignState(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - if _, err := NewClient().DecodeOutputStyle(ctx, "x", json.RawMessage(`{"line":{"text":"ab","spans":[{"start":1,"length":5,"style":{"bold":true}}]}}`)); err == nil { + if _, err := NewClient().DecodeOutputStyle(ctx, []byte("x"), OutputEncodingPolicy{}, json.RawMessage(`{"line":{"text":"ab","spans":[{"start":1,"length":5,"style":{"bold":true}}]}}`)); err == nil { t.Fatal("a state whose range runs past its line was accepted") } } + +type outputEncodingFixture struct { + Encodings []string `json:"encodings"` + Decode []struct { + Name string `json:"name"` + Encoding json.RawMessage `json:"encoding"` + Chunks []string `json:"chunks"` + Lines []OutputLine `json:"lines"` + Open OutputLine `json:"open"` + } `json:"decode"` + Resolve []struct { + Name string `json:"name"` + Policy json.RawMessage `json:"policy"` + Candidates []string `json:"candidates"` + Error string `json:"error"` + } `json:"resolve"` +} + +func readOutputEncodingFixture(t *testing.T) outputEncodingFixture { + t.Helper() + data, err := os.ReadFile(contractfixture.CoreFixture("terminal/output-encoding-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture outputEncodingFixture + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + return fixture +} + +// strictOutputEncodingPolicy reads a fixture policy, failing on a member the +// client has no field for; an absent policy is the empty one. +func strictOutputEncodingPolicy(t *testing.T, raw json.RawMessage) OutputEncodingPolicy { + t.Helper() + var policy OutputEncodingPolicy + if len(raw) == 0 { + return policy + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&policy); err != nil { + t.Fatalf("policy %s: %v", raw, err) + } + return policy +} + +// replayOutputDecode sends chunks in order, passing back each answer's state, +// and returns every finished line and the last open line. +func replayOutputDecode(t *testing.T, client *Client, chunks [][]byte, policy OutputEncodingPolicy) ([]OutputLine, OutputLine) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var state json.RawMessage + lines := []OutputLine{} + var open OutputLine + for _, chunk := range chunks { + decoded, err := client.DecodeOutputStyle(ctx, chunk, policy, state) + if err != nil { + t.Fatal(err) + } + lines = append(lines, decoded.Lines...) + open, state = decoded.Open, decoded.State + } + return lines, open +} + +func assertOutputDecode(t *testing.T, lines []OutputLine, open OutputLine, wantLines []OutputLine, wantOpen OutputLine) { + t.Helper() + if wantLines == nil { + wantLines = []OutputLine{} + } + if !reflect.DeepEqual(lines, wantLines) { + got, _ := json.Marshal(lines) + expected, _ := json.Marshal(wantLines) + t.Fatalf("lines = %s, want %s", got, expected) + } + if !reflect.DeepEqual(open, wantOpen) { + got, _ := json.Marshal(open) + expected, _ := json.Marshal(wantOpen) + t.Fatalf("open = %s, want %s", got, expected) + } +} diff --git a/desktop/internal/core/run_start.go b/desktop/internal/core/run_start.go index ad8bec7141..e507936952 100644 --- a/desktop/internal/core/run_start.go +++ b/desktop/internal/core/run_start.go @@ -57,6 +57,7 @@ type RunStart struct { Arguments []string `json:"arguments"` WorkingDirectory string `json:"workingDirectory"` Environment map[string]string `json:"environment"` + OutputEncoding string `json:"outputEncoding,omitempty"` TemporaryFiles []RunStartFile `json:"temporaryFiles"` Debug *RunStartDebug `json:"debug"` Rerun *RunStartRerun `json:"rerun"` diff --git a/desktop/internal/encodingname/encoding.go b/desktop/internal/encodingname/encoding.go new file mode 100644 index 0000000000..294abd84ef --- /dev/null +++ b/desktop/internal/encodingname/encoding.go @@ -0,0 +1,22 @@ +// Package encodingname supplies presentation names shared by the file and console encoding selectors. +package encodingname + +// labels are the names shown for Core's encoding ids; they are the encodings' own +// names, not translations. +var labels = map[string]string{ + "utf-8": "UTF-8", "utf-8-bom": "UTF-8 BOM", "utf-16le-bom": "UTF-16 LE BOM", "utf-16be-bom": "UTF-16 BE BOM", + "utf-16le": "UTF-16 LE", "utf-16be": "UTF-16 BE", "gbk": "GBK", "gb18030": "GB18030", "big5": "Big5", + "shift-jis": "Shift JIS", "euc-jp": "EUC-JP", "euc-kr": "EUC-KR", "windows-874": "Windows-874", + "windows-1250": "Windows-1250", "windows-1251": "Windows-1251", "windows-1252": "Windows-1252", + "windows-1253": "Windows-1253", "windows-1254": "Windows-1254", "windows-1255": "Windows-1255", + "windows-1256": "Windows-1256", "windows-1257": "Windows-1257", "windows-1258": "Windows-1258", + "koi8-r": "KOI8-R", +} + +// DisplayName returns the display name of a Core encoding ID, preserving unknown IDs. +func DisplayName(id string) string { + if label, ok := labels[id]; ok { + return label + } + return id +} diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index 5d4cc6f17c..6c96b4f349 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -577,6 +577,7 @@ type SettingsMessages struct { Build string Toolchains string Debuggers string + Console string Languages string Tools string SearchPage string diff --git a/desktop/internal/i18n/settings_messages.go b/desktop/internal/i18n/settings_messages.go index 7fe10c0a62..56042d0dc0 100644 --- a/desktop/internal/i18n/settings_messages.go +++ b/desktop/internal/i18n/settings_messages.go @@ -19,6 +19,7 @@ func settingsMessages(language Language) SettingsMessages { Build: Shared(language, "settings.groups.build"), Toolchains: Shared(language, "desktop.toolchains.title"), Debuggers: Shared(language, "desktop.buildSettings.debuggers"), + Console: Shared(language, "desktop.consoleSettings.title"), Languages: Shared(language, "settings.groups.languages"), Tools: Shared(language, "settings.groups.tools"), SearchPage: Shared(language, "desktop.search.settings.title"), diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 6929b4a1e2..1d05e28f48 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -415,6 +415,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.commit.unstageFailed": "Failed to unstage files: {reason}", "desktop.commit.unstageFile": "Unstage {path}", "desktop.commit.where": "{branch} · {head}", + "desktop.consoleSettings.automatic": "Automatic ({encodings})", + "desktop.consoleSettings.automaticFailed": "Automatic (could not read)", + "desktop.consoleSettings.automaticPending": "Automatic (loading)", + "desktop.consoleSettings.directory": "Output encoding: {encoding}", + "desktop.consoleSettings.encoding": "Output encoding", + "desktop.consoleSettings.encodingHelp": "How Lithe reads output from Run, Build and Tests.\nAutomatic uses UTF-8. On Windows only, a line that is not valid UTF-8 falls back to GBK. A run can explicitly declare another encoding.\nChoose an encoding to override automatic decoding. Changes apply to programs started afterwards.", + "desktop.consoleSettings.keywords": "console run build test output encoding charset garbled gbk utf-8", + "desktop.consoleSettings.otherwise": ", otherwise ", + "desktop.consoleSettings.outputCard": "Program Output", + "desktop.consoleSettings.readFailed": "Could not read output encodings.", + "desktop.consoleSettings.title": "Console", "desktop.credentials.importLegacy": "Import Plugin Credentials from Earlier Lithe…", "desktop.credentials.importLegacyBusy": "Importing Plugin Credentials…", "desktop.credentials.importLegacyConfirm": "Import", @@ -3642,6 +3653,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.commit.unstageFailed": "取消暂存文件失败:{reason}", "desktop.commit.unstageFile": "取消暂存 {path}", "desktop.commit.where": "{branch} · {head}", + "desktop.consoleSettings.automatic": "自动({encodings})", + "desktop.consoleSettings.automaticFailed": "自动(读取失败)", + "desktop.consoleSettings.automaticPending": "自动(检测中)", + "desktop.consoleSettings.directory": "输出编码:{encoding}", + "desktop.consoleSettings.encoding": "输出编码", + "desktop.consoleSettings.encodingHelp": "Lithe 怎样读取运行、构建和测试的输出。\n自动模式默认使用 UTF-8。仅 Windows 会在某一行不是合法 UTF-8 时尝试 GBK;运行也可以显式声明其他编码。\n选择具体编码会覆盖自动判断。修改后对之后启动的程序生效。", + "desktop.consoleSettings.keywords": "控制台 运行 构建 测试 输出 编码 字符集 乱码 console encoding gbk utf-8", + "desktop.consoleSettings.otherwise": ",否则 ", + "desktop.consoleSettings.outputCard": "程序输出", + "desktop.consoleSettings.readFailed": "无法读取输出编码。", + "desktop.consoleSettings.title": "控制台", "desktop.credentials.importLegacy": "从旧版 Lithe 导入插件凭据…", "desktop.credentials.importLegacyBusy": "正在导入插件凭据…", "desktop.credentials.importLegacyConfirm": "导入", diff --git a/desktop/internal/pluginservice/runs.go b/desktop/internal/pluginservice/runs.go index 88ad1d7232..c0e866bbfb 100644 --- a/desktop/internal/pluginservice/runs.go +++ b/desktop/internal/pluginservice/runs.go @@ -60,8 +60,10 @@ type RunEvent struct { Label string Workspace string Text string - ExitCode *int - Signal string + // OutputEncoding is the process's declaration, set on RunStarted before any output. + OutputEncoding string + ExitCode *int + Signal string // Rerun is set on RunStarted when the plugin supplied a rerun function. Rerun *RunRerun // PID is the run's root process on RunStarted, 0 when it has none (a debug launch). @@ -442,7 +444,7 @@ func (r *Runs) handleStart(ctx context.Context, params json.RawMessage) (json.Ra r.runs[run.id] = run r.wait.Add(1) r.mu.Unlock() - event := RunEvent{Type: RunStarted, RunID: run.id, PluginID: run.pluginID, Label: start.Label, Workspace: workspace.Path, PID: run.pid} + event := RunEvent{Type: RunStarted, RunID: run.id, PluginID: run.pluginID, Label: start.Label, Workspace: workspace.Path, PID: run.pid, OutputEncoding: start.OutputEncoding} if start.Rerun != nil { event.Rerun = &RunRerun{PluginID: run.pluginID, Function: start.Rerun.Function, Data: start.Rerun.Data, Workspace: workspace.Path} } diff --git a/desktop/internal/pluginservice/runs_test.go b/desktop/internal/pluginservice/runs_test.go index d6a1bdf142..8824f6b6a8 100644 --- a/desktop/internal/pluginservice/runs_test.go +++ b/desktop/internal/pluginservice/runs_test.go @@ -144,7 +144,9 @@ func (h *runHarness) params(t *testing.T, mode string, extra map[string]any) str }, } for key, value := range extra { - if key != "port" { + if key == "outputEncoding" { + params["process"].(map[string]any)[key] = value + } else if key != "port" { params[key] = value } } @@ -196,10 +198,10 @@ func exitedEvent(events []RunEvent) *RunEvent { func TestRunStartReportsOutputAndTheExitCode(t *testing.T) { h := newRunHarness(t) - result, refusal := respond(t, h.service, runFixturePlugin, "run/start", h.params(t, "print", nil)) + result, refusal := respond(t, h.service, runFixturePlugin, "run/start", h.params(t, "print", map[string]any{"outputEncoding": "cp936"})) id := startedRunID(t, result, refusal) events := h.await(t, "the run to exit", func(events []RunEvent) bool { return exitedEvent(events) != nil }) - if events[0].Type != RunStarted || events[0].RunID != id || events[0].Label != "Run print" { + if events[0].Type != RunStarted || events[0].RunID != id || events[0].Label != "Run print" || events[0].OutputEncoding != "gbk" { t.Fatalf("the first event = %+v, want the started run", events[0]) } var output strings.Builder diff --git a/desktop/internal/settingswindow/build_directory_view.go b/desktop/internal/settingswindow/build_directory_view.go index d8882a7b67..e423932c81 100644 --- a/desktop/internal/settingswindow/build_directory_view.go +++ b/desktop/internal/settingswindow/build_directory_view.go @@ -225,6 +225,11 @@ func (w *window) directoryEntries(language i18n.Language) []directoryEntry { entries = append(entries, entry) } separator := i18n.Shared(language, "desktop.buildSettings.listSeparator") + entries = append(entries, directoryEntry{ + key: "console", tile: consoleTile, icon: icons.SquareTerminal, title: titleOf(&w.text.Settings, pageConsole), + desc: i18n.SharedFormat(language, "desktop.consoleSettings.directory", map[string]string{"encoding": w.consoleEncodingLabel(w.sess.values.ConsoleEncoding)}), + open: func() { w.openBuildChild(pageConsole) }, + }) for _, kind := range buildKinds { var names []string count := 0 diff --git a/desktop/internal/settingswindow/build_style.go b/desktop/internal/settingswindow/build_style.go index 04007582a7..32fe58ff4d 100644 --- a/desktop/internal/settingswindow/build_style.go +++ b/desktop/internal/settingswindow/build_style.go @@ -437,6 +437,7 @@ func (w *window) glyphTile(c ui.C, color gfx.Color, icon gfx.Icon, size float32) var ( toolchainsTile = gfx.RGB24(0x30a46c) debuggersTile = gfx.RGB24(0xe5484d) + consoleTile = gfx.RGB24(0x6e56cf) kindTile = gfx.RGB24(0x3e7bfa) ) diff --git a/desktop/internal/settingswindow/console_view.go b/desktop/internal/settingswindow/console_view.go new file mode 100644 index 0000000000..70890b0076 --- /dev/null +++ b/desktop/internal/settingswindow/console_view.go @@ -0,0 +1,67 @@ +package settingswindow + +import ( + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" +) + +// consolePage edits the application's decoding preference. Core owns the encodings and +// automatic candidates; opening the page reads the snapshot without changing settings. +func (w *window) consolePage(c ui.C) { + language := w.marketLanguage() + encodings, known := w.consoleEncodings() + w.pageScroll(c, pageConsole, func() { + w.card(c, i18n.Shared(language, "desktop.consoleSettings.outputCard"), "", func() { + title := i18n.Shared(language, "desktop.consoleSettings.encoding") + w.settingsRow(c.Part("encoding-row"), title, i18n.Shared(language, "desktop.consoleSettings.encodingHelp"), func() { + choices := make([]string, 1, len(encodings.Choices)+1) + for _, encoding := range encodings.Choices { + choices = append(choices, encoding.ID) + } + value := w.sess.values.ConsoleEncoding + if ui.Select(c.Part("encoding"), &value, choices, w.consoleEncodingLabel).FillWidth().Label(title). + Disabled(!known || encodings.Error != "").Changed() { + w.setConsoleEncoding(value, false) + } + }) + if encodings.Error != "" { + ui.Wrap(c, encodings.Error).FontSize(12).Color(w.pal.danger) + } + }) + }) +} + +func (w *window) consoleEncodings() (ConsoleEncodings, bool) { + if read := w.ctrl.opts.ConsoleEncodings; read != nil { + return read() + } + return ConsoleEncodings{}, false +} + +func (w *window) consoleEncodingLabel(id string) string { + encodings, known := w.consoleEncodings() + if id != "" && id != "auto" { + for _, encoding := range encodings.Choices { + if encoding.ID == id { + return encoding.Label + } + } + return id + } + language := w.marketLanguage() + if encodings.Error != "" { + return i18n.Shared(language, "desktop.consoleSettings.automaticFailed") + } + if !known { + return i18n.Shared(language, "desktop.consoleSettings.automaticPending") + } + labels := make([]string, len(encodings.Automatic)) + for index, encoding := range encodings.Automatic { + labels[index] = encoding.Label + } + return i18n.SharedFormat(language, "desktop.consoleSettings.automatic", map[string]string{ + "encodings": strings.Join(labels, i18n.Shared(language, "desktop.consoleSettings.otherwise")), + }) +} diff --git a/desktop/internal/settingswindow/console_view_test.go b/desktop/internal/settingswindow/console_view_test.go new file mode 100644 index 0000000000..ae484a2eb0 --- /dev/null +++ b/desktop/internal/settingswindow/console_view_test.go @@ -0,0 +1,120 @@ +package settingswindow + +import ( + "context" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/encodingname" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// consoleTestEncodings uses the production resolver, with Windows compatibility enabled, +// to exercise the same catalog on every test host. +func consoleTestEncodings(t *testing.T) ConsoleEncodings { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + resolved, err := core.NewClient().ResolveOutputEncoding(ctx, core.OutputEncodingPolicy{Windows: true}) + if err != nil { + t.Fatal(err) + } + view := ConsoleEncodings{} + choice := func(id string) ConsoleEncoding { + return ConsoleEncoding{ID: id, Label: encodingname.DisplayName(id)} + } + for _, id := range resolved.Candidates { + view.Automatic = append(view.Automatic, choice(id)) + } + for _, id := range resolved.Encodings { + view.Choices = append(view.Choices, choice(id)) + } + return view +} + +func TestConsoleEncodingPageAppliesAndRestores(t *testing.T) { + encodings := consoleTestEncodings(t) + var changes []string + w := newWindow(NewController(Options{ + ConsoleEncodings: func() (ConsoleEncodings, bool) { return encodings, true }, + SetConsoleEncoding: func(value string) { changes = append(changes, value) }, + }), Values{}) + w.sess.page = pageConsole + d := openWindow(t, w) + title := i18n.Shared(i18n.English, "desktop.consoleSettings.encoding") + automatic := i18n.SharedFormat(i18n.English, "desktop.consoleSettings.automatic", map[string]string{"encodings": "UTF-8, otherwise GBK"}) + if len(changes) != 0 || d.hit(title).Value != automatic { + t.Fatalf("opening changed settings or missed automatic candidates: %v, %+v", changes, d.hit(title)) + } + d.click(title) + d.click("GBK") + if !slices.Equal(changes, []string{"gbk"}) || d.hit(title).Value != "GBK" { + t.Fatalf("selection = %v, control = %+v", changes, d.hit(title)) + } + d.click(w.text.Settings.RestoreDefaults) + if !slices.Equal(changes, []string{"gbk", ""}) || d.hit(title).Value != automatic { + t.Fatalf("restore = %v, control = %+v", changes, d.hit(title)) + } + d.click(w.text.Settings.Cancel) + w.setConsoleEncoding("big5", false) + if !slices.Equal(changes, []string{"gbk", ""}) { + t.Fatalf("a closed window wrote again: %v", changes) + } +} + +func TestConsoleEncodingPageReflectsCatalogArrivalAndFailure(t *testing.T) { + encodings, known := ConsoleEncodings{}, false + w := newWindow(NewController(Options{ + ConsoleEncodings: func() (ConsoleEncodings, bool) { return encodings, known }, + }), Values{}) + w.sess.page = pageConsole + d := openWindow(t, w) + title := i18n.Shared(i18n.English, "desktop.consoleSettings.encoding") + if hit := d.hit(title); !hit.Disabled || hit.Value != i18n.Shared(i18n.English, "desktop.consoleSettings.automaticPending") { + t.Fatalf("pending = %+v", hit) + } + encodings, known = consoleTestEncodings(t), true + w.inv.Invalidate() + d.pump() + if hit := d.hit(title); hit.Disabled || hit.Value == i18n.Shared(i18n.English, "desktop.consoleSettings.automaticPending") { + t.Fatalf("resolved = %+v", hit) + } + encodings = ConsoleEncodings{Error: i18n.Shared(i18n.English, "desktop.consoleSettings.readFailed")} + w.inv.Invalidate() + d.pump() + if hit := d.hit(title); !hit.Disabled || hit.Value != i18n.Shared(i18n.English, "desktop.consoleSettings.automaticFailed") || !d.text(encodings.Error) { + t.Fatalf("failed = %+v", hit) + } +} + +func TestConsoleEncodingPageBelongsToBuildAndMatchesSearch(t *testing.T) { + if parents[pageConsole] != pageBuild { + t.Fatal("Console is not under Build, Execution, Deployment") + } + w := newWindow(NewController(Options{SettingsNavigation: core.NewClient().SettingsNavigation}), Values{}) + d := openWindow(t, w) + entries := w.directoryEntries(i18n.English) + for _, entry := range entries { + if entry.key == "console" { + entry.open() + if w.sess.page != pageConsole { + t.Fatal("directory entry did not open Console") + } + w.searchField.SetText("GBK") + w.inv.Invalidate() + d.pump() + d.until("Console in the Core-projected encoding search", func() bool { + for _, row := range w.rows { + if row.page == pageConsole { + return true + } + } + return false + }) + return + } + } + t.Fatal("Console missing from the Build directory") +} diff --git a/desktop/internal/settingswindow/console_visual_test.go b/desktop/internal/settingswindow/console_visual_test.go new file mode 100644 index 0000000000..d19c51c35f --- /dev/null +++ b/desktop/internal/settingswindow/console_visual_test.go @@ -0,0 +1,54 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/headless" +) + +// TestVisualConsoleEncoding renders the production settings page using Core's real catalog. +func TestVisualConsoleEncoding(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture console settings") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + encodings := consoleTestEncodings(t) + for _, language := range []i18n.Language{i18n.English, i18n.Chinese} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"/"+theme, func(t *testing.T) { + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, + SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, + ConsoleEncodings: func() (ConsoleEncodings, bool) { return encodings, true }, + }), Values{Theme: theme, Language: language.Code()}) + w.sess.page = pageConsole + session, err := headless.Open(w.config(), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + title := i18n.Shared(language, "desktop.consoleSettings.encoding") + if !d.has(title) { + t.Fatal("Console page did not render") + } + for _, state := range []string{"page", "choices"} { + if state == "choices" { + d.click(title) + } + if err := session.Screenshot(filepath.Join(out, "console-"+state+"-"+theme+"-"+language.Code()+".png")); err != nil { + t.Fatal(err) + } + } + }) + } + } +} diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 96573b94a1..9d0c8736bc 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -121,6 +121,8 @@ type Values struct { // ProcessTermination is the Process Termination page's part of Core's termination // settings; the zero value keeps Core's defaults. ProcessTermination ProcessTermination + // ConsoleEncoding is the output encoding override; empty asks Core to decide per line. + ConsoleEncoding string // SteppingFilters are the user's stepping policies by debug adapter ID. An adapter // without an entry uses the defaults its plugin declares. SteppingFilters map[string]core.DebugSteppingFilters @@ -189,6 +191,18 @@ type StopTime struct { Default, Min, Max int } +// ConsoleEncoding is one encoding Core supports, with its display name. +type ConsoleEncoding struct { + ID, Label string +} + +// ConsoleEncodings is Core's automatic candidates and selectable encodings, in order. +// Error is a failed read; no choices are offered until the read succeeds. +type ConsoleEncodings struct { + Automatic, Choices []ConsoleEncoding + Error string +} + // Seconds is the stop time value gives, as Core applies it. func (t StopTime) Seconds(value ProcessTermination) int { if value.GracefulStopSeconds == nil { @@ -466,6 +480,11 @@ type Options struct { // SetProcessTermination hands a change of Values.ProcessTermination to the settings // owner, like SetTabRows. SetProcessTermination func(ProcessTermination) + // SetConsoleEncoding stores the application preference for newly started consoles. + SetConsoleEncoding func(string) + // ConsoleEncodings reads the resolved encoding catalog safely from the window thread. + // ok is false until Core answers. + ConsoleEncodings func() (encodings ConsoleEncodings, ok bool) // StopTime reads Core's rule for the stop time; it is safe from the window thread, and ok // is false until Core has answered. Nil hides the stop time, for a platform where a // stopped program is ended at once. diff --git a/desktop/internal/settingswindow/model.go b/desktop/internal/settingswindow/model.go index 099ecab129..b25a14c420 100644 --- a/desktop/internal/settingswindow/model.go +++ b/desktop/internal/settingswindow/model.go @@ -31,12 +31,14 @@ const ( pagePlugins pageVersionControl // pageBuild is the group "Build, Execution, Deployment", which also has a page of its - // own: the directory of its pages and what needs attention. The two pages after it + // own: the directory of its pages and what needs attention. The three pages after it // belong to it, and so does a row for each kind of page plugins contribute to it, build - // systems and compilers, which opens that kind's pages as the two pages list theirs. + // systems and compilers, which opens that kind's pages as Toolchains and Debuggers list + // theirs. pageBuild pageToolchains pageDebuggers + pageConsole pageLanguages // pageTools is the group "Tools"; the page after it belongs to it. pageTools @@ -70,6 +72,7 @@ var parents = [pageCount]pageID{ pageBuild: noPage, pageToolchains: pageBuild, pageDebuggers: pageBuild, + pageConsole: pageBuild, pageLanguages: noPage, pageTools: noPage, pageTerminal: pageTools, @@ -132,6 +135,8 @@ func titleOf(messages *i18n.SettingsMessages, id pageID) string { return messages.Toolchains case pageDebuggers: return messages.Debuggers + case pageConsole: + return messages.Console case pageLanguages: return messages.Languages case pageTools: @@ -322,6 +327,8 @@ func pageKeywords(language i18n.Language, id pageID) string { return i18n.Shared(language, "desktop.buildSettings.keywordsToolchains") case pageDebuggers: return i18n.Shared(language, "desktop.buildSettings.keywordsDebuggers") + case pageConsole: + return i18n.Shared(language, "desktop.consoleSettings.keywords") } return "" } diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index 172b8caebc..62be178c9e 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -708,6 +708,17 @@ func (w *window) setProcessTermination(value ProcessTermination, force bool) { } } +// setConsoleEncoding stores a decoding preference for newly started consoles. +func (w *window) setConsoleEncoding(value string, force bool) { + if w.sess.finished.Load() || (!force && w.sess.values.ConsoleEncoding == value) { + return + } + w.sess.values.ConsoleEncoding = value + if w.ctrl.opts.SetConsoleEncoding != nil { + w.ctrl.opts.SetConsoleEncoding(value) + } +} + // sameProcessTermination compares two settings by what they store. func sameProcessTermination(a, b ProcessTermination) bool { confirms := func(v *bool) int { diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index 80ce01be42..5b536c2263 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -372,6 +372,8 @@ func (w *window) content(c ui.C) { w.toolchainsPage(c) case w.sess.page == pageDebuggers: w.debuggersPage(c) + case w.sess.page == pageConsole: + w.consolePage(c) case w.sess.page == pageTerminal && w.ctrl.opts.TerminalShells != nil: w.terminalPage(c) case w.sess.page == pageSearch: @@ -716,6 +718,7 @@ func (w *window) footer(c ui.C) { w.setVimMode(false, true) w.resetEditorPresentation() w.setProcessTermination(ProcessTermination{}, true) + w.setConsoleEncoding("", true) w.resetSteppingFilters() w.setTerminalShell("", true) w.setTerminalBehavior(TerminalBehavior{}, true) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index b5c60936d7..b92053a33b 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -98,7 +98,8 @@ type Kernel interface { processExitKernel processMemoryKernel MatchOutputLinks(context.Context, core.OutputLinkRequest) ([]core.OutputLink, error) - DecodeOutputStyle(ctx context.Context, text string, state json.RawMessage) (core.OutputStyleDecoding, error) + DecodeOutputStyle(ctx context.Context, chunk []byte, policy core.OutputEncodingPolicy, state json.RawMessage) (core.OutputStyleDecoding, error) + ResolveOutputEncoding(ctx context.Context, policy core.OutputEncodingPolicy) (core.OutputEncodings, error) CreateDebugSession(ctx context.Context, request core.DebugCreateSessionRequest) (core.DebugUpdate, error) LaunchDebug(ctx context.Context, sessionID, operationID string, configuration core.DebugLaunchConfiguration) (core.DebugUpdate, error) NormalizeSteppingFilters(ctx context.Context, adapterID string, filters core.DebugSteppingFilters) (core.DebugSteppingFilters, error) @@ -387,6 +388,7 @@ type settings struct { // ProcessTermination is the user's part of Core's process termination settings, as the // Process Termination page edits it; the zero value keeps Core's defaults. ProcessTermination settingswindow.ProcessTermination `json:"processTermination,omitzero"` + ConsoleEncoding string `json:"consoleEncoding,omitempty"` // DebugSteppingFilters are the user's stepping policies by debug adapter ID, as Core // normalized them; an adapter without one uses its plugin's declared defaults. DebugSteppingFilters map[string]core.DebugSteppingFilters `json:"debugSteppingFilters,omitempty"` @@ -644,6 +646,9 @@ type App struct { // stopTime is Core's rule for the stop time once it was read (refreshStopGrace); the // settings window reads it from its own thread. stopTime atomic.Pointer[settingswindow.StopTime] + // Console policies are read by process goroutines; the catalog by the settings window. + consoleEncoding atomic.Pointer[string] + consoleEncodings atomic.Pointer[settingswindow.ConsoleEncodings] settingsSubscription *settingsSubscription // plugins is the plugin stack, nil when the window was built without a plugin @@ -864,6 +869,8 @@ func New(options Options) *App { if settingsErr != nil { a.settings = settings{} } + consoleEncoding := a.settings.ConsoleEncoding + a.consoleEncoding.Store(&consoleEncoding) // A value of a shape this version cannot take leaves only its own setting on the default; // the rest loaded. It is logged below with the failures, and the notice tells it is kept. settingsUnread := a.store.Unread(settingsFile) @@ -1028,6 +1035,7 @@ func (a *App) Run() error { // Core's stop time applies to every process stopped from now on, and Core decides what an // earlier run left behind; both need the window, which delivers their answers. a.refreshStopGrace() + a.refreshConsoleEncodings() a.planStartupSweep() // Development builds mark the Dock icon without changing the product name in the UI. if buildinfo.Development { diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index a13965a8ec..fbd58770fd 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -172,7 +172,7 @@ func (a *App) beginRunOperation(p *project, label, configuration, key string, re // beginOperation begins a task, or with key an application run, as beginBuildOperation says. func (a *App) beginOperation(p *project, kind, label, configuration, key string, restart func(*App, *project)) *buildOperation { - operation := &buildOperation{configuration: configuration, key: key, stopped: make(chan struct{}), decoder: newOutputDecoder(a.kernel)} + operation := &buildOperation{configuration: configuration, key: key, stopped: make(chan struct{}), decoder: newOutputDecoder(a.kernel, a.outputEncodingPolicy())} p.build.sessions++ operation.session = &runEntry{ id: "build-" + strconv.Itoa(p.build.sessions), label: label, restart: restart, operation: operation, @@ -1990,6 +1990,7 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build return func(a *App) { a.finishBuildError(p, op, prepare.Err()) } } workingDirectory := filepath.Join(p.root, filepath.FromSlash(launch.WorkingDirectory)) + op.decoder.declare(launch.OutputEncoding) process, err := buildprocess.Start(ctx, buildprocess.Spec{ Kind: processledger.KindBuild, Executable: execution.Executable, diff --git a/desktop/internal/workbench/build_sync.go b/desktop/internal/workbench/build_sync.go index df5666814e..d0cf19b395 100644 --- a/desktop/internal/workbench/build_sync.go +++ b/desktop/internal/workbench/build_sync.go @@ -57,7 +57,7 @@ func (a *App) beginBuildSync(p *project, instance *buildInstance) *buildSyncFeed if shown != nil && shown.running && p.runEntry(shown.id) == shown { p.build.view = shown.id } - return &buildSyncFeed{app: a, project: p, session: session, stopped: sync.stopped, decoder: newOutputDecoder(a.kernel)} + return &buildSyncFeed{app: a, project: p, session: session, stopped: sync.stopped, decoder: newOutputDecoder(a.kernel, a.outputEncodingPolicy())} } // buildSyncLabel names the session of a model load of instance: its build system, and its root diff --git a/desktop/internal/workbench/chrome.go b/desktop/internal/workbench/chrome.go index 13e2af19b8..fb52f20558 100644 --- a/desktop/internal/workbench/chrome.go +++ b/desktop/internal/workbench/chrome.go @@ -6,6 +6,7 @@ import ( "strconv" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/encodingname" ) // gearMenuWidth is the width of the settings button's menu, which holds five short items @@ -124,10 +125,10 @@ func (a *App) chromeStatusText(i int) string { case itemEncoding: if a.project != nil { if doc := a.project.selectedDocument(a.project.docs.group); doc != nil { - return encodingLabel(doc.encodingID()) + return encodingname.DisplayName(doc.encodingID()) } } - return encodingLabel("utf-8") + return encodingname.DisplayName("utf-8") case itemIndent: if doc := a.selectedEditorDocument(); doc != nil { size, spaces := doc.view.IndentSettings() diff --git a/desktop/internal/workbench/console_encoding.go b/desktop/internal/workbench/console_encoding.go new file mode 100644 index 0000000000..ca449690b6 --- /dev/null +++ b/desktop/internal/workbench/console_encoding.go @@ -0,0 +1,64 @@ +package workbench + +import ( + "context" + "runtime" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/encodingname" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" +) + +// outputEncodingPolicy snapshots the application preference for a new console. Process +// observers may call it off the window thread, so it never reads mutable settings. +func (a *App) outputEncodingPolicy() core.OutputEncodingPolicy { + policy := core.OutputEncodingPolicy{Windows: runtime.GOOS == "windows"} + if setting := a.consoleEncoding.Load(); setting != nil { + policy.Setting = *setting + } + return policy +} + +func (a *App) setConsoleEncoding(value string) { + a.settings.ConsoleEncoding = value + a.consoleEncoding.Store(&value) + a.saveSettings() +} + +// refreshConsoleEncodings reads the catalog and automatic candidates from the same Core +// resolver used by decoding. The immutable snapshot can be read from the settings thread. +func (a *App) refreshConsoleEncodings() { + if a.kernel == nil { + return + } + policy := core.OutputEncodingPolicy{Windows: runtime.GOOS == "windows"} + a.background(nil, outputDecodeTimeout, func(ctx context.Context) func(*App) { + resolved, err := a.kernel.ResolveOutputEncoding(ctx, policy) + return func(a *App) { + view := settingswindow.ConsoleEncodings{} + if err != nil { + a.backgroundFailed("console_encodings", err) + view.Error = i18n.Shared(a.language(), "desktop.consoleSettings.readFailed") + } else { + for _, id := range resolved.Candidates { + view.Automatic = append(view.Automatic, settingswindow.ConsoleEncoding{ID: id, Label: encodingname.DisplayName(id)}) + } + for _, id := range resolved.Encodings { + view.Choices = append(view.Choices, settingswindow.ConsoleEncoding{ID: id, Label: encodingname.DisplayName(id)}) + } + } + a.consoleEncodings.Store(&view) + if a.settingsWindow != nil { + a.settingsWindow.Invalidate() + } + } + }) +} + +func (a *App) consoleEncodingsOption() (settingswindow.ConsoleEncodings, bool) { + if resolved := a.consoleEncodings.Load(); resolved != nil { + return *resolved, true + } + return settingswindow.ConsoleEncodings{}, false +} diff --git a/desktop/internal/workbench/console_encoding_test.go b/desktop/internal/workbench/console_encoding_test.go new file mode 100644 index 0000000000..ec3ec224d3 --- /dev/null +++ b/desktop/internal/workbench/console_encoding_test.go @@ -0,0 +1,155 @@ +package workbench + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// TestConsoleEncodingPipeHelper writes bytes through the same native pipes as a run. +// Waiting for stdin prevents the OS from combining both halves of the GBK character. +func TestConsoleEncodingPipeHelper(t *testing.T) { + stream := os.Getenv("LITHE_TEST_ENCODING_PIPE") + if stream == "" { + return + } + output := os.Stdout + if stream == "stderr" { + output = os.Stderr + } + if _, err := output.WriteString("编译\n\x1b[32m\xb9\xb9\xbd"); err != nil { + os.Exit(2) + } + var ack [1]byte + if _, err := io.ReadFull(os.Stdin, ack[:]); err != nil { + os.Exit(3) + } + if _, err := output.WriteString("\xa8\xb3\xc9\xb9\xa6\x1b[m\r\n"); err != nil { + os.Exit(4) + } + os.Exit(0) +} + +func TestConsoleEncodingThroughNativeProcessPipes(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + for _, stream := range []string{"stdout", "stderr"} { + t.Run(stream, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + input, ack, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer input.Close() + defer ack.Close() + d := newOutputDecoder(core.NewClient(), core.OutputEncodingPolicy{Windows: true}) + buffer := newOutputBuffer(100, 1<<20) + first := make(chan struct{}, 1) + var raw string + var decodeError error + process, err := buildprocess.Start(ctx, buildprocess.Spec{ + Executable: executable, Arguments: []string{"-test.run=^TestConsoleEncodingPipeHelper$"}, + WorkingDirectory: t.TempDir(), Stdin: input, + Environment: map[string]string{"LITHE_TEST_ENCODING_PIPE": stream}, + }, func(kind buildprocess.Stream, text string) { + if string(kind) != stream { + return + } + raw += text + d.deliver(text, func(chunk outputChunk, err error) { + if err != nil { + decodeError = err + } + buffer.apply(chunk) + }) + if strings.HasSuffix(raw, "\xb9\xb9\xbd") { + first <- struct{}{} + } + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { process.Kill(); _ = process.Wait() }) + select { + case <-first: + case <-ctx.Done(): + t.Fatal("the process did not write the first half of the GBK character") + } + if _, err := fmt.Fprint(ack, "x"); err != nil { + t.Fatal(err) + } + if err := process.Wait(); err != nil { + t.Fatal(err) + } + if decodeError != nil || buffer.all() != "编译\n构建成功\n" { + t.Fatalf("pipe output = %q, decode error = %v", buffer.all(), decodeError) + } + if spans := buffer.lines[1].spans; len(spans) != 1 || spans[0].Length != 4 { + t.Fatalf("GBK style ranges = %+v", spans) + } + }) + } +} + +// TestConsoleDecoderPreservesRawBytesAndStyles checks the boundary that previously let +// JSON replace GBK bytes before Core could see them, including a split inside a character. +func TestConsoleDecoderPreservesRawBytesAndStyles(t *testing.T) { + d := newOutputDecoder(core.NewClient(), core.OutputEncodingPolicy{Windows: true}) + b := newOutputBuffer(100, 1<<20) + for _, raw := range []string{"编译\n\x1b[32m\xb9\xb9\xbd", "\xa8\xb3\xc9\xb9\xa6\x1b[m\r\n"} { + d.deliver(raw, func(chunk outputChunk, err error) { + if err != nil { + t.Fatal(err) + } + b.apply(chunk) + }) + } + if b.all() != "编译\n构建成功\n" { + t.Fatalf("decoded text = %q", b.all()) + } + if spans := b.lines[1].spans; len(spans) != 1 || spans[0].Start != 0 || spans[0].Length != 4 || spans[0].Style.Foreground == nil || spans[0].Style.Foreground.Index == nil || *spans[0].Style.Foreground.Index != 2 { + t.Fatalf("GBK colour ranges = %+v", spans) + } +} + +func TestConsoleEncodingSettingIsCapturedForEachNewDecoder(t *testing.T) { + h := newHarness(t, core.NewClient()) + h.app.setConsoleEncoding("gbk") + before := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()) + h.app.setConsoleEncoding("utf-8") + after := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()) + for _, scenario := range []struct { + decoder *outputDecoder + want string + }{{before, "茅"}, {after, "é"}} { + chunk, err := scenario.decoder.decode("é\n") + if err != nil || len(chunk.lines) != 1 || chunk.lines[0].text != scenario.want { + t.Fatalf("decoded = %+v, err = %v, want %q", chunk, err, scenario.want) + } + } + var stored settings + if _, err := h.store.Load(settingsFile, &stored); err != nil || stored.ConsoleEncoding != "utf-8" { + t.Fatalf("saved encoding = %q, err = %v", stored.ConsoleEncoding, err) + } +} + +func TestConsoleDecoderCarriesCharactersAcrossItsOwnPieces(t *testing.T) { + d := newOutputDecoder(core.NewClient(), core.OutputEncodingPolicy{Setting: "gbk"}) + // Bound the unfinished line below Core's line limit, with a GBK lead byte at the + // desktop's 256 KiB piece boundary. + prefix := strings.Repeat("x\n", outputDecodePiece/2-1) + "x" + chunk, err := d.decode(prefix + "\xb9\xb9\n") + if err != nil || len(chunk.lines) == 0 || chunk.lines[len(chunk.lines)-1].text != "x构" { + t.Fatalf("last decoded line was corrupted, err = %v", err) + } +} diff --git a/desktop/internal/workbench/console_selection_test.go b/desktop/internal/workbench/console_selection_test.go index 20b6dfaa47..5fb8469e85 100644 --- a/desktop/internal/workbench/console_selection_test.go +++ b/desktop/internal/workbench/console_selection_test.go @@ -15,7 +15,7 @@ func showRunConsole(t *testing.T, text string) (*harness, *runEntry) { h.open(t.TempDir()) p := h.app.project run := &runEntry{id: "run-1", label: "Serve", output: newOutputBuffer(runOutputMaxLines, runOutputBytes)} - chunk, err := newOutputDecoder(h.app.kernel).decode(text) + chunk, err := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()).decode(text) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/workbench/context_menu_test.go b/desktop/internal/workbench/context_menu_test.go index 3dc50247a9..4d1f97c60f 100644 --- a/desktop/internal/workbench/context_menu_test.go +++ b/desktop/internal/workbench/context_menu_test.go @@ -84,7 +84,7 @@ func TestRunConsoleMenuCopiesTheChosenLineAndTheWholeOutput(t *testing.T) { h.open(t.TempDir()) p := h.app.project run := &runEntry{id: "run-1", label: "Serve", output: newOutputBuffer(runOutputMaxLines, runOutputBytes)} - chunk, err := newOutputDecoder(h.app.kernel).decode("first line\nsecond line\n") + chunk, err := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()).decode("first line\nsecond line\n") if err != nil { t.Fatal(err) } diff --git a/desktop/internal/workbench/encoding.go b/desktop/internal/workbench/encoding.go index e1608a1e58..9dc5698992 100644 --- a/desktop/internal/workbench/encoding.go +++ b/desktop/internal/workbench/encoding.go @@ -8,6 +8,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/documentio" "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/encodingname" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/vivaui/viva/ui" ) @@ -24,22 +25,6 @@ import ( // utf8BOM leads a UTF-8 file with a byte order mark. var utf8BOM = []byte{0xEF, 0xBB, 0xBF} -// encodingLabels are the names shown for Core's encoding ids; they are the encodings' own -// names, not translations. -var encodingLabels = map[string]string{ - "utf-8": "UTF-8", "utf-8-bom": "UTF-8 BOM", "utf-16le-bom": "UTF-16 LE BOM", "utf-16be-bom": "UTF-16 BE BOM", - "utf-16le": "UTF-16 LE", "utf-16be": "UTF-16 BE", "gbk": "GBK", "gb18030": "GB18030", "big5": "Big5", - "shift-jis": "Shift JIS", "euc-jp": "EUC-JP", "euc-kr": "EUC-KR", "windows-1250": "Windows-1250", - "windows-1251": "Windows-1251", "windows-1252": "Windows-1252", "koi8-r": "KOI8-R", -} - -func encodingLabel(id string) string { - if label, ok := encodingLabels[id]; ok { - return label - } - return id -} - // encodingID is the document's encoding as Core names it. func (d *document) encodingID() string { if d.encoding == "" { @@ -162,7 +147,7 @@ func (a *App) encodingMenu(c ui.C, anchor ui.Box) { menu.Sub(i18n.Shared(language, "desktop.encoding.reopen"), func(sub *ui.MenuItems) { sub.WidthRange(180, 180) for _, id := range core.FileEncodings { - if sub.Item(encodingLabel(id)).Clicked() { + if sub.Item(encodingname.DisplayName(id)).Clicked() { c.After(func() { a.reopenWithEncoding(p, d, id) }) } } @@ -170,7 +155,7 @@ func (a *App) encodingMenu(c ui.C, anchor ui.Box) { menu.Sub(i18n.Shared(language, "desktop.encoding.saveAs"), func(sub *ui.MenuItems) { sub.WidthRange(180, 180) for _, id := range core.FileEncodings { - if sub.Item(encodingLabel(id)).Clicked() { + if sub.Item(encodingname.DisplayName(id)).Clicked() { c.After(func() { a.saveWithEncoding(p, d, id) }) } } @@ -270,7 +255,7 @@ type encodingChoice struct { func (a *App) saveEncodingName(id int) string { if p := a.project; p != nil { if d := p.docs.find(id); d != nil { - return encodingLabel(d.encodingID()) + return encodingname.DisplayName(d.encodingID()) } } return "" diff --git a/desktop/internal/workbench/output_style.go b/desktop/internal/workbench/output_style.go index b53f3ec422..ea642a4e95 100644 --- a/desktop/internal/workbench/output_style.go +++ b/desktop/internal/workbench/output_style.go @@ -33,27 +33,39 @@ type outputChunk struct { } // outputDecoder turns one console's output into styled lines through Core's outputStyle.decode, -// carrying Core's state from chunk to chunk. It runs on the goroutines that read the output, never -// on the window thread: deliver decodes and hands the result to post while holding the decoder, so -// the chunks of a console that two streams write reach the window in the order they were decoded. +// carrying Core's state from chunk to chunk. The output is the bytes the process wrote, which Core +// decodes line by line with the encoding the policy picks for each line, so a chunk may end inside +// a character. It runs on the goroutines that read the output, never on the window thread: deliver +// decodes and hands the result to post while holding the decoder, so the chunks of a console that +// two streams write reach the window in the order they were decoded. type outputDecoder struct { kernel Kernel mu sync.Mutex + // policy is the console encoding setting and platform when the console began, and the + // encoding its process declared. + policy core.OutputEncodingPolicy state json.RawMessage - // carry is the start of a character the previous text ended inside. - carry string // open is the line still being written, kept for the plain fallback. open styledLine - // plain is set once Core failed: the rest of the console is split into lines as it is. + // plain is set once Core failed: the rest of the console is split into lines as it is, with + // bytes that are not UTF-8 replaced. plain bool } -func newOutputDecoder(kernel Kernel) *outputDecoder { - return &outputDecoder{kernel: kernel} +func newOutputDecoder(kernel Kernel, policy core.OutputEncodingPolicy) *outputDecoder { + return &outputDecoder{kernel: kernel, policy: policy} } -// deliver decodes text and passes the result to post, with failure set the first time Core could -// not decode this console's output; the window thread logs it once. +// declare records the encoding the console's process says it writes, tried before the others in +// automatic mode; empty is none. Call it before the process writes. +func (d *outputDecoder) declare(encoding string) { + d.mu.Lock() + defer d.mu.Unlock() + d.policy.Declared = encoding +} + +// deliver decodes the bytes text holds and passes the result to post, with failure set the first +// time Core could not decode this console's output; the window thread logs it once. func (d *outputDecoder) deliver(text string, post func(chunk outputChunk, failure error)) { d.mu.Lock() defer d.mu.Unlock() @@ -63,26 +75,14 @@ func (d *outputDecoder) deliver(text string, post func(chunk outputChunk, failur // decode is deliver without the lock and the hand-off; d.mu is held. func (d *outputDecoder) decode(text string) (outputChunk, error) { - text = d.carry + text - d.carry = "" - if cut := completeUTF8(text); cut < len(text) { - d.carry, text = text[cut:], text[:cut] - } chunk := outputChunk{open: d.open} var failure error for len(text) > 0 { - piece := text - if len(piece) > outputDecodePiece { - cut := outputDecodePiece - for cut > 0 && !utf8.RuneStart(piece[cut]) { - cut-- - } - piece = piece[:cut] - } + piece := text[:min(len(text), outputDecodePiece)] text = text[len(piece):] if !d.plain { ctx, cancel := context.WithTimeout(context.Background(), outputDecodeTimeout) - decoded, err := d.kernel.DecodeOutputStyle(ctx, piece, d.state) + decoded, err := d.kernel.DecodeOutputStyle(ctx, []byte(piece), d.policy, d.state) cancel() if err == nil { d.state = decoded.State @@ -94,7 +94,7 @@ func (d *outputDecoder) decode(text string) (outputChunk, error) { } d.plain, d.state, failure = true, nil, err } - chunk.lines, chunk.open = splitPlainOutput(chunk.lines, chunk.open, piece) + chunk.lines, chunk.open = splitPlainOutput(chunk.lines, chunk.open, strings.ToValidUTF8(piece, string(utf8.RuneError))) } d.open = chunk.open return chunk, failure @@ -114,21 +114,6 @@ func splitPlainOutput(lines []styledLine, open styledLine, text string) ([]style } } -// completeUTF8 returns how much of text ends on a character boundary: a character the text ends -// inside is left for the next text. -func completeUTF8(text string) int { - for back := 1; back < utf8.UTFMax && back <= len(text); back++ { - start := len(text) - back - if utf8.RuneStart(text[start]) { - if utf8.FullRuneInString(text[start:]) { - return len(text) - } - return start - } - } - return len(text) -} - // outputBuffer is one console's bounded output: finished lines, oldest first, and the line still // being written. The oldest lines go first when it holds more than maxLines lines or maxBytes // bytes. start is the sequence number of lines[0] and sequence counts the lines ever finished, so diff --git a/desktop/internal/workbench/outputlinks_test.go b/desktop/internal/workbench/outputlinks_test.go index 90e43492ed..267835bb86 100644 --- a/desktop/internal/workbench/outputlinks_test.go +++ b/desktop/internal/workbench/outputlinks_test.go @@ -30,7 +30,7 @@ const outputLinkManifest = `{ func (h *harness) startRunConsole(root, text string) { h.t.Helper() h.app.applyRunEvent(pluginservice.RunEvent{Type: pluginservice.RunStarted, RunID: "run-test", PluginID: "dev.lithe.test.output-links", Label: "Test run", Workspace: root}) - chunk, err := newOutputDecoder(h.app.kernel).decode(text) + chunk, err := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()).decode(text) if err != nil { h.t.Fatal(err) } diff --git a/desktop/internal/workbench/readonly_text_selection_visual_test.go b/desktop/internal/workbench/readonly_text_selection_visual_test.go index e8a84e7f7f..85ae0e0f2e 100644 --- a/desktop/internal/workbench/readonly_text_selection_visual_test.go +++ b/desktop/internal/workbench/readonly_text_selection_visual_test.go @@ -57,7 +57,7 @@ func TestVisualReadOnlyTextSelection(t *testing.T) { h.open(t.TempDir()) p := h.app.project run := &runEntry{id: "run-1", label: "Main", output: newOutputBuffer(runOutputMaxLines, runOutputBytes)} - chunk, err := newOutputDecoder(h.app.kernel).decode(stackTrace) + chunk, err := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()).decode(stackTrace) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/workbench/run_console_wrap_visual_test.go b/desktop/internal/workbench/run_console_wrap_visual_test.go index b2f29bd10e..b49e448058 100644 --- a/desktop/internal/workbench/run_console_wrap_visual_test.go +++ b/desktop/internal/workbench/run_console_wrap_visual_test.go @@ -52,7 +52,7 @@ func TestVisualRunConsoleWrap(t *testing.T) { h.open(t.TempDir()) p := h.app.project run := &runEntry{id: "run-1", label: "Makefile", output: newOutputBuffer(runOutputMaxLines, runOutputBytes)} - chunk, err := newOutputDecoder(h.app.kernel).decode(wrapOutput) + chunk, err := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()).decode(wrapOutput) if err != nil { t.Fatal(err) } diff --git a/desktop/internal/workbench/runs.go b/desktop/internal/workbench/runs.go index 90be47d9bf..7c5f373927 100644 --- a/desktop/internal/workbench/runs.go +++ b/desktop/internal/workbench/runs.go @@ -97,7 +97,9 @@ func (a *App) wirePluginRuns() { // only adds the decoded lines. switch event.Type { case pluginservice.RunStarted: - decoders.start(event.RunID, newOutputDecoder(a.kernel)) + policy := a.outputEncodingPolicy() + policy.Declared = event.OutputEncoding + decoders.start(event.RunID, newOutputDecoder(a.kernel, policy)) case pluginservice.RunOutput: if decoder := decoders.get(event.RunID); decoder != nil { id := event.RunID diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index 05c29f9b29..725d9d55ec 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -214,7 +214,11 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { SetProcessTermination: func(value settingswindow.ProcessTermination) { a.post(func(a *App) { a.setProcessTermination(value) }) }, - StopTime: a.stopTimeOption(), + StopTime: a.stopTimeOption(), + SetConsoleEncoding: func(value string) { + a.post(func(a *App) { a.setConsoleEncoding(value) }) + }, + ConsoleEncodings: a.consoleEncodingsOption, SweepsLeftovers: processledger.Supported, SteppingAdapters: a.steppingAdapters, NormalizeSteppingFilters: a.kernel.NormalizeSteppingFilters, @@ -441,6 +445,7 @@ func (a *App) openSettingsPageWith(surface actionSurface, page settingsPage, que VimMode: a.settings.VimMode, DisableAutoSave: a.settings.DisableAutoSave, ProcessTermination: a.settings.ProcessTermination, + ConsoleEncoding: a.settings.ConsoleEncoding, SteppingFilters: maps.Clone(a.settings.DebugSteppingFilters), Fonts: fontprefs.Normalize(a.settings.Fonts), Keymap: maps.Clone(a.settings.Keymap), diff --git a/desktop/internal/workbench/tests.go b/desktop/internal/workbench/tests.go index f3a30ed1a3..40388d5b54 100644 --- a/desktop/internal/workbench/tests.go +++ b/desktop/internal/workbench/tests.go @@ -258,7 +258,7 @@ func (a *App) executeTestCommand(ctx context.Context, p *project, instance build return func(a *App) { a.finishTestError(p, generation, err) } } output := &testOutput{} - decoder := newOutputDecoder(a.kernel) + decoder := newOutputDecoder(a.kernel, a.outputEncodingPolicy()) operation := &testOperation{} workingDirectory := filepath.Join(p.root, filepath.FromSlash(plan.WorkingDirectory)) process, err := buildprocess.Start(ctx, buildprocess.Spec{ @@ -315,7 +315,7 @@ func (a *App) executeTestProvider(ctx context.Context, p *project, instance buil p.tests.status = a.text.Tests.Running }) output := &testOutput{} - decoder := newOutputDecoder(a.kernel) + decoder := newOutputDecoder(a.kernel, a.outputEncodingPolicy()) var providerResult json.RawMessage for { select { diff --git a/desktop/internal/workbench/tests_test.go b/desktop/internal/workbench/tests_test.go index 6559b3c6b8..f0709acbff 100644 --- a/desktop/internal/workbench/tests_test.go +++ b/desktop/internal/workbench/tests_test.go @@ -291,7 +291,7 @@ func TestTestsPanelDropsStaleResultAndBoundsOutput(t *testing.T) { p.tests.generation = 3 p.tests.output = newOutputBuffer(testOutputMaxLines, testOutputBytes) - decoder := newOutputDecoder(h.app.kernel) + decoder := newOutputDecoder(h.app.kernel, h.app.outputEncodingPolicy()) h.app.streamTestOutput(p, 2, decoder, "stale\n") h.app.streamTestOutput(p, 3, decoder, strings.Repeat("line\n", testOutputMaxLines+50)) h.settle() diff --git a/docs/assets/console-output-encoding/README.md b/docs/assets/console-output-encoding/README.md new file mode 100644 index 0000000000..d4e0e743bf --- /dev/null +++ b/docs/assets/console-output-encoding/README.md @@ -0,0 +1,11 @@ +# 控制台输出编码截图证据 + +这是设置页的实际 Viva 无头截图。设置页由本次新增,旧版没有对应页面;未伪造旧版对照图。图片不包含用户项目或个人路径。 + +- macOS:桌面基于 `0119f4107`,任务提交 `7a6e35315`,配套 Core PR [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128);main 更新后的 Viva 版本已重新采集。编码候选使用真实 Core 的 `windows: true` 策略以检查较长候选文本,**不是 macOS 默认**;macOS 实际默认候选只有 UTF-8。 +- Windows:桌面基于 `4d1b88f03` 加本任务补丁,Core `3ec738a` 加最终 UTF-8/Windows GBK 补丁;Windows 11 原生 x64 SSH 主机,Go 1.27.3、Rust 1.100.0 GNU 目标。本次基线更新之前采集,最新 Viva 版本未在 Windows 重拍,PR 保持 Draft。 +- 场景:`page` 为设置页,`choices` 为输出编码菜单;每端含英文/中文、深色/浅色,共 8 张。每张 1800×1400 像素。 +- 命令:`LITHE_VISUAL_OUTPUT_DIR=<输出目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/settingswindow -run '^TestVisualConsoleEncoding$' -count=1 -timeout=90s`,当时通过 `LITHE_CORE_RUST_DIR` 链接配套 Core。 +- 完整应用窗口的 Run、Build、Tests、复制和链接操作未逐项验收;截图和编码组件测试不替代该验收,功能矩阵保持 `pending`。 + +目录 `macos/` 和 `windows/` 保存上述实际采集的 PNG,PR 使用分支链接嵌入。 diff --git a/docs/assets/console-output-encoding/macos/console-choices-dark-en.png b/docs/assets/console-output-encoding/macos/console-choices-dark-en.png new file mode 100644 index 0000000000..09b75a97ef Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-choices-dark-en.png differ diff --git a/docs/assets/console-output-encoding/macos/console-choices-dark-zh-Hans.png b/docs/assets/console-output-encoding/macos/console-choices-dark-zh-Hans.png new file mode 100644 index 0000000000..b5cb5b10fc Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-choices-dark-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/macos/console-choices-light-en.png b/docs/assets/console-output-encoding/macos/console-choices-light-en.png new file mode 100644 index 0000000000..b2dee2a256 Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-choices-light-en.png differ diff --git a/docs/assets/console-output-encoding/macos/console-choices-light-zh-Hans.png b/docs/assets/console-output-encoding/macos/console-choices-light-zh-Hans.png new file mode 100644 index 0000000000..4aff1a5133 Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-choices-light-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/macos/console-page-dark-en.png b/docs/assets/console-output-encoding/macos/console-page-dark-en.png new file mode 100644 index 0000000000..6433b95465 Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-page-dark-en.png differ diff --git a/docs/assets/console-output-encoding/macos/console-page-dark-zh-Hans.png b/docs/assets/console-output-encoding/macos/console-page-dark-zh-Hans.png new file mode 100644 index 0000000000..9cbefd4b58 Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-page-dark-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/macos/console-page-light-en.png b/docs/assets/console-output-encoding/macos/console-page-light-en.png new file mode 100644 index 0000000000..b7e8ef8984 Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-page-light-en.png differ diff --git a/docs/assets/console-output-encoding/macos/console-page-light-zh-Hans.png b/docs/assets/console-output-encoding/macos/console-page-light-zh-Hans.png new file mode 100644 index 0000000000..505c4f2599 Binary files /dev/null and b/docs/assets/console-output-encoding/macos/console-page-light-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/windows/console-choices-dark-en.png b/docs/assets/console-output-encoding/windows/console-choices-dark-en.png new file mode 100644 index 0000000000..8e384b0c3f Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-choices-dark-en.png differ diff --git a/docs/assets/console-output-encoding/windows/console-choices-dark-zh-Hans.png b/docs/assets/console-output-encoding/windows/console-choices-dark-zh-Hans.png new file mode 100644 index 0000000000..7deedb081c Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-choices-dark-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/windows/console-choices-light-en.png b/docs/assets/console-output-encoding/windows/console-choices-light-en.png new file mode 100644 index 0000000000..9c29934195 Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-choices-light-en.png differ diff --git a/docs/assets/console-output-encoding/windows/console-choices-light-zh-Hans.png b/docs/assets/console-output-encoding/windows/console-choices-light-zh-Hans.png new file mode 100644 index 0000000000..0cd2803ede Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-choices-light-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/windows/console-page-dark-en.png b/docs/assets/console-output-encoding/windows/console-page-dark-en.png new file mode 100644 index 0000000000..44140fe02d Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-page-dark-en.png differ diff --git a/docs/assets/console-output-encoding/windows/console-page-dark-zh-Hans.png b/docs/assets/console-output-encoding/windows/console-page-dark-zh-Hans.png new file mode 100644 index 0000000000..3b4ac7bb9a Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-page-dark-zh-Hans.png differ diff --git a/docs/assets/console-output-encoding/windows/console-page-light-en.png b/docs/assets/console-output-encoding/windows/console-page-light-en.png new file mode 100644 index 0000000000..d021016c53 Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-page-light-en.png differ diff --git a/docs/assets/console-output-encoding/windows/console-page-light-zh-Hans.png b/docs/assets/console-output-encoding/windows/console-page-light-zh-Hans.png new file mode 100644 index 0000000000..1e1c896c28 Binary files /dev/null and b/docs/assets/console-output-encoding/windows/console-page-light-zh-Hans.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 42a8495ead..86d811aca9 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,6 +27,9 @@ native_path() { fi } +# Lithe-core-rust #128 (604699f), on top of #127: outputStyle.decode preserves raw +# bytes and decodes each line as UTF-8, with GBK fallback on Windows; outputEncoding.resolve +# supplies actual candidates. run/start and build prepareRun may declare outputEncoding (#2186). # Lithe-core-rust main at 98e6940 (#119 protocol changelog only) on top of #118 (8c77c3f, on top of #117 plugin # SDK documentation only): the toolchain catalog records a decision on each workspace (trusted, # distrusted for safe mode, or unknown) and trusted locations, toolchains.catalogState reports it as @@ -286,7 +289,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # rows), #13, #8, #7, #6 and #4. # Search pages, unsaved snapshots, source identities and budgets from Core #125, # merged on top of the build-option changes through Core #124. -PINNED_CORE_REVISION="3c0fcffcbc7067be86b832ca2ee3acfc48bf6187" +PINNED_CORE_REVISION="604699f0df9a7c5ec1b245d3f2526d158f5a8eed" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/features/console-encoding.json b/shared/i18n/features/console-encoding.json new file mode 100644 index 0000000000..0330e66553 --- /dev/null +++ b/shared/i18n/features/console-encoding.json @@ -0,0 +1,116 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.consoleSettings.title", + "description": "Console settings page under Build, Execution, Deployment: its sidebar title and heading", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.keywords", + "description": "Console settings page: the words besides its title a settings search finds it by", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.outputCard", + "description": "Console settings page: title of the card about the output of the programs Lithe runs", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.encoding", + "description": "Console settings page: label of the select that chooses the output encoding", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.encodingHelp", + "description": "Console settings page: help of the output encoding, shown from its information glyph", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.automatic", + "description": "Console settings page: the automatic choice, with the encodings it tries on this machine in order", + "platforms": [ + "desktop" + ], + "parameters": { + "encodings": "string" + } + }, + { + "id": "desktop.consoleSettings.automaticPending", + "description": "Console settings page: the automatic choice before Core said which encodings it tries", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.otherwise", + "description": "Console settings page: what joins two encodings automatic mode tries, the later used when the earlier does not fit a line", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.directory", + "description": "Build, Execution, Deployment page: the line about the Console page, naming the output encoding in force", + "platforms": [ + "desktop" + ], + "parameters": { + "encoding": "string" + } + }, + { + "id": "desktop.consoleSettings.automaticFailed", + "description": "Console settings page: automatic encoding when Core could not resolve the catalog", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.consoleSettings.readFailed", + "description": "Console settings page: error when Core cannot resolve output encodings", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.consoleSettings.title": "Console", + "desktop.consoleSettings.keywords": "console run build test output encoding charset garbled gbk utf-8", + "desktop.consoleSettings.outputCard": "Program Output", + "desktop.consoleSettings.encoding": "Output encoding", + "desktop.consoleSettings.encodingHelp": "How Lithe reads output from Run, Build and Tests.\nAutomatic uses UTF-8. On Windows only, a line that is not valid UTF-8 falls back to GBK. A run can explicitly declare another encoding.\nChoose an encoding to override automatic decoding. Changes apply to programs started afterwards.", + "desktop.consoleSettings.automatic": "Automatic ({encodings})", + "desktop.consoleSettings.automaticPending": "Automatic (loading)", + "desktop.consoleSettings.otherwise": ", otherwise ", + "desktop.consoleSettings.directory": "Output encoding: {encoding}", + "desktop.consoleSettings.automaticFailed": "Automatic (could not read)", + "desktop.consoleSettings.readFailed": "Could not read output encodings." + }, + "zh-CN": { + "desktop.consoleSettings.title": "控制台", + "desktop.consoleSettings.keywords": "控制台 运行 构建 测试 输出 编码 字符集 乱码 console encoding gbk utf-8", + "desktop.consoleSettings.outputCard": "程序输出", + "desktop.consoleSettings.encoding": "输出编码", + "desktop.consoleSettings.encodingHelp": "Lithe 怎样读取运行、构建和测试的输出。\n自动模式默认使用 UTF-8。仅 Windows 会在某一行不是合法 UTF-8 时尝试 GBK;运行也可以显式声明其他编码。\n选择具体编码会覆盖自动判断。修改后对之后启动的程序生效。", + "desktop.consoleSettings.automatic": "自动({encodings})", + "desktop.consoleSettings.automaticPending": "自动(检测中)", + "desktop.consoleSettings.otherwise": ",否则 ", + "desktop.consoleSettings.directory": "输出编码:{encoding}", + "desktop.consoleSettings.automaticFailed": "自动(读取失败)", + "desktop.consoleSettings.readFailed": "无法读取输出编码。" + } + } +} diff --git a/shared/platform-feature-matrix/features/console-output-encoding.json b/shared/platform-feature-matrix/features/console-output-encoding.json new file mode 100644 index 0000000000..0fe3b36e82 --- /dev/null +++ b/shared/platform-feature-matrix/features/console-output-encoding.json @@ -0,0 +1,35 @@ +{ + "id": "console-output-encoding", + "area": "运行与调试", + "group": "运行输出", + "capability": "运行、构建和测试控制台保留进程原始字节,由 Rust Core 按行读取 UTF-8 和 Windows GBK,支持固定输出编码及插件声明", + "owner": "Run", + "notes": "桌面桥接以 base64 字节调用 outputStyle.decode;Core 使用插件声明、UTF-8、仅 Windows 的 GBK 自动候选或用户固定的编码。所有平台默认 UTF-8,仅 Windows 增加 GBK 回退,不读取系统代码页。设置页位于构建、执行、部署下,显示真实候选和 18 种编码,修改只影响新控制台。macOS 通过 94 项相关测试,SSH Windows 11 原生 x64 主机通过 95 项相关测试,包含 stdout/stderr 握手拆分 GBK 字符、混合行、颜色范围、声明传递与设置交互;两端相关竞态测试及中英文明暗无头截图通过。完整应用窗口的 Run、Build、Tests、复制和链接操作未逐项验收,verification 保持 pending。宿主固定到 Core PR #128 的 604699f 修订,包含最终默认策略与插件声明契约。", + "verification": "在简体中文 Windows 上输出 GBK 和 UTF-8 的不同日志行,并把多字节字符拆成多次写入;检查 Run、Build、Tests 的中文、颜色、复制和输出链接。切换到固定 GBK,再恢复自动,重启程序检查设置;插件 run/start 与 build prepareRun 声明 outputEncoding 时检查优先级。macOS/Linux 自动候选默认只有 UTF-8。自动化:core/output_style_test.go、core/run_start_test.go、core/build_test.go、pluginservice/runs_test.go、workbench/console_encoding_test.go、settingswindow/console_view_test.go、settingswindow/console_visual_test.go。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/output_style.go", + "desktop/internal/core/output_style_test.go", + "desktop/internal/workbench/console_encoding.go", + "desktop/internal/workbench/console_encoding_test.go", + "desktop/internal/settingswindow/console_view.go", + "desktop/internal/settingswindow/console_view_test.go", + "desktop/internal/settingswindow/console_visual_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/output_style.go", + "desktop/internal/core/output_style_test.go", + "desktop/internal/workbench/console_encoding.go", + "desktop/internal/workbench/console_encoding_test.go", + "desktop/internal/settingswindow/console_view.go", + "desktop/internal/settingswindow/console_view_test.go", + "desktop/internal/settingswindow/console_visual_test.go" + ] + } +}