diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c47a96..cd954a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,7 +116,7 @@ jobs: - name: Install pytest for the host suite run: python -m pip install --disable-pip-version-check pytest - name: Verify Python highlighting, run configurations, and dependencies on Lithe 0.8.9 - run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride)?|ManualRunAndDependencies)$' + run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(PinnedInterpreter)?|ManualRunAndDependencies)$' - name: Run the full Python host suite on the pinned desktop env: GOFLAGS: -tags=vivahead diff --git a/README.md b/README.md index df834a1..4da8c0c 100644 --- a/README.md +++ b/README.md @@ -1,149 +1,191 @@ -# Python Support for Lithe (`io.github.lithe-idea.python-support`) - -Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for static type checking and LSP navigation and [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging. A Rust backend discovers interpreters and starts the language server. The build integration uses a pytest discovery command and a Python provider for build models, run entries, and test execution. - -遵循 Lithe 插件契约 v1(`schemaVersion: 0`),为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、宿主工具链驱动的 `Pyrefly` 解释器注入、`.venv` / `.conda` / `conda` / `uv` / `pyenv` 多来源环境发现、动态 `pytest` 测试树收集与执行、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。 - -## 兼容性(Compatibility) - -Python Support v1.0.0 要求 Lithe 0.8.9 或更新版本。Lithe 0.8.9 支持安装插件并处理 `.py`、`.pyi` 和 `.pyw` 文件。Lithe 0.8.10 起还能按 shebang 识别无后缀 Python 脚本。 - -Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the plugin and work with `.py`, `.pyi`, and `.pyw` files. Lithe 0.8.10 and later also recognize extensionless Python scripts by their shebang. - ---- - -## 核心能力(Capabilities) - -1. **语言与编辑器基础(`languages: python`)** - - 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。 - - 按 shebang 识别的无后缀脚本同样支持 Python 高亮、注释和 Pyrefly 诊断。 -2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)** - - 「设置 → 语言与框架 → Python」在设置表单上方展示类型诊断和代码补全的示例。修改设置时,预览直接显示草稿效果。 - - 插件包内的 Rust 后端直接启动 Pyrefly,无需先找到 Python。宿主会传入可用于自动启动的解释器路径,缺失时由 Pyrefly 按自身规则发现项目环境。构建、测试与调试仍用宿主选择的 Python。 - - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),每个包也包含同一目标架构的 `bin/lithe-python-backend`(Windows 为 `.exe`)。 - - `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`)。 - - 当宿主在调用参数中传入已选定的非项目内解释器 `tools.python.executable`(如外部 `conda`、`uv`、`pyenv` 或系统环境)时,自动注入 `workspaceConfiguration.python.pythonPath`;当 `tools.python` 缺失(未选定或项目内虚拟环境尚未获信任)时优雅省略 `pythonPath`,保留 `pyrefly` 原生 `.venv` / `pyproject.toml` 自动发现且不阻断启动。 -3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchainProviders: 0`)** - - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。 - - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。Pipenv 默认环境按完整的 `Pipfile` 路径匹配,并遵守同目录的 Python 版本约束。宿主观察这些输入并在变化后重新查询。 - - 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。 -4. **构建、运行与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders: 1`)** - - `python` 通过 `test.discoveryCommand` 启动 `python -I -B scripts/discover_tests.py`。宿主使用选定解释器和构建实例目录运行命令,并提供 `${outputFile}`。命令运行 `pytest --collect-only`,汇报函数、类方法和参数化用例的精确选择器。发现为空时写入有效的 `litheTestDiscovery` v0 空列表。选择器或报告超出契约限制时整次发现失败。pytest 缓存与报告位于宿主 `${workspaceStateDir}` 下的本次发现目录,由宿主在操作结束时清理。宿主负责取消并回收整个进程树,收集脚本保留 45 秒的 pytest 超时。 - - Python 构建提供者 `scripts/build_provider.py` 使用 `python -I -B` 启动,处理以下请求。 - - `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置; - - `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。 - - 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划。默认使用项目选定的 Python;指定「Python 解释器覆盖」时,使用宿主解析的显式解释器。 - - `scripts/run_entrypoint.py` 随插件 ZIP 安装,运行时只读。它在宿主管理的进程树内转发解释器覆盖,并检查包入口的实际来源。包名被其他模块遮蔽时给出错误。旧宿主未传界面语言时,入口错误同时提供中英文。 - - 仅用 `environment.yml` 或 `environment.yaml` 管理 Conda 环境的项目也会识别为 Python 构建实例。 - - 在「运行/调试配置 → + → Python」手动配置脚本路径或模块名。可设置解释器选项、脚本参数、工作目录和环境变量。运行时沿用项目的 Python 工具链及解释器覆盖设置,支持选用 Conda、uv 和普通虚拟环境。 - - 构建面板的「依赖」显示所选解释器中已安装的 Python 包版本与依赖关系。展开或重新加载时用 `python -I -B` 读取发行包元数据,跳过用户级 site-packages 及其启动钩子,支持无 pip 的环境。包共享的子树只展开一次,循环依赖以叶节点结束。 - - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。 - - `uv`(`uv.lock`):`uv sync`、`uv lock`。 - - `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。 - - `ruff`(`ruff.toml` / `.ruff.toml` / `pyproject.toml`):`ruff check`(带诊断 `lineMatcher`)与 `ruff format`。 -5. **调试器(`debugAdapters: debugpy`)** - - 以 `["-I", "-B"]` 隔离参数启动 `scripts/debugpy_adapter.py --log-dir ${logDir}`,双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持已安装插件目录零字节码写入,支持本地 `launch` 与远程 TCP `attach`(`host` / `port` / `pathMappings`)。 -6. **终端 Traceback 链接与新建项目向导(`outputLinkMatchers` & `projectGenerators`)** - - 自动识别终端输出中的 `File "...", line N` 并支持跳转源码;新建项目向导支持固定项目级 `python` 解释器(`pinAs: "project"`)及创建 `.venv`(`venv` / `uv`)。 - ---- - -## 日志接线说明(Structured Logging v2 Wiring) - -插件包含包内 Rust SDK 后端、构建提供者(`scripts/build_provider.py`)与声明式贡献,诊断通过 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md`、`shared/plugins/contract/v1/README.md#structured-plugin-diagnostics` 与 `shared/plugins/guides/plugin-logging.md`),**零自建插件日志文件**,已安装插件目录在运行期保持 **100% 只读**。 - -### 1. 后端与构建 Provider 协议接线(统一通道:`plugins/io.github.lithe-idea.python-support/host`) - -Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 发送结构化诊断,与宿主代记的声明式贡献共用通道 `plugins/io.github.lithe-idea.python-support/host`(见 Core `rust/logging/events/plugins.json`): -- **强制协商 `litheLogging` 0**:`initialize` 缺少 `experimental.litheLogging` `versions: [0]` 时立即以 `-32600` 拒绝握手;两种后端的 `stdout` 均只输出 `Content-Length` JSON-RPC 帧。 -- **请求级 `operationId` 关联与时序**:所有 `lithe/log` 通知严格在对应 JSON-RPC 响应帧发出**之前**写入 `stdout`,携带宿主请求传入的 `operationID`(回退为受控请求 ID),确保 Core 将诊断精确关联到活跃操作。 -- **取消不记失败**:收到 `$/cancelRequest` 时停止扫描或终止构建子进程组(POSIX 进程组 / Windows Job Object),返回 `-32800` 且不发送 `operationFinished` 或 `operationFailed`。 - -| `operation` | 所属进程 | 成功事件与级别 | 降级 / 恢复事件(`WARN`) | 失败事件与级别(`ERROR`) | 受控 `code` 类别标识 | -| --- | --- | --- | --- | --- | --- | -| `initialize` | Rust 后端 / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | — | 握手失败由 Core / 宿主记录 | 宿主协议错误 | -| `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`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` | -| `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` | -| `settings.preview` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(预览更新成功不发 `INFO`) | — | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `python.preview.unknownRegion`、`sdk.view.invalidEvent`、`internal_error` | -| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`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` | -| `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` | -| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` | -| `lithe/build/prepareRun` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRunEntrypoint`、`python.staleRunEntrypoint`、`python.interpreterUnavailable`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` | -| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` | - -`toolchains/query` 是高频只读操作,成功由 SDK 返回事实。取消、读取失败、扫描超限与不安全输入通过 `plugin.toolchain.*` 结构化返回。宿主工具链层观察并处理查询及解码失败。协议 v0 的 SDK 无该操作的诊断回调。 - -### 2. 宿主代记的声明式插件操作(通道:`plugins/io.github.lithe-idea.python-support/host`) - -声明式启动的语言服务器子进程、调试适配器、依赖查询和测试发现命令由宿主与 Core 经 `diagnostics.recordPluginOperation` 将唯一终态代记到 `plugins/io.github.lithe-idea.python-support/host`。用户主动取消或停止不记录。 - -| `operation` | 声明来源 | 记录方 | 成功事件与级别 | 失败事件与级别 | 可能的 `host.*` 失败类别标识(`code`) | -| --- | --- | --- | --- | --- | --- | -| `languageServer/start` | `languageServers[]`(`pyrefly.resolveLaunch` 解析后的 `pyrefly lsp` 进程) | 启动前失败由桌面宿主记录;进入启动后经 `lsp.startServer.startupOperation` 交由 Core 记录唯一终态 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` | -| `debugAdapter/start` | `debugAdapters[]`(`debugpy`) | 桌面宿主(`op` 为调试会话 ID;用户停止与 Core 拒绝建会话不记录) | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` | -| `lithe/build/dependencies` | `buildSystems[].dependencies`(读取所选解释器的包元数据) | 桌面宿主 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.commandFailed`、`host.timedOut`、`host.outputInvalid` | -| `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand`(`pytest --collect-only`) | 桌面宿主 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.commandFailed`、`host.timedOut`、`host.outputInvalid` | - -### 3. 上游子进程通道、隐私红线与原生日志文件 - -| 组件 / 命令 | v2 结构化通道或原生文件位置 | 级别、限流、脱敏与清理策略 | +# Python Support for Lithe + +为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Python 支持:Pyrefly 代码智能和类型检查;构建窗口里的运行入口、pytest 测试树和已安装包的依赖树; +uv、conda、Ruff、mypy 任务;debugpy 调试;在「新建项目」里创建带 `.venv` 的 Python 项目;设置页画出各项设置的效果和 Lithe 查找解释器的顺序。 +这是一个**社区插件**,按插件契约 v0 编写,由 `plugin.json`、几个随包的 Python 脚本、项目模板和一个用 Rust SDK 写的后端组成。 +Pyrefly 和 debugpy 随插件包分发,Python 解释器、pytest、uv、conda、Ruff 用你电脑上的。 + +> English: Python support for Lithe — Pyrefly code intelligence and type checking, run entries, a pytest test tree and +> the installed-package tree in the build window, uv/conda/Ruff/mypy tasks, debugpy debugging, a Python project entry in +> New Project, and previews on the settings pages. Pyrefly and debugpy ship in the plugin; the interpreter, pytest, uv, +> conda and Ruff stay your own. Pick the interpreter on Settings › Build, Execution, Deployment › Toolchains. + +> **兼容性**:需要 Lithe 桌面端 0.8.9 或更新版本;0.8.10 起还能按 shebang 识别没有后缀的 Python 脚本。 +> 各版本的变化见 [docs/releases](docs/releases)。 + +## 功能 + +| 功能 | 说明 | +| --- | --- | +| 代码智能 | 补全、自动导入、跳转定义、悬停、类型诊断,由随包的 [Pyrefly](https://github.com/facebook/pyrefly) 1.4.1 提供 | +| 识别文件 | `.py`、`.pyi`、`.pyw`;0.8.10 起首行是 Python shebang 的无后缀脚本也按 Python 打开 | +| 运行 | 工具栏「当前文件」运行带 `if __name__ == "__main__"` 的脚本和包里的 `__main__.py`;构建窗口列出 `[project.scripts]`、Django `manage.py`、FastAPI、Flask 等入口;「运行/调试配置 → + → Python」可以手动配置脚本或模块 | +| 测试 | `pytest --collect-only` 收集函数、类方法、参数化用例和 doctest,组成测试树;可以运行整个套件或单个用例 | +| 依赖 | 构建窗口的「依赖」列出所选解释器里已安装的包、版本和依赖关系,不需要 pip | +| 任务 | `pip install -r requirements.txt`、`mypy`;有 `uv.lock` 时 `uv sync`、`uv lock`;有 `environment.yml` 时 `conda env update`;有 Ruff 配置时 `ruff check`、`ruff format` | +| 调试 | 随包的 debugpy 1.8.22,支持启动和按地址附加(`host`、`port`、`pathMappings`) | +| 输出链接 | 终端和运行输出里 Traceback 的 `File "…", line N` 可以点击跳到源码 | +| 新建项目 | 选解释器、选是否用 venv 或 uv 建 `.venv`、是否加示例代码;创建后项目固定使用所选解释器 | +| 工具链 | 找到项目的 `.venv` 和电脑上 uv、pyenv、conda、python.org 装的 Python,按 `.python-version` 和 `requires-python` 选版本,见下文“Python 解释器” | +| 设置预览 | 语言页和构建工具页画出设置的效果和解释器的查找顺序,见下文“设置预览” | + +## 设置 + +**插件设置**(「语言与框架 › Python」,也在 设置 → 插件 → Python Support →「设置」),都立即生效: + +| 设置 | 默认 | 说明 | | --- | --- | --- | -| Rust 后端 / `build_provider.py` | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 | -| `pyrefly lsp`(语言服务器) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`(或宿主内置 `lsp/python`) | Core 记录 `plugins.host.process.started`、`plugins.host.protocol.initialized`、`plugins.host.session.updated`;`window/logMessage` 与 `window/showMessage` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `plugins.host.stderr.received` 记为 `DEBUG`(仅详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要,拒绝 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 | -| `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle),按 `` 建文件并随宿主日志会话生命周期统一保留与清理。 | -| `pytest`、构建任务与项目生成 | 测试发现报告(`${outputFile}`)、构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `pytest --collect-only` 的缓存与报告同目录,随宿主发现操作结束清理。宿主可向用户展示失败命令的部分输出。v2 结构化诊断只保存阶段类别和耗时。 | +| 类型检查模式 | 默认 | Pyrefly 的预设:默认、自动、关闭、基础、宽松、严格、全部。项目有 `pyrefly.toml` 或 `[tool.pyrefly]` 时以项目配置为准;“自动”沿用附近的 mypy 或 Pyright 配置,没有时按“基础” | +| 隐藏类型错误 | 关 | 所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转、补全照常。开启后类型检查模式选什么都不显示类型错误 | +| 诊断范围 | 仅打开的文件 | 或者“整个工作区”:没打开的文件也报告错误级别的问题 | +| 自动导入补全 | 开 | 补全列出还没导入的名字,确认时插入 `import` | +| 自动导入路径风格 | 绝对导入 | 插入导入时用完整模块路径还是包内相对路径。也用于“移动符号”“转换模块”代码操作;关闭自动导入补全后只有这两个操作用它 | +| 补全函数括号 | 关 | 补全函数或方法时加上 `()`,光标停在括号里 | ---- +## Python 解释器 -## 本地构建、缓存与测试(Build, Cache & Verification) +Pyrefly 分析代码、运行、测试、调试、读取依赖、安装依赖都用同一个解释器。Lithe 按这个顺序找: -### 构建与缓存目录说明(跨工作树复用规则) +1. **项目环境**:为项目固定的解释器;项目里的 `.venv`、`venv`、`.conda`(项目要先被信任);项目的 `.python-version` 和 + `pyproject.toml` 的 `requires-python` 决定选哪个版本。 +2. **全局默认**:全局固定的解释器,其次默认版本。 +3. **自动发现**:`VIRTUAL_ENV`,`PATH` 里的 `python3`、`python`,然后是 uv、pyenv、conda、python.org 装的 Python。 -| 路径 | 归属与用途 | 生命周期 | 跨 Git Worktree 复用策略 | -| --- | --- | --- | --- | -| `.cache/` | `scripts/package.mjs` 下载并经 SHA-256 校验的上游原始归档(`pyrefly` 6 平台压缩包、`debugpy` wheel、`tomli` wheel、`packaging` wheel) | 本地持久化缓存(已被 `.gitignore` 忽略) | **可安全复制复用**(文件名含上游版本与平台,读取前强制校验 `vendor-lock.json` SHA-256;复制到新工作树 `.cache/`,勿跨并发打包共享写) | -| `backend/target/` | Rust 后端编译输出,包含按平台目标区分的产物 | 随工作树保留,可重新由 Cargo 生成 | 不共享,构建时由固定的 Cargo.lock 和 Rust 目标重建。Cargo 使用全局 registry 与 Git 依赖下载缓存。 | -| `.artifacts/stage/` | 打包过程中的单平台解包暂存目录 | 每次 `scripts/package.mjs` 按平台重建(`.gitignore` 忽略) | **不可复用**(构建中间产物,毫秒级重建) | -| `.artifacts/lithe-host/` | `scripts/e2e-host.mjs` 检出的宿主稀疏工作树及其编译产物 | 本地按需保留(`.gitignore` 忽略) | 其内部 `.artifacts/desktop` 在同一操作系统、CPU 架构与相同 `PINNED_CORE_REVISION` 前提下可按宿主规则复制加速,不得跨工作树软链共用;任何运行时会话日志目录(`sessions//plugins/.../files/`)与状态目录严禁跨工作树复制 | -| `grammars/python.first-line.json`(插件包内) | 插件的 TextMate 首行元数据。普通文件和按首行识别的脚本都沿用宿主的 `source.python` 高亮 | 构建时随 ZIP 打包,运行时只读,随插件版本更新或卸载 | 由插件源码随包生成,无运行时缓存 | -| `vendor/packaging/`(插件包内) | 依赖查询用的 PEP 508 解析器,版本和 SHA-256 见 `vendor-lock.json` | 构建阶段解包,运行时只读,随插件更新或卸载 | 按锁定的 wheel 重建 | -| 依赖查询报告 | 宿主为每次查询在插件的工作区状态目录分配临时文件 | 宿主读取并清理,运行结束后无需保留 | 不复制 | -| `dist/` | 最终产出的 `python-support--.zip` 发布包 | 打包输出(`.gitignore` 忽略) | 按需重新运行 `node scripts/package.mjs` 生成 | +换解释器在 **设置 → 构建、执行、部署 → 工具链**:为项目或全局固定一个找到的安装,或者添加其他目录。 +「语言与框架 › Python」顶部那一行显示当前用的解释器,点它也会到工具链页。 -### 常用命令 +**目前用不了的解释器**([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316)):在 macOS 和 Linux 上,Lithe 拒绝程序链接到安装目录外的 +Python,固定也不行。受影响的有: -打包需要 Node.js 与 Rust 1.87,并由 `backend/Cargo.lock` 固定依赖。SDK 固定到 Core 的 Git 提交。Linux 目标使用 musl,Windows 使用 MSVC 并静态链接 C 运行库,macOS 使用系统链接器。发布使用 CI 的六平台构建矩阵。 +- 建在项目外的虚拟环境:`python -m venv`、`uv venv`、virtualenv 建的,以及 Poetry、Pipenv、virtualenvwrapper 默认建的环境; +- Homebrew 的 Python,它不会出现在安装列表里。 -插件测试使用真实 pytest。将 pytest 安装到 `PYTHON` 对应的环境,或通过 `PYTEST_PYTHON` 指定已安装 pytest 的解释器。 +在此之前请把环境建在项目里:`python3 -m venv .venv` 或 `uv venv`;Poetry 先运行 `poetry config virtualenvs.in-project true`, +Pipenv 设置 `PIPENV_VENV_IN_PROJECT=1`。也可以固定 uv、pyenv、python.org 装的基础解释器,但那里没有环境里装的包。 + +1.0.0 的“Python 解释器覆盖”设置在 1.1.0 删除了:它只管运行,Pyrefly 却用工具链里的解释器,两边可能不一致。原来填过的路径不再生效,请在工具链页固定它。 + +## 设置预览 + +两块预览由插件后端按界面语言、外观和设置窗口宽度画出。它们用示例代码,不读取打开的项目;截图里的路径和版本是测试数据。 + +**语言与框架 › Python**:顶部是当前用的 Python 解释器。下面四张卡片各对应一项设置: + +| 卡片 | 画出什么 | +| --- | --- | +| 类型检查模式 | 示例代码在所选预设下报告哪些错误;隐藏类型错误开启时标为“已隐藏” | +| 诊断范围 | 一个小项目里哪些文件会被检查 | +| 自动导入补全 | 补全列出未导入的 `greet`,确认后按绝对或相对路径插入导入;关闭时只补全已导入的名字 | +| 补全函数括号 | 确认补全后是 `greet()` 还是 `greet` | + +Python 语言设置页的解释器和效果预览,深色外观 + +还没应用的修改先画进预览:改动的卡片换成强调色边框,值前加圆点,右上角标出“含未应用的修改”。下图打开了补全函数括号: + +还没应用的修改先显示在预览里,英文浅色外观 + +**构建工具 › Python**:画出上面三步查找顺序,以及解释器用在哪些流程。这一页没有设置项,换解释器要到工具链页。 + +构建工具 › Python 画出 Lithe 查找 Python 解释器的顺序,深色外观 + +## 依赖的程序 + +| 程序 | 用途 | 来源 | +| --- | --- | --- | +| Python 3.9 或更新,调试要 3.10 或更新 | 运行、测试、调试、依赖、读取项目 | 你电脑上的,见上文“Python 解释器” | +| pytest | 测试树和运行测试 | 装在项目用的解释器里 | +| mypy | `mypy` 任务 | 装在项目用的解释器里 | +| uv、conda、ruff | 对应的任务 | `PATH` | +| Pyrefly 1.4.1 | 代码智能 | 随插件包 | +| debugpy 1.8.22 | 调试 | 随插件包,由项目用的解释器运行,需要 Python 3.10 或更新 | + +安装插件时 Lithe 会列出这些程序和插件需要的权限,确认后才安装。 + +## 安装 + +在 **设置 → 插件** 的市场里搜索 Python Support 安装。也可以从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-python/releases) +下载对应平台的 `python-support-<版本>-<平台>.zip`(`darwin-arm64`、`darwin-x64`、`windows-x64`、`windows-arm64`、`linux-x64`、`linux-arm64`), +在 **设置 → 插件** 里点 **从文件安装…**,核对 SHA-256 和权限后确认。 + +## 工作方式 + +- 后端用 [Rust 插件 SDK](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/shared/plugins/sdk/rust) 编写,回答 + `pyrefly.resolveLaunch`(启动 Pyrefly 并传入所选解释器)、`settings.view`(两块设置预览)和 `toolchains/query`(读取 conda 登记、uv、pyenv、 + Poetry、Pipenv 环境和项目的版本要求)。后端不保存状态,也不写文件。 +- 构建提供者 `scripts/build_provider.py` 由所选解释器以 `python -I -B` 启动,回答 `lithe/build/model`、`test`、`runEntrypoints` 和 `prepareRun`。 + 它只用 `ast` 和 `tomllib` 读项目,不执行项目代码。 +- 测试树由 `test.discoveryCommand` 运行 `scripts/discover_tests.py` 得到;报告和 pytest 缓存在 Lithe 分配的目录里,用完由 Lithe 清理。 +- debugpy 按 `debugAdapters` 的声明由 `scripts/debugpy_adapter.py` 启动;新建项目由 `projectGenerators` 声明,模板在 `templates/python/`。 +- 插件目录在运行时保持只读:随包的脚本都以 `-B` 和 `PYTHONDONTWRITEBYTECODE=1` 运行,不写字节码。 + +## 诊断日志 + +后端和构建提供者接入 Lithe 的日志协议,每次请求的成败自动记录;设置预览、运行入口探测、环境检查这类频繁的只读请求,成功时不记录。 +插件只在真的降级时上报一次 WARN,恢复后再记一次: + +| 类别 | 什么时候 | +| --- | --- | +| `invalid_tool_hint` / `tool_hint_restored` | Lithe 传来的解释器不可用,Pyrefly 按自己的规则找环境 / 又可用了 | +| `pyproject_parse_failed` / `pyproject_restored` | `pyproject.toml` 解析失败,构建模型里少了它声明的入口 / 修好了 | + +Pyrefly 和 debugpy 的启动结果由 Lithe 记在插件的日志通道。debugpy 自己的日志写在本次会话的插件目录 +`plugins/io.github.lithe-idea.python-support/files/debugpy.*.log`。程序和测试的输出只显示在运行、调试和构建窗口里,不进诊断日志。 + +## 本地打包 + +需要 Node.js 22+、Rust 1.87+ 和对应的 target(`rustup target add`)。上游的 Pyrefly、debugpy、Tomli、Packaging 按 `vendor-lock.json` +的 SHA-256 下载到 `.cache/`,可以复制到其他工作树复用。 ```bash -# 打包当前开发平台(例如 macOS Apple Silicon) -node scripts/package.mjs --platform darwin-arm64 +cargo test --locked --manifest-path backend/Cargo.toml # 后端单元测试 +node scripts/package.mjs --platform darwin-arm64 # 不带 --platform 时打六个平台 +node --test --test-timeout=60000 scripts/package/*.test.mjs # 核对 dist/ 里的每个包 +PYTEST_PYTHON=/path/to/python node scripts/test.mjs # 用真实的 Pyrefly、pytest、debugpy 跑插件流程 +``` -# 本机具备全部六种 Rust 目标和链接器时打包全部平台 -node scripts/package.mjs +输出 `dist/python-support-<版本>-<平台>.zip`。`scripts/test.mjs` 需要一个装了 pytest 的解释器:用 `PYTEST_PYTHON` 指定,或装进 `PYTHON` +(默认 `python3`)。`PYTHON` 要是 3.10 或更新,调试流程要用它建的虚拟环境运行 debugpy。`plugin.json` 的格式见 Rust Core 仓库的 +[插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md)和 +[构建工具接入指南](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/guides/build-tool-integration.md)。 -# 校验 dist/ 下构建产物的目录安全性、Windows 文件名/大小写兼容性与清单一致性 -node --test --test-timeout=60000 scripts/package/*.test.mjs +## 宿主端到端测试 -# 运行 Rust 规则测试、打包后端协议验证及真实 Pyrefly / pytest / debugpy 工作流 -cargo test --locked --manifest-path backend/Cargo.toml -node scripts/test.mjs +`e2e/host/` 里的测试用 Lithe 桌面端自己的测试工具安装真实插件包,操作编辑器、构建窗口、调试和设置页。 +`e2e/host/lithe-host.json` 记录测试最后一次通过时的宿主版本,主仓库不读取本仓库。 -# 使用 e2e/host/lithe-host.json 固定的桌面主线提交运行完整宿主套件 -node scripts/e2e-host.mjs +需要 Node.js 22+、Go、Rust 工具链、`git` 和两个 Python: -# 用同一个 ZIP 检查 0.8.9 能安装插件并正常高亮 .py -node scripts/e2e-host.mjs --source https://github.com/1lck/Lithe-IDEA.git --ref desktop-v0.8.9 --run '^TestPythonSupportPluginGrammarHighlighting$' +- `PATH` 里的 `python3` 要是 3.10 或更新(调试用的 debugpy 需要),并且能用 `--copies` 建虚拟环境。Homebrew(`/opt/homebrew/opt/python@3.x/libexec/bin`)或 python.org 装的都可以;uv 装的独立版本复制出来不能运行,Xcode 自带的是 3.9; +- `PYTEST_PYTHON` 指向装了 pytest 的真实安装,不能是虚拟环境(固定解释器的测试会固定它,见 #2316)。例如 + `uv python install 3.12 --install-dir .artifacts/test-python`,再用 `uv pip install --python <它的 python3.12> --break-system-packages pytest`。 -# 也可使用另一个兼容的本地检出和提交 -node scripts/e2e-host.mjs --source /path/to/Lithe-IDEA --ref COMPATIBLE_HOST_COMMIT +```bash +node scripts/package.mjs --platform darwin-arm64 +export LITHE_TEST_PYTHON_PLUGIN_ARCHIVE="$PWD/dist/python-support-1.1.0-darwin-arm64.zip" +PYTEST_PYTHON=/path/to/python3.12 node scripts/e2e-host.mjs +# 用同一个包检查 0.8.9:高亮、当前文件运行、固定解释器、手动运行 +PYTEST_PYTHON=/path/to/python3.12 node scripts/e2e-host.mjs --ref desktop-v0.8.9 \ + --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(PinnedInterpreter)?|ManualRunAndDependencies)$' ``` ---- +插件包路径要写绝对路径。脚本把宿主检出到 `.artifacts/lithe-host`,复制 `e2e/host/desktop/` 下的测试后运行;`--source`、`--ref`、`--run` +分别换宿主来源、换宿主版本、只跑部分测试。升级 `revision` 时可能要同步修改测试。 + +## 功能矩阵 + +各项能力在各平台上的实现与验收状态见 [docs/feature-matrix.md](docs/feature-matrix.md),改动插件行为时在同一个 PR 里更新它。 + +## 发布新版本 + +1. 修改 `io.github.lithe-idea.python-support/plugin.json` 的 `version`:修复升修订号,加功能升次版本号,特别大的革新才升主版本号。 + 依赖还没发布的宿主能力时照样升次版本号,作为预发布版本发布。写好 `docs/releases/v<版本>.md`,合入 `main`。 +2. 推送同名标签,例如 `git tag v1.1.0 && git push origin v1.1.0`。 +3. `Release` 工作流核对标签与版本,打六个平台的包并发布 Release,说明里附 SHA-256 和 `docs/releases/v<版本>.md`。 + `release.yml` 的 `PRERELEASE_TAGS` 里的版本标为预发布,目前是 `v0.1.0` 和 `v0.1.1`。 +4. Lithe Store 的自动追踪会为稳定版本开合并请求,合并后用户即可更新。 -## 许可证(License) +## 许可 -- 插件清单、Rust 后端、脚本、模板、图标与文档采用 [Apache-2.0](LICENSE) 许可协议。 -- 随包分发的第三方开源组件(Pyrefly `1.4.1`、debugpy `1.8.22`、Tomli `2.5.0`,均为 MIT 许可)完整版权声明与许可证全文见 [io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt](io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt) 及包内 `vendor/debugpy/ThirdPartyNotices.txt`。Packaging `25.0` 采用 Apache-2.0 或 BSD-2-Clause,原始许可证随包分发。 -- Rust 后端的依赖及对应许可证由 `Cargo.lock` 固定,全文随包附在 `RUST-THIRD-PARTY-NOTICES.txt`。 +插件本身采用 [Apache-2.0](LICENSE)。随包分发的 Pyrefly 1.4.1、debugpy 1.8.22、Tomli 2.5.0(MIT)和 Packaging 25.0(Apache-2.0 或 BSD-2-Clause) +的声明见 [THIRD-PARTY-NOTICES.txt](io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt) 和包内 `vendor/debugpy/ThirdPartyNotices.txt`; +Rust 后端依赖的许可证随包附在 `RUST-THIRD-PARTY-NOTICES.txt`。 diff --git a/backend/src/main.rs b/backend/src/main.rs index 9a7264d..8d1cfdb 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -4,7 +4,7 @@ mod discovery; mod inspect; mod pyrefly; mod requirements; -mod settings_preview; +mod view; use lithe_plugin_sdk::Backend; @@ -20,11 +20,8 @@ fn main() { .expect("the inspect function ID is valid") .suppress_success_diagnostics(inspect::FUNCTION) .expect("the inspect function is registered") - .view(settings_preview::FUNCTION, settings_preview::draw) - .expect("the preview function ID is valid") - .suppress_success_diagnostics(settings_preview::FUNCTION) - .expect("the preview function is registered") .toolchain_provider("python", discovery::query) .expect("the Python provider ID is valid"); + view::register(&mut backend).expect("the view function is valid"); std::process::exit(backend.listen()); } diff --git a/backend/src/pyrefly.rs b/backend/src/pyrefly.rs index b2ea86c..e8441aa 100644 --- a/backend/src/pyrefly.rs +++ b/backend/src/pyrefly.rs @@ -33,8 +33,8 @@ impl LaunchResolver { enum_setting(settings, "diagnosticMode", &["openFilesOnly", "workspace"]); let mut python = json!({ "pyrefly": { - "typeCheckingMode": enum_setting(settings, "typeCheckingMode", &["default", "auto", "basic", "strict", "all", "off"]), - "displayTypeErrors": enum_setting(settings, "displayTypeErrors", &["force-on", "default", "error-missing-imports", "force-off"]), + "typeCheckingMode": enum_setting(settings, "typeCheckingMode", &["default", "auto", "off", "basic", "legacy", "strict", "all"]), + "disableTypeErrors": settings["disableTypeErrors"].as_bool().unwrap_or(false), "diagnosticMode": diagnostic_mode, }, "analysis": { diff --git a/backend/src/settings_preview.rs b/backend/src/settings_preview.rs deleted file mode 100644 index 9fe8942..0000000 --- a/backend/src/settings_preview.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! Draws examples of Python diagnostics and completion from the settings window's draft. - -use lithe_plugin_sdk::view::{ViewEvent, ViewEventKind, ViewResult, ViewSurface}; -use lithe_plugin_sdk::{Context, FunctionError, PluginError}; -use serde_json::{json, Value}; - -pub(crate) const FUNCTION: &str = "settings.preview"; - -pub(crate) fn draw(event: ViewEvent, context: &Context) -> Result { - context.check_cancelled()?; - if !matches!(&event.surface, ViewSurface::SettingRegion(id) if id == "language") { - return Err(PluginError::new( - "python.preview.unknownRegion", - "The Python settings preview requires the Python language region.", - ) - .into()); - } - if !matches!( - event.kind, - ViewEventKind::Open | ViewEventKind::Settings | ViewEventKind::Resize - ) { - return Ok(ViewResult::Unchanged); - } - Ok(ViewResult::View(vec![canvas(&event)])) -} - -fn canvas(event: &ViewEvent) -> Value { - let language = event.language.split('-').next() == Some("zh"); - let words = |en, zh| if language { zh } else { en }; - let value = |key| event.draft.get(key).or_else(|| event.effective.get(key)); - let changed = [ - "displayTypeErrors", - "autoImportCompletions", - "completeFunctionParens", - "importFormat", - ] - .into_iter() - .any(|key| { - event - .draft - .get(key) - .is_some_and(|draft| Some(draft) != event.effective.get(key)) - }); - let (diagnostic, tone) = match value("displayTypeErrors").and_then(Value::as_str) { - Some("force-off") => ( - words("Type errors hidden", "隐藏类型错误"), - "$textSecondary", - ), - Some("error-missing-imports") => ( - words("Missing imports only", "仅报告缺失导入"), - "$textSecondary", - ), - Some("default") => ( - words( - "Depends on Pyrefly project configuration", - "由项目的 Pyrefly 配置决定", - ), - "$textSecondary", - ), - _ => ( - words( - "Type error: expected int, got str", - "类型错误:应为 int,实际为 str", - ), - "$error", - ), - }; - let auto_import = value("autoImportCompletions") - .and_then(Value::as_bool) - .unwrap_or(true); - let completion = if value("completeFunctionParens").and_then(Value::as_bool) == Some(true) { - "greet()" - } else { - "greet" - }; - let import = if value("importFormat").and_then(Value::as_str) == Some("relative") { - "from .utils import greet" - } else { - "from app.utils import greet" - }; - - let width = event.width.unwrap_or(640.0).clamp(260.0, 4000.0); - let gap = 12.0; - let card_top = if changed { 53.0 } else { 30.0 }; - let (card_width, second_x, second_y) = if width >= 570.0 { - let card_width = (width - gap) / 2.0; - (card_width, card_width + gap, card_top) - } else { - (width, 0.0, card_top + 90.0 + gap) - }; - let height = (second_y + 91.0) as u16; - let title = words("Preview", "效果预览"); - let mut nodes = vec![text(0.0, 17.0, width, title, "strong", "$text")]; - if changed { - nodes.push(text( - 0.0, - 39.0, - width, - words("Includes changes not applied yet", "含未应用的修改"), - "caption", - "$textSecondary", - )); - } - nodes.push(card( - 0.0, - card_top, - card_width, - words("Type diagnostics", "类型诊断"), - [ - ("count: int = \"3\"", "monoSmall", "$text"), - (diagnostic, "caption", tone), - ], - )); - let first_line = if auto_import { - (import, "monoSmall", "$text") - } else { - ( - words("Auto-import off", "自动导入已关闭"), - "caption", - "$textSecondary", - ) - }; - nodes.push(card( - second_x, - second_y, - card_width, - words("Code completion", "代码补全"), - [first_line, (completion, "monoSmall", "$accent")], - )); - let mut result = json!({ - "type": "canvas", "id": "pythonPreview", "label": words("Preview of Python settings", "Python 设置效果预览"), - "height": height, "viewBox": [0, 0, width, height], "nodes": nodes, - }); - if event.width.is_some() { - result["on"] = json!(["resize"]); - } - result -} - -fn card(x: f64, y: f64, width: f64, title: &str, lines: [(&str, &str, &str); 2]) -> Value { - let inner = width - 26.0; - let [(first, first_style, first_color), (second, second_style, second_color)] = lines; - json!({ - "type": "group", "x": x, "y": y, "children": [ - {"type": "rect", "x": 0.5, "y": 0.5, "w": width - 1.0, "h": 89, "radius": 8, "fill": "$surface", "stroke": "$line"}, - text(13.0, 23.0, inner, title, "strong", "$text"), - text(13.0, 49.0, inner, first, first_style, first_color), - text(13.0, 72.0, inner, second, second_style, second_color), - ], - }) -} - -fn text(x: f64, y: f64, width: f64, value: &str, style: &str, color: &str) -> Value { - json!({"type": "text", "x": x, "y": y, "text": value, "style": style, "color": color, "maxWidth": width}) -} diff --git a/backend/src/view/language.rs b/backend/src/view/language.rs new file mode 100644 index 0000000..5bfeed5 --- /dev/null +++ b/backend/src/view/language.rs @@ -0,0 +1,807 @@ +//! The Python language page's region: the interpreter row the host draws, +//! then a preview of what each Pyrefly option does to a piece of code, in +//! four cards that follow the rows below them. +//! +//! The scene is as wide as the view the host reports, so a unit is a point: +//! the cards stand two to a row when two of the narrowest fit, else one above +//! the other, and widen with the window. A host that reports no width gets +//! the scene for the region in the smallest settings window, 613 points as +//! measured in the host. The code in the editor-like boxes is laid out on the +//! scene's own monospace grid, so the marks on it line up in every host font. +//! +//! What the type checking card reports is what Pyrefly 1.4.1, the version +//! `vendor-lock.json` packages, reports for the sample with each preset and +//! no Pyrefly config, its error codes and messages verbatim. + +use super::scene::{ + code, column, group, pair, path, pill, rect, runs, squiggle, text, text_width, token, Node, + CAPTION, STRONG, +}; +use super::settings::{ImportFormat, Mode, Scope, Settings}; +use super::words::Words; +use serde_json::{json, Value}; + +pub const CANVAS_ID: &str = "pyrefly-preview"; +pub const INTERPRETER_ID: &str = "interpreter"; + +/// The tools the interpreter section lists, as `requiresTools` names them: +/// the host draws each as the Toolchains page does, with its version and +/// path, and opens that page on a click. +pub const TOOLS: [&str; 1] = ["python"]; + +/// The settings the cards show; a draft of any of them marks the preview. +pub const SETTINGS: [&str; 6] = [ + "typeCheckingMode", + "disableTypeErrors", + "diagnosticMode", + "autoImportCompletions", + "importFormat", + "completeFunctionParens", +]; + +/// The scene's width for a host that reports none. +pub const DEFAULT_WIDTH: f64 = 610.0; +/// The narrowest card: the longest message line ends 228 units into the +/// bar, and every pill keeps room beside its title. A view narrower than one +/// such card is scaled down by the host. +pub const MIN_CARD_W: f64 = 292.0; +const HEADER: f64 = 28.0; +const GAP: f64 = 10.0; +/// A card's title row, the line under it that says what the value does, and +/// the editor-like box below them. +const TITLE_Y: f64 = 22.0; +const NOTE_Y: f64 = 41.0; +const BOX_X: f64 = 10.0; +const BOX_Y: f64 = 50.0; +/// The box heights of the type checking and scope cards and of the two +/// completion ones: a type error's message needs the most. +const BOX_H: [f64; 2] = [138.0, 84.0]; +const CARD_H: [f64; 2] = [BOX_Y + BOX_H[0] + BOX_X, BOX_Y + BOX_H[1] + BOX_X]; + +/// Where the four cards go in a scene of a given width. +pub struct Layout { + pub width: f64, + /// Two when two of the narrowest cards fit side by side, else one. + pub columns: usize, + card_w: f64, +} + +impl Layout { + pub fn new(width: Option) -> Self { + let width = width.unwrap_or(DEFAULT_WIDTH).max(MIN_CARD_W); + let columns = if width >= 2.0 * MIN_CARD_W + GAP { + 2 + } else { + 1 + }; + let card_w = (width - (columns - 1) as f64 * GAP) / columns as f64; + Self { + width, + columns, + card_w, + } + } + + fn box_w(&self) -> f64 { + self.card_w - 2.0 * BOX_X + } + + /// The top-left corner of each card, row after row, and the scene's + /// height under the last row. The cards of a row are one height: the + /// type checking and scope ones, or the two completion ones. + fn places(&self) -> ([(f64, f64); 4], f64) { + let mut places = [(0.0, 0.0); 4]; + let mut y = HEADER; + for (index, place) in places.iter_mut().enumerate() { + let column = index % self.columns; + if index > 0 && column == 0 { + y += CARD_H[(index - 1) / 2] + GAP; + } + *place = (column as f64 * (self.card_w + GAP), y); + } + (places, y + CARD_H[1]) + } +} + +/// Code colors after the IDE themes Lithe's editor follows. +fn keyword() -> Value { + pair("#0033B3", "#CF8E6D") +} +fn function() -> Value { + pair("#00627A", "#56A8F5") +} +fn builtin() -> Value { + pair("#000080", "#8888C6") +} +fn string() -> Value { + pair("#067D17", "#6AAB73") +} +fn number() -> Value { + pair("#1750EB", "#2AACB8") +} +fn plain() -> Value { + token("$text") +} +fn editor() -> Value { + pair("#FFFFFF", "#1E1F22") +} + +/// One card: the row it follows and what that row's value does. +struct Card<'a> { + title: &'a str, + /// The value shown in the pill. + value: &'a str, + /// False for a switched-off option, whose pill is neutral. + lit: bool, + note: &'a str, + /// Whether what the card shows follows a draft not applied yet. + changed: bool, + preview: Vec, +} + +/// The region's nodes: the interpreter row, then the preview. +pub fn view(settings: &Settings, words: &Words, width: Option) -> Vec { + let tools: Vec = TOOLS + .iter() + .map(|tool| json!({ "type": "tool", "tool": tool })) + .collect(); + vec![ + json!({ + "type": "section", + "id": INTERPRETER_ID, + "title": words.interpreter_title, + "info": words.interpreter_info, + "children": tools, + }), + canvas(settings, words, width), + ] +} + +/// The preset's place in `Words::modes` and `Words::mode_notes`. +fn mode_index(mode: Mode) -> usize { + match mode { + Mode::Auto => 0, + Mode::Off => 1, + Mode::Basic => 2, + Mode::Legacy => 3, + Mode::Default => 4, + Mode::Strict => 5, + Mode::All => 6, + } +} + +/// The pill value, whether it is lit, and the note of each card, in the +/// order the cards stand. +fn values<'a>(settings: &Settings, words: &'a Words) -> [(&'a str, bool, &'a str); 4] { + let switch = |on: bool| if on { words.on } else { words.off }; + let mode = if settings.hide_type_errors { + (words.hidden, false, words.hidden_note) + } else { + let index = mode_index(settings.mode); + ( + words.modes[index], + settings.mode != Mode::Off, + words.mode_notes[index], + ) + }; + let scope = match settings.scope { + Scope::OpenFiles => (words.scope_open, false, words.scope_open_note), + Scope::Workspace => (words.scope_workspace, true, words.scope_workspace_note), + }; + let import = match (settings.auto_import, settings.import_format) { + (false, _) => (words.off, false, words.import_off_note), + (true, ImportFormat::Absolute) => (words.import_absolute, true, words.import_absolute_note), + (true, ImportFormat::Relative) => (words.import_relative, true, words.import_relative_note), + }; + let parens = ( + switch(settings.function_parens), + settings.function_parens, + if settings.function_parens { + words.parens_on_note + } else { + words.parens_off_note + }, + ); + [mode, scope, import, parens] +} + +/// The preview for a view `width` points wide, or for the smallest settings +/// window when the host reports no width. A host that reports it sends +/// `resize` with the new width, and the scene is drawn again for it. +pub fn canvas(settings: &Settings, words: &Words, width: Option) -> Value { + let layout = Layout::new(width); + let box_w = layout.box_w(); + let changed = settings.any_changed(&SETTINGS); + let mut nodes = vec![ + text(0.0, 17.0, words.preview_title, "strong"), + text( + layout.width, + 17.0, + if changed { + words.includes_draft + } else { + words.follows_options + }, + "caption", + ) + .align("end") + .color(token(if changed { "$accent" } else { "$textMuted" })) + .max_width(layout.width - text_width(words.preview_title, STRONG) - 16.0), + ]; + let [mode, scope, import, parens] = values(settings, words); + let cards = [ + Card { + title: words.mode_title, + value: mode.0, + lit: mode.1, + note: mode.2, + changed: settings.any_changed(&["typeCheckingMode", "disableTypeErrors"]), + preview: type_check_preview(settings.reporting(), words, box_w), + }, + Card { + title: words.scope_title, + value: scope.0, + lit: scope.1, + note: scope.2, + changed: settings.is_changed("diagnosticMode"), + preview: scope_preview(settings.scope, words, box_w), + }, + Card { + title: words.import_title, + value: import.0, + lit: import.1, + note: import.2, + // The path style decides this card only while auto-import is on. + changed: settings.is_changed("autoImportCompletions") + || (settings.auto_import && settings.is_changed("importFormat")), + preview: import_preview( + settings.auto_import.then_some(settings.import_format), + words, + ), + }, + Card { + title: words.parens_title, + value: parens.0, + lit: parens.1, + note: parens.2, + changed: settings.is_changed("completeFunctionParens"), + preview: parens_preview(settings.function_parens, words), + }, + ]; + let (places, height) = layout.places(); + for (index, (card, (x, y))) in cards.into_iter().zip(places).enumerate() { + nodes.push(group(x, y, draw(card, index / 2, layout.card_w))); + } + let mut canvas = json!({ + "type": "canvas", + "id": CANVAS_ID, + "label": words.preview_label, + "height": height.ceil() as u64, + "viewBox": [0, 0, layout.width, height], + "nodes": nodes.into_iter().map(Value::from).collect::>(), + }); + if width.is_some() { + canvas["on"] = json!(["resize"]); + } + canvas +} + +/// A card `card_w` wide whose box is `BOX_H[kind]` tall: its title, a pill +/// with the value shown and, when that value is a draft, an accent outline +/// and a dot in front of the pill; the line saying what the value does; then +/// the preview in an editor-like box. A lit pill writes in `$text`: accent ink +/// on the selection fill falls to about 2:1 in Lithe's dark theme. +fn draw(card: Card, kind: usize, card_w: f64) -> Vec { + let (fill, ink) = if card.lit { + (token("$selection"), token("$text")) + } else { + (token("$badge"), token("$textSecondary")) + }; + let (_, width) = pill(0.0, 0.0, card.value, fill.clone(), ink.clone()); + let pill_x = card_w - 12.0 - width; + let (pill, _) = pill(pill_x, 8.0, card.value, fill, ink); + let frame = rect(0.0, 0.0, card_w, CARD_H[kind]) + .radius(8.0) + .fill(token("$surface")); + let mut nodes = vec![ + if card.changed { + frame.stroke(token("$accent"), 1.2) + } else { + frame.stroke(token("$line"), 1.0) + }, + text(12.0, TITLE_Y, card.title, "strong").max_width(pill_x - 12.0 - 18.0), + pill, + text(12.0, NOTE_Y, card.note, "caption") + .color(token("$textSecondary")) + .max_width(card_w - 24.0), + rect(BOX_X, BOX_Y, card_w - 2.0 * BOX_X, BOX_H[kind]) + .radius(6.0) + .fill(editor()) + .stroke(token("$line"), 1.0), + group(BOX_X, BOX_Y, card.preview), + ]; + if card.changed { + nodes.push( + rect(pill_x - 11.0, 15.0, 6.0, 6.0) + .radius(3.0) + .fill(token("$accent")), + ); + } + nodes +} + +/// The first code line's baseline in the boxes, and the left edge of the +/// code after the line numbers. +const CODE_TOP: f64 = 22.0; +const CODE_X: f64 = 32.0; +const LINE: f64 = 16.0; + +/// Code lines with line numbers in a gutter, `LINE` units apart. +fn numbered(lines: Vec>) -> Vec { + let mut nodes = Vec::new(); + for (index, line) in lines.iter().enumerate() { + let y = CODE_TOP + index as f64 * LINE; + nodes.push( + text(CODE_X - 10.0, y, &(index + 1).to_string(), "monoSmall") + .align("end") + .color(token("$textMuted")), + ); + nodes.extend(code(CODE_X, y, line)); + } + nodes +} + +/// A wavy underline under columns `start` to `end` of line `line`. +fn underline(line: usize, start: usize, end: usize, color: &str) -> Node { + path(squiggle( + column(CODE_X, start), + column(CODE_X, end), + CODE_TOP + line as f64 * LINE + 3.0, + )) + .stroke(token(color), 1.0) +} + +/// An error Pyrefly reports for the sample: where, under which code, and its +/// message in the lines the bar shows. +struct TypeError { + line: usize, + start: usize, + end: usize, + code: &'static str, + message: &'static [&'static str], +} + +/// What Pyrefly 1.4.1 reports for the sample, in the order the presets add +/// them: `basic` reports the first; `legacy` and `default` add the second; +/// `strict` the third; `all` the last two. The message after `…` is cut. +const ERRORS: [TypeError; 5] = [ + TypeError { + line: 3, + start: 6, + end: 10, + code: "unknown-name", + message: &["Could not find name `totl`"], + }, + TypeError { + line: 2, + start: 9, + end: 12, + code: "bad-argument-type", + message: &[ + "Argument `Literal['3']` is not assignable", + "to parameter `k` with type `float` …", + ], + }, + TypeError { + line: 0, + start: 10, + end: 11, + code: "implicit-any-parameter", + message: &["`scale` is missing an annotation for", "parameter `x`"], + }, + TypeError { + line: 1, + start: 11, + end: 16, + code: "no-any-return-implicit", + message: &[ + "Returning implicit Any from function", + "declared to return \"float\"", + ], + }, + TypeError { + line: 2, + start: 0, + end: 13, + code: "unused-call-result", + message: &[ + "Result of call expression is of type", + "`float` and is not used …", + ], + }, +]; + +/// How many of `ERRORS` a preset reports, and which of them the bar shows: +/// the first one the preset adds to the one below it. +fn reported(mode: Mode) -> (usize, Option) { + match mode.applied() { + Mode::Off | Mode::Auto => (0, None), + Mode::Basic => (1, Some(0)), + Mode::Legacy | Mode::Default => (2, Some(1)), + Mode::Strict => (3, Some(2)), + Mode::All => (5, Some(3)), + } +} + +/// A function missing an annotation, a call with a string for a float, and a +/// misspelled name, in a box `box_w` wide; under it what the preset in force +/// reports. Nothing is reported while type errors are hidden or off. +fn type_check_preview(reporting: Option, words: &Words, box_w: f64) -> Vec { + let mut nodes = numbered(vec![ + vec![ + ("def ", keyword()), + ("scale", function()), + ("(x, k: ", plain()), + ("float", builtin()), + (") -> ", plain()), + ("float", builtin()), + (":", plain()), + ], + vec![(" return ", keyword()), ("x * k", plain())], + vec![ + ("scale(", plain()), + ("2", number()), + (", ", plain()), + ("\"3\"", string()), + (")", plain()), + ], + vec![("print", builtin()), ("(totl)", plain())], + ]); + let (count, shown) = reporting.map_or((0, None), reported); + for error in &ERRORS[..count] { + nodes.push(underline(error.line, error.start, error.end, "$error")); + } + let Some(shown) = shown else { + return nodes; + }; + let error = &ERRORS[shown]; + let tally = format!(" · {}", (words.errors)(count)); + let mut lines = vec![vec![ + (error.code, token("$text")), + (tally.as_str(), token("$textSecondary")), + ]]; + for line in error.message { + lines.push(vec![(*line, token("$textSecondary"))]); + } + nodes.push(message_bar( + CODE_TOP + 3.0 * LINE + 12.0, + box_w, + Severity::Error, + &lines, + )); + nodes +} + +/// A small project in a box `box_w` wide, one file open in the editor, and +/// what Pyrefly checks in each file: in the workspace scope it publishes the +/// errors of the files not open too, but only error-level diagnostics. +fn scope_preview(scope: Scope, words: &Words, box_w: f64) -> Vec { + // Each row: its depth, its name, whether it is a folder, and whether the + // file is open. + const ROWS: [(usize, &str, bool, bool); 6] = [ + (0, "app", true, false), + (1, "main.py", false, true), + (1, "utils.py", false, false), + (1, "models.py", false, false), + (0, "tests", true, false), + (1, "test_models.py", false, false), + ]; + let mut nodes = Vec::new(); + for (index, (depth, name, folder, open)) in ROWS.into_iter().enumerate() { + let y = CODE_TOP + index as f64 * 18.0; + let x = 12.0 + depth as f64 * 16.0; + if folder { + nodes.push(text(x, y, "▾", "caption").color(token("$textMuted"))); + nodes.push(text(x + 12.0, y, name, "caption").color(token("$text"))); + continue; + } + nodes.push( + rect(x, y - 9.0, 8.0, 10.0) + .radius(2.0) + .stroke(token("$textMuted"), 1.0), + ); + nodes.push(text(x + 14.0, y, name, "caption").color(token("$text"))); + let (status, color) = match (open, scope) { + (true, _) => (words.checked, "$success"), + (false, Scope::Workspace) => (words.errors_only, "$textSecondary"), + (false, Scope::OpenFiles) => (words.not_checked, "$textMuted"), + }; + if open { + let tag_x = x + 14.0 + text_width(name, CAPTION) + 6.0; + let tag_w = text_width(words.open_tag, CAPTION) + 10.0; + nodes.push( + rect(tag_x, y - 10.0, tag_w, 14.0) + .radius(7.0) + .fill(token("$selection")), + ); + nodes.push( + text(tag_x + tag_w / 2.0, y, words.open_tag, "caption") + .align("center") + .color(token("$text")), + ); + } + nodes.push( + text(box_w - 10.0, y, status, "caption") + .align("end") + .color(token(color)), + ); + } + nodes +} + +/// The caret at column `at` of line `line`. +fn caret(line: usize, at: usize) -> Node { + rect( + column(CODE_X, at) - 0.5, + CODE_TOP + line as f64 * LINE - 11.0, + 1.4, + 14.0, + ) + .fill(token("$text")) +} + +/// The import line a completion of `greet` writes, in `format`. +fn import_line(format: ImportFormat) -> Vec<(&'static str, Value)> { + vec![ + ("from ", keyword()), + ( + match format { + ImportFormat::Absolute => "app.utils", + ImportFormat::Relative => ".utils", + }, + plain(), + ), + (" import ", keyword()), + ("greet", plain()), + ] +} + +/// A completion list under the code at column `at`, below line `line`: its +/// one row, or the words saying it has none. +fn completion_list(line: usize, at: usize, row: Option<(&str, &str)>, empty: &str) -> Vec { + const W: f64 = 150.0; + let x = column(CODE_X, at) - 4.0; + let y = CODE_TOP + line as f64 * LINE + 6.0; + let mut nodes = vec![rect(x, y, W, 22.0) + .radius(4.0) + .fill(token("$surface")) + .stroke(token("$line"), 1.0)]; + match row { + Some((name, module)) => { + nodes.push( + rect(x + 2.0, y + 2.0, W - 4.0, 18.0) + .radius(3.0) + .fill(token("$selection")), + ); + nodes.push(text(x + 8.0, y + 15.0, "ƒ", "caption").color(function())); + nodes.extend(code(x + 20.0, y + 15.0, &[(name, plain())])); + nodes.push( + text(x + W - 8.0, y + 15.0, module, "caption") + .align("end") + .color(token("$textMuted")), + ); + } + None => nodes.push(text(x + 8.0, y + 15.0, empty, "caption").color(token("$textMuted"))), + } + nodes +} + +/// A name from a module not imported yet, typed halfway. With auto-import +/// on, the completion list offers it and accepting writes the import above, +/// in the chosen path style; off, nothing in scope matches. +fn import_preview(format: Option, words: &Words) -> Vec { + let typed = vec![("message = gre", plain())]; + let Some(format) = format else { + let mut nodes = numbered(vec![typed]); + nodes.push(caret(0, 13)); + nodes.extend(completion_list(0, 10, None, words.no_suggestions)); + return nodes; + }; + let import = import_line(format); + let length: usize = import.iter().map(|(piece, _)| piece.chars().count()).sum(); + // The import line the completion writes, tinted, and its legend under + // the list, clear of the code. + let mut nodes = vec![rect( + CODE_X - 3.0, + CODE_TOP - 11.0, + column(0.0, length) + 6.0, + 15.0, + ) + .radius(3.0) + .fill(token("$accent")) + .opacity(0.14)]; + nodes.extend(numbered(vec![import, typed])); + nodes.push(caret(1, 13)); + nodes.extend(completion_list(1, 10, Some(("greet", "app.utils")), "")); + nodes.push( + rect(12.0, 70.0, 8.0, 8.0) + .radius(2.0) + .fill(token("$accent")) + .opacity(0.3), + ); + nodes.push(text(25.0, 78.0, words.inserted_on_accept, "caption").color(token("$textMuted"))); + nodes +} + +/// What accepting the completion of a function writes: its name and, with +/// parentheses on, `()` with the caret between them. +fn parens_preview(parens: bool, words: &Words) -> Vec { + let mut call = vec![("message = ", plain()), ("greet", plain())]; + if parens { + call.push(("()", plain())); + } + let mut nodes = Vec::new(); + if parens { + nodes.push( + rect( + column(CODE_X, 15) - 1.0, + CODE_TOP + LINE - 11.0, + column(0.0, 2) + 2.0, + 15.0, + ) + .radius(3.0) + .fill(token("$accent")) + .opacity(0.14), + ); + } + nodes.extend(numbered(vec![import_line(ImportFormat::Absolute), call])); + nodes.push(caret(1, if parens { 16 } else { 15 })); + nodes.push( + text( + CODE_X, + CODE_TOP + 2.0 * LINE + 10.0, + words.after_accepting, + "caption", + ) + .color(token("$textMuted")), + ); + nodes +} + +#[derive(Clone, Copy)] +enum Severity { + Error, +} + +/// A diagnostic under the code at `y`, in a box `box_w` wide: its icon and +/// its message, a line of runs to each entry of `lines`. +fn message_bar(y: f64, box_w: f64, severity: Severity, lines: &[Vec<(&str, Value)>]) -> Node { + let bar_w = box_w - 12.0; + let bar_h = 8.0 + 14.0 * lines.len() as f64; + let mut children = match severity { + Severity::Error => vec![ + rect(0.0, 0.0, bar_w, bar_h) + .radius(5.0) + .fill(pair("#FDEEEE", "#402929")), + rect(7.0, 4.5, 12.0, 12.0).radius(6.0).fill(token("$error")), + path("M13 7.4 V11 M13 13.2 V13.3".into()) + .stroke("#FFFFFF", 1.4) + .set("cap", "round"), + ], + }; + for (index, line) in lines.iter().enumerate() { + children + .push(runs(25.0, 15.0 + 14.0 * index as f64, line, "caption").max_width(bar_w - 31.0)); + } + group(6.0, y, children) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::view::words; + + #[test] + fn every_title_keeps_its_room_beside_its_pill_in_the_narrowest_card() { + for language in ["en", "zh-Hans"] { + let w = words::for_language(language); + let mut pairs: Vec<(&str, &str)> = w + .modes + .iter() + .chain([&w.hidden]) + .map(|value| (w.mode_title, *value)) + .collect(); + pairs.extend([w.scope_open, w.scope_workspace].map(|value| (w.scope_title, value))); + pairs.extend( + [w.off, w.import_absolute, w.import_relative].map(|value| (w.import_title, value)), + ); + pairs.extend([w.on, w.off].map(|value| (w.parens_title, value))); + for (title, value) in pairs { + // As `draw` places them: the pill 12 units from the card's + // right edge, the title from 12 units and 18 short of the pill. + let pill_x = MIN_CARD_W - 12.0 - (text_width(value, CAPTION) + 16.0); + let room = pill_x - 12.0 - 18.0; + let title_w = text_width(title, STRONG); + assert!( + title_w <= room, + "{language}: {title} ({title_w}) beside {value} ({room})" + ); + } + } + } + + #[test] + fn every_note_fits_the_narrowest_card() { + for language in ["en", "zh-Hans"] { + let w = words::for_language(language); + let notes = w.mode_notes.iter().copied().chain([ + w.hidden_note, + w.scope_open_note, + w.scope_workspace_note, + w.import_absolute_note, + w.import_relative_note, + w.import_off_note, + w.parens_on_note, + w.parens_off_note, + ]); + for note in notes { + let width = text_width(note, CAPTION); + assert!(width <= MIN_CARD_W - 24.0, "{language}: {note} ({width})"); + } + } + } + + #[test] + fn every_message_line_fits_the_bar_of_the_narrowest_box() { + let room = MIN_CARD_W - 2.0 * BOX_X - 12.0 - 31.0; + for language in ["en", "zh-Hans"] { + let w = words::for_language(language); + for error in &ERRORS { + let head = format!("{} · {}", error.code, (w.errors)(5)); + for line in error.message.iter().copied().chain([head.as_str()]) { + let width = text_width(line, CAPTION); + assert!(width <= room, "{language}: {line} ({width} of {room})"); + } + } + } + } + + #[test] + fn the_message_bar_stays_inside_the_type_checking_box() { + let longest = ERRORS + .iter() + .map(|error| error.message.len() + 1) + .max() + .unwrap(); + let bottom = CODE_TOP + 3.0 * LINE + 12.0 + 8.0 + 14.0 * longest as f64; + assert!(bottom <= BOX_H[0], "{bottom}"); + } + + #[test] + fn the_longest_code_line_fits_the_narrowest_box() { + let box_w = MIN_CARD_W - 2.0 * BOX_X; + let longest = "def scale(x, k: float) -> float:".chars().count(); + assert!( + column(CODE_X, longest) <= box_w, + "{}", + column(CODE_X, longest) + ); + // The completion list, from column 10 of the code. + assert!(column(CODE_X, 10) - 4.0 + 150.0 <= box_w); + } + + #[test] + fn each_error_marks_the_text_pyrefly_reports_it_on() { + let lines = [ + "def scale(x, k: float) -> float:", + " return x * k", + "scale(2, \"3\")", + "print(totl)", + ]; + let marked: Vec<&str> = ERRORS + .iter() + .map(|error| &lines[error.line][error.start..error.end]) + .collect(); + assert_eq!(marked, ["totl", "\"3\"", "x", "x * k", "scale(2, \"3\")"]); + } +} diff --git a/backend/src/view/mod.rs b/backend/src/view/mod.rs new file mode 100644 index 0000000..428048e --- /dev/null +++ b/backend/src/view/mod.rs @@ -0,0 +1,807 @@ +//! The views of the plugin's settings regions (`settingRegions` in +//! `plugin.json`): previews that follow the settings window as the user +//! edits the rows below them. They read settings only; Pyrefly, the build +//! tools and the interpreter stay with the host. + +mod language; +mod resolution; +mod scene; +mod settings; +mod words; + +use lithe_plugin_sdk::view::{ViewEvent, ViewEventKind, ViewResult, ViewSurface}; +use lithe_plugin_sdk::{Backend, Context, FunctionError, PluginError, SdkError}; +use serde_json::{json, Value}; +use settings::Settings; + +/// The view function every region names in `view.function`. +const VIEW: &str = "settings.view"; + +/// The region on the Python language page and the one on the Python build +/// system page. The plugin's own Settings tab has none: its detail pane is +/// too narrow for a preview, and each page already shows its own. +const LANGUAGE_REGION: &str = "language"; +const PYTHON_REGION: &str = "python"; + +/// The tool the Python page's row shows, as `toolDefinitions` names it. +const PYTHON_TOOL: &str = "python"; + +pub fn register(backend: &mut Backend) -> Result<(), SdkError> { + backend.view(VIEW, view)?; + // A view answers every keystroke in the settings window; its failures + // and degradations are still logged. + backend.suppress_success_diagnostics(VIEW)?; + Ok(()) +} + +fn view(event: ViewEvent, context: &Context) -> Result { + if !redraws(&event.kind) { + return Ok(ViewResult::Unchanged); + } + let (nodes, unrecognized) = render(&event)?; + if unrecognized > 0 { + context + .diagnostics() + .degraded(VIEW, "setting.unrecognized", Some(unrecognized))?; + } + Ok(ViewResult::View(nodes)) +} + +/// Whether the event changes what the view draws: it opens, the settings +/// change, or the view's width settles at a new value. +fn redraws(kind: &ViewEventKind) -> bool { + matches!( + kind, + ViewEventKind::Open | ViewEventKind::Settings | ViewEventKind::Resize + ) +} + +/// The nodes of the event's region, laid out for the width the event +/// carries, and how many settings held a value the preview could not read +/// and shows as the default. +fn render(event: &ViewEvent) -> Result<(Vec, u64), PluginError> { + let ViewSurface::SettingRegion(region) = &event.surface else { + return Err(unknown_region()); + }; + let words = words::for_language(&event.language); + match region.as_str() { + LANGUAGE_REGION => { + let settings = Settings::read(event); + let nodes = language::view(&settings, words, event.width); + Ok((nodes, settings.unrecognized)) + } + PYTHON_REGION => Ok(( + vec![ + json!({ "type": "tool", "tool": PYTHON_TOOL }), + resolution::canvas(words, event.width), + ], + 0, + )), + _ => Err(unknown_region()), + } +} + +fn unknown_region() -> PluginError { + PluginError::new( + "python.view.unknownRegion", + "This view draws the Python Support plugin's settings regions only.", + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Map; + + fn event(region: &str, language: &str, effective: Value, draft: Value) -> ViewEvent { + event_at("settings", region, language, None, effective, draft) + } + + /// A `kind` event for `region`, with the view's width when the host + /// reports it. + fn event_at( + kind: &str, + region: &str, + language: &str, + width: Option, + effective: Value, + draft: Value, + ) -> ViewEvent { + let mut event = json!({ + "event": kind, + "instance": "i1", + "surface": { "settingRegionID": region }, + "language": language, + "settings": { "effective": effective, "draft": draft }, + }); + if let Some(width) = width { + event["width"] = json!(width); + } + ViewEvent::parse(&event).unwrap() + } + + fn nodes(region: &str, language: &str, effective: Value, draft: Value) -> Vec { + render(&event(region, language, effective, draft)) + .unwrap() + .0 + } + + fn nodes_at( + region: &str, + language: &str, + width: f64, + effective: Value, + draft: Value, + ) -> Vec { + let event = event_at("resize", region, language, Some(width), effective, draft); + render(&event).unwrap().0 + } + + /// The region's one canvas: the last of its nodes, after the rows the + /// host draws. + fn canvas(nodes: &[Value]) -> &Value { + let canvas = nodes.last().unwrap(); + assert_eq!(canvas["type"], "canvas"); + canvas + } + + /// How far right what `nodes` draws reaches, in view-box units, from a + /// parent at `x0`: rects, code characters, text that ends at its x and + /// text cut at a maximum width. Other text has no extent the plugin + /// knows, and paths are drawn inside the rects here. + fn right_edge(nodes: &[Value], x0: f64) -> f64 { + let mut edge: f64 = 0.0; + for node in nodes { + let x = x0 + node.get("x").and_then(Value::as_f64).unwrap_or(0.0); + let character = node["style"] == "monoSmall" + && node["text"] + .as_str() + .is_some_and(|text| text.chars().count() == 1); + let reach = match ( + node["type"].as_str(), + node.get("align").and_then(Value::as_str), + ) { + (Some("rect"), _) => x + node["w"].as_f64().unwrap(), + (Some("text"), Some("end")) => x, + (Some("text"), None) if character => x + scene::MONO_ADVANCE, + (Some("text"), None) => node + .get("maxWidth") + .and_then(Value::as_f64) + .map_or(0.0, |width| x + width), + _ => 0.0, + }; + edge = edge.max(reach); + for key in ["children", "nodes"] { + if let Some(children) = node.get(key).and_then(Value::as_array) { + edge = edge.max(right_edge(children, x)); + } + } + } + edge + } + + /// Room for the rounding of positions and sizes to tenths. + const ROUNDING: f64 = 0.1; + + /// Every node of a scene, the nested ones included. + fn walk<'a>(node: &'a Value, out: &mut Vec<&'a Value>) { + out.push(node); + for key in ["children", "nodes"] { + if let Some(children) = node.get(key).and_then(Value::as_array) { + for child in children { + walk(child, out); + } + } + } + } + + fn all(nodes: &[Value]) -> Vec<&Value> { + let mut out = Vec::new(); + for node in nodes { + walk(node, &mut out); + } + out + } + + /// The words of a scene, runs joined, and code laid out a character to a + /// node joined back into its lines, spaces included. + fn words_of(nodes: &[Value]) -> String { + let mut out = String::new(); + // The last code character's position. + let mut cell: Option<(f64, f64)> = None; + for node in all(nodes) { + let text = node.get("text").and_then(Value::as_str); + if let Some(character) = text.filter(|text| { + text.chars().count() == 1 + && node["style"] == "monoSmall" + && node.get("align").is_none() + }) { + let (x, y) = (node["x"].as_f64().unwrap(), node["y"].as_f64().unwrap()); + match cell { + Some((last_x, last_y)) if last_y == y => { + let columns = ((x - last_x) / scene::MONO_ADVANCE).round() as usize; + out.push_str(&" ".repeat(columns.saturating_sub(1))); + } + Some(_) => out.push('\n'), + None => {} + } + out.push_str(character); + cell = Some((x, y)); + continue; + } + if cell.take().is_some() { + out.push('\n'); + } + if let Some(text) = text { + out.push_str(text); + out.push('\n'); + } + if let Some(runs) = node.get("runs").and_then(Value::as_array) { + for run in runs { + out.push_str(run["text"].as_str().unwrap()); + } + out.push('\n'); + } + } + out + } + + const MODES: [&str; 7] = ["auto", "off", "basic", "legacy", "default", "strict", "all"]; + + fn settings_cases() -> Vec<(Value, Value)> { + let mut cases = Vec::new(); + for mode in MODES { + cases.push((json!({ "typeCheckingMode": mode }), json!({}))); + } + cases.push(( + json!({ "typeCheckingMode": "all", "disableTypeErrors": false }), + json!({ "disableTypeErrors": true }), + )); + for (scope, auto_import, format, parens) in [ + ("workspace", true, "relative", true), + ("openFilesOnly", false, "relative", false), + ("workspace", true, "absolute", false), + ] { + cases.push(( + json!({ + "diagnosticMode": scope, + "autoImportCompletions": auto_import, + "importFormat": format, + "completeFunctionParens": parens, + }), + json!({}), + )); + } + cases + } + + /// The limits `plugin-ui.schema.json` sets on what the view draws here. + fn check_limits(nodes: &[Value]) { + let canvases: Vec<_> = all(nodes) + .into_iter() + .filter(|node| node["type"] == "canvas") + .collect(); + assert!(!canvases.is_empty() && canvases.len() <= 8); + for canvas in canvases { + let label = canvas["label"].as_str().unwrap(); + assert!(!label.trim().is_empty() && label.chars().count() <= 120); + let height = canvas["height"].as_u64().expect("a whole height"); + assert!((1..=2000).contains(&height)); + let mut scene = Vec::new(); + walk(canvas, &mut scene); + assert!(scene.len() <= 2000, "{} nodes", scene.len()); + assert!(serde_json::to_vec(canvas).unwrap().len() <= 256 * 1024); + for node in scene { + if let Some(text) = node.get("text").and_then(Value::as_str) { + assert!(text.chars().count() <= 1024); + assert!(!text + .chars() + .any(|c| c.is_control() && c != '\n' && c != '\t')); + } + if let Some(runs) = node.get("runs").and_then(Value::as_array) { + assert!(!runs.is_empty() && runs.len() <= 64); + } + if let Some(dash) = node.get("dash").and_then(Value::as_array) { + assert!((1..=8).contains(&dash.len())); + } + for color in ["fill", "color", "stroke"] { + if let Some(value) = node.get(color) { + check_color(value); + } + } + } + } + for section in all(nodes) + .into_iter() + .filter(|node| node["type"] == "section") + { + assert!(section["title"].as_str().unwrap().chars().count() <= 120); + assert!(section["info"].as_str().unwrap().chars().count() <= 480); + } + } + + fn check_color(value: &Value) { + let plain = |value: &Value| { + let value = value.as_str().unwrap(); + let tokens = [ + "$text", + "$textSecondary", + "$textMuted", + "$accent", + "$success", + "$warning", + "$error", + "$surface", + "$background", + "$sidebar", + "$line", + "$hover", + "$selection", + "$badge", + ]; + let hex = value.len() == 7 + && value.starts_with('#') + && value[1..].chars().all(|c| c.is_ascii_hexdigit()); + assert!(hex || tokens.contains(&value), "{value}"); + }; + match value { + Value::Object(pair) => { + plain(&pair["light"]); + plain(&pair["dark"]); + } + _ => plain(value), + } + } + + #[test] + fn every_region_draws_within_the_limits_in_both_languages() { + for region in [LANGUAGE_REGION, PYTHON_REGION] { + for language in ["en", "zh-Hans"] { + for (effective, draft) in settings_cases() { + check_limits(&nodes(region, language, effective, draft)); + } + } + } + } + + /// The width each region has in the smallest settings window, measured + /// in the host: the language page, and the build system page's detail + /// pane. + const REGION_WIDTHS: [(&str, f64); 2] = [(LANGUAGE_REGION, 613.0), (PYTHON_REGION, 344.0)]; + + /// The narrowest scene of each region; a narrower view is scaled down. + const MIN_WIDTHS: [(&str, f64); 2] = [ + (LANGUAGE_REGION, language::MIN_CARD_W), + (PYTHON_REGION, resolution::MIN_WIDTH), + ]; + + #[test] + fn without_a_width_each_scene_fits_its_region_in_the_smallest_window() { + for (region, width) in REGION_WIDTHS { + for language in ["en", "zh-Hans"] { + let nodes = nodes(region, language, json!({}), json!({})); + let canvas = canvas(&nodes); + let view_box = canvas["viewBox"].as_array().unwrap(); + let view_width = view_box[2].as_f64().unwrap(); + assert!(view_width <= width, "{region}: {view_width}"); + assert!(width - view_width < 10.0, "{region} leaves room unused"); + assert_eq!( + canvas["height"].as_f64().unwrap(), + view_box[3].as_f64().unwrap().ceil(), + "{region}" + ); + assert!(canvas.get("pan").is_none()); + // A host that reports no width cannot send resize, and one + // from before resize existed rejects the word. + assert!(canvas.get("on").is_none(), "{region}"); + } + } + } + + #[test] + fn each_scene_is_as_wide_as_the_view_and_draws_inside_it() { + let widths = [330.0, 344.0, 480.0, 593.0, 594.0, 613.0, 900.0, 1400.0]; + for (region, _) in REGION_WIDTHS { + for language in ["en", "zh-Hans"] { + for (effective, draft) in settings_cases() { + for width in widths { + let nodes = + nodes_at(region, language, width, effective.clone(), draft.clone()); + check_limits(&nodes); + let canvas = canvas(&nodes); + let view_box = canvas["viewBox"].as_array().unwrap(); + assert_eq!(view_box[2].as_f64().unwrap(), width, "{region} at {width}"); + assert_eq!( + canvas["height"].as_f64().unwrap(), + view_box[3].as_f64().unwrap().ceil(), + "{region} at {width}" + ); + assert!(canvas.get("pan").is_none()); + assert_eq!(canvas["on"], json!(["resize"]), "{region} at {width}"); + let reach = right_edge(std::slice::from_ref(canvas), 0.0); + assert!( + reach <= width + ROUNDING, + "{region} {language} at {width}: {reach}" + ); + } + } + } + } + } + + #[test] + fn a_view_narrower_than_the_narrowest_scene_gets_the_narrowest() { + for (region, min) in MIN_WIDTHS { + let nodes = nodes_at(region, "en", 200.0, json!({}), json!({})); + assert_eq!( + canvas(&nodes)["viewBox"][2].as_f64().unwrap(), + min, + "{region}" + ); + } + } + + /// The x and the content's reach of each language card, the frame first + /// among each card's children. + fn cards(width: f64, language: &str, effective: Value) -> Vec<(f64, f64, f64)> { + let nodes = nodes_at(LANGUAGE_REGION, language, width, effective, json!({})); + canvas(&nodes)["nodes"] + .as_array() + .unwrap() + .iter() + .filter(|node| node["type"] == "group") + .map(|card| { + let children = card["children"].as_array().unwrap(); + let frame = children[0]["w"].as_f64().unwrap(); + ( + card["x"].as_f64().unwrap(), + frame, + right_edge(children, 0.0), + ) + }) + .collect() + } + + #[test] + fn the_cards_stand_two_to_a_row_only_when_two_of_the_narrowest_fit() { + let two = 2.0 * language::MIN_CARD_W + 10.0; + for language in ["en", "zh-Hans"] { + for (effective, _) in settings_cases() { + for (width, columns) in [(two - 1.0, 1), (two, 2), (1400.0, 2), (330.0, 1)] { + let cards = cards(width, language, effective.clone()); + assert_eq!(cards.len(), 4); + let beside = cards.iter().filter(|(x, ..)| *x > 0.0).count(); + assert_eq!( + beside, + if columns == 2 { 2 } else { 0 }, + "{language} at {width}" + ); + for (x, frame, reach) in cards { + assert!( + reach <= frame + ROUNDING, + "{language} at {width}: {reach} past {frame}" + ); + assert!(x + frame <= width + ROUNDING, "{language} at {width}"); + } + } + } + } + } + + #[test] + fn a_resize_draws_the_view_again_for_the_new_width() { + assert!(redraws(&ViewEventKind::Resize)); + assert!(redraws(&ViewEventKind::Open) && redraws(&ViewEventKind::Settings)); + assert!(!redraws(&ViewEventKind::Close) && !redraws(&ViewEventKind::Viewport)); + for (region, _) in REGION_WIDTHS { + let wide = nodes_at(region, "en", 760.0, json!({}), json!({})); + assert_eq!(canvas(&wide)["viewBox"][2], json!(760.0), "{region}"); + } + } + + #[test] + fn each_region_draws_the_host_rows_of_its_tools_then_its_preview() { + let language = nodes(LANGUAGE_REGION, "en", json!({}), json!({})); + assert_eq!(language.len(), 2); + assert_eq!(language[0]["type"], "section"); + let tools: Vec<&str> = language[0]["children"] + .as_array() + .unwrap() + .iter() + .map(|row| { + assert_eq!(row["type"], "tool"); + row["tool"].as_str().unwrap() + }) + .collect(); + assert_eq!(tools, language::TOOLS); + assert_eq!(canvas(&language)["id"], language::CANVAS_ID); + + let python = nodes(PYTHON_REGION, "en", json!({}), json!({})); + assert_eq!(python.len(), 2); + assert_eq!(python[0], json!({ "type": "tool", "tool": "python" })); + assert_eq!(canvas(&python)["id"], resolution::CANVAS_ID); + } + + /// Every tool a row names is one `plugin.json` defines or requires, so + /// the host can resolve it. + #[test] + fn every_tool_row_names_a_tool_of_the_manifest() { + let manifest: Value = serde_json::from_str(include_str!( + "../../../io.github.lithe-idea.python-support/plugin.json" + )) + .unwrap(); + let mut known: Vec<&str> = manifest["toolDefinitions"] + .as_array() + .unwrap() + .iter() + .map(|tool| tool["id"].as_str().unwrap()) + .collect(); + for tool in manifest["requiresTools"].as_array().unwrap() { + known.push(tool["id"].as_str().or(tool.as_str()).unwrap()); + } + for region in [LANGUAGE_REGION, PYTHON_REGION] { + for node in all(&nodes(region, "en", json!({}), json!({}))) { + if node["type"] == "tool" { + let tool = node["tool"].as_str().unwrap(); + assert!(known.contains(&tool), "{region}: {tool} not in {known:?}"); + } + } + } + } + + /// The regions `plugin.json` declares are the ones this view draws, on + /// the pages it draws them for. + #[test] + fn every_declared_region_names_this_view() { + let manifest: Value = serde_json::from_str(include_str!( + "../../../io.github.lithe-idea.python-support/plugin.json" + )) + .unwrap(); + let regions: Vec<(&str, &Value)> = manifest["settingRegions"] + .as_array() + .unwrap() + .iter() + .map(|region| { + assert_eq!(region["view"]["function"], VIEW); + (region["id"].as_str().unwrap(), ®ion["page"]) + }) + .collect(); + assert_eq!( + regions, + [ + (LANGUAGE_REGION, &json!({ "languageID": "python" })), + (PYTHON_REGION, &json!({ "buildSystemID": "python" })), + ] + ); + } + + /// The error codes the type checking card marks under each preset, and + /// the code its message bar names. + fn reported(effective: Value, draft: Value) -> (usize, String) { + let nodes = nodes(LANGUAGE_REGION, "en", effective, draft); + let card = &canvas(&nodes)["nodes"].as_array().unwrap()[2]; + let squiggles = all(std::slice::from_ref(card)) + .into_iter() + .filter(|node| node["type"] == "path" && node["stroke"] == "$error") + .count(); + (squiggles, words_of(std::slice::from_ref(card))) + } + + #[test] + fn each_preset_reports_what_pyrefly_reports_for_the_sample() { + for (mode, count, code, message) in [ + ("auto", 1, "unknown-name", "Could not find name `totl`"), + ("basic", 1, "unknown-name", "Could not find name `totl`"), + ( + "legacy", + 2, + "bad-argument-type", + "Argument `Literal['3']` is not assignable", + ), + ( + "default", + 2, + "bad-argument-type", + "to parameter `k` with type `float`", + ), + ( + "strict", + 3, + "implicit-any-parameter", + "is missing an annotation for", + ), + ( + "all", + 5, + "no-any-return-implicit", + "Returning implicit Any from function", + ), + ] { + let (squiggles, shown) = reported(json!({ "typeCheckingMode": mode }), json!({})); + assert_eq!(squiggles, count, "{mode}"); + let errors = if count == 1 { + "1 error".to_string() + } else { + format!("{count} errors") + }; + assert!( + shown.contains(&format!("{code} · {errors}")), + "{mode}: {shown}" + ); + assert!(shown.contains(message), "{mode}: {shown}"); + assert!( + shown.contains("def scale(x, k: float) -> float:"), + "{shown}" + ); + assert!(shown.contains("print(totl)"), "{shown}"); + } + } + + #[test] + fn off_and_hidden_type_errors_report_nothing() { + let (squiggles, shown) = reported(json!({ "typeCheckingMode": "off" }), json!({})); + assert_eq!(squiggles, 0); + assert!( + shown.contains("No type errors") && !shown.contains(" · "), + "{shown}" + ); + let (squiggles, shown) = reported( + json!({ "typeCheckingMode": "all", "disableTypeErrors": true }), + json!({}), + ); + assert_eq!(squiggles, 0); + assert!(shown.contains("Hidden") && shown.contains("Hide type errors is on")); + assert!(!shown.contains("no-any-return-implicit")); + } + + #[test] + fn the_scope_preview_checks_files_not_open_only_in_the_workspace_scope() { + let shown = |scope: &str| { + words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "diagnosticMode": scope }), + json!({}), + )) + }; + let open = shown("openFilesOnly"); + assert_eq!(open.matches("Checked").count(), 1, "{open}"); + assert_eq!(open.matches("Not checked").count(), 3, "{open}"); + assert!(!open.contains("Errors only")); + let workspace = shown("workspace"); + assert_eq!(workspace.matches("Checked").count(), 1, "{workspace}"); + assert_eq!(workspace.matches("Errors only").count(), 3, "{workspace}"); + assert!(!workspace.contains("Not checked")); + assert!(workspace.contains("main.py") && workspace.contains("test_models.py")); + } + + #[test] + fn auto_import_writes_the_import_in_the_chosen_style_only_while_on() { + let shown = |auto_import: bool, format: &str| { + words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "autoImportCompletions": auto_import, "importFormat": format }), + json!({}), + )) + }; + // Each code line follows its line number. + let absolute = shown(true, "absolute"); + assert!( + absolute.contains("1\nfrom app.utils import greet\n2\nmessage = gre"), + "{absolute}" + ); + assert!(absolute.contains("inserted on accept")); + let relative = shown(true, "relative"); + assert!( + relative.contains("1\nfrom .utils import greet\n2\nmessage = gre"), + "{relative}" + ); + let off = shown(false, "relative"); + assert!( + off.contains("1\nmessage = gre") && off.contains("No suggestions"), + "{off}" + ); + // The parentheses card below imports greet by its full path. + assert!( + !off.contains("from .utils") && !off.contains("inserted on accept"), + "{off}" + ); + assert!(off.contains("Suggests only names already in scope")); + } + + #[test] + fn function_parentheses_follow_the_completed_name_only_while_on() { + let shown = |parens: bool| { + words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "completeFunctionParens": parens }), + json!({}), + )) + }; + assert!(shown(true).contains("message = greet()")); + let off = shown(false); + assert!(off.contains("message = greet\n") && !off.contains("greet()")); + } + + #[test] + fn a_draft_shows_in_the_preview_before_it_is_applied() { + let saved = words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "typeCheckingMode": "basic" }), + json!({}), + )); + assert!(!saved.contains("implicit-any-parameter")); + assert!(saved.contains("follows the options below")); + let draft = words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "typeCheckingMode": "basic" }), + json!({ "typeCheckingMode": "strict" }), + )); + assert!(draft.contains("implicit-any-parameter")); + assert!(draft.contains("Includes changes not applied yet")); + let chinese = words_of(&nodes( + LANGUAGE_REGION, + "zh-Hans", + json!({}), + json!({ "disableTypeErrors": true }), + )); + assert!(chinese.contains("含未应用的修改") && chinese.contains("已隐藏")); + } + + #[test] + fn the_python_diagram_lists_the_lookup_in_order_then_pyrefly() { + let shown = words_of(&nodes(PYTHON_REGION, "en", json!({}), json!({}))); + let order: Vec = [ + "Tried first", + ".venv, venv, .conda", + "Global default", + "Tried last", + "VIRTUAL_ENV", + "Pyrefly uses the same interpreter", + ] + .iter() + .map(|word| { + shown + .find(word) + .unwrap_or_else(|| panic!("{word} in {shown}")) + }) + .collect(); + assert!(order.windows(2).all(|pair| pair[0] < pair[1]), "{order:?}"); + let chinese = words_of(&nodes(PYTHON_REGION, "zh-Hans", json!({}), json!({}))); + assert!(chinese.contains("项目环境") && chinese.contains("自动发现")); + } + + #[test] + fn an_unknown_region_and_a_tool_window_fail_with_the_plugins_code() { + let unknown = render(&event("other", "en", json!({}), json!({}))).unwrap_err(); + assert_eq!(unknown.code(), "python.view.unknownRegion"); + let window = ViewEvent::parse(&json!({ + "event": "open", + "instance": "i1", + "surface": { "toolWindowID": "python" }, + "language": "en", + "settings": { "effective": Map::new(), "draft": Map::new() }, + })) + .unwrap(); + assert_eq!( + render(&window).unwrap_err().code(), + "python.view.unknownRegion" + ); + } + + #[test] + fn a_value_the_preview_cannot_read_is_counted() { + let (_, unrecognized) = render(&event( + LANGUAGE_REGION, + "en", + json!({ "typeCheckingMode": "pedantic" }), + json!({ "completeFunctionParens": "yes" }), + )) + .unwrap(); + assert_eq!(unrecognized, 2); + } +} diff --git a/backend/src/view/resolution.rs b/backend/src/view/resolution.rs new file mode 100644 index 0000000..1dc7837 --- /dev/null +++ b/backend/src/view/resolution.rs @@ -0,0 +1,258 @@ +//! The Python build system page's diagram: the order in which Lithe looks for +//! the Python interpreter, and what Pyrefly does with the one it finds. +//! +//! The steps follow `toolDefinitions[python].invocation.executables` in +//! `plugin.json`: what the Toolchains page sets for the project and the +//! environments in it, then what it sets for every project, then the +//! automatic lookup. The view sees the plugin's settings only, not the +//! Toolchains page, so it shows the order; the toolchain row above it shows +//! the interpreter found. +//! +//! The region sits in the build system page's detail pane, 344 points wide +//! in the smallest settings window as measured in the host, so the steps +//! stand one above the other, numbered on a rail. The scene is as wide as +//! the view the host reports, so a unit is a point and the steps widen with +//! the window; a host that reports no width gets the smallest window's. + +use super::scene::{group, path, pill, rect, text, text_width, token, Node, CAPTION}; +use super::words::Words; +use serde_json::{json, Value}; + +pub const CANVAS_ID: &str = "python-resolution"; + +/// The scene's width for a host that reports none. +pub const DEFAULT_WIDTH: f64 = 340.0; +/// The narrowest scene: the row of uses and every step's lines fit it in +/// both languages. A view narrower than it is scaled down by the host. +pub const MIN_WIDTH: f64 = 330.0; +const HEADER: f64 = 28.0; +/// The middle of the rail of numbered dots left of the steps. +const RAIL: f64 = 11.0; +const DOT: f64 = 20.0; +const STEP_X: f64 = 30.0; +const STEP_H: f64 = 64.0; +const STEP_GAP: f64 = 10.0; +/// The middle of a step's title row, where its dot sits. +const TITLE_MIDDLE: f64 = 17.0; +/// The left edge of a step's lines, and their room on its right. +const LINE_X: f64 = 12.0; +/// The top of the Pyrefly card, after the three steps. +const PYREFLY_Y: f64 = HEADER + 3.0 * (STEP_H + STEP_GAP); +/// The top of the row of what the interpreter is used for. +const USES_Y: f64 = PYREFLY_Y + STEP_H + 14.0; +pub const HEIGHT: f64 = USES_Y + 22.0; + +struct Step<'a> { + title: &'a str, + lines: [&'a str; 2], + chip: &'a str, + /// The first step tried, whose chip is lit. + first: bool, +} + +/// The diagram for a view `width` points wide, or for the smallest settings +/// window when the host reports no width. A host that reports it sends +/// `resize` with the new width, and the scene is drawn again for it. +pub fn canvas(words: &Words, width: Option) -> Value { + let scene_w = width.unwrap_or(DEFAULT_WIDTH).max(MIN_WIDTH); + let step_w = scene_w - STEP_X; + let steps = [ + Step { + title: words.step_project, + lines: words.step_project_detail, + chip: words.first, + first: true, + }, + Step { + title: words.step_global, + lines: words.step_global_detail, + chip: words.then, + first: false, + }, + Step { + title: words.step_automatic, + lines: words.step_automatic_detail, + chip: words.last, + first: false, + }, + ]; + + let mut nodes = vec![text(0.0, 17.0, words.resolution_title, "strong")]; + for (index, step) in steps.iter().enumerate() { + let y = HEADER + index as f64 * (STEP_H + STEP_GAP); + if index > 0 { + // The rail joins the dots. + let above = y - STEP_GAP - STEP_H + TITLE_MIDDLE + DOT / 2.0 + 4.0; + let below = y + TITLE_MIDDLE - DOT / 2.0 - 4.0; + nodes.push( + path(format!("M{RAIL} {above} V{below}")) + .stroke(token("$line"), 2.0) + .set("cap", "round"), + ); + } + nodes.push(draw(y, index + 1, step, step_w)); + } + nodes.push(pyrefly(words, step_w)); + nodes.extend(uses(words).0); + let mut canvas = json!({ + "type": "canvas", + "id": CANVAS_ID, + "label": words.resolution_label, + "height": HEIGHT.ceil() as u64, + "viewBox": [0, 0, scene_w, HEIGHT], + "nodes": nodes.into_iter().map(Value::from).collect::>(), + }); + if width.is_some() { + canvas["on"] = json!(["resize"]); + } + canvas +} + +/// A step at `y`: its numbered dot on the rail and its card, `step_w` wide. +fn draw(y: f64, number: usize, step: &Step, step_w: f64) -> Node { + let frame = rect(0.0, 0.0, step_w, STEP_H) + .radius(8.0) + .fill(token("$surface")) + .stroke(token("$line"), 1.0); + // Accent ink on the selection fill falls to about 2:1 in the dark theme. + let (fill, ink) = if step.first { + (token("$selection"), token("$text")) + } else { + (token("$badge"), token("$textSecondary")) + }; + let (_, chip_w) = pill(0.0, 0.0, step.chip, fill.clone(), ink.clone()); + let chip_x = step_w - 10.0 - chip_w; + let (chip, _) = pill(chip_x, TITLE_MIDDLE - 10.0, step.chip, fill, ink); + let mut card = vec![ + frame, + text(LINE_X, TITLE_MIDDLE + 4.5, step.title, "strong").max_width(chip_x - LINE_X - 10.0), + chip, + ]; + card.extend(lines(&step.lines, step_w)); + group( + 0.0, + y, + vec![ + rect(RAIL - DOT / 2.0, TITLE_MIDDLE - DOT / 2.0, DOT, DOT) + .radius(DOT / 2.0) + .fill(token("$badge")), + text(RAIL, TITLE_MIDDLE + 4.0, &number.to_string(), "caption") + .align("center") + .color(token("$textSecondary")), + group(STEP_X, 0.0, card), + ], + ) +} + +/// A card's two lines of detail, in a card `card_w` wide. +fn lines(lines: &[&str; 2], card_w: f64) -> Vec { + lines + .iter() + .zip([40.0, 55.0]) + .map(|(line, y)| { + text(LINE_X, y, line, "caption") + .color(token("$textSecondary")) + .max_width(card_w - 2.0 * LINE_X) + }) + .collect() +} + +/// What happens once the interpreter is found: Pyrefly is started with it +/// and resolves third-party imports from its site-packages. Off the rail, in +/// a dashed frame, since it is not a step of the lookup. +fn pyrefly(words: &Words, step_w: f64) -> Node { + let mut card = vec![ + rect(0.0, 0.0, step_w, STEP_H) + .radius(8.0) + .stroke(token("$line"), 1.0) + .dash(&[4.0, 3.0]), + text(LINE_X, TITLE_MIDDLE + 4.5, words.pyrefly_title, "strong") + .max_width(step_w - 2.0 * LINE_X), + ]; + card.extend(lines(&words.pyrefly_detail, step_w)); + group( + 0.0, + PYREFLY_Y, + vec![ + // An arrow from the rail into the card: what the steps found + // leads here. It starts under the last step's dot, as the rail + // between the steps does. + path(format!( + "M{RAIL} {} V{TITLE_MIDDLE} H{}", + TITLE_MIDDLE + DOT / 2.0 + 4.0 - STEP_H - STEP_GAP, + STEP_X - 6.0 + )) + .stroke(token("$line"), 2.0) + .set("cap", "round"), + path(format!( + "M{} {} L{} {TITLE_MIDDLE} L{} {}", + STEP_X - 9.0, + TITLE_MIDDLE - 4.0, + STEP_X - 4.0, + STEP_X - 9.0, + TITLE_MIDDLE + 4.0 + )) + .stroke(token("$line"), 2.0) + .set("cap", "round"), + group(STEP_X, 0.0, card), + ], + ) +} + +/// What Lithe uses the interpreter for, after the cards, and where the row +/// ends. +fn uses(words: &Words) -> (Vec, f64) { + let mut nodes = + vec![text(0.0, USES_Y + 14.0, words.used_for, "caption").color(token("$textMuted"))]; + let mut x = text_width(words.used_for, CAPTION) + 8.0; + let mut end = x; + for word in words.uses { + let (chip, width) = pill(x, USES_Y, word, token("$badge"), token("$textSecondary")); + nodes.push(chip); + end = x + width; + x = end + 6.0; + } + (nodes, end) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::view::scene::STRONG; + use crate::view::words; + + #[test] + fn the_row_of_uses_fits_the_narrowest_scene_in_both_languages() { + for language in ["en", "zh-Hans"] { + let (_, end) = uses(words::for_language(language)); + assert!(end <= MIN_WIDTH, "{language}: {end}"); + } + } + + #[test] + fn every_line_of_every_card_fits_the_narrowest_scene() { + let room = MIN_WIDTH - STEP_X - 2.0 * LINE_X; + for language in ["en", "zh-Hans"] { + let w = words::for_language(language); + for line in [ + w.step_project_detail, + w.step_global_detail, + w.step_automatic_detail, + w.pyrefly_detail, + ] + .concat() + { + let width = text_width(line, CAPTION); + assert!(width <= room, "{language}: {line} ({width} of {room})"); + } + let width = text_width(w.pyrefly_title, STRONG); + assert!(width <= room, "{language}: {} ({width})", w.pyrefly_title); + let width = text_width(w.resolution_title, STRONG); + assert!( + width <= MIN_WIDTH, + "{language}: {} ({width})", + w.resolution_title + ); + } + } +} diff --git a/backend/src/view/scene.rs b/backend/src/view/scene.rs new file mode 100644 index 0000000..86a320a --- /dev/null +++ b/backend/src/view/scene.rs @@ -0,0 +1,272 @@ +//! Building blocks of the canvas scenes, shaped as `plugin-ui.schema.json` +//! describes them. +//! +//! Coordinates are view-box units. A canvas without `pan` shows its whole +//! view box, scaled to the view's width but never past its `height`, from +//! the top-left corner. Each scene is drawn for the width the host reports +//! and is as tall as its view box, so one unit is one point, and it lists +//! `resize` to be drawn again when the window's width changes. A host that +//! reports no width gets the scene for the smallest settings window, which a +//! wider window shows whole at the same size. + +use serde_json::{json, Map, Value}; + +/// The pixel sizes of the host's `caption` and `strong` text styles at +/// scale 1. +pub const CAPTION: f64 = 11.0; +pub const STRONG: f64 = 13.0; + +/// How far one character of `monoSmall` code advances in the scenes. +/// +/// A host draws monospace text in its own font, rounded to its screen's +/// pixels, so one character takes 7 points with SF Mono on macOS and 6 with +/// Consolas on Windows. Code that a selection, a caret, a field or a squiggle +/// marks is therefore laid out by [`code`], one character to a node on this +/// grid, which is SF Mono's: the marks then sit on the right characters on +/// every host, and on macOS the code looks as the host itself draws it. +pub const MONO_ADVANCE: f64 = 7.0; + +/// The left edge of column `column` of code that starts at `x`. +pub fn column(x: f64, column: usize) -> f64 { + x + column as f64 * MONO_ADVANCE +} + +/// One line of `monoSmall` code from `x`, its baseline at `y`, in pieces of +/// their own colors: a character to a node on the [`MONO_ADVANCE`] grid. A +/// space takes its column and no node. +pub fn code(x: f64, y: f64, pieces: &[(&str, Value)]) -> Vec { + let mut nodes = Vec::new(); + let mut index = 0; + for (piece, color) in pieces { + for character in piece.chars() { + if !character.is_whitespace() { + nodes.push( + text(column(x, index), y, &character.to_string(), "monoSmall") + .color(color.clone()), + ); + } + index += 1; + } + } + nodes +} + +/// One canvas node. +pub struct Node(Map); + +impl Node { + fn of(kind: &str) -> Self { + let mut node = Map::new(); + node.insert("type".into(), kind.into()); + Self(node) + } + + pub fn set(mut self, key: &str, value: impl Into) -> Self { + self.0.insert(key.into(), value.into()); + self + } + + /// A number field, rounded to a tenth so the scene stays short. + pub fn at(self, key: &str, value: f64) -> Self { + self.set(key, round(value)) + } + + pub fn fill(self, color: impl Into) -> Self { + self.set("fill", color) + } + + pub fn stroke(self, color: impl Into, width: f64) -> Self { + self.set("stroke", color).at("width", width) + } + + pub fn radius(self, radius: f64) -> Self { + self.at("radius", radius) + } + + pub fn opacity(self, opacity: f64) -> Self { + self.at("opacity", opacity) + } + + pub fn color(self, color: impl Into) -> Self { + self.set("color", color) + } + + pub fn max_width(self, width: f64) -> Self { + self.at("maxWidth", width) + } + + pub fn align(self, align: &str) -> Self { + self.set("align", align) + } + + /// A dashed outline: lengths of dash and gap, in turn. + pub fn dash(self, lengths: &[f64]) -> Self { + let lengths: Vec = lengths.iter().map(|length| round(*length)).collect(); + self.set("dash", lengths) + } +} + +impl From for Value { + fn from(node: Node) -> Self { + Value::Object(node.0) + } +} + +fn round(value: f64) -> Value { + let tenths = (value * 10.0).round(); + if tenths % 10.0 == 0.0 { + json!((tenths / 10.0) as i64) + } else { + json!(tenths / 10.0) + } +} + +pub fn rect(x: f64, y: f64, w: f64, h: f64) -> Node { + Node::of("rect").at("x", x).at("y", y).at("w", w).at("h", h) +} + +/// One line of text with its baseline at `y`. +pub fn text(x: f64, y: f64, value: &str, style: &str) -> Node { + Node::of("text") + .at("x", x) + .at("y", y) + .set("text", value) + .set("style", style) +} + +/// One line of text in pieces of their own colors. +pub fn runs(x: f64, y: f64, pieces: &[(&str, Value)], style: &str) -> Node { + let runs: Vec = pieces + .iter() + .map(|(text, color)| json!({ "text": text, "color": color })) + .collect(); + Node::of("text") + .at("x", x) + .at("y", y) + .set("runs", runs) + .set("style", style) +} + +pub fn path(d: String) -> Node { + Node::of("path").set("d", d) +} + +/// Children placed relative to `(x, y)`. +pub fn group(x: f64, y: f64, children: Vec) -> Node { + let children: Vec = children.into_iter().map(Value::from).collect(); + Node::of("group") + .at("x", x) + .at("y", y) + .set("children", children) +} + +/// A color that follows the light and the dark theme. +pub fn pair(light: &str, dark: &str) -> Value { + json!({ "light": light, "dark": dark }) +} + +pub fn token(name: &str) -> Value { + Value::from(name) +} + +/// The width text of `size` pixels takes in the host's interface font, +/// estimated, since only the host measures text. Wide characters take a whole +/// em; the estimate errs wide so a pill around the text never clips it. +pub fn text_width(value: &str, size: f64) -> f64 { + let ems: f64 = value + .chars() + .map(|character| match character { + ' ' => 0.3, + '\u{2E80}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{FF00}'..='\u{FFEF}' => 1.0, + 'A'..='Z' | '0'..='9' | 'm' | 'w' => 0.66, + 'i' | 'j' | 'l' | '.' | ',' | ':' | ';' | '\'' | '|' | '!' => 0.3, + _ => 0.55, + }) + .sum(); + ems * size +} + +/// A rounded label: its background and its words, centered. +pub fn pill(x: f64, y: f64, words: &str, fill: Value, ink: Value) -> (Node, f64) { + let width = text_width(words, CAPTION) + 16.0; + let node = group( + x, + y, + vec![ + rect(0.0, 0.0, width, 20.0).radius(10.0).fill(fill), + text(width / 2.0, 14.0, words, "caption") + .align("center") + .color(ink), + ], + ); + (node, width) +} + +/// A wavy underline from `x0` to `x1`, its middle at `y`. +pub fn squiggle(x0: f64, x1: f64, y: f64) -> String { + let mut d = format!("M{} {}", fmt(x0), fmt(y)); + let mut x = x0; + let mut up = true; + while x < x1 { + x = (x + 2.0).min(x1); + let dy = if up { -1.5 } else { 1.5 }; + d.push_str(&format!(" L{} {}", fmt(x), fmt(y + dy))); + up = !up; + } + d +} + +fn fmt(value: f64) -> String { + round(value).to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_are_rounded_to_tenths_and_whole_numbers_stay_integers() { + let node = Value::from(rect(1.0, 2.25, 3.04, 10.0 / 3.0)); + assert_eq!(node["x"], json!(1)); + assert_eq!(node["y"], json!(2.3)); + assert_eq!(node["w"], json!(3)); + assert_eq!(node["h"], json!(3.3)); + } + + #[test] + fn wide_characters_take_a_whole_em() { + assert_eq!(text_width("开启", 10.0), 20.0); + assert!(text_width("On", 10.0) < text_width("开启", 10.0)); + } + + #[test] + fn code_puts_each_character_on_its_column_and_skips_spaces() { + let nodes: Vec = code( + 10.0, + 5.0, + &[("a b", token("$text")), ("c", token("$accent"))], + ) + .into_iter() + .map(Value::from) + .collect(); + let placed: Vec<(&str, f64)> = nodes + .iter() + .map(|node| (node["text"].as_str().unwrap(), node["x"].as_f64().unwrap())) + .collect(); + assert_eq!(placed, [("a", 10.0), ("b", 24.0), ("c", 31.0)]); + assert_eq!(nodes[2]["color"], json!("$accent")); + } + + #[test] + fn a_dash_is_rounded_like_every_other_length() { + let node = Value::from(rect(0.0, 0.0, 10.0, 10.0).dash(&[3.0, 2.25])); + assert_eq!(node["dash"], json!([3, 2.3])); + } + + #[test] + fn a_squiggle_ends_where_it_is_asked_to() { + let d = squiggle(10.0, 15.0, 20.0); + assert!(d.starts_with("M10 20")); + assert!(d.ends_with("L15 21.5") || d.ends_with("L15 18.5"), "{d}"); + } +} diff --git a/backend/src/view/settings.rs b/backend/src/view/settings.rs new file mode 100644 index 0000000..16f25de --- /dev/null +++ b/backend/src/view/settings.rs @@ -0,0 +1,249 @@ +//! The values the previews show, read from a view event. +//! +//! A preview follows the settings window as the user edits it, so a value the +//! user changed but has not applied (the draft) wins over the saved one, and a +//! setting with neither shows the default `plugin.json` declares. + +use lithe_plugin_sdk::view::ViewEvent; +use serde_json::Value; + +/// Pyrefly's preset for files no Pyrefly config covers: the +/// `typeCheckingMode` setting, sent as `python.pyrefly.typeCheckingMode`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// Migrates a nearby mypy or Pyright config, else checks as `Basic`. + Auto, + Off, + Basic, + Legacy, + Default, + Strict, + All, +} + +impl Mode { + pub fn parse(value: &str) -> Option { + Some(match value { + "auto" => Mode::Auto, + "off" => Mode::Off, + "basic" => Mode::Basic, + "legacy" => Mode::Legacy, + "default" => Mode::Default, + "strict" => Mode::Strict, + "all" => Mode::All, + _ => return None, + }) + } + + /// The preset Pyrefly checks the preview's sample with. The sample has no + /// mypy or Pyright config beside it, so `Auto` falls back to `Basic`. + pub fn applied(self) -> Self { + match self { + Mode::Auto => Mode::Basic, + mode => mode, + } + } +} + +/// How far Pyrefly's diagnostics reach: the `diagnosticMode` setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + OpenFiles, + Workspace, +} + +impl Scope { + fn parse(value: &str) -> Option { + Some(match value { + "openFilesOnly" => Scope::OpenFiles, + "workspace" => Scope::Workspace, + _ => return None, + }) + } +} + +/// The module path an auto-import writes: the `importFormat` setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ImportFormat { + Absolute, + Relative, +} + +impl ImportFormat { + fn parse(value: &str) -> Option { + Some(match value { + "absolute" => ImportFormat::Absolute, + "relative" => ImportFormat::Relative, + _ => return None, + }) + } +} + +/// The plugin's settings as the settings window holds them now. +#[derive(Debug)] +pub struct Settings { + pub mode: Mode, + /// Pyrefly's `disableTypeErrors`: no file shows type errors, whatever + /// the preset or the project's own Pyrefly config says. + pub hide_type_errors: bool, + pub scope: Scope, + pub auto_import: bool, + pub import_format: ImportFormat, + pub function_parens: bool, + /// The settings whose draft differs from the value in force. + changed: Vec<&'static str>, + /// Values of the wrong type or outside the declared options, shown as the + /// default instead. + pub unrecognized: u64, +} + +impl Settings { + pub fn read(event: &ViewEvent) -> Self { + let mut reader = Reader { + event, + changed: Vec::new(), + unrecognized: 0, + }; + let mode = reader.read("typeCheckingMode", Value::from("default"), |value| { + value.as_str().and_then(Mode::parse) + }); + let hide_type_errors = reader.boolean("disableTypeErrors", false); + let scope = reader.read("diagnosticMode", Value::from("openFilesOnly"), |value| { + value.as_str().and_then(Scope::parse) + }); + let auto_import = reader.boolean("autoImportCompletions", true); + let import_format = reader.read("importFormat", Value::from("absolute"), |value| { + value.as_str().and_then(ImportFormat::parse) + }); + let function_parens = reader.boolean("completeFunctionParens", false); + Self { + mode, + hide_type_errors, + scope, + auto_import, + import_format, + function_parens, + changed: reader.changed, + unrecognized: reader.unrecognized, + } + } + + /// The preset that decides what the sample reports: none while type + /// errors are hidden, which silences every preset. + pub fn reporting(&self) -> Option { + (!self.hide_type_errors).then(|| self.mode.applied()) + } + + /// Whether the user changed `id` without applying it yet. + pub fn is_changed(&self, id: &str) -> bool { + self.changed.contains(&id) + } + + pub fn any_changed(&self, ids: &[&str]) -> bool { + ids.iter().any(|id| self.is_changed(id)) + } +} + +struct Reader<'a> { + event: &'a ViewEvent, + changed: Vec<&'static str>, + unrecognized: u64, +} + +impl Reader<'_> { + fn read( + &mut self, + id: &'static str, + default: Value, + parse: impl Fn(&Value) -> Option, + ) -> T { + let saved = self.event.effective.get(id).unwrap_or(&default); + if let Some(draft) = self.event.draft.get(id) { + if draft != saved { + self.changed.push(id); + } + } + let shown = self.event.draft.get(id).unwrap_or(saved); + match parse(shown) { + Some(value) => value, + None => { + self.unrecognized += 1; + parse(&default).expect("the declared default parses") + } + } + } + + fn boolean(&mut self, id: &'static str, default: bool) -> bool { + self.read(id, Value::Bool(default), Value::as_bool) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn event(effective: Value, draft: Value) -> ViewEvent { + ViewEvent::parse(&json!({ + "event": "settings", + "instance": "i1", + "surface": { "settingRegionID": "language" }, + "language": "en", + "settings": { "effective": effective, "draft": draft }, + })) + .unwrap() + } + + #[test] + fn a_setting_without_a_value_shows_its_declared_default() { + let settings = Settings::read(&event(json!({}), json!({}))); + assert_eq!(settings.mode, Mode::Default); + assert!(!settings.hide_type_errors); + assert_eq!(settings.scope, Scope::OpenFiles); + assert!(settings.auto_import && !settings.function_parens); + assert_eq!(settings.import_format, ImportFormat::Absolute); + assert_eq!(settings.unrecognized, 0); + assert!(!settings.any_changed(&["typeCheckingMode", "disableTypeErrors", "importFormat"])); + } + + #[test] + fn the_draft_wins_over_the_saved_value_and_counts_as_a_change() { + let settings = Settings::read(&event( + json!({ "typeCheckingMode": "basic", "importFormat": "absolute", "disableTypeErrors": false }), + json!({ "typeCheckingMode": "strict", "disableTypeErrors": false, "importFormat": "relative" }), + )); + assert_eq!(settings.mode, Mode::Strict); + assert_eq!(settings.import_format, ImportFormat::Relative); + assert!(settings.is_changed("typeCheckingMode")); + assert!(settings.is_changed("importFormat")); + // A draft equal to the value in force changes nothing. + assert!(!settings.is_changed("disableTypeErrors")); + assert!(!settings.is_changed("diagnosticMode")); + } + + #[test] + fn a_value_outside_the_declaration_shows_the_default_and_is_counted() { + let settings = Settings::read(&event( + json!({ "typeCheckingMode": "pedantic", "autoImportCompletions": "yes" }), + // The removed setting the kill switch replaced is not read at all. + json!({ "displayTypeErrors": "force-off" }), + )); + assert_eq!(settings.mode, Mode::Default); + assert!(settings.auto_import && !settings.hide_type_errors); + assert_eq!(settings.unrecognized, 2); + } + + #[test] + fn automatic_checks_the_unconfigured_sample_as_basic_and_hidden_errors_report_nothing() { + let read = |mode: &str, hide: bool| { + Settings::read(&event( + json!({ "typeCheckingMode": mode, "disableTypeErrors": hide }), + json!({}), + )) + .reporting() + }; + assert_eq!(read("auto", false), Some(Mode::Basic)); + assert_eq!(read("legacy", false), Some(Mode::Legacy)); + assert_eq!(read("strict", true), None); + } +} diff --git a/backend/src/view/words.rs b/backend/src/view/words.rs new file mode 100644 index 0000000..78e725d --- /dev/null +++ b/backend/src/view/words.rs @@ -0,0 +1,274 @@ +//! The words the previews show, in the languages the plugin translates its +//! settings to. Setting names and values match the titles of the declared +//! rows under the region (`plugin.json` and `l10n/zh-Hans.json`), and the +//! toolchain layers match the host's Toolchains page, so a card names what +//! changes it. +//! +//! Python code and Pyrefly's own output, such as its error codes and +//! messages, stay as the tools write them. + +pub struct Words { + pub preview_title: &'static str, + pub preview_label: &'static str, + pub follows_options: &'static str, + pub includes_draft: &'static str, + pub on: &'static str, + pub off: &'static str, + + pub interpreter_title: &'static str, + pub interpreter_info: &'static str, + + pub mode_title: &'static str, + /// The pill of each preset, in the order of `Mode`: automatic, off, + /// basic, legacy, default, strict, all. + pub modes: [&'static str; 7], + pub mode_notes: [&'static str; 7], + /// The pill and the note while the kill switch hides every type error. + pub hidden: &'static str, + pub hidden_note: &'static str, + /// How many errors the sample reports, after the error code shown. + pub errors: fn(usize) -> String, + + pub scope_title: &'static str, + pub scope_open: &'static str, + pub scope_workspace: &'static str, + pub scope_open_note: &'static str, + pub scope_workspace_note: &'static str, + /// The tag of the file open in the editor, and what each file gets. + pub open_tag: &'static str, + pub checked: &'static str, + pub errors_only: &'static str, + pub not_checked: &'static str, + + pub import_title: &'static str, + pub import_absolute: &'static str, + pub import_relative: &'static str, + pub import_absolute_note: &'static str, + pub import_relative_note: &'static str, + pub import_off_note: &'static str, + /// The legend on the import line the completion writes. + pub inserted_on_accept: &'static str, + pub no_suggestions: &'static str, + + pub parens_title: &'static str, + pub parens_on_note: &'static str, + pub parens_off_note: &'static str, + pub after_accepting: &'static str, + + pub resolution_title: &'static str, + pub resolution_label: &'static str, + pub step_project: &'static str, + pub step_project_detail: [&'static str; 2], + pub step_global: &'static str, + pub step_global_detail: [&'static str; 2], + pub step_automatic: &'static str, + pub step_automatic_detail: [&'static str; 2], + pub pyrefly_title: &'static str, + pub pyrefly_detail: [&'static str; 2], + pub first: &'static str, + pub then: &'static str, + pub last: &'static str, + pub used_for: &'static str, + pub uses: [&'static str; 5], +} + +fn errors_zh(count: usize) -> String { + format!("共 {count} 个错误") +} + +fn errors_en(count: usize) -> String { + match count { + 1 => "1 error".into(), + count => format!("{count} errors"), + } +} + +const ZH: Words = Words { + preview_title: "效果预览", + preview_label: "Pyrefly 选项的效果预览", + follows_options: "示例代码,随下方选项即时变化", + includes_draft: "含未应用的修改", + on: "开", + off: "关", + + interpreter_title: "Python 解释器", + interpreter_info: "Pyrefly 分析代码、运行、测试和安装依赖都用这个解释器,Pyrefly 从它的 site-packages 解析第三方库。点击这一行,到「工具链」页为项目或全局选择 .venv、uv、conda、pyenv 等环境,或添加其他目录。", + + mode_title: "类型检查模式", + modes: ["自动", "关闭", "基础", "宽松", "默认", "严格", "全部"], + mode_notes: [ + "沿用附近的 mypy、Pyright 配置,否则同基础", + "不报告类型错误,补全和跳转照常可用", + "只报告 Pyrefly 确信的错误", + "比默认宽松,适合从 mypy 迁移", + "Pyrefly 的标准规则", + "另外要求参数注解等", + "所有检查都按错误报告", + ], + hidden: "已隐藏", + hidden_note: "「隐藏类型错误」已开启,所有文件都不显示", + errors: errors_zh, + + scope_title: "诊断范围", + scope_open: "仅打开的文件", + scope_workspace: "整个工作区", + scope_open_note: "只检查编辑器里打开的文件", + scope_workspace_note: "未打开的文件也报告错误级别的问题", + open_tag: "已打开", + checked: "已检查", + errors_only: "只报错误", + not_checked: "不检查", + + import_title: "自动导入补全", + import_absolute: "绝对导入", + import_relative: "相对导入", + import_absolute_note: "补全未导入的名字,确认时按完整路径导入", + import_relative_note: "补全未导入的名字,确认时按相对路径导入", + import_off_note: "只补全已导入或本文件里的名字", + inserted_on_accept: "确认后插入", + no_suggestions: "无建议", + + parens_title: "补全函数括号", + parens_on_note: "补全函数时加上括号,光标停在括号里", + parens_off_note: "只插入函数名", + after_accepting: "确认补全 greet 后", + + resolution_title: "Lithe 按这个顺序找 Python 解释器", + resolution_label: "Lithe 查找 Python 解释器的顺序", + step_project: "项目环境", + step_project_detail: [ + "为项目固定的解释器 → .venv、venv、.conda", + "→ .python-version、requires-python 的版本", + ], + step_global: "全局默认", + step_global_detail: [ + "全局固定的解释器,其次默认版本", + "在「工具链」页的全局范围选择", + ], + step_automatic: "自动发现", + step_automatic_detail: [ + "VIRTUAL_ENV → PATH 中的 python3、python", + "→ uv、pyenv、conda、python.org 的安装", + ], + pyrefly_title: "Pyrefly 用同一个解释器", + pyrefly_detail: [ + "从它的 site-packages 解析第三方库", + "换解释器后,缺失导入的报错随之更新", + ], + first: "先找这里", + then: "其次", + last: "最后", + used_for: "用于", + uses: ["语言服务", "运行", "测试", "调试", "安装依赖"], +}; + +const EN: Words = Words { + preview_title: "Preview", + preview_label: "Preview of the Pyrefly options", + follows_options: "Sample code; follows the options below", + includes_draft: "Includes changes not applied yet", + on: "On", + off: "Off", + + interpreter_title: "Python interpreter", + interpreter_info: "Pyrefly analyzes the code with this interpreter, and Lithe runs, tests and installs packages with it; Pyrefly resolves third-party imports from its site-packages. Choose the row to pick a .venv, uv, conda or pyenv environment, or another directory, for the project or for all projects on the Toolchains page.", + + mode_title: "Type checking mode", + modes: ["Automatic", "Off", "Basic", "Legacy", "Default", "Strict", "All"], + mode_notes: [ + "Uses a mypy or Pyright config, else Basic", + "No type errors; completion still works", + "Only errors Pyrefly is sure of", + "Looser than Default, for mypy migration", + "Pyrefly's standard rules", + "Also asks for parameter annotations", + "Every check, reported as an error", + ], + hidden: "Hidden", + hidden_note: "Hide type errors is on: no file shows them", + errors: errors_en, + + scope_title: "Diagnostic scope", + scope_open: "Open files only", + scope_workspace: "Entire workspace", + scope_open_note: "Checks only the files open in the editor", + scope_workspace_note: "Files not open report their errors too", + open_tag: "open", + checked: "Checked", + errors_only: "Errors only", + not_checked: "Not checked", + + import_title: "Auto-import completions", + import_absolute: "Absolute", + import_relative: "Relative", + import_absolute_note: "Suggests unimported names, by full path", + import_relative_note: "Suggests unimported names, relatively", + import_off_note: "Suggests only names already in scope", + inserted_on_accept: "inserted on accept", + no_suggestions: "No suggestions", + + parens_title: "Complete function parentheses", + parens_on_note: "Adds () after a function, caret inside", + parens_off_note: "Inserts the function name only", + after_accepting: "After accepting greet", + + resolution_title: "How Lithe finds the Python interpreter", + resolution_label: "The order in which Lithe looks for the Python interpreter", + step_project: "Project", + step_project_detail: [ + "Pinned for the project → .venv, venv, .conda", + "→ .python-version, requires-python", + ], + step_global: "Global default", + step_global_detail: [ + "Pinned globally, then the default version", + "Set on the Toolchains page, for all", + ], + step_automatic: "Automatic", + step_automatic_detail: [ + "VIRTUAL_ENV → python3, python on PATH", + "→ uv, pyenv, conda and python.org installs", + ], + pyrefly_title: "Pyrefly uses the same interpreter", + pyrefly_detail: [ + "It resolves third-party imports from its", + "site-packages, so switching updates them", + ], + first: "Tried first", + then: "Then", + last: "Tried last", + used_for: "Used to", + uses: ["analyze", "run", "test", "debug", "install"], +}; + +/// The words for the host's interface language: Chinese for a `zh` tag, +/// English otherwise. +pub fn for_language(tag: &str) -> &'static Words { + if tag == "zh" || tag.starts_with("zh-") { + &ZH + } else { + &EN + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_chinese_tag_of_any_script_or_region_gets_chinese() { + for tag in ["zh", "zh-Hans", "zh-CN", "zh-Hant-TW"] { + assert_eq!(for_language(tag).on, ZH.on, "{tag}"); + } + for tag in ["en", "en-GB", "fr", "zhx", ""] { + assert_eq!(for_language(tag).on, EN.on, "{tag}"); + } + } + + #[test] + fn the_error_count_reads_in_each_language() { + assert_eq!((EN.errors)(1), "1 error"); + assert_eq!((EN.errors)(3), "3 errors"); + assert_eq!((ZH.errors)(2), "共 2 个错误"); + } +} diff --git a/docs/assets/settings-previews/build-tools-zh-Hans-dark.png b/docs/assets/settings-previews/build-tools-zh-Hans-dark.png new file mode 100644 index 0000000..90ddd10 Binary files /dev/null and b/docs/assets/settings-previews/build-tools-zh-Hans-dark.png differ diff --git a/docs/assets/settings-previews/language-en-draft-light.png b/docs/assets/settings-previews/language-en-draft-light.png new file mode 100644 index 0000000..f9c71dd Binary files /dev/null and b/docs/assets/settings-previews/language-en-draft-light.png differ diff --git a/docs/assets/settings-previews/language-zh-Hans-dark.png b/docs/assets/settings-previews/language-zh-Hans-dark.png new file mode 100644 index 0000000..cc7450a Binary files /dev/null and b/docs/assets/settings-previews/language-zh-Hans-dark.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 452efa5..69be3b6 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -12,29 +12,28 @@ | 能力域 | 功能项 | `darwin-arm64` | `darwin-x64` | `windows-x64` / `windows-arm64` | `linux-x64` / `linux-arm64` | 最近实机验证 | 实现与测试证据路径(本仓库) | | --- | --- | --- | --- | --- | --- | --- | --- | -| Python 设置效果预览 (`settingRegions`) | 「语言与框架 → Python」显示类型诊断和代码补全示例,随当前设置草稿更新。预览使用固定示例,保存仍由宿主表单处理。 | ✅ 包内后端与无头设置窗口通过 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | `2026-11-22`(`darwin-arm64`,固定宿主与 0.8.13,中文深色与英文浅色) | `backend/src/settings_preview.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go` | -| Python 解释器覆盖设置 | 在「设置 → 语言与框架 → Python」显示用于构建、运行和 pytest 的解释器覆盖路径。已保存的覆盖值继续按 `pythonExecutable` 读取。 | ✅ Core 设置目录与保存值回读通过 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | `2026-11-22`(`darwin-arm64`,桌面 0.8.13 固定 Core) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/package/archives.test.mjs` | +| Python 设置效果预览 (`settingRegions`) | 「语言与框架 → Python」顶部显示当前解释器(工具行,点击到「工具链」页),下面四张卡片画出类型检查模式(含隐藏类型错误)、诊断范围、自动导入补全和补全函数括号的效果,随设置草稿更新。「构建工具 → Python」画出解释器的三步查找顺序和用途。预览使用固定示例,保存仍由宿主表单处理。 | ✅ 包内后端与无头设置窗口通过 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | `2026-11-23`(`darwin-arm64`,固定宿主 `60885168`,中文深色与英文浅色、草稿、窗口变宽) | `backend/src/view/`
`scripts/test.mjs`
`e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go` | | 语言基础 (`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`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` | | 无后缀 Python 脚本 | 支持 TextMate 首行匹配的桌面按解释器路径或 `env` shebang 打开,提供 Python 高亮、注释与 Pyrefly 诊断 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | `2026-11-20`(`darwin-arm64`,桌面 `645a3aee8`) | `io.github.lithe-idea.python-support/grammars/python.first-line.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` | | 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | -| 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`) | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | +| 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。Homebrew 规则保留,但它的 `libexec/bin/python3` 链接到安装目录外,Core 目前以 `unsafePath` 跳过([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。 | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用项目 Python 或经宿主解析的显式解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-20(macOS ARM64,Lithe 0.8.9、0.8.11 工作台端到端) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | -| 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用项目选定的解释器或插件解释器覆盖设置。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | +| 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用工具链解析出的解释器,包括在「工具链」页为项目固定的解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(macOS ARM64,Lithe 0.8.9 与固定宿主 `60885168` 工作台端到端,含固定解释器) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | +| 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用工具链为项目解析出的解释器。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(Lithe 0.8.9 与固定宿主 `60885168`,脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时用 `python -I -B` 读取所选 Python 环境中已安装的包、版本和依赖关系,跳过用户级 site-packages 及其启动钩子,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | +| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`,需要 Python 3.10 或更新(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | | 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 新建项目向导 (`projectGenerators`) | `python-project`:选择并固定项目级 `python` 工具链(`pinAs: "project"`),可选 `none` / `venv (.venv)` / `uv (.venv)` 与示例代码生成(Windows 自动将 `python3` 命令切换为 `python`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(Windows 清单 `python` 命令切换已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/templates/python/`
`scripts/package/archives.test.mjs`
`e2e/host/desktop/internal/projectgen/python_integration_test.go` | -| 国际化 (`l10n`) | 英文默认文案 + `l10n/zh-Hans.json` 简体中文完整设置与分组翻译 | ✅ 已验证 | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/l10n/zh-Hans.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | +| 国际化 (`l10n`) | 英文默认文案 + `l10n/zh-Hans.json` 简体中文完整设置与分组翻译。设置预览的文字由包内后端按宿主语言选择中文或英文。 | ✅ 已验证 | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | ⏳ pending(归档与 Core `settingsState` 已校验) | `2026-11-23`(`darwin-arm64`,设置预览中英文) | `io.github.lithe-idea.python-support/l10n/zh-Hans.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 工具链提供者 (`litheToolchains` / `toolchains/query`) | 包内 Rust 后端在全局与项目上下文读取 Conda 登记、uv、pyenv、Poetry/Pipenv 环境以及项目版本声明。Pipenv 默认环境按完整的 `Pipfile` 路径识别,所选解释器须满足同目录的项目版本约束。安装、要求与观察路径作为事实交回宿主验证。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待宿主验收 | ⏳ 待宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `backend/src/discovery.rs`
`backend/src/discovery/project.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | ## 宿主版本与验证 - 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1`、`buildProviders: 1`、`runConfigurationTypes: 0` 和 `languages: 0`。桌面 0.8.9 支持安装、当前文件运行和原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。 -- `e2e/host/lithe-host.json` 固定支持 TextMate 首行匹配的桌面主线提交 `645a3aee8`。 -- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮、当前文件运行、手动运行配置和依赖树,并在固定的桌面主线上运行完整宿主套件,额外覆盖项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。 +- `e2e/host/lithe-host.json` 固定桌面主线提交 `60885168`。 +- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮、当前文件运行(含为项目固定的解释器)、手动运行配置和依赖树,并在固定的桌面主线上运行完整宿主套件,额外覆盖设置预览、项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。 - macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。 - 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。 -- 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 +- 宿主按 Core 的文件事实校验安装。程序链接到安装目录外的安装会以 `unsafePath` 被拒绝,包括在 macOS 和 Linux 上建在项目外的虚拟环境(venv、`uv venv`、virtualenv、Poetry、Pipenv)和 Homebrew 的 Python,固定、`VIRTUAL_ENV` 和发现规则都一样([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。项目内环境由宿主信任流程单独处理。所以固定解释器的端到端用例固定的是 `PYTEST_PYTHON` 指向的真实安装。 diff --git a/docs/releases/v1.1.0.md b/docs/releases/v1.1.0.md new file mode 100644 index 0000000..53ebc77 --- /dev/null +++ b/docs/releases/v1.1.0.md @@ -0,0 +1,51 @@ +## 中文 + +- 「设置 › 语言与框架 › Python」顶部显示当前使用的 Python 解释器,点击可打开「工具链」页更换。下面的预览卡片按尚未保存的设置画出类型检查模式、诊断范围、自动导入补全和补全函数括号的效果。 +- 「设置 › 构建、执行、部署 › 构建工具 › Python」显示 Lithe 查找解释器的顺序:项目固定的解释器和项目里的 `.venv`、`venv`、`.conda`,然后是全局设置,最后是自动发现。 +- Pyrefly 分析、运行、测试和调试都使用「工具链」页为项目解析出的同一个解释器。 +- 新增「隐藏类型错误」,替代原来的「显示类型错误」。开启后所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转和补全照常可用。 +- 类型检查模式新增“宽松”预设。“自动”会沿用附近的 mypy 或 Pyright 配置,没有时按“基础”检查。 +- 类型检查模式和自动导入路径风格的说明写明了它们和其他设置的关系,例如开启「隐藏类型错误」后预设不再显示类型错误,关闭「自动导入补全」后只有代码操作会用到路径风格。 + +### 升级与兼容性 + +Python Support v1.1.0 要求 Lithe 0.8.9 或更新版本。从 0.8.10 开始,Lithe 还能按 shebang 自动识别无后缀脚本。 + +v1.1.0 删除了「Python 解释器覆盖路径」设置。升级后,已经保存的路径不再生效,请在「设置 › 构建、执行、部署 › 工具链」为项目固定解释器。 + +调试需要 Python 3.10 或更新版本。内置的 debugpy 1.8.22 不支持 Python 3.9,以前在 3.9 上启动调试会直接退出、没有任何提示;现在 Lithe 会在启动调试前检查解释器版本。运行、测试和依赖树仍支持 Python 3.9。 + +原来的「显示类型错误」选择不会迁移到新设置: + +- 选过“关闭”的,请开启「隐藏类型错误」。 +- 选过“仅已配置项目”的,请把类型检查模式设为“关闭”。有自己 Pyrefly 配置的项目仍按项目配置检查。 +- “仅报告缺失导入”不再提供。 + +已知限制:在 macOS 和 Linux 上,建在项目外的虚拟环境(`python -m venv`、`uv venv`、virtualenv,以及 Poetry、Pipenv 默认建的环境)和 Homebrew 安装的 Python 暂时不能选作解释器([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。在此之前,可以把环境建在项目里的 `.venv`(Poetry 用 `poetry config virtualenvs.in-project true`,Pipenv 设 `PIPENV_VENV_IN_PROJECT=1`),或者固定 uv、pyenv、python.org 安装的解释器。 + +--- + +## English + +- **Settings › Languages & Frameworks › Python** now shows the Python interpreter in use at the top. Click it to change it on the Toolchains page. The preview cards below draw the effect of the type checking mode, diagnostic scope, auto-import completions and function parentheses, following settings you have not saved yet. +- **Settings › Build, Execution, Deployment › Build Tools › Python** shows the order in which Lithe looks for an interpreter: the project's pinned interpreter and its `.venv`, `venv` or `.conda`, then the global setting, then automatic discovery. +- Pyrefly analysis, runs, tests and debugging all use the one interpreter the Toolchains page resolves for the project. +- **Hide type errors** replaces **Display type errors**. When it is on, no file shows type errors, including projects with their own Pyrefly config. Hover, go to definition and completion keep working. +- The type checking mode has a new **Legacy** preset. **Automatic** follows a nearby mypy or Pyright config, and checks as **Basic** when there is none. +- The descriptions of the type checking mode and the auto-import module path style now explain how they depend on other settings. For example, no preset shows type errors while **Hide type errors** is on, and with **Auto-import completions** off only code actions use the path style. + +### Upgrade and compatibility + +Python Support v1.1.0 requires Lithe 0.8.9 or later. Starting with 0.8.10, Lithe can also recognize extensionless scripts by their shebang. + +v1.1.0 removes the **Python executable override** setting. After you upgrade, a saved path no longer applies. Pin the interpreter for the project in **Settings › Build, Execution, Deployment › Toolchains** instead. + +Debugging requires Python 3.10 or later. The bundled debugpy 1.8.22 does not support Python 3.9, and starting a debug session on 3.9 used to exit without any message. Lithe now checks the interpreter version before it starts debugging. Runs, tests and the dependency tree still support Python 3.9. + +Your **Display type errors** choice does not carry over to the new setting: + +- If you chose **Off**, turn on **Hide type errors**. +- If you chose **Configured projects only**, set the type checking mode to **Off**. Projects with their own Pyrefly config are still checked by that config. +- **Missing imports only** is no longer available. + +Known limitation: on macOS and Linux, virtual environments outside the project (made by `python -m venv`, `uv venv` or virtualenv, and the environments Poetry and Pipenv create by default) and Homebrew Python cannot be chosen as the interpreter yet ([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316)). Until then, create the environment in the project as `.venv` (for Poetry, `poetry config virtualenvs.in-project true`; for Pipenv, set `PIPENV_VENV_IN_PROJECT=1`), or pin an interpreter installed by uv, pyenv or python.org. diff --git a/e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go b/e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go index bb5758d..ee1f9fa 100644 --- a/e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go +++ b/e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go @@ -5,8 +5,11 @@ package settingswindow import ( "context" "encoding/json" + "errors" "os" + "os/exec" "path/filepath" + "strings" "testing" "time" @@ -17,6 +20,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" "github.com/vivaui/viva/headless" ) @@ -36,11 +40,80 @@ func (s pythonPreviewSource) View(ctx context.Context, editor pluginservice.Sett return s.service.CallView(ctx, pluginservice.SettingsViewCall(editor, region, function, "", event, previous, closing)) } +// pythonToolchains reads the installed plugins' tools for one workspace, as the workbench +// does, so the regions' tool rows show the interpreter Lithe resolves there. The test pins +// nothing. +type pythonToolchains struct { + kernel toolchain.Kernel + service *pluginservice.Service + root string +} + +func (l pythonToolchains) Load(ctx context.Context) (toolchain.Snapshot, error) { + entries, err := l.service.Manager.Installed() + if err != nil { + return toolchain.Snapshot{}, err + } + plugins, err := l.service.ToolchainPlugins(ctx, entries) + if err != nil { + return toolchain.Snapshot{}, err + } + manifests := make([]json.RawMessage, 0, len(plugins)) + for _, plugin := range plugins { + manifests = append(manifests, plugin.Manifest) + } + // Without a global root the project's own .venv may be probed, as a trusted project's is. + return toolchain.Load(ctx, l.kernel, l.root, ".", manifests, l.service.ToolchainOptions(l.root, toolchain.Options{ProjectCodeAllowed: true})) +} + +func (pythonToolchains) Save(_ context.Context, snapshot toolchain.Snapshot, _ []toolchain.Edit) (toolchain.Snapshot, error) { + return snapshot, errors.New("the settings preview test pins no interpreter") +} + +// pythonWorkspace is a project with its own .venv, made by the Python the suite runs pytest +// with, and that environment's version, which the tool rows show. +func pythonWorkspace(t *testing.T) (string, string) { + t.Helper() + python := os.Getenv("PYTEST_PYTHON") + if python == "" { + for _, name := range []string{"python3", "python"} { + if found, err := exec.LookPath(name); err == nil { + python = found + break + } + } + } + if python == "" { + t.Skip("set PYTEST_PYTHON or put python3 on PATH to make the project's .venv") + } + root := t.TempDir() + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + venv := filepath.Join(root, ".venv") + if out, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", venv).CombinedOutput(); err != nil { + t.Fatalf("make the project's .venv: %v\n%s", err, out) + } + executable := filepath.Join(venv, "bin", "python") + if _, err := os.Stat(executable); err != nil { + executable = filepath.Join(venv, "Scripts", "python.exe") + } + out, err := exec.CommandContext(ctx, executable, "-c", "import platform; print(platform.python_version())").Output() + if err != nil { + t.Fatalf("read the .venv's version: %v", err) + } + return root, strings.TrimSpace(string(out)) +} + +// TestPythonPluginSettingsPreview opens the Python language page and the Python build page +// in the settings window and checks what the plugin's views draw there: the interpreter row +// above the preview cards, a draft shown before it is applied, and the order Lithe looks for +// the interpreter in. func TestPythonPluginSettingsPreview(t *testing.T) { archive := os.Getenv("LITHE_TEST_PYTHON_PLUGIN_ARCHIVE") if archive == "" { t.Skip("set LITHE_TEST_PYTHON_PLUGIN_ARCHIVE to the packaged Python plugin") } + root, version := pythonWorkspace(t) ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) defer cancel() kernel := core.NewClient() @@ -65,11 +138,12 @@ func TestPythonPluginSettingsPreview(t *testing.T) { t.Fatal(err) } for _, look := range []struct { - theme, title, toggle, draft string - language i18n.Language + theme, title, toggle, accepted, draft, order string + language i18n.Language }{ - {"light", "Preview", "Complete function parentheses", "Includes changes not applied yet", i18n.English}, - {"dark", "效果预览", "补全函数括号", "含未应用的修改", i18n.Chinese}, + {"light", "Preview", "Complete function parentheses", "After accepting greet", "Includes changes not applied yet", + "How Lithe finds the Python interpreter", i18n.English}, + {"dark", "效果预览", "补全函数括号", "确认补全 greet 后", "含未应用的修改", "Lithe 按这个顺序找 Python 解释器", i18n.Chinese}, } { t.Run(look.theme, func(t *testing.T) { w := newWindow(NewController(Options{ @@ -80,11 +154,12 @@ func TestPythonPluginSettingsPreview(t *testing.T) { }, SettingsNavigation: kernel.SettingsNavigation, PluginSettings: pythonPreviewSource{service}, + Toolchains: pythonToolchains{kernel: kernel, service: service, root: root}, }), Values{Theme: look.theme, Language: look.language.Code()}) w.sess.page = pageLanguages w.sess.open[pageLanguages] = true config := w.config() - config.Width, config.Height = 1080, 800 + config.Width, config.Height = 1270, 1170 session, err := headless.Open(config, nil, headless.Options{}) if err != nil { t.Fatal(err) @@ -92,22 +167,19 @@ func TestPythonPluginSettingsPreview(t *testing.T) { t.Cleanup(session.Close) t.Cleanup(w.closeRegion) d := &windowDriver{t: t, w: w, driver: session.Driver()} - const page = "language:python" - d.until("installed Python settings page", func() bool { return w.dynamic.selected(page) != nil }) - w.selectSettingsPage(pageLanguages, page) - d.until("Python settings preview and completion toggle", func() bool { - if err := w.pluginSettings.failed; err != nil { - t.Fatalf("load settings: %v", err) - } - if w.region != nil && w.region.session.Err() != nil { - t.Fatalf("draw preview: %v", w.region.session.Err()) - } - return d.text(look.title) && d.has(look.toggle) - }) - if d.text(look.draft) || !d.text("greet") { - t.Fatal("the preview did not show the saved default") + drawn := func(what string, cond func() bool) { + t.Helper() + d.until(what, func() bool { + if err := w.pluginSettings.failed; err != nil { + t.Fatalf("load settings: %v", err) + } + if w.region != nil && w.region.session.Err() != nil { + t.Fatalf("draw the region: %v", w.region.session.Err()) + } + return cond() + }) } - capture := func(state string) { + capture := func(name string) { t.Helper() out := os.Getenv("LITHE_PYTHON_VISUAL_DIR") if out == "" { @@ -119,17 +191,39 @@ func TestPythonPluginSettingsPreview(t *testing.T) { if err := session.Advance(250 * time.Millisecond); err != nil { t.Fatal(err) } - if err := session.Screenshot(filepath.Join(out, "python-settings-preview-"+look.theme+"-"+state+".png")); err != nil { + if err := session.Screenshot(filepath.Join(out, "python-settings-"+name+"-"+look.theme+".png")); err != nil { t.Fatal(err) } } - capture("saved") + + const languagePage, buildPage = "language:python", "buildSystem:python" + d.until("installed Python settings pages", func() bool { + return w.dynamic.selected(languagePage) != nil && w.dynamic.selected(buildPage) != nil + }) + w.selectSettingsPage(pageLanguages, languagePage) + drawn("the interpreter row, the preview and the completion toggle", func() bool { + return d.text(version) && d.text(look.title) && d.text(look.accepted) && d.has(look.toggle) + }) + if d.text(look.draft) { + t.Fatal("the preview marked a draft before anything was edited") + } + capture("language") + d.click(look.toggle) - d.until("preview of the unsaved completion change", func() bool { return d.text(look.draft) && d.text("greet()") }) - capture("draft") + drawn("the preview of the unapplied completion change", func() bool { return d.text(look.draft) }) + capture("language-draft") if _, err := os.Stat(w.pluginSettings.editor.Snapshot.GlobalPath()); !os.IsNotExist(err) { - t.Fatalf("preview wrote the draft to the settings file: %v", err) + t.Fatalf("the preview wrote the draft to the settings file: %v", err) + } + + w.openContributedPage(buildPage, pythonSettingsPlugin) + drawn("the interpreter row and the lookup order on the Python build page", func() bool { + return w.dynamicPage == buildPage && d.text(version) && d.text(look.order) + }) + if d.text(look.title) { + t.Fatal("the Python build page shows the language page's preview") } + capture("build") }) } } diff --git a/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go b/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go index 4776efa..766fe5f 100644 --- a/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go @@ -1,8 +1,8 @@ package workbench import ( + "cmp" "context" - "encoding/json" "os" "os/exec" "path/filepath" @@ -21,11 +21,14 @@ func TestPythonSupportPluginRunCurrentFile(t *testing.T) { checkPythonCurrentFileRun(t, false) } -func TestPythonSupportPluginRunCurrentFileInterpreterOverride(t *testing.T) { +// TestPythonSupportPluginRunCurrentFilePinnedInterpreter pins another +// interpreter for the project, as the Toolchains page does, and expects the +// run to use it over the project's .venv. +func TestPythonSupportPluginRunCurrentFilePinnedInterpreter(t *testing.T) { checkPythonCurrentFileRun(t, true) } -func checkPythonCurrentFileRun(t *testing.T, override bool) { +func checkPythonCurrentFileRun(t *testing.T, pinned bool) { t.Helper() archive := pythonArchiveForE2E(t) ctx, cancel := context.WithTimeout(t.Context(), time.Minute) @@ -65,36 +68,19 @@ func checkPythonCurrentFileRun(t *testing.T, override bool) { if _, err := trust.Save(ctx, kernel, true, false); err != nil { t.Fatal(err) } - wantVenv := venv - if override { - overrideDir, err := filepath.EvalSymlinks(t.TempDir()) - if err != nil { - t.Fatal(err) - } - wantVenv = filepath.Join(overrideDir, "configured interpreter") - if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", wantVenv).CombinedOutput(); err != nil { - t.Fatalf("create configured environment: %v\n%s", err, output) - } - configured := filepath.Join(wantVenv, "bin", "python") - if runtime.GOOS == "windows" { - configured = filepath.Join(wantVenv, "Scripts", "python.exe") - } - settings, err := json.Marshal(map[string]map[string]string{ - pythonSupportPluginID: {"pythonExecutable": configured}, - }) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(preferences.Dir(), "plugin-settings.json"), settings, 0o600); err != nil { - t.Fatal(err) - } - } h := newHarnessWithOptions(t, Options{ Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences, Languages: []string{"en"}, }) installPythonArchive(t, ctx, h.app.plugins, archive) h.app.reloadPluginLanguages() + wantPrefix := venv + if pinned { + home, version := pythonInstallationForE2E(t, ctx, cmp.Or(os.Getenv("PYTEST_PYTHON"), python)) + wantPrefix = home + addPythonInstallationForE2E(t, ctx, h, home) + pinPythonForE2E(t, ctx, kernel, root, home, version) + } h.open(root) p := h.app.project if p == nil { @@ -109,7 +95,11 @@ func checkPythonCurrentFileRun(t *testing.T, override bool) { awaitStateWithin(t, h, 20*time.Second, "the current file to start running", func() bool { for _, notice := range noticeTexts(h.app) { if notice == notRunnable { - t.Fatalf("the toolbar rejected the Python entrypoint: %s", notice) + var models []string + for _, instance := range p.build.instances { + models = append(models, instance.BuildSystemID+": "+instance.modelError) + } + t.Fatalf("the toolbar rejected the Python entrypoint: %s\nbuild models: %q", notice, models) } } return p.runConfigs.selected != "" @@ -117,8 +107,8 @@ func checkPythonCurrentFileRun(t *testing.T, override bool) { run := awaitProcessRun(t, h, p, "main.py", nil) checkOutput := func(output string) { t.Helper() - if !strings.Contains(output, "current file ran") || !strings.Contains(output, wantVenv) { - t.Fatalf("expected the program to use Python environment %q:\n%s", wantVenv, output) + if !strings.Contains(output, "current file ran") || !strings.Contains(output, wantPrefix) { + t.Fatalf("expected the program to run with sys.prefix %q:\n%s", wantPrefix, output) } } checkOutput(run.output.all()) diff --git a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go index 5a21ec2..6c7dd37 100644 --- a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go @@ -13,6 +13,7 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "runtime" "slices" "strings" @@ -27,7 +28,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" - "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" @@ -136,6 +136,96 @@ func resolvePytestToolForE2E(t *testing.T, ctx context.Context, systemPython str return core.BuildTool{Executable: executable} } +// pythonInstallationForE2E returns the home without links (sys.prefix) and +// the version of the Python installation python, for a test to pin. It fails +// when python is a virtual environment: Core refuses to pin an environment +// outside the workspace, because its python links back to the interpreter it +// was made from. Set PYTEST_PYTHON to an installation, such as one from +// actions/setup-python, uv python install or pyenv. +func pythonInstallationForE2E(t *testing.T, ctx context.Context, python string) (home, version string) { + t.Helper() + facts, err := exec.CommandContext(ctx, python, "-c", "import platform, sys; print(sys.prefix); print(platform.python_version()); print(sys.prefix != sys.base_prefix)").Output() + if err != nil { + t.Fatalf("read the installation of %s: %v", python, err) + } + lines := strings.Split(strings.TrimSpace(string(facts)), "\n") + if len(lines) != 3 { + t.Fatalf("unexpected interpreter facts %q", facts) + } + if strings.TrimSpace(lines[2]) == "True" { + t.Fatalf("%s is a virtual environment; set PYTEST_PYTHON to a Python installation with pytest, since Core refuses to pin an environment outside the workspace", python) + } + if home, err = filepath.EvalSymlinks(strings.TrimSpace(lines[0])); err != nil { + t.Fatal(err) + } + return home, strings.TrimSpace(lines[1]) +} + +// pinPythonForE2E pins the installation at home as the workspace's Python +// interpreter, as choosing it on the Toolchains page does, and returns a +// function that removes the pin again. The page keys a pin by the tool +// definition's own ID. The pin is kept in the workspace's .lithe folder; +// removing it also removes that folder when the pin created it. +func pinPythonForE2E(t *testing.T, ctx context.Context, kernel toolchain.Kernel, workspace, home, version string) func() { + t.Helper() + created := filepath.Join(workspace, ".lithe") + if _, err := os.Stat(created); err == nil { + created = "" + } + pin := &core.ToolchainPin{Home: filepath.ToSlash(home), Version: version, Provider: "host:manual"} + _, baseline, err := toolchain.SavePin(ctx, kernel, workspace, ".", "python", pin, nil) + if err != nil { + t.Fatalf("pin the test interpreter: %v", err) + } + return func() { + t.Helper() + if _, _, err := toolchain.SavePin(ctx, kernel, workspace, ".", "python", nil, baseline); err != nil { + t.Fatalf("remove the test interpreter's pin: %v", err) + } + if created != "" { + if err := os.RemoveAll(created); err != nil { + t.Fatal(err) + } + } + } +} + +// addPythonInstallationForE2E adds home to the machine's Python installations, +// as adding an installation on the Toolchains page does. Hosts such as 0.8.9 +// probe a pinned home only when discovery or this list finds it, and discovery +// does not search where a test interpreter usually is (the actions/setup-python +// tool cache, or a folder passed to uv python install --install-dir). +func addPythonInstallationForE2E(t *testing.T, ctx context.Context, h *harness, home string) { + t.Helper() + pages := settingsToolchains{app: h.app} + machine, err := pages.LoadScope(ctx, "global") + if err != nil { + t.Fatalf("read the machine's toolchains: %v", err) + } + for index := range machine.Tools { + tool := &machine.Tools[index] + if tool.ID != "python" && !strings.HasSuffix(tool.ID, ":python") { + continue + } + tool.CustomHomes = append(slices.Clone(tool.CustomHomes), filepath.ToSlash(home)) + if _, err := pages.Save(ctx, machine, []toolchain.Edit{{Tool: tool.ID}}); err != nil { + t.Fatalf("add the test interpreter as a Python installation: %v", err) + } + return + } + t.Fatal("the Toolchains page lists no Python tool") +} + +// trustProjectCode marks the workspace of the launch request at request, a +// pointer to a struct, as trusted. Hosts from 0.8.13 on start no language +// server or build provider that runs project code without it (safe mode); +// older hosts have no such field and start them anyway. +func trustProjectCode(request any) { + if field := reflect.ValueOf(request).Elem().FieldByName("ProjectCodeAllowed"); field.IsValid() { + field.SetBool(true) + } +} + // registeredPythonEnvironments creates isolated external interpreters listed in a // temporary Conda registry. Both the provider and the workbench see that same home. func registeredPythonEnvironments(t *testing.T, ctx context.Context) (systemPython, providerHome string, registeredHomes []string) { @@ -318,6 +408,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { TemporaryDirectory: tempDir, Architecture: core.PluginArchitecture(), } + trustProjectCode(&lspDirs) lspPlan, err := kernel.PlanPluginLanguageServer(ctx, normalizedManifest, "python", lspDirs) if err != nil { t.Fatalf("PlanPluginLanguageServer: %v", err) @@ -514,7 +605,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { buildProject := &project{root: workspace} buildProject.trust.codeAllowed.Store(true) buildWsState := t.TempDir() - providerClient, err := buildprovider.Start(ctx, service.Backend, pluginbackend.StartRequest{ + providerRequest := pluginbackend.StartRequest{ Manifest: normalizedManifest, PackageDirectory: installedDir, PluginID: pythonSupportPluginID, @@ -527,7 +618,9 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { Architecture: core.PluginArchitecture(), RootURI: pythonFileURI(workspace), WorkingDirectory: workspace, - }) + } + trustProjectCode(&providerRequest) + providerClient, err := buildprovider.Start(ctx, service.Backend, providerRequest) if err != nil { t.Fatalf("buildprovider.Start(python): %v", err) } @@ -598,18 +691,8 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { if instance.System.Test == nil || !instance.System.Test.DiscoveryCommand { t.Fatal("installed Python build system did not expose command discovery") } - preferences := pluginsettings.New(kernel, appStore.Dir()) - settings, err := preferences.Load(ctx, instance.Manifest, workspace) - if err != nil { - t.Fatal(err) - } - pythonSetting, err := json.Marshal(pytestTool.Executable) - if err != nil { - t.Fatal(err) - } - if _, err := preferences.Save(ctx, settings, "global", []core.PluginSettingEdit{{ID: "pythonExecutable", Value: pythonSetting}}, nil); err != nil { - t.Fatalf("set the test interpreter: %v", err) - } + home, version := pythonInstallationForE2E(t, ctx, pytestTool.Executable) + unpin := pinPythonForE2E(t, ctx, kernel, workspace, home, version) workbench := &App{kernel: kernel, plugins: service, store: appStore, text: i18n.For(i18n.English)} discoveryOperation := core.NewOperation() discoveryCtx := core.WithOrigin(ctx, core.Origin{Operation: discoveryOperation}) @@ -617,6 +700,8 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { if err != nil { t.Fatalf("workbench command discovery: %v", err) } + // The toolchain checks below resolve the workspace without a pin. + unpin() discoveryFiles, err := os.ReadDir(buildStateDirectory(service.Root, workspace, instance)) if err != nil || len(discoveryFiles) != 0 { t.Fatalf("discovery left workspace state entries %v (%v)", discoveryFiles, err) diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index 8a9f9c6..07f7348 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,13 +1,13 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "645a3aee86e3ee5d6a308defa350678f8048baa8", + "revision": "60885168df05daacda63c1c522026b00ce1446c2", "packages": { "./internal/projectgen": "^TestPythonPlugin", "./internal/settingswindow": "^TestPythonPluginSettingsPreview$", "./internal/workbench": "^TestPythonSupportPlugin" }, "requiredEnvironment": { - "LITHE_TEST_PYTHON_PLUGIN_ARCHIVE": "python-support--.zip to install, for example dist/python-support-1.0.0-darwin-arm64.zip" + "LITHE_TEST_PYTHON_PLUGIN_ARCHIVE": "python-support--.zip to install, for example dist/python-support-1.1.0-darwin-arm64.zip" }, "repositoryEnvironment": { "LITHE_PLUGIN_PYTHON_DIR": "io.github.lithe-idea.python-support" diff --git a/io.github.lithe-idea.python-support/l10n/zh-Hans.json b/io.github.lithe-idea.python-support/l10n/zh-Hans.json index df7c06b..097580c 100644 --- a/io.github.lithe-idea.python-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.python-support/l10n/zh-Hans.json @@ -27,31 +27,22 @@ } }, "settings": { - "pythonExecutable": { - "title": "Python 解释器覆盖路径", - "description": "显式指定用于构建、运行和 pytest 测试的 Python 解释器路径。留空时自动使用 Python 工具链解析结果(依次查找 .venv、venv、.conda、VIRTUAL_ENV、PATH 与已发现的 conda / uv / pyenv 安装)。" - }, "typeCheckingMode": { "title": "类型检查模式", - "description": "控制 Pyrefly 类型检查的严格程度;选择“自动”时遵循项目中的 pyrefly.toml 或 pyproject.toml 中的 [tool.pyrefly] 配置。", + "description": "Pyrefly 对没有 pyrefly.toml 或 [tool.pyrefly] 的文件使用的预设;项目自己的 Pyrefly 配置优先。“自动”沿用附近的 mypy 或 Pyright 配置,没有时按“基础”检查。开启“隐藏类型错误”后,选哪个预设都不显示类型错误。", "options": { - "auto": "自动(遵循项目配置)", + "default": "默认", + "auto": "自动", "off": "关闭", "basic": "基础", - "default": "默认", + "legacy": "宽松", "strict": "严格", - "all": "全部规则" + "all": "全部" } }, - "displayTypeErrors": { - "title": "显示类型错误", - "description": "控制 Pyrefly 在所有文件中展示类型错误、仅在含 Pyrefly 配置的项目中展示,或仅报告缺失导入。", - "options": { - "force-on": "始终开启", - "default": "仅已配置项目", - "error-missing-imports": "仅报告缺失导入", - "force-off": "关闭" - } + "disableTypeErrors": { + "title": "隐藏类型错误", + "description": "开启后所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转和补全照常可用。" }, "diagnosticMode": { "title": "诊断范围", @@ -65,26 +56,28 @@ "title": "自动导入补全", "description": "在代码补全中包含尚未导入模块的符号,并在确认补全时自动插入 import 语句。" }, - "completeFunctionParens": { - "title": "补全函数括号", - "description": "补全 Python 函数或方法调用时自动补齐圆括号。" - }, "importFormat": { "title": "自动导入路径风格", - "description": "控制 Pyrefly 自动插入导入语句时优先使用绝对模块路径还是包内相对路径。", + "description": "Pyrefly 插入导入语句时写绝对模块路径还是包内相对路径:接受自动导入补全时,以及“移动符号”“转换模块”代码操作中。关闭“自动导入补全”后,只有这两种代码操作会用到它。", "options": { "absolute": "绝对导入", "relative": "相对导入" } + }, + "completeFunctionParens": { + "title": "补全函数括号", + "description": "补全 Python 函数或方法调用时自动补齐圆括号。" } }, "settingRegions": { "language": { - "keywords": ["类型检查", "诊断", "代码补全", "效果预览"] + "keywords": ["解释器", "虚拟环境", "类型检查", "诊断", "代码补全", "效果预览"] + }, + "python": { + "keywords": ["解释器", "查找顺序", "虚拟环境"] } }, "sections": { - "Python Interpreter": "Python 解释器", "Pyrefly": "Pyrefly", "Completions": "代码补全" } diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index 8a8bce7..72e5358 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.python-support", "displayName": "Python Support", - "version": "1.0.0", + "version": "1.1.0", "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -95,46 +95,31 @@ } ], "settings": [ - { - "id": "pythonExecutable", - "type": "file", - "title": "Python executable override", - "description": "Explicit path to the Python interpreter for build, run, and pytest commands. Leave empty to resolve automatically from the Python toolchain (.venv, venv, .conda, VIRTUAL_ENV, PATH, or discovered conda / uv / pyenv installations).", - "default": "", - "effect": "reload", - "page": { "languageID": "python" }, - "section": "Python Interpreter" - }, { "id": "typeCheckingMode", "type": "enum", "title": "Type checking mode", - "description": "Controls Pyrefly's type-checking strictness. Choose auto to enable type checking only in projects with pyrefly.toml or [tool.pyrefly].", + "description": "Pyrefly's preset for files no pyrefly.toml or [tool.pyrefly] covers; a project's own Pyrefly config wins. Automatic follows a nearby mypy or Pyright config, else checks as Basic. While Hide type errors is on, no preset shows type errors.", "default": "default", "options": [ { "value": "default", "title": "Default" }, - { "value": "auto", "title": "Automatic (configured projects only)" }, + { "value": "auto", "title": "Automatic" }, + { "value": "off", "title": "Off" }, { "value": "basic", "title": "Basic" }, + { "value": "legacy", "title": "Legacy" }, { "value": "strict", "title": "Strict" }, - { "value": "all", "title": "All" }, - { "value": "off", "title": "Off" } + { "value": "all", "title": "All" } ], "effect": "immediate", "page": { "languageID": "python" }, "section": "Pyrefly" }, { - "id": "displayTypeErrors", - "type": "enum", - "title": "Display type errors", - "description": "Whether Pyrefly publishes type errors in editor diagnostics across all files, only in projects with a Pyrefly config, or limits diagnostics to missing imports.", - "default": "force-on", - "options": [ - { "value": "force-on", "title": "Always on" }, - { "value": "default", "title": "Configured projects only" }, - { "value": "error-missing-imports", "title": "Missing imports only" }, - { "value": "force-off", "title": "Off" } - ], + "id": "disableTypeErrors", + "type": "boolean", + "title": "Hide type errors", + "description": "Hide type errors in every file, including projects with their own Pyrefly config. Hover, go to definition and completion keep working.", + "default": false, "effect": "immediate", "page": { "languageID": "python" }, "section": "Pyrefly" @@ -163,21 +148,11 @@ "page": { "languageID": "python" }, "section": "Completions" }, - { - "id": "completeFunctionParens", - "type": "boolean", - "title": "Complete function parentheses", - "description": "Automatically append parentheses when completing a Python function or method call.", - "default": false, - "effect": "immediate", - "page": { "languageID": "python" }, - "section": "Completions" - }, { "id": "importFormat", "type": "enum", "title": "Auto-import module path style", - "description": "Prefer absolute module paths or package-relative imports when Pyrefly inserts imports.", + "description": "Whether Pyrefly writes absolute module paths or package-relative imports when it inserts an import: on accepting an auto-import completion, and in the move-symbol and convert-module code actions. With Auto-import completions off, only those code actions use it.", "default": "absolute", "options": [ { "value": "absolute", "title": "Absolute" }, @@ -186,14 +161,36 @@ "effect": "immediate", "page": { "languageID": "python" }, "section": "Completions" + }, + { + "id": "completeFunctionParens", + "type": "boolean", + "title": "Complete function parentheses", + "description": "Automatically append parentheses when completing a Python function or method call.", + "default": false, + "effect": "immediate", + "page": { "languageID": "python" }, + "section": "Completions" } ], "settingRegions": [ { "id": "language", "page": { "languageID": "python" }, - "keywords": ["Pyrefly", "type checking", "diagnostics", "completions", "preview"], - "view": { "function": "settings.preview" } + "keywords": [ + "interpreter", "virtual environment", "venv", "uv", "conda", "pyenv", + "Pyrefly", "type checking", "diagnostics", "completions", "preview" + ], + "view": { "function": "settings.view" } + }, + { + "id": "python", + "page": { "buildSystemID": "python" }, + "keywords": [ + "interpreter", "lookup order", ".venv", "VIRTUAL_ENV", "PATH", + ".python-version", "requires-python", "uv", "conda", "pyenv" + ], + "view": { "function": "settings.view" } } ], "languageServers": [ @@ -209,7 +206,7 @@ "python": { "pyrefly": { "typeCheckingMode": "${setting:typeCheckingMode}", - "displayTypeErrors": "${setting:displayTypeErrors}", + "disableTypeErrors": "${setting:disableTypeErrors}", "diagnosticMode": "${setting:diagnosticMode}" }, "analysis": { @@ -499,7 +496,6 @@ }, "invocation": { "executables": [ - { "kind": "setting", "settingID": "pythonExecutable" }, { "kind": "toolchain", "toolchainID": "python" } ], "version": { @@ -516,7 +512,6 @@ "runtimeArguments": ["-I", "-B"], "entry": "scripts/build_provider.py" }, - "initializationOptions": { "pythonExecutable": "${setting:pythonExecutable}" }, "executesProjectCode": true, "mayUseNetwork": false }, @@ -915,7 +910,7 @@ "launch": { "kind": "runtime", "tool": "python", - "minimumVersion": "3.9", + "minimumVersion": "3.10", "runtimeArguments": ["-I", "-B"], "entry": "scripts/debugpy_adapter.py" }, diff --git a/io.github.lithe-idea.python-support/scripts/build_provider.py b/io.github.lithe-idea.python-support/scripts/build_provider.py index f050271..f52cd0f 100644 --- a/io.github.lithe-idea.python-support/scripts/build_provider.py +++ b/io.github.lithe-idea.python-support/scripts/build_provider.py @@ -184,14 +184,10 @@ def create_build_provider_server() -> JsonRpcServer: workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()} degraded_model_roots: set[str] = set() state_lock = threading.Lock() - configured_interpreter = False locale = "" def _on_init(params: dict[str, Any]) -> None: - nonlocal configured_interpreter, locale - initialization = params.get("initializationOptions") - if isinstance(initialization, dict): - configured_interpreter = bool(initialization.get("pythonExecutable")) + nonlocal locale if isinstance(params.get("locale"), str): locale = params["locale"] folders = params.get("workspaceFolders") @@ -229,11 +225,6 @@ def _resolve_runtime_and_env(params: dict[str, Any]) -> tuple[str, dict[str, str raw_exec = tool.get("executable") if isinstance(raw_exec, str) and raw_exec.strip(): python_exec = raw_exec.strip() - options = params.get("options") - if isinstance(options, dict): - opt_exec = options.get("pythonExecutable") - if isinstance(opt_exec, str) and opt_exec.strip(): - python_exec = opt_exec.strip() env = dict(os.environ) raw_env = params.get("environment") @@ -421,13 +412,6 @@ def handle_prepare_run(params: dict[str, Any], ctx: CallContext) -> dict[str, An *_string_args(params.get("optionArguments")), *_string_args(launch.get("arguments", params.get("userArguments"))), ] - if configured_interpreter: - tool = params.get("tool") - executable = tool.get("executable") if isinstance(tool, dict) else None - if not isinstance(executable, str) or not Path(executable).is_absolute(): - raise PluginError("python.interpreterUnavailable", run_message("interpreter", locale)) - environment.setdefault("PYTHON_EXECUTABLE", executable) - arguments = ["-I", "-B", _ENTRYPOINT_LAUNCHER, "interpreter", executable, *arguments] return { "executable": {"kind": "toolchain", "value": "python"}, "arguments": arguments, diff --git a/io.github.lithe-idea.python-support/scripts/run_entrypoint.py b/io.github.lithe-idea.python-support/scripts/run_entrypoint.py index 1aca606..f7ff4cb 100644 --- a/io.github.lithe-idea.python-support/scripts/run_entrypoint.py +++ b/io.github.lithe-idea.python-support/scripts/run_entrypoint.py @@ -1,6 +1,5 @@ """Launch Python entrypoints within the process tree owned by the host.""" -import os import sys from importlib import import_module from importlib.util import find_spec, module_from_spec @@ -16,10 +15,6 @@ "The saved Python entrypoint is no longer available. Open the file and run it again.", "保存的 Python 入口已失效。请打开文件并重新运行。", ), - "interpreter": ( - "Lithe could not resolve the configured Python interpreter. Check the Python executable override.", - "Lithe 无法解析配置的 Python 解释器。请检查 Python 解释器覆盖设置。", - ), "shadowed": ( "A module or package with the same name shadows the selected Python entrypoint.", "当前包入口被同名模块或包遮蔽。", @@ -35,18 +30,6 @@ def run_message(key: str, locale: str) -> str: return chinese if locale.replace("_", "-").split("-", 1)[0].lower() == "zh" else english -def _run_with_interpreter(executable: str, args: list[str]) -> int: - # Match the build invocation's executable-directory PATH precedence. - os.environ["PATH"] = os.pathsep.join(filter(None, (str(Path(executable).parent), os.environ.get("PATH")))) - argv = [executable, *args] - if os.name == "nt": - import subprocess - - # The host's Job Object owns this child. Keep the parent alive to report its exit code. - return subprocess.call(argv, executable=executable) - os.execv(executable, argv) - - def _run_package(import_root: str, package: str, selected_file: str, locale: str, args: list[str]) -> int: source = Path(selected_file).resolve() if sys.path and sys.path[0] == str(Path(__file__).parent): @@ -81,8 +64,5 @@ def _run_package(import_root: str, package: str, selected_file: str, locale: str if __name__ == "__main__": - action, *args = sys.argv[1:] - if action == "interpreter": - raise SystemExit(_run_with_interpreter(args[0], args[1:])) - import_root, package, selected_file, locale, *program_args = args + _package_action, import_root, package, selected_file, locale, *program_args = sys.argv[1:] raise SystemExit(_run_package(import_root, package, selected_file, locale, program_args)) diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs index ee04bc3..a12ad76 100644 --- a/scripts/package/archives.test.mjs +++ b/scripts/package/archives.test.mjs @@ -11,11 +11,19 @@ const baseManifest = JSON.parse(readFileSync(`${PACKAGE_ID}/plugin.json`, "utf8" const lock = JSON.parse(readFileSync("vendor-lock.json", "utf8")); const version = baseManifest.version; -test("the Python interpreter override is on the Python language page on every platform", () => { +test("every platform shows the settings views on the Python language and build pages, with no interpreter override", () => { for (const platform of Object.keys(lock.pyrefly.platforms)) { const manifest = manifestForPlatform(baseManifest, platform, lock); - const interpreter = manifest.settings.find(({ id }) => id === "pythonExecutable"); - assert.deepEqual(interpreter?.page, { languageID: "python" }, platform); + assert.deepEqual( + manifest.settingRegions.map(({ id, page, view }) => ({ id, page, view: view.function })), + [ + { id: "language", page: { languageID: "python" }, view: "settings.view" }, + { id: "python", page: { buildSystemID: "python" }, view: "settings.view" }, + ], + platform, + ); + // The interpreter is the python tool's pin on the Toolchains page. + assert.equal(manifest.settings.find(({ id }) => id === "pythonExecutable"), undefined, platform); } }); diff --git a/scripts/test.mjs b/scripts/test.mjs index 2835dc0..96f9026 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -711,7 +711,7 @@ try { assert.deepEqual(initOk.result.capabilities.experimental.litheLogging, { version: 0 }); assert.deepEqual(initOk.result.capabilities.experimental.litheFunctions, { version: 0, - functions: [{ id: "pyrefly.resolveLaunch" }, { id: "python.inspectEnvironment" }, { id: "settings.preview" }], + functions: [{ id: "pyrefly.resolveLaunch" }, { id: "python.inspectEnvironment" }, { id: "settings.view" }], }); assert.deepEqual(initOk.result.capabilities.experimental.litheToolchains, { version: 0, @@ -723,7 +723,7 @@ try { const previewEvent = { instance: "python-settings-preview", surface: { settingRegionID: region.id }, - settings: { effective: { displayTypeErrors: "force-on", completeFunctionParens: false }, draft: {} }, + settings: { effective: { typeCheckingMode: "default", completeFunctionParens: false }, draft: {} }, }; peer.send({ jsonrpc: "2.0", id: 21, method: "lithe/function/invoke", @@ -731,30 +731,49 @@ try { params: { ...previewEvent, event: "open", language: "en", width: 640 } }, }); const opened = await peer.waitFor((m) => m.id === 21, "Python preview open"); - const [wide] = opened.result.view; + const [interpreterSection, wide] = opened.result.view; + assert.equal(interpreterSection.type, "section"); + assert.deepEqual(interpreterSection.children, [{ type: "tool", tool: "python" }]); assert.deepEqual(wide.on, ["resize"]); assert.equal(wide.viewBox[2], 640); - assert.match(JSON.stringify(wide), /Type error: expected int, got str/); - assert.doesNotMatch(JSON.stringify(wide), /greet\(\)|not applied/); + assert.match(JSON.stringify(wide), /"text":"bad-argument-type"\},\{"color":"\$textSecondary","text":" · 2 errors"/); + assert.doesNotMatch(JSON.stringify(wide), /not applied/); peer.send({ jsonrpc: "2.0", id: 22, method: "lithe/function/invoke", params: { operationID: "op-preview-draft", functionID: region.view.function, params: { ...previewEvent, event: "settings", language: "zh-Hans", width: 360, settings: { ...previewEvent.settings, draft: { - displayTypeErrors: "force-off", completeFunctionParens: true, importFormat: "relative", + disableTypeErrors: true, completeFunctionParens: true, importFormat: "relative", } } } }, }); const drafted = await peer.waitFor((m) => m.id === 22, "Python preview draft"); - const [narrow] = drafted.result.view; + const [, narrow] = drafted.result.view; assert.equal(narrow.viewBox[2], 360); assert.ok(narrow.height > wide.height); - assert.match(JSON.stringify(narrow), /含未应用的修改/); - assert.match(JSON.stringify(narrow), /隐藏类型错误/); - assert.match(JSON.stringify(narrow), /from \.utils import greet/); - assert.match(JSON.stringify(narrow), /greet\(\)/); + const drawn = JSON.stringify(narrow); + assert.match(drawn, /含未应用的修改/); + assert.match(drawn, /"text":"已隐藏"/); + assert.doesNotMatch(drawn, /bad-argument-type/); + assert.match(drawn, /"text":"相对导入"/); + assert.match(drawn, /补全函数时加上括号/); + + const lookup = pluginManifest.settingRegions.find(({ id }) => id === "python"); + assert.deepEqual(lookup.page, { buildSystemID: "python" }); + assert.equal(lookup.view.function, region.view.function); + peer.send({ + jsonrpc: "2.0", id: 23, method: "lithe/function/invoke", + params: { operationID: "op-preview-lookup", functionID: lookup.view.function, + params: { ...previewEvent, surface: { settingRegionID: lookup.id }, event: "open", language: "en" } }, + }); + const lookedUp = await peer.waitFor((m) => m.id === 23, "Python lookup order open"); + const [toolRow, order] = lookedUp.result.view; + assert.deepEqual(toolRow, { type: "tool", tool: "python" }); + assert.equal(order.id, "python-resolution"); + assert.equal(order.on, undefined); + assert.match(JSON.stringify(order), /Tried first[\s\S]*Global default[\s\S]*Tried last[\s\S]*Pyrefly uses the same interpreter/); assert.ok(!peer.allReceived.some((m) => - m.method === "lithe/log" && ["op-preview-open", "op-preview-draft"].includes(m.params?.operationId), + m.method === "lithe/log" && ["op-preview-open", "op-preview-draft", "op-preview-lookup"].includes(m.params?.operationId), ), "Successful preview events should not produce logs"); // 3. Resolve launch with external tools.python.executable on Unix. @@ -775,7 +794,7 @@ try { temporaryDirectory: tempDir, settings: { typeCheckingMode: "strict", - displayTypeErrors: "force-on", + disableTypeErrors: false, diagnosticMode: "openFilesOnly", autoImportCompletions: true, completeFunctionParens: true, @@ -800,6 +819,8 @@ try { assert.deepEqual(resolvedUnixAnswer.arguments, ["lsp"]); assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pythonPath, extPython); assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.typeCheckingMode, "strict"); + assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.disableTypeErrors, false); + assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.pyrefly.displayTypeErrors, undefined); assert.equal(resolvedUnixAnswer.workspaceConfiguration.python.analysis.completeFunctionParens, true); // Verify lithe/log operationFinished arrived strictly BEFORE response id=3! @@ -1752,16 +1773,6 @@ try { assert.equal(collision.status, 1); assert.match(collision.stderr, /当前包入口被同名模块或包遮蔽/); - const launcher = join(unpackedPluginDir, "scripts", "run_entrypoint.py"); - const interpreter = run(pythonCmd, ["-c", "import sys; print(sys.executable)"]).trim(); - const forwarded = spawnSync(pythonCmd, ["-I", "-B", launcher, "interpreter", interpreter, - "-c", "import sys; print(sys.argv[1]); sys.exit(17)", "argument with spaces"], { - cwd: wsDir, encoding: "utf8", timeout: 5000, windowsHide: true, - }); - assert.ifError(forwarded.error); - assert.equal(forwarded.status, 17, forwarded.stderr); - assert.equal(forwarded.stdout.trim(), "argument with spaces"); - for (const [id, entrypoint] of [[73, "script:../worker.py"], [74, "script:missing.py"]]) { const response = await prepareRun(id, { entrypoint }); assert.equal(response.error?.code, -32000); @@ -1948,7 +1959,7 @@ try { const expandedPythonConfig = { pyrefly: { typeCheckingMode: "default", - displayTypeErrors: "force-on", + disableTypeErrors: false, diagnosticMode: "openFilesOnly", extraProjectExcludes: [".venv/**"], }, @@ -2019,10 +2030,18 @@ try { const logDir = join(scratch, "debugpy-logs"); mkdirSync(logDir, { recursive: true }); + // debugpy 1.8.22 requires Python 3.10. On 3.9 the adapter fails to import + // with stderr already closed, so the host must refuse older interpreters. + assert.equal(adapter.launch.process.launch.minimumVersion, "3.10"); const venvPython = process.platform === "win32" ? join(demoDir, ".venv", "Scripts", "python.exe") : join(demoDir, ".venv", "bin", "python3"); + const version = run(venvPython, ["-I", "-B", "-c", "import sys; print(*sys.version_info[:2])"]).trim().split(" ").map(Number); + assert.ok( + version[0] > 3 || (version[0] === 3 && version[1] >= 10), + `debugpy needs Python 3.10 or later, but ${pythonCmd} is ${version.join(".")}. Set PYTHON to a newer interpreter.`, + ); const args = [ ...adapter.launch.process.launch.runtimeArguments, entryScript,