Skip to content

Commit 71cee07

Browse files
committed
feat(settings): 为 Python 设置添加效果预览
1 parent 98df575 commit 71cee07

9 files changed

Lines changed: 358 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the
1818
- 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。
1919
- 按 shebang 识别的无后缀脚本同样支持 Python 高亮、注释和 Pyrefly 诊断。
2020
2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)**
21+
- 「设置 → 语言与框架 → Python」在设置表单上方展示类型诊断和代码补全的示例。修改设置时,预览直接显示草稿效果。
2122
- 插件包内的 Rust 后端直接启动 Pyrefly,无需先找到 Python。宿主会传入可用于自动启动的解释器路径,缺失时由 Pyrefly 按自身规则发现项目环境。构建、测试与调试仍用宿主选择的 Python。
2223
- 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),每个包也包含同一目标架构的 `bin/lithe-python-backend`(Windows 为 `.exe`)。
2324
- `languageServers[0]` 采用 `"launch": {"kind": "backend", "function": "pyrefly.resolveLaunch", "timeoutMilliseconds": 30000}`:根据 `platform.os` 动态返回包内 `bin/pyrefly` 或 `bin/pyrefly.exe` 与 `arguments: ["lsp"]`,合并全部即时设置(`typeCheckingMode`、`displayTypeErrors`、`diagnosticMode`、`autoImportCompletions`、`completeFunctionParens`、`importFormat`)。
@@ -63,6 +64,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0
6364
| `initialize` | Rust 后端 / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | — | 握手失败由 Core / 宿主记录 | 宿主协议错误 |
6465
| `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)<br>恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` |
6566
| `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` |
67+
| `settings.preview` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(预览更新成功不发 `INFO`) | — | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `python.preview.unknownRegion`、`sdk.view.invalidEvent`、`internal_error` |
6668
| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)<br>恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
6769
| `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` |
6870
| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` |

‎backend/src/main.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ mod discovery;
44
mod inspect;
55
mod pyrefly;
66
mod requirements;
7+
mod settings_preview;
78

89
use lithe_plugin_sdk::Backend;
910

@@ -19,6 +20,10 @@ fn main() {
1920
.expect("the inspect function ID is valid")
2021
.suppress_success_diagnostics(inspect::FUNCTION)
2122
.expect("the inspect function is registered")
23+
.view(settings_preview::FUNCTION, settings_preview::draw)
24+
.expect("the preview function ID is valid")
25+
.suppress_success_diagnostics(settings_preview::FUNCTION)
26+
.expect("the preview function is registered")
2227
.toolchain_provider("python", discovery::query)
2328
.expect("the Python provider ID is valid");
2429
std::process::exit(backend.listen());

‎backend/src/settings_preview.rs‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
//! Draws examples of Python diagnostics and completion from the settings window's draft.
2+
3+
use lithe_plugin_sdk::view::{ViewEvent, ViewEventKind, ViewResult, ViewSurface};
4+
use lithe_plugin_sdk::{Context, FunctionError, PluginError};
5+
use serde_json::{json, Value};
6+
7+
pub(crate) const FUNCTION: &str = "settings.preview";
8+
9+
pub(crate) fn draw(event: ViewEvent, context: &Context) -> Result<ViewResult, FunctionError> {
10+
context.check_cancelled()?;
11+
if !matches!(&event.surface, ViewSurface::SettingRegion(id) if id == "language") {
12+
return Err(PluginError::new(
13+
"python.preview.unknownRegion",
14+
"The Python settings preview requires the Python language region.",
15+
)
16+
.into());
17+
}
18+
if !matches!(
19+
event.kind,
20+
ViewEventKind::Open | ViewEventKind::Settings | ViewEventKind::Resize
21+
) {
22+
return Ok(ViewResult::Unchanged);
23+
}
24+
Ok(ViewResult::View(vec![canvas(&event)]))
25+
}
26+
27+
fn canvas(event: &ViewEvent) -> Value {
28+
let language = event.language.split('-').next() == Some("zh");
29+
let words = |en, zh| if language { zh } else { en };
30+
let value = |key| event.draft.get(key).or_else(|| event.effective.get(key));
31+
let changed = [
32+
"displayTypeErrors",
33+
"autoImportCompletions",
34+
"completeFunctionParens",
35+
"importFormat",
36+
]
37+
.into_iter()
38+
.any(|key| {
39+
event
40+
.draft
41+
.get(key)
42+
.is_some_and(|draft| Some(draft) != event.effective.get(key))
43+
});
44+
let (diagnostic, tone) = match value("displayTypeErrors").and_then(Value::as_str) {
45+
Some("force-off") => (
46+
words("Type errors hidden", "隐藏类型错误"),
47+
"$textSecondary",
48+
),
49+
Some("error-missing-imports") => (
50+
words("Missing imports only", "仅报告缺失导入"),
51+
"$textSecondary",
52+
),
53+
Some("default") => (
54+
words(
55+
"Depends on Pyrefly project configuration",
56+
"由项目的 Pyrefly 配置决定",
57+
),
58+
"$textSecondary",
59+
),
60+
_ => (
61+
words(
62+
"Type error: expected int, got str",
63+
"类型错误:应为 int,实际为 str",
64+
),
65+
"$error",
66+
),
67+
};
68+
let auto_import = value("autoImportCompletions")
69+
.and_then(Value::as_bool)
70+
.unwrap_or(true);
71+
let completion = if value("completeFunctionParens").and_then(Value::as_bool) == Some(true) {
72+
"greet()"
73+
} else {
74+
"greet"
75+
};
76+
let import = if value("importFormat").and_then(Value::as_str) == Some("relative") {
77+
"from .utils import greet"
78+
} else {
79+
"from app.utils import greet"
80+
};
81+
82+
let width = event.width.unwrap_or(640.0).clamp(260.0, 4000.0);
83+
let gap = 12.0;
84+
let card_top = if changed { 53.0 } else { 30.0 };
85+
let (card_width, second_x, second_y) = if width >= 570.0 {
86+
let card_width = (width - gap) / 2.0;
87+
(card_width, card_width + gap, card_top)
88+
} else {
89+
(width, 0.0, card_top + 90.0 + gap)
90+
};
91+
let height = (second_y + 91.0) as u16;
92+
let title = words("Preview", "效果预览");
93+
let mut nodes = vec![text(0.0, 17.0, width, title, "strong", "$text")];
94+
if changed {
95+
nodes.push(text(
96+
0.0,
97+
39.0,
98+
width,
99+
words("Includes changes not applied yet", "含未应用的修改"),
100+
"caption",
101+
"$textSecondary",
102+
));
103+
}
104+
nodes.push(card(
105+
0.0,
106+
card_top,
107+
card_width,
108+
words("Type diagnostics", "类型诊断"),
109+
[
110+
("count: int = \"3\"", "monoSmall", "$text"),
111+
(diagnostic, "caption", tone),
112+
],
113+
));
114+
let first_line = if auto_import {
115+
(import, "monoSmall", "$text")
116+
} else {
117+
(
118+
words("Auto-import off", "自动导入已关闭"),
119+
"caption",
120+
"$textSecondary",
121+
)
122+
};
123+
nodes.push(card(
124+
second_x,
125+
second_y,
126+
card_width,
127+
words("Code completion", "代码补全"),
128+
[first_line, (completion, "monoSmall", "$accent")],
129+
));
130+
let mut result = json!({
131+
"type": "canvas", "id": "pythonPreview", "label": words("Preview of Python settings", "Python 设置效果预览"),
132+
"height": height, "viewBox": [0, 0, width, height], "nodes": nodes,
133+
});
134+
if event.width.is_some() {
135+
result["on"] = json!(["resize"]);
136+
}
137+
result
138+
}
139+
140+
fn card(x: f64, y: f64, width: f64, title: &str, lines: [(&str, &str, &str); 2]) -> Value {
141+
let inner = width - 26.0;
142+
let [(first, first_style, first_color), (second, second_style, second_color)] = lines;
143+
json!({
144+
"type": "group", "x": x, "y": y, "children": [
145+
{"type": "rect", "x": 0.5, "y": 0.5, "w": width - 1.0, "h": 89, "radius": 8, "fill": "$surface", "stroke": "$line"},
146+
text(13.0, 23.0, inner, title, "strong", "$text"),
147+
text(13.0, 49.0, inner, first, first_style, first_color),
148+
text(13.0, 72.0, inner, second, second_style, second_color),
149+
],
150+
})
151+
}
152+
153+
fn text(x: f64, y: f64, width: f64, value: &str, style: &str, color: &str) -> Value {
154+
json!({"type": "text", "x": x, "y": y, "text": value, "style": style, "color": color, "maxWidth": width})
155+
}

‎docs/feature-matrix.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
| 能力域 | 功能项 | `darwin-arm64` | `darwin-x64` | `windows-x64` / `windows-arm64` | `linux-x64` / `linux-arm64` | 最近实机验证 | 实现与测试证据路径(本仓库) |
1414
| --- | --- | --- | --- | --- | --- | --- | --- |
15+
| Python 设置效果预览 (`settingRegions`) | 「语言与框架 → Python」显示类型诊断和代码补全示例,随当前设置草稿更新。预览使用固定示例,保存仍由宿主表单处理。 | ✅ 包内后端与无头设置窗口通过 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | `2026-11-22`(`darwin-arm64`,固定宿主与 0.8.13,中文深色与英文浅色) | `backend/src/settings_preview.rs`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go` |
1516
| Python 解释器覆盖设置 | 在「设置 → 语言与框架 → Python」显示用于构建、运行和 pytest 的解释器覆盖路径。已保存的覆盖值继续按 `pythonExecutable` 读取。 | ✅ Core 设置目录与保存值回读通过 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | `2026-11-22`(`darwin-arm64`,桌面 0.8.13 固定 Core) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/package/archives.test.mjs` |
1617
| 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` / `.conda` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ pending(归档与清单已校验) | `2026-11-20`(`darwin-arm64`,0.8.9 复验 `.py` 高亮) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`<br>`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` |
1718
| 无后缀 Python 脚本 | 支持 TextMate 首行匹配的桌面按解释器路径或 `env` shebang 打开,提供 Python 高亮、注释与 Pyrefly 诊断 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | `2026-11-20`(`darwin-arm64`,桌面 `645a3aee8`) | `io.github.lithe-idea.python-support/grammars/python.first-line.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` |
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
//go:build vivahead
2+
3+
package settingswindow
4+
5+
import (
6+
"context"
7+
"encoding/json"
8+
"os"
9+
"path/filepath"
10+
"testing"
11+
"time"
12+
13+
"github.com/1lck/Lithe-IDEA/desktop/internal/core"
14+
"github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
15+
"github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall"
16+
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice"
17+
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings"
18+
"github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust"
19+
"github.com/1lck/Lithe-IDEA/desktop/internal/store"
20+
"github.com/vivaui/viva/headless"
21+
)
22+
23+
const pythonSettingsPlugin = "io.github.lithe-idea.python-support"
24+
25+
type pythonPreviewSource struct{ service *pluginservice.Service }
26+
27+
func (s pythonPreviewSource) Load(ctx context.Context, id string, language i18n.Language) (pluginservice.SettingsEditor, error) {
28+
return s.service.LoadSettingsEditor(ctx, id, "", language.Code())
29+
}
30+
31+
func (s pythonPreviewSource) Save(ctx context.Context, editor pluginservice.SettingsEditor, scope string, edits []core.PluginSettingEdit) (pluginsettings.SaveResult, error) {
32+
return s.service.SaveSettingsEditor(ctx, editor, scope, edits, nil)
33+
}
34+
35+
func (s pythonPreviewSource) View(ctx context.Context, editor pluginservice.SettingsEditor, region, function string, event, previous json.RawMessage, closing bool) (json.RawMessage, bool, error) {
36+
return s.service.CallView(ctx, pluginservice.SettingsViewCall(editor, region, function, "", event, previous, closing))
37+
}
38+
39+
func TestPythonPluginSettingsPreview(t *testing.T) {
40+
archive := os.Getenv("LITHE_TEST_PYTHON_PLUGIN_ARCHIVE")
41+
if archive == "" {
42+
t.Skip("set LITHE_TEST_PYTHON_PLUGIN_ARCHIVE to the packaged Python plugin")
43+
}
44+
ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
45+
defer cancel()
46+
kernel := core.NewClient()
47+
service, err := pluginservice.Open(kernel, store.At(t.TempDir()), filepath.Join(t.TempDir(), "plugins"))
48+
if err != nil {
49+
t.Fatal(err)
50+
}
51+
t.Cleanup(service.Host.StopAll)
52+
plan, err := service.Installer.Prepare(ctx, plugininstall.Request{ArchivePath: archive, Root: service.Root, Source: plugintrust.Disk})
53+
if err != nil {
54+
t.Fatal(err)
55+
}
56+
if plan.ID != pythonSettingsPlugin {
57+
_ = service.Installer.Discard(plan)
58+
t.Fatalf("unexpected package ID %q", plan.ID)
59+
}
60+
if _, err := service.Installer.Commit(plan); err != nil {
61+
_ = service.Installer.Discard(plan)
62+
t.Fatal(err)
63+
}
64+
if err := service.Manager.SetEnabled(pythonSettingsPlugin, true); err != nil {
65+
t.Fatal(err)
66+
}
67+
for _, look := range []struct {
68+
theme, title, toggle, draft string
69+
language i18n.Language
70+
}{
71+
{"light", "Preview", "Complete function parentheses", "Includes changes not applied yet", i18n.English},
72+
{"dark", "效果预览", "补全函数括号", "含未应用的修改", i18n.Chinese},
73+
} {
74+
t.Run(look.theme, func(t *testing.T) {
75+
w := newWindow(NewController(Options{
76+
Text: func() *i18n.Messages { return i18n.For(look.language) }, Language: func() i18n.Language { return look.language },
77+
SystemLanguage: look.language, SystemDark: func() bool { return look.theme == "dark" },
78+
SettingsPages: func(ctx context.Context, language i18n.Language) ([]core.SettingsPage, error) {
79+
return service.SettingsPages(ctx, language.Code())
80+
},
81+
SettingsNavigation: kernel.SettingsNavigation,
82+
PluginSettings: pythonPreviewSource{service},
83+
}), Values{Theme: look.theme, Language: look.language.Code()})
84+
w.sess.page = pageLanguages
85+
w.sess.open[pageLanguages] = true
86+
config := w.config()
87+
config.Width, config.Height = 1080, 800
88+
session, err := headless.Open(config, nil, headless.Options{})
89+
if err != nil {
90+
t.Fatal(err)
91+
}
92+
t.Cleanup(session.Close)
93+
t.Cleanup(w.closeRegion)
94+
d := &windowDriver{t: t, w: w, driver: session.Driver()}
95+
const page = "language:python"
96+
d.until("installed Python settings page", func() bool { return w.dynamic.selected(page) != nil })
97+
w.selectSettingsPage(pageLanguages, page)
98+
d.until("Python settings preview and completion toggle", func() bool {
99+
if err := w.pluginSettings.failed; err != nil {
100+
t.Fatalf("load settings: %v", err)
101+
}
102+
if w.region != nil && w.region.session.Err() != nil {
103+
t.Fatalf("draw preview: %v", w.region.session.Err())
104+
}
105+
return d.text(look.title) && d.has(look.toggle)
106+
})
107+
if d.text(look.draft) || !d.text("greet") {
108+
t.Fatal("the preview did not show the saved default")
109+
}
110+
capture := func(state string) {
111+
t.Helper()
112+
out := os.Getenv("LITHE_PYTHON_VISUAL_DIR")
113+
if out == "" {
114+
return
115+
}
116+
if err := os.MkdirAll(out, 0o700); err != nil {
117+
t.Fatal(err)
118+
}
119+
if err := session.Advance(250 * time.Millisecond); err != nil {
120+
t.Fatal(err)
121+
}
122+
if err := session.Screenshot(filepath.Join(out, "python-settings-preview-"+look.theme+"-"+state+".png")); err != nil {
123+
t.Fatal(err)
124+
}
125+
}
126+
capture("saved")
127+
d.click(look.toggle)
128+
d.until("preview of the unsaved completion change", func() bool { return d.text(look.draft) && d.text("greet()") })
129+
capture("draft")
130+
if _, err := os.Stat(w.pluginSettings.editor.Snapshot.GlobalPath()); !os.IsNotExist(err) {
131+
t.Fatalf("preview wrote the draft to the settings file: %v", err)
132+
}
133+
})
134+
}
135+
}

‎e2e/host/lithe-host.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"revision": "645a3aee86e3ee5d6a308defa350678f8048baa8",
44
"packages": {
55
"./internal/projectgen": "^TestPythonPlugin",
6+
"./internal/settingswindow": "^TestPythonPluginSettingsPreview$",
67
"./internal/workbench": "^TestPythonSupportPlugin"
78
},
89
"requiredEnvironment": {

‎io.github.lithe-idea.python-support/l10n/zh-Hans.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@
7878
}
7979
}
8080
},
81+
"settingRegions": {
82+
"language": {
83+
"keywords": ["类型检查", "诊断", "代码补全", "效果预览"]
84+
}
85+
},
8186
"sections": {
8287
"Python Interpreter": "Python 解释器",
8388
"Pyrefly": "Pyrefly",

‎io.github.lithe-idea.python-support/plugin.json‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
"runConfigurationTypes": 0,
2323
"settings": 0,
2424
"toolDefinitions": 0,
25-
"toolchainProviders": 0
25+
"toolchainProviders": 0,
26+
"ui": 0
2627
},
2728
"requiresTools": ["python"],
2829
"permissions": [
@@ -32,7 +33,8 @@
3233
"languageServer.launch",
3334
"process.build",
3435
"project.generate",
35-
"toolchains.provide"
36+
"toolchains.provide",
37+
"ui.contribute"
3638
],
3739
"activationEvents": [
3840
"onBuildSystem:conda",
@@ -186,6 +188,14 @@
186188
"section": "Completions"
187189
}
188190
],
191+
"settingRegions": [
192+
{
193+
"id": "language",
194+
"page": { "languageID": "python" },
195+
"keywords": ["Pyrefly", "type checking", "diagnostics", "completions", "preview"],
196+
"view": { "function": "settings.preview" }
197+
}
198+
],
189199
"languageServers": [
190200
{
191201
"languageID": "python",

0 commit comments

Comments
 (0)