diff --git a/README.md b/README.md index b5854c6..1f4b847 100644 --- a/README.md +++ b/README.md @@ -1,186 +1,188 @@ # Rust Support for Lithe -为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Rust 支持:用 rustup 装的 `rust-analyzer` 提供代码智能, -用 Cargo 识别软件包和工作区,在构建窗口里列出软件包和目标,运行 Build、Check、Clippy、Doc 和 Clean, -运行二进制和示例,查看依赖树;用 CodeLLDB 调试,CodeLLDB 在第一次需要时由 Lithe 下载;在「新建项目」里创建 Cargo 软件包。 -这是一个**社区插件**,按插件契约 v0 编写。插件包含一份 `plugin.json`、几份项目模板,和一个用 Rust SDK 写的后端; -cargo、rustup 和 rust-analyzer 用你电脑上的。 - -> English: Rust support for Lithe — code intelligence through the rust-analyzer of your rustup toolchain, Cargo -> packages and workspaces in the build window (model, Build, Check, Clippy, Doc, Clean, running binaries and -> examples, the dependency tree), debugging with CodeLLDB, which Lithe downloads the first time you debug, and a -> Rust package entry in New Project. The plugin is a `plugin.json`, a few project templates and a backend written -> with the Rust plugin SDK; cargo, rustup and rust-analyzer stay your own. - -> **兼容性**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 -> (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。下载 CodeLLDB 用的是下载型命令安装器 -> ([1lck/Lithe-IDEA#2241](https://github.com/1lck/Lithe-IDEA/pull/2241),固定了 -> [Lithe-core-rust#133](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/133) 的 Core),桌面端 0.8.11 还没有它, -> 会拒绝安装这个插件;0.1.0 因此作为预发布版本发布。rustup 装的 `cargo` 和 `rust-analyzer` 是指向 `rustup` 的链接, -> 工具定义要在 macOS 上找到它们,需要固定了 [Lithe-core-rust#135](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/135) -> 的桌面端([1lck/Lithe-IDEA#2242](https://github.com/1lck/Lithe-IDEA/pull/2242))。 - -本插件取代 `lithe-plugin-cargo`:Cargo 构建系统并入这里,那个插件不再维护。两个插件都声明了 `cargo` 构建系统, -不要同时启用。 +为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Rust 支持:rust-analyzer 代码智能;构建窗口里的 Cargo 软件包和目标, +可以 Build、Check、Clippy、Doc、Clean、运行,并查看依赖树;CodeLLDB 调试;在「新建项目」里创建 Cargo 软件包;设置页画出各项设置的效果预览。 +这是一个**社区插件**,按插件契约 v0 编写,由 `plugin.json`、项目模板和一个用 Rust SDK 写的后端组成。 +cargo、rustup 和 rust-analyzer 用你电脑上的,CodeLLDB 在第一次调试前由 Lithe 下载。 + +> English: Rust support for Lithe — rust-analyzer code intelligence, Cargo packages in the build window (Build, +> Check, Clippy, Doc, Clean, run, dependency tree), CodeLLDB debugging, a Cargo package entry in New Project and +> previews on the Rust and Cargo settings pages. cargo, rustup and rust-analyzer stay your own; Lithe downloads +> CodeLLDB the first time you debug. + +> **兼容性**:需要 Lithe 桌面端 0.8.12 或更新版本(`desktop-v*`),旧版 macOS Lithe 无法安装。 +> 各版本依赖的宿主能力见 [docs/releases](docs/releases)。 + +本插件取代 `lithe-plugin-cargo`。两个插件都声明了 `cargo` 构建系统,不要同时启用。 ## 功能 | 功能 | 说明 | | --- | --- | -| 代码智能 | 补全、跳转定义、悬停、诊断、格式化,由 `rust-analyzer` 提供;保存时运行 `cargo check`(或 `cargo clippy`),结果显示为诊断 | +| 代码智能 | 补全、跳转定义、悬停、诊断、格式化,由 `rust-analyzer` 提供;保存时运行 `cargo check` 或 `cargo clippy`,结果显示为诊断 | | 识别软件包 | 含 `Cargo.toml` 的最外层目录是构建根;`cargo metadata --no-deps` 的结果组成软件包和目标,只读清单,不联网 | -| 构建 | Build(`cargo build`)、Check、Clippy 作用于工作区、单个软件包或单个目标;Doc(`cargo doc --no-deps`)、Clean 作用于工作区或软件包 | -| 运行 | 每个二进制和示例在构建窗口里有运行按钮,执行 `cargo run --bin` 或 `cargo run --example`;打开 `src/main.rs`、`src/bin/*.rs`、`examples/*.rs` 时编辑器里也有运行入口 | -| 诊断 | 构建任务用 `--message-format=short`,`文件:行:列: error|warning: 消息` 的输出显示为问题 | -| 依赖 | `cargo metadata` 解析出的依赖图按 `cargo tree` 的样子列出;同一个软件包第二次出现时不再展开 | +| 构建 | Build、Check、Clippy 作用于工作区、软件包或单个目标;Doc(`--no-deps`)和 Clean 作用于工作区或软件包 | +| 运行 | 每个二进制和示例在构建窗口里有运行按钮(`cargo run --bin` / `--example`);编辑器打开 `src/main.rs`、`src/bin/*.rs`、`examples/*.rs` 时也有运行入口 | +| 诊断 | 构建输出里 `文件:行:列: error|warning: 消息` 形式的内容显示为问题 | +| 依赖 | 按 `cargo tree` 的样子列出依赖图;同一个软件包再次出现时不展开 | | 同步 | `Cargo.toml`、`Cargo.lock`、`.cargo/config(.toml)`、`rust-toolchain(.toml)` 变化后重新读取 | -| 调试 | 构建窗口里二进制和示例的「调试」:先构建,再用 CodeLLDB 启动程序,支持断点、单步、调用栈、变量,程序输出显示在调试控制台 | -| 新建项目 | 「新建项目」里的 Rust:选择 Cargo,选二进制或库,生成 `Cargo.toml`、`.gitignore` 和 `src/main.rs` 或 `src/lib.rs`,不运行 `cargo new` | -| 工具链 | 在常见位置找到 cargo、rustup 和 rust-analyzer;项目可以固定用其中一个 Cargo 构建和运行 | +| 调试 | 二进制和示例的「调试」:先构建,再用 CodeLLDB 启动,支持断点、单步、调用栈、变量 | +| 新建项目 | 选择 Cargo,选二进制或库,生成 `Cargo.toml`、`.gitignore` 和 `src/main.rs` 或 `src/lib.rs` | +| 工具链 | 找到电脑上的 cargo、rustup 和 rust-analyzer;项目可以固定用其中一个 Cargo | +| 设置预览 | Rust 语言页和 Cargo 构建工具页画出设置的效果,见下文“设置预览” | ## 设置和构建选项 -**插件设置**(设置 → 插件 → Rust Support →「设置」,也显示在「语言与框架 › Rust」页): +**插件设置**(设置 → 插件 → Rust Support →「设置」,也显示在「语言与框架 › Rust」页),开关默认都开启: -| 设置 | 生效方式 | 说明 | +| 设置 | 生效 | 说明 | | --- | --- | --- | -| Check on save | 立即 | 保存 Rust 文件时运行 Cargo 检查,把结果显示为诊断 | -| Check command | 立即 | 保存时检查用 `cargo check` 还是 `cargo clippy`;Clippy 多报告它的 lint,耗时更长 | -| Install rust-analyzer with rustup | 下次启动语言服务器 | 项目的 rustup 工具链缺少 rust-analyzer 时,先运行 `rustup component add rust-analyzer rust-src` 再启动它;需要联网 | +| Check on save | 立即 | 保存 Rust 文件时运行 Cargo 检查(`checkOnSave`) | +| Check command | 立即 | 用 `cargo check`(默认)还是 `cargo clippy`;Clippy 多报告 lint,耗时更长(`check.command`) | +| Expand procedural macros | 语言服务器下次启动 | 展开 `derive(Serialize)`、`#[tokio::main]` 等过程宏,生成的代码才能补全和跳转;开启时也会运行构建脚本(`procMacro.enable`) | +| Run build scripts | 语言服务器下次启动 | 运行 `build.rs`,分析它生成到 `OUT_DIR` 的代码和设置的 cfg(`cargo.buildScripts.enable`) | +| Highlight code in doc comments | 立即 | 高亮文档注释里的 Rust 代码和条目链接(`semanticHighlighting.doc.comment.inject.enable`) | +| Install rust-analyzer with rustup | 语言服务器下次启动 | 工具链缺 rust-analyzer 时先运行 `rustup component add rust-analyzer rust-src`,需要联网 | -前两项通过 `workspace/configuration` 发给正在运行的 rust-analyzer,不需要重启语言服务器。 +括号里是对应的 rust-analyzer 配置。 -**构建选项**(构建窗口 →「构建选项」),只对当前工作区生效: +**构建选项**(构建窗口 →「构建选项」),只对当前工作区生效,加到构建、检查、Clippy、Doc、运行和调试的命令里,Clean 只看 Release Profile: | 选项 | 传给 cargo 的内容 | | --- | --- | -| Release Profile | `--release`,程序输出到 `target/release` | -| Features | 选中的特性,按软件包列出;命令只传入它所构建的软件包的特性(`--features`) | +| Release Profile | `--release`,输出到 `target/release` | +| Features | 按软件包选中的特性,只传给所构建的软件包(`--features`) | | All Features | `--all-features`,忽略上面选择的特性 | | No Default Features | `--no-default-features` | | Offline | `--offline` | -选项会加到构建、检查、Clippy、Doc、运行和调试的命令里,Clean 只看 Release Profile。 +**工具链**(设置 →「构建、执行、部署」→「工具链」):Lithe 在 `~/.cargo` 和 Homebrew(Linux 上是 Linuxbrew)里查找 cargo、 +rustup 和 rust-analyzer,用 `--version` 读出版本。构建用的 Cargo 依次取:项目固定的、全局默认的、`CARGO_HOME/bin/cargo`、 +`PATH` 里的 `cargo`、找到的安装。选中的 Cargo 所在的 `bin` 目录加到命令的 `PATH` 前面。 + +## 设置预览 + +两块预览由插件后端按界面语言、外观和设置窗口宽度画出。它们用示例代码,不读取打开的项目;截图里的路径和版本是测试数据。 + +**语言与框架 › Rust**:顶部列出 Lithe 用的 cargo、rust-analyzer 和 rustup,点一行到「工具链」页更换。下面四张卡片各对应一项设置: + +| 卡片 | 开启时 | 关闭时 | +| --- | --- | --- | +| 展开过程宏 | `#[derive(Serialize)]` 下面画出生成的 `impl Serialize` | 显示“未展开” | +| 运行构建脚本 | `include!(concat!(env!("OUT_DIR"), …))` 正常解析 | 标出 `` `OUT_DIR` not set `` | +| 高亮文档注释中的代码 | 注释里的代码和 `` [`i32`] `` 链接按源码着色 | 整段是注释颜色 | +| 保存时检查 | `cargo check` 报告未使用变量;`cargo clippy` 另外报告 `len_zero` | 只有 rust-analyzer 自己的诊断 | + +Rust 语言设置页的工具链和效果预览,深色外观 + +还没应用的修改先画进预览:改动的卡片换成强调色边框,值前加圆点,右上角标出“含未应用的修改”。 +下图关掉了三个开关、把检查命令改成 `cargo clippy`: + +还没应用的修改先显示在预览里,浅色外观 + +**构建工具 › Cargo**:画出 Lithe 查找 cargo 的三步(项目环境、全局默认、自动发现)、rustup 选 Rust 版本的顺序, +以及 cargo 用在哪些流程。这一页没有设置项,换 cargo 要到「工具链」页。 -**工具链**(设置 →「构建、执行、部署」→「工具链」):插件声明了 `cargo`、`rustup` 和 `rust-analyzer` 三个工具, -Lithe 在 `~/.cargo`、Homebrew(`/opt/homebrew/Cellar`、`/usr/local/Cellar`,Linux 上是 Linuxbrew)里查找, -用 `--version` 读出版本,列在这里。构建用的 Cargo 按顺序取第一个可用的:项目固定的 Cargo、全局默认的 Cargo、 -`CARGO_HOME` 里的 `bin/cargo`、`PATH` 里的 `cargo`、找到的安装。选中的 Cargo 所在的 `bin` 目录加到命令的 `PATH` 前面。 +Cargo 构建工具页画出 Lithe 查找 cargo 的顺序,浅色外观 ## rust-analyzer -rust-analyzer 每次启动前,Lithe 都会问插件后端该怎样启动它(`rustAnalyzer.launch`),所以它跟着项目的工具链走: +每次启动 rust-analyzer 前,Lithe 都问插件后端怎样启动(`rustAnalyzer.launch`),所以它跟着项目的工具链走: | Lithe 找到的 | 怎样启动 | | --- | --- | -| 不是 rustup 代理的 rust-analyzer(在设置里选的,或单独安装的) | 直接启动它,`CARGO` 设为构建系统用的 Cargo | -| rustup | `rustup run <工具链> rust-analyzer`,工具链是 rustup 在项目目录里选出的那一个。工具链缺少 rust-analyzer 组件时,先用 `rustup component add` 装上它和 rust-src(可在设置里关闭) | +| 不是 rustup 代理的 rust-analyzer(设置里选的或单独安装的) | 直接启动,`CARGO` 设为构建系统用的 Cargo | +| rustup | `rustup run <项目的工具链> rust-analyzer`;缺少组件时先装上它和 rust-src(可在设置里关闭) | | 只有 rust-analyzer 的 rustup 代理 | 启动这个代理 | -| 都没有 | 报错,提示怎样安装 rust-analyzer | +| 都没有 | 报错,提示怎样安装 | -rustup 运行时带 `RUSTUP_AUTO_INSTALL=0`:只查询项目用哪个工具链时,不会顺便安装工具链。项目要求的工具链没有安装时, -错误信息里给出安装它的命令。工具链放在项目目录里时,它是项目代码,插件不启动它的 rust-analyzer。 +rustup 运行时带 `RUSTUP_AUTO_INSTALL=0`,不会顺便安装工具链;项目要求的工具链没装时,错误信息给出安装命令。 +工具链放在项目目录里时它属于项目代码,插件不启动它的 rust-analyzer。 ## 调试 -在构建窗口里,二进制或示例的运行按钮旁边有「调试」。点击后插件先用 `cargo build` 构建这个目标(带上构建选项), -再让 CodeLLDB 启动构建出的程序,在断点处停下。 +构建窗口里二进制或示例的「调试」会先用 `cargo build` 构建这个目标(带上构建选项),再让 CodeLLDB 启动程序。 -- 程序的工作目录是软件包所在的目录,运行参数和环境变量和运行时相同。 -- CodeLLDB 以 `sourceLanguages: ["rust"]` 启动,变量按 Rust 的类型显示。 -- 程序结束后会话自动结束,输出留在调试控制台里。 -- 目前只支持启动调试(launch),不支持附加到运行中的进程,也不支持调试测试。 -- 从经过符号链接的路径打开项目时(例如 macOS 上从 `/tmp` 打开,`/tmp` 是 `/private/tmp` 的链接),断点不会停下: - rustc 在调试信息里记下的是解析掉链接后的真实路径,CodeLLDB 按完整路径匹配断点。请从真实路径打开项目。 +- 工作目录是软件包所在目录,参数和环境变量和运行时相同;变量按 Rust 类型显示;程序结束后会话自动结束,输出留在调试控制台。 +- 只支持启动调试,不支持附加到进程,也不支持调试测试。 +- 从符号链接路径打开项目时(如 macOS 的 `/tmp`),断点不会停下:调试信息里记的是真实路径。请从真实路径打开项目。 -**CodeLLDB 不在插件包里。** 第一次调试前,打开 **设置 → 插件 → 已安装**,选中 Rust Support,切到 **功能**: -调试能力卡片上显示“未找到 codelldb”,旁边有 **安装** 按钮。点击后 Lithe 从 -[vadimcn/codelldb](https://github.com/vadimcn/codelldb/releases/tag/v1.12.3) 的 1.12.3 版下载对应平台的 VSIX(Apple Silicon 的约 45 MB), -核对插件清单里写死的 SHA-256,解压到 Lithe 给插件的状态目录,之后启动调试时直接用 `extension/adapter/codelldb`。 -卸载插件时一起删除。 +**CodeLLDB 不在插件包里。** 第一次调试前,在 **设置 → 插件 → 已安装 → Rust Support → 功能** 的调试卡片上点 **安装**。 +Lithe 从 [vadimcn/codelldb 1.12.3](https://github.com/vadimcn/codelldb/releases/tag/v1.12.3) 下载对应平台的 VSIX +(Apple Silicon 约 45 MB),核对清单里的 SHA-256,解压到插件的状态目录;卸载插件时一起删除。 | 平台 | CodeLLDB 包 | | --- | --- | -| macOS Apple Silicon | `codelldb-darwin-arm64.vsix` | -| macOS Intel | `codelldb-darwin-x64.vsix` | +| macOS Apple Silicon / Intel | `codelldb-darwin-arm64.vsix` / `codelldb-darwin-x64.vsix` | | Windows x64 | `codelldb-win32-x64.vsix` | -| Linux x64、ARM64 | `codelldb-linux-x64.vsix`、`codelldb-linux-arm64.vsix` | +| Linux x64 / ARM64 | `codelldb-linux-x64.vsix` / `codelldb-linux-arm64.vsix` | -CodeLLDB 1.12.3 没有发布 Windows ARM64 的包,那里没有调试,其他功能可用。也可以自己把 `codelldb` 放进 Lithe -能看到的 `PATH`,Lithe 会直接用它。 +CodeLLDB 1.12.3 没有 Windows ARM64 的包,那里不能调试,其他功能可用。也可以把自己的 `codelldb` 放进 `PATH`,Lithe 会直接用它。 ## 新建项目 -「新建项目」对话框左侧有 **Rust**。可以填写: +「新建项目」对话框左侧选 **Rust**: | 字段 | 说明 | | --- | --- | -| Cargo | 项目构建和运行用的 Cargo,从「工具链」找到的安装里选。创建后项目固定使用它(记在项目的 `.lithe/toolchains/local.json`),以后可以在「工具链」里修改。没有找到 Cargo 时留空,不影响创建 | -| Crate | Binary(默认)生成打印 `Hello, Rustacean!` 的 `src/main.rs`;Library 生成带一个测试的 `src/lib.rs`。创建后打开这个文件 | -| Package name | 写进 `Cargo.toml` 的 `name`,也是程序的名字。默认是小写的项目名;只能用字母、数字、`-` 和 `_`,以字母开头,项目名里有空格时需要改掉 | -| Edition(高级) | 2024(默认)或 2021。Edition 2024 需要 Rust 1.85 或更新版本 | +| Cargo | 从「工具链」找到的安装里选,创建后项目固定使用它(`.lithe/toolchains/local.json`);没找到时留空,不影响创建 | +| Crate | Binary(默认)生成打印 `Hello, Rustacean!` 的 `src/main.rs`;Library 生成带一个测试的 `src/lib.rs` | +| Package name | `Cargo.toml` 的 `name`,默认是小写的项目名;只能用字母、数字、`-` 和 `_`,以字母开头 | +| Edition(高级) | 2024(默认,需要 Rust 1.85+)或 2021 | -`Cargo.toml` 由模板直接写出,不运行 `cargo new` 或 `cargo init`,所以创建项目不需要联网,也不需要先装好 cargo。 -生成的 `.gitignore` 忽略 `/target`。这些字段目前只有英文名称:插件语言文件还不能翻译新建项目的字段。 +文件由模板直接写出,不运行 `cargo new`,不需要联网,也不需要先装好 cargo;`.gitignore` 忽略 `/target`。 +这些字段目前只有英文名称:插件语言文件还不能翻译新建项目的字段。 ## 依赖的程序 | 程序 | 用途 | 查找方式 | | --- | --- | --- | -| `cargo` | 读取软件包、构建、检查、运行、依赖、调试前构建 | 「工具链」选出的 Cargo,最后找 `PATH` 里的 `cargo` | -| `rustup` | 选项目的工具链、启动和安装 rust-analyzer | 「工具链」选出的 rustup,最后找 `PATH` 里的 `rustup` | +| `cargo` | 读取软件包、构建、检查、运行、依赖、调试前构建 | 「工具链」选出的 Cargo,最后找 `PATH` | +| `rustup` | 选项目的工具链、启动和安装 rust-analyzer | 「工具链」选出的 rustup,最后找 `PATH` | | `rust-analyzer` | 代码智能 | 见上文“rust-analyzer” | -| `codelldb`(CodeLLDB 1.12.3) | 调试 | 先找在 Lithe 里安装时记下的目录,再找 `PATH` 里的 `codelldb` | +| `codelldb`(1.12.3) | 调试 | 先找在 Lithe 里安装的,再找 `PATH` | -安装插件时 Lithe 会列出这些程序和插件需要的权限(启动插件后端、启动语言服务器、运行构建命令、启动调试器、 -创建项目、读取工作区元数据、安装插件所需的命令行工具),确认后才会安装。cargo 和 rustup 需要自己安装, -推荐用 [rustup](https://rustup.rs)。 +cargo 和 rustup 需要自己安装,推荐用 [rustup](https://rustup.rs)。安装插件时 Lithe 会列出这些程序和插件需要的权限,确认后才安装。 ## 安装 -1. 从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-rust/releases) 下载对应平台的包:macOS 用 `rust-support-<版本>-darwin.zip`, - Windows x64 用 `rust-support-<版本>-windows-x64.zip`,Windows ARM64 用 `rust-support-<版本>-windows-arm64.zip`。 -2. 在 Lithe 中打开 **设置 → 插件**,点击页面标题栏右侧的 **从文件安装…**,选中这个 zip,核对 SHA-256 和权限后确认。 -3. 打开含 `Cargo.toml` 的项目。构建窗口会出现 Cargo,打开 `.rs` 文件时启动 rust-analyzer。 - -darwin 包同时支持 Apple Silicon 和 Intel Mac。三个包只有后端程序不同:macOS 是通用二进制 `bin/backend`, -Windows 是对应架构的 `bin/backend.exe`。 +1. 从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-rust/releases) 下载对应平台的包:macOS 用 `rust-support-<版本>-darwin.zip`(Apple Silicon 和 Intel 通用), + Windows 用 `rust-support-<版本>-windows-x64.zip` 或 `rust-support-<版本>-windows-arm64.zip`。 +2. 在 Lithe 的 **设置 → 插件** 里点标题栏右侧的 **从文件安装…**,选中 zip,核对 SHA-256 和权限后确认。 +3. 打开含 `Cargo.toml` 的项目:构建窗口出现 Cargo,打开 `.rs` 文件时启动 rust-analyzer。 ## 工作方式 -- 插件后端是一个用 [Rust 插件 SDK](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/shared/plugins/sdk/rust) - 写的程序,Lithe 按两种身份分别启动它:插件后端回答 `rustAnalyzer.launch`;Cargo 构建提供者回答 +- 后端用 [Rust 插件 SDK](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/shared/plugins/sdk/rust) 编写, + Lithe 按两种身份启动它:插件后端回答 `rustAnalyzer.launch` 和 `settings.view`;Cargo 构建提供者回答 `lithe/build/model`、`dependencies`、`execute`、`prepareRun`、`prepareDebug` 和 `runEntrypoints`。 -- 后端不保存状态,也不写文件:每次请求都重新问 Cargo 或 rustup。Cargo 只写项目的 target 目录,rustup 只写它自己的工具链。 -- 运行由后端给出 `cargo run` 的命令行,Lithe 运行它;调试由后端先构建,再把程序路径交给 Lithe,Lithe 按 - `debugAdapters` 的声明启动 CodeLLDB(`stdio` 传输)。 -- rust-analyzer 由 Lithe 按 `languageServers` 的声明启动,命令行由后端给出;插件设置通过 `workspaceConfiguration` - 里的 `${setting:}` 传给它。 -- CodeLLDB 由 Lithe 按 `commandInstallers` 的 `download` 声明下载、校验和解压到插件状态目录。 -- 新建项目由 `projectGenerators` 声明,Lithe 把 `templates/rust/` 里的模板展开到新目录;模板名以 `dot-` 开头的文件生成为点文件。 +- 后端不保存状态,也不写文件,每次请求都重新问 Cargo 或 rustup。Cargo 只写项目的 target 目录,rustup 只写它自己的工具链。 +- 设置预览由两个 `settingRegions`(`language`、`cargo`)声明,`settings.view` 按发来的语言、宽度、已保存设置和草稿画出画布,只读不写。 +- rust-analyzer 按 `languageServers` 的声明启动,插件设置通过 `workspaceConfiguration` 里的 `${setting:}` 传给它。 +- 调试时后端先构建,Lithe 再按 `debugAdapters` 的声明启动 CodeLLDB(`stdio` 传输);CodeLLDB 按 `commandInstallers` 的 `download` 声明下载。 +- 新建项目由 `projectGenerators` 声明,模板在 `templates/rust/`,以 `dot-` 开头的文件生成为点文件。 - 插件目录在运行时保持只读。 ## 诊断日志 -后端用 Rust SDK 接入 Lithe 的日志协议,SDK 自动记录每次请求的成功或失败;编辑器每次打开 Rust 文件都会问运行入口, -这一项的成功不记录。插件只在真的降级时上报一次 WARN: +后端用 Rust SDK 接入 Lithe 的日志协议,SDK 自动记录每次请求的成败(编辑器打开 Rust 文件时询问运行入口的成功不记录)。 +插件只在真的降级时上报一次 WARN: | 类别 | 什么时候 | | --- | --- | | `cargo.membersOutsideFolder` | 工作区有成员在打开的文件夹之外,模型里不列出它们 | | `cargo.dependencyTreeTruncated` | 依赖树超过 Core 的上限,后面的依赖没有列出 | -| `cargo.outputTruncated` | 构建任务的输出超过 Core 保留的 32 MiB,最终结果被截断(构建输出窗口里仍是完整的) | -| `rust.noWorkspaceFolder` | 启动 rust-analyzer 时 Lithe 没有给出工作区文件夹,按 rustup 的默认工具链启动 | +| `cargo.outputTruncated` | 构建输出超过 Core 保留的 32 MiB,最终结果被截断(构建输出窗口里仍完整) | +| `rust.noWorkspaceFolder` | 启动 rust-analyzer 时没有工作区文件夹,按 rustup 的默认工具链启动 | | `rust.rustSrcMissing` | rust-analyzer 装上了,但 rust-src 没装上,标准库的跳转和补全不可用 | -rust-analyzer 和 CodeLLDB 由 Lithe 启动,它们的启动结果由 Lithe 记在插件的日志通道里;rust-analyzer 的 -`window/logMessage` 和有界的 stderr 进语言服务日志,CodeLLDB 和被调试程序的输出只显示在调试控制台里。 -cargo 的输出显示在构建输出里,不复制进诊断日志。 +rust-analyzer 和 CodeLLDB 的启动结果由 Lithe 记在插件的日志通道;rust-analyzer 的 `window/logMessage` 和有界的 stderr +进语言服务日志。CodeLLDB、被调试程序和 cargo 的输出只显示在调试控制台或构建输出里,不进诊断日志。 ## 本地打包 -需要 Rust 工具链和对应的 target(`rustup target add`):macOS 上构建 darwin(Apple Silicon 和 Intel 合成一个通用二进制并做 -ad-hoc 签名),Windows 上构建 windows-x64 和 windows-arm64。再用 Node.js 22+ 和 `zip`(macOS 或 Linux)打包: +需要 Rust 工具链和对应的 target(`rustup target add`)、Node.js 22+ 和 `zip`。macOS 上构建 darwin(通用二进制,ad-hoc 签名), +Windows 上构建 windows-x64 和 windows-arm64: ```bash (cd backend && cargo test --locked) # 后端单元测试 @@ -189,57 +191,42 @@ node scripts/package.mjs --platforms darwin # CI 和发布时三个平台都 node --test scripts/package/*.test.mjs # 核对 dist/ 里的每个包 ``` -输出 `dist/rust-support-<版本>-<平台>.zip` 和它们的 SHA-256。每个包带 `bin/backend`(Windows 是 `bin/backend.exe`, -包里的 `plugin.json` 相应改写启动路径)和列出后端所用 crate 许可证的 `THIRD_PARTY_LICENSES.txt`,不带 CodeLLDB。 -本地开发时,用 **设置 → 插件 → 从文件安装…** 选择这个 zip 安装。 - -`plugin.json` 的完整格式见 Rust Core 仓库里的 +输出 `dist/rust-support-<版本>-<平台>.zip` 和 SHA-256。包里有后端程序和后端所用 crate 的 `THIRD_PARTY_LICENSES.txt`, +不带 CodeLLDB。`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) 和[语言服务器插件生命周期](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/guides/lsp-plugin-lifecycle.md)。 ## 宿主端到端测试 -`e2e/host/` 里的测试通过 Lithe 桌面端自己的测试工具(宿主的 `desktop/internal/workbench` 和 `desktop/internal/projectgen` 包) -安装真实插件包,像用户一样操作构建窗口、编辑器和调试窗口。主仓库不读取本仓库,`e2e/host/lithe-host.json` -记录测试最后一次通过时的宿主版本。 +`e2e/host/` 里的测试用 Lithe 桌面端自己的测试工具安装真实插件包,操作构建窗口、编辑器、调试窗口和设置页的预览。 +`e2e/host/lithe-host.json` 记录测试最后一次通过时的宿主版本,主仓库不读取本仓库。 -需要 Node.js 22+、Go、Rust 工具链(构建宿主固定的 Rust Core)、`git`,以及测试要用的 `cargo`、`rustup` 和 -rust-analyzer 组件(`rustup component add rust-analyzer`;测试不会替你安装)。调试测试会联网下载 CodeLLDB: +需要 Node.js 22+、Go、Rust 工具链、`git`,以及装好 rust-analyzer 组件的 rustup(测试不会替你安装);调试测试会联网下载 CodeLLDB: ```bash node scripts/build-backend.mjs darwin node scripts/package.mjs --platforms darwin -LITHE_TEST_RUST_PLUGIN_ARCHIVE="$PWD/dist/rust-support-0.1.0-darwin.zip" node scripts/e2e-host.mjs +LITHE_TEST_RUST_PLUGIN_ARCHIVE="$PWD/dist/rust-support-0.1.1-darwin.zip" node scripts/e2e-host.mjs ``` -插件包路径要写绝对路径。脚本把固定版本的宿主(只取 `desktop/` 和 `scripts/`)检出到 `.artifacts/lithe-host`, -复制 `e2e/host/desktop/` 下的测试,再在那里运行宿主的 `scripts/desktop/desktop-go.sh test`;第一次运行会克隆并构建 -Rust Core,`LITHE_CORE_RUST_DIR` 可以指向本地的 Core 检出。`--source <本地 Lithe 检出>` 从本地仓库检出宿主, -`--ref <分支或 commit>` 换一个宿主版本试跑,`--run <正则>` 只跑部分测试。测试用的是宿主内部的测试工具, -升级 `lithe-host.json` 的 `revision` 时可能要同步修改测试。 +插件包路径要写绝对路径。脚本把固定版本的宿主检出到 `.artifacts/lithe-host`,复制 `e2e/host/desktop/` 下的测试后运行; +第一次会克隆并构建 Rust Core,`LITHE_CORE_RUST_DIR` 可以指向本地的 Core 检出。`--source <本地 Lithe 检出>`、 +`--ref <分支或 commit>`、`--run <正则>` 分别换宿主来源、换宿主版本、只跑部分测试。升级 `revision` 时可能要同步修改测试。 ## 功能矩阵 -插件各项能力在 macOS 和 Windows 上的实现与验收状态见 [docs/feature-matrix.md](docs/feature-matrix.md)。 -Lithe 主仓库的功能矩阵不收录插件能力,改动插件行为时在同一个 PR 里更新这一页。 +各项能力在 macOS 和 Windows 上的实现与验收状态见 [docs/feature-matrix.md](docs/feature-matrix.md),改动插件行为时在同一个 PR 里更新它。 ## 发布新版本 -1. 同时修改 `io.github.lithe-idea.rust-support/plugin.json` 和 `backend/Cargo.toml` 的 `version`:修复升修订号(0.1.0 → 0.1.1), - 加功能升次版本号(0.1.0 → 0.2.0);只有特别大的革新才升主版本号,由维护者决定。新功能要求还没有发布的 - 宿主能力或 Core 版本时,照样升次版本号,并作为预发布版本发布(见第 3 步)。合入 `main`。 -2. 推送同名标签: - - ```bash - git tag v0.1.0 && git push origin v0.1.0 - ``` - -3. `Release` 工作流会核对标签与版本一致、打包并发布 Release(说明里附 SHA-256 和 - `docs/releases/v<版本>.md`)。`release.yml` 里 `PRERELEASE_TAGS` 列出的版本会标为预发布版本: - 目前是依赖还没发布的下载型命令安装器(1lck/Lithe-IDEA#2241)和 rustup 链接修复(1lck/Lithe-IDEA#2242)的 `v0.1.0`。 -4. Lithe Store 的自动追踪会发现稳定版本并开合并请求,合并后用户即可在 Lithe 中更新。自动追踪会跳过预发布版本; - 需要收录时在 Store 中手工提交条目,并使用已发布 ZIP 的实际 SHA-256。 +1. 同时修改 `io.github.lithe-idea.rust-support/plugin.json` 和 `backend/Cargo.toml` 的 `version`:修复升修订号,加功能升次版本号, + 特别大的革新才升主版本号。依赖还没发布的宿主能力时照样升次版本号,作为预发布版本发布。合入 `main`。 +2. 推送同名标签,例如 `git tag v0.1.1 && git push origin v0.1.1`。 +3. `Release` 工作流核对标签与版本、打包并发布 Release,说明里附 SHA-256 和 `docs/releases/v<版本>.md`。 + `release.yml` 的 `PRERELEASE_TAGS` 里的版本标为预发布,目前只有 `v0.1.0`。 +4. Lithe Store 的自动追踪会为稳定版本开合并请求,合并后用户即可更新。预发布版本要收录时,在 Store 中手工提交条目, + 并使用已发布 ZIP 的实际 SHA-256。 ## 许可 diff --git a/backend/Cargo.lock b/backend/Cargo.lock index b9c9099..624c7f3 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -56,7 +56,7 @@ dependencies = [ [[package]] name = "rust-support-backend" -version = "0.1.0" +version = "0.1.1" dependencies = [ "libc", "lithe-plugin-sdk", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 9bb8f83..b36898a 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,12 +1,12 @@ [package] name = "rust-support-backend" # Kept equal to the plugin's version; scripts/package.mjs refuses a mismatch. -version = "0.1.0" +version = "0.1.1" edition = "2021" license = "Apache-2.0" rust-version = "1.87" publish = false -description = "The Cargo build provider of the Rust Support plugin for Lithe." +description = "The backend of the Rust Support plugin for Lithe: the Cargo build provider and the settings previews." [[bin]] name = "backend" diff --git a/backend/src/main.rs b/backend/src/main.rs index 7121b1f..0dd4da2 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -3,7 +3,10 @@ //! //! - The plugin backend answers the `rustAnalyzer.launch` function: the //! rust-analyzer command line, following the project's rustup toolchain -//! and adding the rust-analyzer component when it is missing. +//! and adding the rust-analyzer component when it is missing. It also +//! draws the views of the settings regions (`settings.view`): the Rust +//! page's toolchain rows and a preview of the rust-analyzer options, and +//! the order in which the Cargo page's cargo is looked for. //! - The Cargo build provider answers the host's `lithe/build/*` requests //! for the `cargo` build system of `plugin.json`: //! @@ -32,6 +35,7 @@ mod options; mod paths; mod process; mod request; +mod view; use lithe_plugin_sdk::Backend; use paths::Workspace; @@ -60,6 +64,7 @@ fn main() { analyzer::answer(¶ms, context) }) .expect("the function ID is valid"); + view::register(&mut backend).expect("the view ID is valid"); let handlers = Arc::clone(&workspace); let current = move || paths::current(&handlers); diff --git a/backend/src/view/language.rs b/backend/src/view/language.rs new file mode 100644 index 0000000..14859f2 --- /dev/null +++ b/backend/src/view/language.rs @@ -0,0 +1,686 @@ +//! The Rust language page's region: the toolchain rows the host draws, then +//! a preview of what each rust-analyzer 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. + +use super::scene::{ + code, column, group, pair, path, pill, rect, runs, squiggle, text, text_width, token, Node, + CAPTION, STRONG, +}; +use super::settings::{Check, Settings}; +use super::words::Words; +use serde_json::{json, Value}; + +pub const CANVAS_ID: &str = "rust-analyzer-preview"; +pub const TOOLCHAIN_ID: &str = "toolchain"; + +/// The tools the toolchain section lists, as `requiresTools` names them: the +/// host draws each as the Toolchains page does, with its version and path. +pub const TOOLS: [&str; 3] = ["cargo", "rust-analyzer", "rustup"]; + +/// The settings the cards show; a draft of any of them marks the preview. +pub const SETTINGS: [&str; 5] = [ + "procMacro", + "buildScripts", + "docCommentInject", + "checkOnSave", + "checkCommand", +]; + +/// The scene's width for a host that reports none. +pub const DEFAULT_WIDTH: f64 = 610.0; +/// The narrowest card: the longest build script line ends 263 units into the +/// box, and the pill keeps room beside the longest 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 macro and build script cards and of the doc +/// comment and check ones: the macro's expansion needs the most. +const BOX_H: [f64; 2] = [124.0, 108.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 + /// macro and build script ones, or the doc comment and check 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 string() -> Value { + pair("#067D17", "#6AAB73") +} +fn number() -> Value { + pair("#1750EB", "#2AACB8") +} +fn attribute() -> Value { + pair("#9E880D", "#B3AE60") +} +fn doc() -> Value { + pair("#8C8C8C", "#5F826B") +} +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 toolchain rows, 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": TOOLCHAIN_ID, + "title": words.toolchain_title, + "info": words.toolchain_info, + "children": tools, + }), + canvas(settings, words, width), + ] +} + +/// 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 build_note = if settings.build_scripts { + words.build_on + } else if settings.proc_macro { + words.build_implied + } else { + words.build_off + }; + let (check, check_note) = match (settings.check_on_save, settings.check_command) { + (false, _) => (words.off, words.check_off), + (true, Check::Check) => ("cargo check", words.check_check), + (true, Check::Clippy) => ("cargo clippy", words.check_clippy), + }; + [ + ( + switch(settings.proc_macro), + settings.proc_macro, + if settings.proc_macro { + words.macro_on + } else { + words.macro_off + }, + ), + ( + switch(settings.build_scripts), + settings.build_scripts, + build_note, + ), + ( + switch(settings.doc_comment_inject), + settings.doc_comment_inject, + if settings.doc_comment_inject { + words.doc_on + } else { + words.doc_off + }, + ), + (check, settings.check_on_save, check_note), + ] +} + +/// 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 [macros, build, docs, check] = values(settings, words); + let cards = [ + Card { + title: words.macro_title, + value: macros.0, + lit: macros.1, + note: macros.2, + changed: settings.is_changed("procMacro"), + preview: macro_preview(settings.proc_macro, words, box_w), + }, + Card { + title: words.build_title, + value: build.0, + lit: build.1, + note: build.2, + // Procedural macros decide this card while build scripts are off. + changed: settings.is_changed("buildScripts") + || (!settings.build_scripts && settings.is_changed("procMacro")), + preview: build_preview(settings.runs_build_scripts(), box_w), + }, + Card { + title: words.doc_title, + value: docs.0, + lit: docs.1, + note: docs.2, + changed: settings.is_changed("docCommentInject"), + preview: doc_preview(settings.doc_comment_inject), + }, + Card { + title: words.check_title, + value: check.0, + lit: check.1, + note: check.2, + changed: settings.any_changed(&["checkOnSave", "checkCommand"]), + preview: check_preview( + settings.check_on_save.then_some(settings.check_command), + box_w, + ), + }, + ]; + 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) +} + +/// A derive on a struct in a box `box_w` wide and, when procedural macros +/// expand, the impl it generates in a dashed frame under it. The impl is the +/// head of what serde's derive writes. +fn macro_preview(expand: bool, words: &Words, box_w: f64) -> Vec { + const TOP: f64 = 50.0; + const HEIGHT: f64 = 62.0; + let frame_x = CODE_X - 8.0; + let frame_w = box_w - frame_x - 8.0; + let mut nodes = numbered(vec![ + vec![ + ("#[derive(", attribute()), + ("Serialize", plain()), + (")]", attribute()), + ], + vec![ + ("struct ", keyword()), + ("User { name: ", plain()), + ("String", plain()), + (" }", plain()), + ], + ]); + if !expand { + nodes.push( + rect(frame_x, TOP, frame_w, HEIGHT) + .radius(4.0) + .stroke(token("$line"), 1.0) + .dash(&[4.0, 3.0]), + ); + nodes.push( + text( + frame_x + frame_w / 2.0, + TOP + HEIGHT / 2.0 + 4.0, + words.macro_not_expanded, + "caption", + ) + .align("center") + .color(token("$textMuted")), + ); + return nodes; + } + nodes.push( + rect(frame_x, TOP, frame_w, HEIGHT) + .radius(4.0) + .fill(token("$accent")) + .opacity(0.06), + ); + nodes.push( + rect(frame_x, TOP, frame_w, HEIGHT) + .radius(4.0) + .stroke(token("$accent"), 1.0) + .dash(&[4.0, 3.0]) + .opacity(0.7), + ); + // The caption sits on the frame's top edge, over a patch of the box's + // color, as a legend does. + let legend_end = frame_x + frame_w - 8.0; + let legend_w = text_width(words.macro_expanded, CAPTION); + nodes.push(rect(legend_end - legend_w - 4.0, TOP - 6.0, legend_w + 8.0, 11.0).fill(editor())); + nodes.push( + text(legend_end, TOP + 4.0, words.macro_expanded, "caption") + .align("end") + .color(token("$accent")), + ); + let lines = [ + vec![ + ("impl ", keyword()), + ("Serialize ", plain()), + ("for ", keyword()), + ("User {", plain()), + ], + vec![ + (" fn ", keyword()), + ("serialize", function()), + ("(&", plain()), + ("self", keyword()), + (", …)", plain()), + ], + vec![("}", plain())], + ]; + for (index, line) in lines.iter().enumerate() { + nodes.extend(code(CODE_X, TOP + 18.0 + index as f64 * LINE, line)); + } + nodes +} + +/// Code a build script generates into `OUT_DIR`, included in a box `box_w` +/// wide. Without build scripts `OUT_DIR` is unset, and rust-analyzer reports +/// it with its own message; the function the file defines stays unknown. +fn build_preview(runs_build_scripts: bool, box_w: f64) -> Vec { + let greet = if runs_build_scripts { + function() + } else { + plain() + }; + let mut nodes = numbered(vec![ + vec![ + ("include!", function()), + ("(", plain()), + ("concat!", function()), + ("(", plain()), + ], + vec![ + (" ", plain()), + ("env!", function()), + ("(", plain()), + ("\"OUT_DIR\"", string()), + ("), ", plain()), + ("\"/gen.rs\"", string()), + ("));", plain()), + ], + vec![ + ("fn ", keyword()), + ("main", function()), + ("() { ", plain()), + ("greet", greet), + ("() }", plain()), + ], + ]); + if runs_build_scripts { + return nodes; + } + nodes.push(underline(1, 4, 19, "$error")); + nodes.push(message_bar( + CODE_TOP + 2.0 * LINE + 12.0, + box_w, + Severity::Error, + &[ + vec![( + "`OUT_DIR` not set, build scripts may", + token("$textSecondary"), + )], + vec![("have failed to run", token("$textSecondary"))], + ], + )); + nodes +} + +/// A doc comment with an example and a link to `i32`, and the function it +/// documents. With injection on, rust-analyzer highlights the example's code +/// and the link as source; off, the comment keeps one color. +fn doc_preview(inject: bool) -> Vec { + let (link, example): (Value, Vec<(&str, Value)>) = if inject { + ( + keyword(), + vec![ + ("/// ", doc()), + ("let ", keyword()), + ("two = ", plain()), + ("add_one", function()), + ("(", plain()), + ("1", number()), + (");", plain()), + ], + ) + } else { + (doc(), vec![("/// let two = add_one(1);", doc())]) + }; + numbered(vec![ + vec![ + ("/// Adds one to an [`", doc()), + ("i32", link), + ("`].", doc()), + ], + vec![("/// ```", doc())], + example, + vec![("/// ```", doc())], + vec![ + ("fn ", keyword()), + ("add_one", function()), + ("(x: ", plain()), + ("i32", keyword()), + (") -> ", plain()), + ("i32", keyword()), + (" {", plain()), + ], + ]) +} + +/// A function with an unused variable and a length compared to zero, in a +/// box `box_w` wide, and what the check on save reports: nothing when it is +/// off, rustc's warning for `cargo check`, and Clippy's `len_zero` too for +/// `cargo clippy`. The messages are the tools' own. +fn check_preview(check: Option, box_w: f64) -> Vec { + let mut nodes = numbered(vec![ + vec![ + ("fn ", keyword()), + ("empty", function()), + ("(v: &[", plain()), + ("u8", keyword()), + ("]) -> ", plain()), + ("bool", keyword()), + (" {", plain()), + ], + vec![ + (" let ", keyword()), + ("n = v.", plain()), + ("len", function()), + ("();", plain()), + ], + vec![ + (" v.", plain()), + ("len", function()), + ("() == ", plain()), + ("0", number()), + ], + vec![("}", plain())], + ]); + let Some(check) = check else { + return nodes; + }; + nodes.push(underline(1, 8, 9, "$warning")); + let (code, message) = match check { + Check::Check => ("warning", ": unused variable: `n`"), + Check::Clippy => { + nodes.push(underline(2, 4, 16, "$warning")); + ("len_zero", ": length comparison to zero") + } + }; + nodes.push(message_bar( + CODE_TOP + 3.0 * LINE + 10.0, + box_w, + Severity::Warning, + &[vec![ + (code, token("$text")), + (message, token("$textSecondary")), + ]], + )); + nodes +} + +#[derive(Clone, Copy)] +enum Severity { + Warning, + 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::Warning => vec![ + rect(0.0, 0.0, bar_w, bar_h) + .radius(5.0) + .fill(pair("#FFF4DE", "#3B3124")), + path("M13 5 L19 16 H7 Z".into()).fill(token("$warning")), + path("M13 8.6 V12 M13 14 V14.1".into()) + .stroke("#FFFFFF", 1.4) + .set("cap", "round"), + ], + 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 words = words::for_language(language); + let switches = [words.macro_title, words.build_title, words.doc_title] + .into_iter() + .flat_map(|title| [(title, words.on), (title, words.off)]); + let check = [words.off, "cargo check", "cargo clippy"] + .into_iter() + .map(|value| (words.check_title, value)); + for (title, value) in switches.chain(check) { + // 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); + for note in [ + w.macro_on, + w.macro_off, + w.build_on, + w.build_off, + w.build_implied, + w.doc_on, + w.doc_off, + w.check_off, + w.check_check, + w.check_clippy, + ] { + let width = text_width(note, CAPTION); + assert!(width <= MIN_CARD_W - 24.0, "{language}: {note} ({width})"); + } + } + } + + #[test] + fn the_longest_code_line_fits_the_narrowest_box() { + let box_w = MIN_CARD_W - 2.0 * BOX_X; + let longest = " env!(\"OUT_DIR\"), \"/gen.rs\"));".chars().count(); + assert!( + column(CODE_X, longest) <= box_w, + "{}", + column(CODE_X, longest) + ); + } +} diff --git a/backend/src/view/mod.rs b/backend/src/view/mod.rs new file mode 100644 index 0000000..8a128b1 --- /dev/null +++ b/backend/src/view/mod.rs @@ -0,0 +1,704 @@ +//! 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; rust-analyzer, Cargo +//! and the toolchain 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 Rust language page and the one on the Cargo 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 CARGO_REGION: &str = "cargo"; + +/// The tool the Cargo page's row shows, as `toolDefinitions` names it. +const CARGO_TOOL: &str = "cargo"; + +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)) + } + CARGO_REGION => Ok(( + vec![ + json!({ "type": "tool", "tool": CARGO_TOOL }), + resolution::canvas(words, event.width), + ], + 0, + )), + _ => Err(unknown_region()), + } +} + +fn unknown_region() -> PluginError { + PluginError::new( + "rust.view.unknownRegion", + "This view draws the Rust 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 + } + + fn settings_cases() -> Vec<(Value, Value)> { + let mut cases = Vec::new(); + for proc_macro in [true, false] { + for build_scripts in [true, false] { + cases.push(( + json!({ "procMacro": proc_macro, "buildScripts": build_scripts }), + json!({}), + )); + } + } + for (on_save, command) in [(true, "check"), (true, "clippy"), (false, "clippy")] { + cases.push(( + json!({ "checkOnSave": on_save, "checkCommand": command, "docCommentInject": false }), + json!({ "docCommentInject": true }), + )); + } + 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, CARGO_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), (CARGO_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), + (CARGO_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 cargo = nodes(CARGO_REGION, "en", json!({}), json!({})); + assert_eq!(cargo.len(), 2); + assert_eq!(cargo[0], json!({ "type": "tool", "tool": "cargo" })); + assert_eq!(canvas(&cargo)["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.rust-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, CARGO_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:?}"); + } + } + } + } + + #[test] + fn the_macro_preview_shows_the_expansion_only_while_macros_expand() { + let shown = |proc_macro: bool| { + words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "procMacro": proc_macro }), + json!({}), + )) + }; + let on = shown(true); + assert!(on.contains("#[derive(Serialize)]")); + assert!(on.contains("impl Serialize for User {") && on.contains("from derive")); + let off = shown(false); + assert!(off.contains("#[derive(Serialize)]") && !off.contains("impl Serialize")); + assert!(off.contains("Not expanded")); + } + + #[test] + fn out_dir_is_unset_only_while_neither_option_runs_build_scripts() { + let message = "`OUT_DIR` not set, build scripts may"; + let shown = |proc_macro: bool, build_scripts: bool| { + words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "procMacro": proc_macro, "buildScripts": build_scripts }), + json!({}), + )) + }; + assert!(shown(false, false).contains(message)); + assert!(shown(false, false).contains("build.rs does not run")); + let implied = shown(true, false); + assert!(!implied.contains(message)); + assert!(implied.contains("procedural macros still run them")); + assert!(!shown(false, true).contains(message) && !shown(true, true).contains(message)); + } + + #[test] + fn the_doc_comment_example_is_highlighted_as_code_only_with_injection() { + let example = |inject: bool| -> Vec { + let nodes = nodes( + LANGUAGE_REGION, + "en", + json!({ "docCommentInject": inject }), + json!({}), + ); + all(&nodes) + .into_iter() + .filter(|node| node["text"] == "1" && node["style"] == "monoSmall") + .filter(|node| node.get("align").is_none()) + .map(|node| node["color"].clone()) + .collect() + }; + // The `1` passed to add_one: a number when injected, the comment's + // color otherwise. + assert_eq!( + example(true), + [json!({ "light": "#1750EB", "dark": "#2AACB8" })] + ); + assert_eq!( + example(false), + [json!({ "light": "#8C8C8C", "dark": "#5F826B" })] + ); + } + + #[test] + fn the_check_preview_reports_what_the_command_reports() { + let shown = |on_save: bool, command: &str| { + words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "checkOnSave": on_save, "checkCommand": command }), + json!({}), + )) + }; + let check = shown(true, "check"); + assert!(check.contains("warning: unused variable: `n`") && !check.contains("len_zero")); + assert!(check.contains("cargo check")); + let clippy = shown(true, "clippy"); + assert!(clippy.contains("len_zero: length comparison to zero")); + let off = shown(false, "clippy"); + assert!(!off.contains("unused variable") && !off.contains("len_zero")); + assert!(off.contains("Only rust-analyzer's own diagnostics")); + } + + #[test] + fn a_draft_shows_in_the_preview_before_it_is_applied() { + let saved = words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "checkCommand": "check" }), + json!({}), + )); + assert!(!saved.contains("len_zero")); + assert!(saved.contains("follows the options below")); + let draft = words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "checkCommand": "check" }), + json!({ "checkCommand": "clippy" }), + )); + assert!(draft.contains("len_zero")); + assert!(draft.contains("Includes changes not applied yet")); + let chinese = words_of(&nodes( + LANGUAGE_REGION, + "zh-Hans", + json!({}), + json!({ "procMacro": false }), + )); + assert!(chinese.contains("含未应用的修改") && chinese.contains("未展开")); + } + + #[test] + fn the_cargo_diagram_lists_the_lookup_in_order_then_rustup() { + let shown = words_of(&nodes(CARGO_REGION, "en", json!({}), json!({}))); + let order: Vec = [ + "Tried first", + "Global default", + "Tried last", + "rustup picks", + ] + .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(CARGO_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(), "rust.view.unknownRegion"); + let window = ViewEvent::parse(&json!({ + "event": "open", + "instance": "i1", + "surface": { "toolWindowID": "rust" }, + "language": "en", + "settings": { "effective": Map::new(), "draft": Map::new() }, + })) + .unwrap(); + assert_eq!( + render(&window).unwrap_err().code(), + "rust.view.unknownRegion" + ); + } + + #[test] + fn a_value_the_preview_cannot_read_is_counted() { + let (_, unrecognized) = render(&event( + LANGUAGE_REGION, + "en", + json!({ "checkCommand": "miri" }), + json!({ "procMacro": "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..f0de594 --- /dev/null +++ b/backend/src/view/resolution.rs @@ -0,0 +1,248 @@ +//! The Cargo build system page's diagram: the order in which Lithe looks for +//! the `cargo` program, and how rustup then picks the Rust version. +//! +//! The steps follow `toolDefinitions[cargo].invocation.executables` in +//! `plugin.json`: what the Toolchains page sets for the project, 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 cargo 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 = "cargo-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 rustup card, after the three steps. +const RUSTUP_Y: f64 = HEADER + 3.0 * (STEP_H + STEP_GAP); +/// The top of the row of what the program is used for. +const USES_Y: f64 = RUSTUP_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(rustup(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 cargo is found: when it is rustup's proxy, rustup picks +/// the toolchain it runs. Off the rail, in a dashed frame, since it is not a +/// step of the lookup. +fn rustup(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.rustup_title, "strong") + .max_width(step_w - 2.0 * LINE_X), + ]; + card.extend(lines(&words.rustup_detail, step_w)); + group( + 0.0, + RUSTUP_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 runs the program 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::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.rustup_detail, + ] + .concat() + { + let width = text_width(line, CAPTION); + assert!(width <= room, "{language}: {line} ({width} of {room})"); + } + } + } +} 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..f6ecbbe --- /dev/null +++ b/backend/src/view/settings.rs @@ -0,0 +1,181 @@ +//! 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; + +/// The Cargo command the check on save runs: the `checkCommand` setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Check { + Check, + Clippy, +} + +impl Check { + fn parse(value: &str) -> Option { + Some(match value { + "check" => Check::Check, + "clippy" => Check::Clippy, + _ => return None, + }) + } +} + +/// The plugin's settings as the settings window holds them now. +#[derive(Debug)] +pub struct Settings { + pub proc_macro: bool, + pub build_scripts: bool, + pub doc_comment_inject: bool, + pub check_on_save: bool, + pub check_command: Check, + /// 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 proc_macro = reader.boolean("procMacro", true); + let build_scripts = reader.boolean("buildScripts", true); + let doc_comment_inject = reader.boolean("docCommentInject", true); + let check_on_save = reader.boolean("checkOnSave", true); + let check_command = reader.read("checkCommand", Value::from("check"), |value| { + value.as_str().and_then(Check::parse) + }); + Self { + proc_macro, + build_scripts, + doc_comment_inject, + check_on_save, + check_command, + changed: reader.changed, + unrecognized: reader.unrecognized, + } + } + + /// Whether rust-analyzer runs build scripts: their own setting, or + /// procedural macros, which need them built. + pub fn runs_build_scripts(&self) -> bool { + self.build_scripts || self.proc_macro + } + + /// 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!(settings.proc_macro && settings.build_scripts && settings.doc_comment_inject); + assert!(settings.check_on_save); + assert_eq!(settings.check_command, Check::Check); + assert_eq!(settings.unrecognized, 0); + assert!(!settings.any_changed(&["procMacro", "buildScripts", "checkCommand"])); + } + + #[test] + fn the_draft_wins_over_the_saved_value_and_counts_as_a_change() { + let settings = Settings::read(&event( + json!({ "procMacro": true, "checkCommand": "check", "checkOnSave": true }), + json!({ "procMacro": false, "checkOnSave": true, "checkCommand": "clippy" }), + )); + assert!(!settings.proc_macro); + assert_eq!(settings.check_command, Check::Clippy); + assert!(settings.is_changed("procMacro")); + assert!(settings.is_changed("checkCommand")); + // A draft equal to the value in force changes nothing. + assert!(!settings.is_changed("checkOnSave")); + assert!(!settings.is_changed("buildScripts")); + } + + #[test] + fn a_value_outside_the_declaration_shows_the_default_and_is_counted() { + let settings = Settings::read(&event( + json!({ "checkCommand": "miri", "buildScripts": "yes" }), + json!({}), + )); + assert_eq!(settings.check_command, Check::Check); + assert!(settings.build_scripts); + assert_eq!(settings.unrecognized, 2); + } + + #[test] + fn procedural_macros_run_build_scripts_whatever_their_own_setting() { + let read = |proc_macro: bool, build_scripts: bool| { + Settings::read(&event( + json!({ "procMacro": proc_macro, "buildScripts": build_scripts }), + json!({}), + )) + .runs_build_scripts() + }; + assert!(read(true, false) && read(false, true) && read(true, true)); + assert!(!read(false, false)); + } +} diff --git a/backend/src/view/words.rs b/backend/src/view/words.rs new file mode 100644 index 0000000..a633f46 --- /dev/null +++ b/backend/src/view/words.rs @@ -0,0 +1,191 @@ +//! The words the previews show, in the languages the plugin translates its +//! settings to. Setting names 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. +//! +//! Rust code and the tools' own output, such as diagnostics, 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 toolchain_title: &'static str, + pub toolchain_info: &'static str, + + pub macro_title: &'static str, + pub macro_on: &'static str, + pub macro_off: &'static str, + /// The caption on the generated code, and in its place when it is not. + pub macro_expanded: &'static str, + pub macro_not_expanded: &'static str, + + pub build_title: &'static str, + pub build_on: &'static str, + pub build_off: &'static str, + /// Build scripts switched off while procedural macros still run them. + pub build_implied: &'static str, + + pub doc_title: &'static str, + pub doc_on: &'static str, + pub doc_off: &'static str, + + pub check_title: &'static str, + pub check_off: &'static str, + pub check_check: &'static str, + pub check_clippy: &'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 rustup_title: &'static str, + pub rustup_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], +} + +const ZH: Words = Words { + preview_title: "效果预览", + preview_label: "rust-analyzer 选项的效果预览", + follows_options: "示例代码,随下方选项即时变化", + includes_draft: "含未应用的修改", + on: "开", + off: "关", + + toolchain_title: "工具链", + toolchain_info: + "Lithe 用这些程序读取项目、构建和提供语言服务。点击一行,到「工具链」页选择其他版本或位置。", + + macro_title: "展开过程宏", + macro_on: "展开 derive 和属性宏,生成的代码参与补全和跳转", + macro_off: "不展开,过程宏生成的代码不可见", + macro_expanded: "derive 生成", + macro_not_expanded: "未展开", + + build_title: "运行构建脚本", + build_on: "运行 build.rs,OUT_DIR 里生成的代码可以分析", + build_off: "不运行 build.rs,OUT_DIR 里的代码无法解析", + build_implied: "已关闭,但「展开过程宏」开启,仍会运行", + + doc_title: "高亮文档注释中的代码", + doc_on: "文档示例里的 Rust 代码和链接按源码着色", + doc_off: "文档注释整段显示为注释颜色", + + check_title: "保存时检查", + check_off: "保存时不检查,只显示 rust-analyzer 的诊断", + check_check: "保存时运行 cargo check,报告编译器警告", + check_clippy: "保存时运行 cargo clippy,另外报告 lint", + + resolution_title: "Lithe 按这个顺序找 cargo", + resolution_label: "Lithe 查找 cargo 程序的顺序", + step_project: "项目环境", + step_project_detail: [ + "为项目固定的 cargo,其次项目选的版本", + "在「工具链」页的项目范围选择", + ], + step_global: "全局默认", + step_global_detail: [ + "全局固定的 cargo,其次默认版本", + "在「工具链」页的全局范围选择", + ], + step_automatic: "自动发现", + step_automatic_detail: [ + "CARGO_HOME/bin → PATH 中的 cargo", + "→ ~/.cargo、Homebrew 的安装", + ], + rustup_title: "rustup 选 Rust 版本", + rustup_detail: [ + "cargo 是 rustup 的代理时,按目录覆盖", + "→ rust-toolchain.toml → 默认工具链", + ], + first: "先找这里", + then: "其次", + last: "最后", + used_for: "用于", + uses: ["读取项目", "构建", "检查", "运行", "调试"], +}; + +const EN: Words = Words { + preview_title: "Preview", + preview_label: "Preview of the rust-analyzer options", + follows_options: "Sample code; follows the options below", + includes_draft: "Includes changes not applied yet", + on: "On", + off: "Off", + + toolchain_title: "Toolchain", + toolchain_info: "Lithe runs these programs to read the project, build it and analyze the code. Choose a row to pick another version or location on the Toolchains page.", + + macro_title: "Expand procedural macros", + macro_on: "Generated code feeds completion and navigation", + macro_off: "Not expanded; the generated code is unseen", + macro_expanded: "from derive", + macro_not_expanded: "Not expanded", + + build_title: "Run build scripts", + build_on: "Runs build.rs, so code in OUT_DIR resolves", + build_off: "build.rs does not run; OUT_DIR is unset", + build_implied: "Off, but procedural macros still run them", + + doc_title: "Highlight code in doc comments", + doc_on: "Code and links in docs look like source", + doc_off: "Doc comments take one comment color", + + check_title: "Check on save", + check_off: "Only rust-analyzer's own diagnostics", + check_check: "Runs cargo check on save: compiler warnings", + check_clippy: "Runs cargo clippy on save: also its lints", + + resolution_title: "How Lithe finds cargo", + resolution_label: "The order in which Lithe looks for the cargo program", + step_project: "Project", + step_project_detail: ["Pinned for the project, then its version", "Set on the Toolchains page, for the project"], + 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: ["CARGO_HOME/bin → cargo on PATH", "→ ~/.cargo and Homebrew installs"], + rustup_title: "rustup picks the Rust version", + rustup_detail: ["When cargo is rustup's proxy: override", "→ rust-toolchain.toml → default toolchain"], + first: "Tried first", + then: "Then", + last: "Tried last", + used_for: "Used to", + uses: ["read projects", "build", "check", "run", "debug"], +}; + +/// 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}"); + } + } +} diff --git a/docs/assets/settings-previews/cargo-zh-Hans-light.png b/docs/assets/settings-previews/cargo-zh-Hans-light.png new file mode 100644 index 0000000..1b19b9a Binary files /dev/null and b/docs/assets/settings-previews/cargo-zh-Hans-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..aa11158 Binary files /dev/null and b/docs/assets/settings-previews/language-zh-Hans-dark.png differ diff --git a/docs/assets/settings-previews/language-zh-Hans-draft-light.png b/docs/assets/settings-previews/language-zh-Hans-draft-light.png new file mode 100644 index 0000000..f65f211 Binary files /dev/null and b/docs/assets/settings-previews/language-zh-Hans-draft-light.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 5ed336e..9c80b31 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -22,6 +22,7 @@ | --- | --- | --- | --- | --- | | `rust-support-plugin` | rust-analyzer 代码智能,Cargo 构建、运行和依赖,cargo / rustup / rust-analyzer 工具定义 | implemented / pending | implemented / pending | 2026-11-21 macOS workbench 集成测试通过;Windows 后端只在 CI 构建,没有在 Windows 版 Lithe 里运行过 | | `rust-debug-codelldb` | 用按需下载的 CodeLLDB 调试二进制和示例 | implemented / pending | partial / pending | 2026-11-21 macOS workbench 集成测试通过;Windows 没有运行过;Windows ARM64 没有 CodeLLDB 包 | +| `rust-settings-previews` | Rust 语言设置页和 Cargo 构建工具页里插件自己画的预览 | implemented / pending | implemented / pending | 2026-11-22 macOS 宿主端到端测试通过(本地 0.1.1 包,宿主 `a6afaaf`);Windows 后端只在 CI 构建,没有在 Windows 版 Lithe 里运行过 | | `rust-project-generator` | 「新建项目」里的 Rust(Cargo 软件包),Cargo 选择 | implemented / pending | implemented / pending | 2026-11-21 macOS 宿主集成测试通过;Windows 没有运行过 | ## rust-support-plugin @@ -31,7 +32,8 @@ `cargo metadata --no-deps` 组成软件包和目标;在构建窗口里运行 Build、Check、Clippy、Doc、Clean,运行二进制和示例, `cargo metadata` 的依赖图按 `cargo tree` 的样子列出;`Cargo.toml`、`Cargo.lock`、`.cargo/config(.toml)`、 `rust-toolchain(.toml)` 变化后重新读取;构建选项 Release Profile、Features、All Features、No Default Features、Offline; -插件设置 Check on save、Check command、Install rust-analyzer with rustup。`toolDefinitions` 声明 `cargo`、`rustup`、 +插件设置 Check on save、Check command、Expand procedural macros、Run build scripts、Highlight code in doc comments、 +Install rust-analyzer with rustup,前两项和高亮文档注释立即生效,其余在语言服务器下次启动时生效。`toolDefinitions` 声明 `cargo`、`rustup`、 `rust-analyzer`,在 `~/.cargo`(`CARGO_HOME`)和 Homebrew 里查找,列在「构建、执行、部署 › 工具链」里,项目可以固定一个 Cargo。 | 平台 | 实现 | 验证 | 说明 | @@ -166,6 +168,70 @@ Edition 2024(默认)或 2021。由模板写出 `Cargo.toml` 和忽略 `/targ 5. 选 Edition 2021 创建,`Cargo.toml` 里是 `edition = "2021"`。 6. 「工具链」里这个项目固定的是创建时选的 Cargo。 +## rust-settings-previews + +**能力**:0.1.1 起插件后端(`bin/backend`)实现 `settings.view` 视图函数,给两个 `settingRegions` 画画布: + +- `language`(「语言 › Rust」):先是宿主画的「工具链」一节,列出 cargo、rust-analyzer、rustup 的版本和路径,点一行到「工具链」页改; + 下面四张卡片画 rust-analyzer 选项在编辑器里的样子:展开过程宏(`procMacro`,开启时显示 derive 生成的代码)、 + 运行构建脚本(`buildScripts`,关闭时 `OUT_DIR` 里的代码无法解析;关闭但过程宏开启时标出“仍会运行”)、 + 高亮文档注释中的代码(`docCommentInject`)、保存时检查(`checkOnSave`、`checkCommand`:不检查、cargo check 的编译器警告、 + cargo clippy 另外的 lint)。 +- `cargo`(「构建、执行、部署 › 构建工具 › Cargo」):宿主画的 cargo 一行,下面是 Lithe 查找 cargo 的顺序(项目环境、全局默认、 + 自动发现,按 `toolDefinitions` 的 `cargo` 排列),rustup 选 Rust 版本的顺序(目录覆盖、`rust-toolchain.toml`、默认工具链), + 以及 cargo 用于哪些流程。查找顺序不随插件设置变化,实际找到的 cargo 看上面那一行。 + +语言页读设置窗口里还没应用的草稿,草稿和已保存的值不同时对应卡片先变,边框换成强调色、值标签前加一个圆点,标题行右侧的说明换成“含未应用的修改”。 +画面中英文跟随设置窗口的语言,浅色和深色外观用宿主的颜色标记或成对颜色。后端只读设置,不启动 cargo、rustup 或 rust-analyzer,也不写插件目录。 + +场景按视图事件里的 `width` 排版:语言页放得下两张最窄的卡片(宽度至少 594)时两张一行,否则一张一行,卡片随宽度变宽, +文字和代码保持原来的字号;Cargo 页的步骤卡片随宽度变宽。画布声明 `on: ["resize"]`,窗口宽度稳定后宿主发 `resize`, +后端按新宽度重画。事件里没有 `width` 时按最窄设置窗口的区域宽度画(语言页 610、Cargo 页 340),也不声明 `resize`。 + +| 平台 | 实现 | 验证 | 说明 | +| --- | --- | --- | --- | +| macOS | implemented | pending | 后端是 Apple Silicon 和 Intel 的通用二进制 | +| Windows | implemented | pending | 后端在 CI 里为 x64 和 ARM64 构建;还没有在 Windows 版 Lithe 里打开过设置预览 | + +**证据**: + +- `io.github.lithe-idea.rust-support/plugin.json`:`settingRegions` 的 `language`(`languageID: rust`)、`cargo`(`buildSystemID: cargo`), + `requires` 的 `backend: 0`、`ui: 0`,权限 `backend.launch`、`ui.contribute`;设置 `procMacro`、`buildScripts`、`docCommentInject`。 +- `backend/src/view/`:视图函数和场景;`cargo test --locked` 检查每个场景在两种语言、各个宽度下都在契约限制内、viewBox 宽度等于事件宽度、 + 卡片内容不超出卡片,两张一行只在放得下两张最窄卡片时出现,没有宽度时退回最窄窗口的排版且不声明 `resize`, + 草稿让预览先变并标出未应用的修改,以及各设置对预览的影响。 +- `e2e/host/desktop/internal/workbench/rust_support_plugin_settings_view_e2e_test.go`:`TestRustSupportPluginDrawsItsSettingsRegions` + 经设置窗口自己的设置来源启动安装包里的后端,用中英文打开两个区域,由 Core 校验每次回答;检查画布前列出的工具、 + viewBox 宽度等于区域宽度、画布高度放得下 viewBox、不写 `pan` 并声明 `resize`;语言页发 `checkCommand: clippy` 草稿, + cargo check 的说明换成 clippy 的 lint 并标出未应用的修改;再以 760 的宽度发 `resize`,检查按新宽度重画且草稿标记仍在;安装目录的文件不变。 + +**依赖的宿主能力**:插件视图和设置区域(1lck/Lithe-IDEA#2183,Core Lithe-core-rust#104,桌面端 0.8.7 起), +视图事件带 `width` 和 `resize`(1lck/Lithe-IDEA#2191,Core Lithe-core-rust#109,桌面端 0.8.10 起)。插件其他功能本来就需要桌面端 0.8.12, +所以 0.1.1 要求 0.8.12 及以上,这两项都已包含。 + +**限制**: + +- 代码按 SF Mono 的 7pt 字宽一个字符一个节点排版,标记才能对准字符;Windows 上 Consolas 的字更窄,代码间距会比宿主自己画的略宽。 + 文字宽度按字号估算,不是宿主量出来的;卡片窄时较长的说明由宿主按最大宽度截断。 +- 预览画的是固定的示例代码,不是当前项目里的代码;Cargo 页不显示实际找到的 cargo,那是上面工具行的事。 +- 环境变量、rustfmt 额外参数和设置子页暂时没做;标准库路径不显示为“自动(实际路径)”。 + +**最近验证**:2026-11-22,macOS(Apple Silicon),本地构建的 `rust-support-0.1.1-darwin.zip`,宿主 main `a6afaaf`。 +`TestRustSupportPluginDrawsItsSettingsRegions` 通过:后端由宿主启动,两个区域在中英文下按区域宽度(610、340)各画出工具行和一张画布, +声明 `resize`、不写 `pan`;clippy 草稿让保存时检查卡片换成 clippy 的说明并标出未应用的修改;以 760 发 `resize` 后按新宽度重画, +草稿标记仍在;安装目录的文件不变。同一次运行里另外两个 workbench 测试(构建和语言服务、CodeLLDB 调试)和四个 projectgen 测试也通过。另把后端画出的场景放进插件 e2e 覆盖层里的宿主无头界面截图(浅色和深色,中英文,默认值、草稿和 Cargo 页), +README 的“设置预览”放了其中的中文截图。没有做手工验收。 + +**验证方法**(macOS): + +1. 用桌面端 0.8.12 或更新版本安装插件包,打开「设置 › 语言 › Rust」:顶部是工具链一节,下面四张预览卡片,浅色和深色外观下文字和代码都清楚。 + 拖宽、拖窄设置窗口,停下后预览按新宽度重新排版:放得下时两张一行,窄了一张一行,字号不变,不放大也不被裁掉。 +2. 关掉展开过程宏、运行构建脚本、高亮文档注释中的代码,把 Check command 改成 clippy,先不点应用:对应卡片立刻变化, + 标出“含未应用的修改”;点应用后标记消失。只关运行构建脚本时,卡片说明构建脚本仍会因过程宏运行。 +3. 打开「设置 › 构建、执行、部署 › 构建工具 › Cargo」:上面是 cargo 一行,下面是查找 cargo 的三步和 rustup 的版本选择; + 拖宽窗口后步骤卡片跟着变宽。 +4. 界面语言换成中文,两个预览都显示中文。 + ## Windows 安装包 `-windows-x64.zip` 和 `-windows-arm64.zip` 与 darwin 包只有后端程序不同(`bin/backend.exe`,包里的 `plugin.json` diff --git a/docs/releases/v0.1.1.md b/docs/releases/v0.1.1.md new file mode 100644 index 0000000..c214f16 --- /dev/null +++ b/docs/releases/v0.1.1.md @@ -0,0 +1,23 @@ +0.1.1 补上 Rust 常用的 rust-analyzer 选项,并给 Rust 的两个设置页加上插件自己画的预览,改设置时直接看到效果。这是正式版本。 + +功能: +- 新增三个设置:展开过程宏、运行构建脚本、高亮文档注释中的代码,默认都开启。前两项在语言服务器下次启动时生效,高亮文档注释中的代码和原有的保存时检查一样立即生效。 +- 「设置 › 语言 › Rust」顶部列出 cargo、rust-analyzer 和 rustup 的版本和路径,点一行到「工具链」页选择其他版本或位置。下面四张预览卡片画出这几个选项在编辑器里的样子:过程宏展开后生成的代码、关掉构建脚本后 `OUT_DIR` 里的代码无法解析、文档注释里的代码是否着色、保存时检查报告编译器警告还是 Clippy 的 lint。 +- 「构建工具 › Cargo」页画出 Lithe 查找 cargo 的顺序(项目环境、全局默认、自动发现)和 rustup 选 Rust 版本的顺序。 +- 改了还没应用的选项会先在预览里显示,并标出“含未应用的修改”。预览跟随界面语言和浅色、深色外观;设置窗口变宽时卡片放得下就两张一行。 + +已知限制: +- 还不能设置传给 rust-analyzer 的环境变量和 rustfmt 的额外参数,标准库路径也还没有显示。 +- 预览画的是示例代码,不是当前项目的代码。 +- Windows 上代码的字距比 Lithe 自己画的略宽:预览按 SF Mono 的字宽排版代码,标记才能对准字符。 + +验证: +- 在 macOS 上跑宿主端到端测试:后端由宿主启动,两个预览在中英文下都画出、通过 Core 校验,草稿会改变预览,窗口变宽后按新宽度重画,插件安装目录不被写入;原有的构建、调试和新建项目测试也都通过。 +- 用宿主无头界面截图检查了中英文、浅色和深色外观、默认值和未应用的修改。 +- Windows 包的后端只在 CI 里构建,还没有在 Windows 版 Lithe 里打开过;状态见 `docs/feature-matrix.md`。 + +权限:新增 `ui.contribute`(在设置页显示预览)。 + +兼容性: +- 需要 Lithe 桌面端 0.8.12 或更新版本,和 0.1.0 相同。 +- 发布包按平台分开:`-darwin.zip`(Apple Silicon 和 Intel 通用)、`-windows-x64.zip`、`-windows-arm64.zip`。 diff --git a/e2e/host/desktop/internal/workbench/rust_support_plugin_settings_view_e2e_test.go b/e2e/host/desktop/internal/workbench/rust_support_plugin_settings_view_e2e_test.go new file mode 100644 index 0000000..6eb2d73 --- /dev/null +++ b/e2e/host/desktop/internal/workbench/rust_support_plugin_settings_view_e2e_test.go @@ -0,0 +1,246 @@ +package workbench + +import ( + "context" + "encoding/json" + "os" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +// This opt-in integration test installs the released Rust Support archive and opens its two +// settings regions as the settings window does: through the window's own settings source, +// which starts the packaged backend, sends the region's view events and has Core check every +// answer. Every event carries the region's width, as the window measures it, and a resize to +// a wider window draws the scene again at the new width. It needs neither cargo nor +// rust-analyzer, since the backend reads settings only. + +// rustRegion is one of the plugin's settings regions: its width in the smallest settings +// window, the tools its view lists above the canvas, the words of its canvas in each language, +// and a draft row of the window that changes the preview, with the words the saved settings +// draw that the draft replaces, and a word only the draft draws. +type rustRegion struct { + id string + width float64 + tools []string + words map[i18n.Language][]string + draft map[string]any + saved map[i18n.Language]string + drafts string +} + +var rustRegions = []rustRegion{ + {id: "language", width: 610, tools: []string{"cargo", "rust-analyzer", "rustup"}, words: map[i18n.Language][]string{ + i18n.English: {"Preview", "Preview of the rust-analyzer options", "Expand procedural macros"}, + i18n.Chinese: {"效果预览", "rust-analyzer 选项的效果预览", "展开过程宏"}, + }, draft: map[string]any{"checkCommand": "clippy"}, saved: map[i18n.Language]string{ + i18n.English: "Runs cargo check on save: compiler warnings", + i18n.Chinese: "保存时运行 cargo check,报告编译器警告", + }, drafts: "len_zero"}, + // The Cargo page shows how Lithe finds cargo, which no setting of the plugin changes. + {id: "cargo", width: 340, tools: []string{"cargo"}, words: map[i18n.Language][]string{ + i18n.English: {"How Lithe finds cargo", "The order in which Lithe looks for the cargo program"}, + i18n.Chinese: {"Lithe 按这个顺序找 cargo", "Lithe 查找 cargo 程序的顺序"}, + }}, +} + +// rustDrawnCanvas is the canvas node of a region's view, as Core checked it. +type rustDrawnCanvas struct { + Type string `json:"type"` + ID string `json:"id"` + Label string `json:"label"` + Height float64 `json:"height"` + ViewBox []float64 `json:"viewBox"` + Pan json.RawMessage `json:"pan"` + On []string `json:"on"` + Nodes []json.RawMessage `json:"nodes"` +} + +// rustDrawnNode is a node of a region's view: a tool row, a section holding tool rows, or +// the canvas. +type rustDrawnNode struct { + Type string `json:"type"` + Tool string `json:"tool"` + Children []rustDrawnNode `json:"children"` +} + +// rustSceneWords are the words of every text node of a scene, nested ones included, a run +// joined into its line. Code drawn a character to a node gives single characters. +func rustSceneWords(t *testing.T, scene []json.RawMessage) string { + t.Helper() + var words []string + var walk func(nodes []json.RawMessage) + walk = func(nodes []json.RawMessage) { + for _, raw := range nodes { + var node struct { + Text string `json:"text"` + Runs []struct{ Text string } `json:"runs"` + Children []json.RawMessage `json:"children"` + } + if err := json.Unmarshal(raw, &node); err != nil { + t.Fatalf("a scene node is not an object: %s", raw) + } + line := node.Text + for _, run := range node.Runs { + line += run.Text + } + if line != "" { + words = append(words, line) + } + walk(node.Children) + } + } + walk(scene) + return strings.Join(words, "\n") +} + +// drawRustRegion sends one view event to region and returns the canvas it drew, after +// checking that the view lists the region's tools, in order, and ends with that one canvas. +func drawRustRegion(t *testing.T, ctx context.Context, sources pluginSettingsSources, editor pluginservice.SettingsEditor, region rustRegion, event map[string]any) rustDrawnCanvas { + t.Helper() + encoded, err := json.Marshal(event) + if err != nil { + t.Fatal(err) + } + drawn, changed, err := sources.View(ctx, editor, region.id, "settings.view", encoded, nil, false) + if err != nil { + t.Fatalf("%s region, %s event: %v", region.id, event["event"], err) + } + if !changed { + t.Fatalf("%s region, %s event: the view drew nothing new", region.id, event["event"]) + } + var nodes []json.RawMessage + if err := json.Unmarshal(drawn, &nodes); err != nil || len(nodes) == 0 { + t.Fatalf("%s region: Core returned %s: %v", region.id, drawn, err) + } + var tools []string + var walk func(nodes []rustDrawnNode) + walk = func(nodes []rustDrawnNode) { + for _, node := range nodes { + if node.Type == "tool" { + tools = append(tools, node.Tool) + } + walk(node.Children) + } + } + rows := make([]rustDrawnNode, len(nodes)-1) + for i, raw := range nodes[:len(nodes)-1] { + if err := json.Unmarshal(raw, &rows[i]); err != nil { + t.Fatalf("%s region: a node is not an object: %s", region.id, raw) + } + if rows[i].Type == "canvas" { + t.Fatalf("%s region: want one canvas, at the end; got %s", region.id, drawn) + } + } + walk(rows) + if !slices.Equal(tools, region.tools) { + t.Fatalf("%s region: the view lists the tools %v, want %v", region.id, tools, region.tools) + } + var canvas rustDrawnCanvas + if err := json.Unmarshal(nodes[len(nodes)-1], &canvas); err != nil || canvas.Type != "canvas" { + t.Fatalf("%s region: the view does not end with a canvas: %s", region.id, drawn) + } + return canvas +} + +// rustDrawnAt checks that a region's canvas is drawn for a view width points wide: its view +// box is that wide, it shows whole at one unit to a point, and it listens for resize. +func rustDrawnAt(t *testing.T, region string, canvas rustDrawnCanvas, width float64) { + t.Helper() + if len(canvas.ViewBox) != 4 || canvas.ViewBox[2] != width || canvas.ViewBox[3] < 1 { + t.Fatalf("%s region: view box %v, want one %g wide", region, canvas.ViewBox, width) + } + if canvas.Height < canvas.ViewBox[3] || len(canvas.Pan) > 0 { + t.Fatalf("%s region: height %g, pan %s; the scene must show whole at one unit to a point", region, canvas.Height, canvas.Pan) + } + if !slices.Contains(canvas.On, "resize") { + t.Fatalf("%s region: on %v, want resize so the scene follows the window", region, canvas.On) + } +} + +func TestRustSupportPluginDrawsItsSettingsRegions(t *testing.T) { + archive := os.Getenv("LITHE_TEST_RUST_PLUGIN_ARCHIVE") + if archive == "" { + t.Skip("set LITHE_TEST_RUST_PLUGIN_ARCHIVE to a rust-support--darwin.zip") + } + h, installed := openRustSupportWindow(t, archive) + t.Cleanup(h.app.plugins.Host.StopAll) + before := rustPackageDigest(t, installed) + sources := pluginSettingsSources{app: h.app} + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + instance := 0 + for _, language := range []i18n.Language{i18n.English, i18n.Chinese} { + editor, err := sources.Load(ctx, rustSupportPluginID, language) + if err != nil { + t.Fatalf("load the settings page in %s: %v", language.Code(), err) + } + draftNote := map[i18n.Language]string{i18n.English: "Includes changes not applied yet", i18n.Chinese: "含未应用的修改"}[language] + for _, region := range rustRegions { + instance++ + name := "e2e-" + strconv.Itoa(instance) + // The window's open event carries no settings when nothing is drafted; the host + // adds the saved ones, read from the installed plugin. + opened := drawRustRegion(t, ctx, sources, editor, region, map[string]any{ + "event": "open", "instance": name, "language": language.Code(), "width": region.width, + }) + rustDrawnAt(t, region.id, opened, region.width) + words := rustSceneWords(t, opened.Nodes) + for _, want := range region.words[language] { + if !strings.Contains(words, want) && opened.Label != want { + t.Fatalf("%s region in %s: %q is not drawn; the scene says:\n%s", region.id, language.Code(), want, words) + } + } + if strings.Contains(words, draftNote) { + t.Fatalf("%s region: the saved settings are drawn as a draft", region.id) + } + + settings := map[string]any{"effective": map[string]any{}, "draft": map[string]any{}} + if region.draft != nil { + // A draft row of the window shows in the preview before it is applied. + settings["draft"] = region.draft + drafted := drawRustRegion(t, ctx, sources, editor, region, map[string]any{ + "event": "settings", "instance": name, "language": language.Code(), + "width": region.width, "settings": settings, + }) + rustDrawnAt(t, region.id, drafted, region.width) + draftWords := rustSceneWords(t, drafted.Nodes) + saved := region.saved[language] + if !strings.Contains(words, saved) || strings.Contains(words, region.drafts) || + strings.Contains(draftWords, saved) || !strings.Contains(draftWords, region.drafts) || !strings.Contains(draftWords, draftNote) { + t.Fatalf("%s region in %s: the draft %v is not drawn and marked; saved:\n%s\ndrafted:\n%s", region.id, language.Code(), region.draft, words, draftWords) + } + } + + // The window widens: the host sends resize with the new width, and the plugin lays + // the same scene out again at it, a draft still drawn and marked. + const wider = 760 + resized := drawRustRegion(t, ctx, sources, editor, region, map[string]any{ + "event": "resize", "instance": name, "language": language.Code(), + "width": wider, "settings": settings, + }) + rustDrawnAt(t, region.id, resized, wider) + resizedWords := rustSceneWords(t, resized.Nodes) + if region.draft != nil && (!strings.Contains(resizedWords, region.drafts) || !strings.Contains(resizedWords, draftNote)) { + t.Fatalf("%s region in %s: the resized scene lost the draft; it says:\n%s", region.id, language.Code(), resizedWords) + } + for _, want := range region.words[language] { + if !strings.Contains(resizedWords, want) && resized.Label != want { + t.Fatalf("%s region in %s: the resized scene lost %q; it says:\n%s", region.id, language.Code(), want, resizedWords) + } + } + } + } + if h.app.plugins.Host.Running(rustSupportPluginID) == nil { + t.Fatal("the backend is not running after drawing the regions") + } + h.app.plugins.Host.StopAll() + assertRustPackageUnchanged(t, installed, before) +} diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index 78d257b..14bc534 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -4,10 +4,10 @@ "timeout": "90m", "packages": { "./internal/projectgen": "^TestRustPlugin", - "./internal/workbench": "^TestRustSupportPlugin(BuildsAndServesAPackage|DownloadsCodeLLDBAndDebugsAProgram)$" + "./internal/workbench": "^TestRustSupportPlugin(BuildsAndServesAPackage|DownloadsCodeLLDBAndDebugsAProgram|DrawsItsSettingsRegions)$" }, "requiredEnvironment": { - "LITHE_TEST_RUST_PLUGIN_ARCHIVE": "rust-support--darwin.zip to install, for example dist/rust-support-0.1.0-darwin.zip" + "LITHE_TEST_RUST_PLUGIN_ARCHIVE": "rust-support--darwin.zip to install, for example dist/rust-support-0.1.1-darwin.zip" }, "repositoryEnvironment": { "LITHE_PLUGIN_RUST_DIR": "io.github.lithe-idea.rust-support" diff --git a/io.github.lithe-idea.rust-support/l10n/zh-Hans.json b/io.github.lithe-idea.rust-support/l10n/zh-Hans.json index 997d4bd..cc70544 100644 --- a/io.github.lithe-idea.rust-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.rust-support/l10n/zh-Hans.json @@ -13,11 +13,44 @@ "clippy": "cargo clippy" } }, + "procMacro": { + "title": "展开过程宏", + "description": "编译并运行过程宏(如 derive(Serialize)、#[tokio::main]),它们生成的代码才能用于补全、跳转和类型推断。开启时也会运行构建脚本。" + }, + "buildScripts": { + "title": "运行构建脚本", + "description": "运行各软件包的 build.rs,分析它生成到 OUT_DIR 的代码和它设置的 cfg。开启“展开过程宏”时,构建脚本仍会运行。" + }, + "docCommentInject": { + "title": "高亮文档注释中的代码", + "description": "像源代码一样高亮文档注释示例中的 Rust 代码和指向条目的链接。" + }, "installRustAnalyzer": { "title": "用 rustup 安装 rust-analyzer", "description": "项目的 rustup 工具链缺少 rust-analyzer 时,先用 rustup component add 安装 rust-analyzer 和 rust-src,再启动它。" } }, + "settingRegions": { + "language": { + "keywords": [ + "工具链", + "过程宏", + "宏展开", + "构建脚本", + "文档注释", + "代码高亮", + "保存时检查", + "效果预览" + ] + }, + "cargo": { + "keywords": [ + "Cargo 程序", + "工具链", + "查找顺序" + ] + } + }, "buildOptions": { "cargo": { "release": { diff --git a/io.github.lithe-idea.rust-support/plugin.json b/io.github.lithe-idea.rust-support/plugin.json index 95cee52..57abf43 100644 --- a/io.github.lithe-idea.rust-support/plugin.json +++ b/io.github.lithe-idea.rust-support/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.rust-support", "displayName": "Rust Support", - "version": "0.1.0", + "version": "0.1.1", "pluginAPIVersion": 0, "requires": { "backend": 0, @@ -14,7 +14,8 @@ "languages": 0, "projectGenerators": 0, "settings": 0, - "toolDefinitions": 1 + "toolDefinitions": 1, + "ui": 0 }, "requiresTools": [ "cargo", @@ -33,6 +34,7 @@ "languageServer.launch", "process.build", "project.generate", + "ui.contribute", "workspace.metadata" ], "activationEvents": [ @@ -75,6 +77,40 @@ } ] }, + { + "id": "procMacro", + "type": "boolean", + "title": "Expand procedural macros", + "description": "Build and run procedural macros such as derive(Serialize) and #[tokio::main], so the code they generate takes part in completion, navigation and type inference. Build scripts run too while this is on.", + "default": true, + "page": { + "languageID": "rust" + }, + "section": "rust-analyzer" + }, + { + "id": "buildScripts", + "type": "boolean", + "title": "Run build scripts", + "description": "Run each package's build.rs so the code it generates into OUT_DIR and the cfg flags it sets are analyzed. Build scripts still run while Expand procedural macros is on.", + "default": true, + "page": { + "languageID": "rust" + }, + "section": "rust-analyzer" + }, + { + "id": "docCommentInject", + "type": "boolean", + "title": "Highlight code in doc comments", + "description": "Highlight the Rust code in doc comment examples, and links to items, as source code.", + "default": true, + "effect": "immediate", + "page": { + "languageID": "rust" + }, + "section": "rust-analyzer" + }, { "id": "installRustAnalyzer", "type": "boolean", @@ -87,6 +123,48 @@ "section": "rust-analyzer" } ], + "settingRegions": [ + { + "id": "language", + "page": { + "languageID": "rust" + }, + "keywords": [ + "rust-analyzer", + "toolchain", + "proc macro", + "macro expansion", + "build script", + "OUT_DIR", + "doc comment", + "highlighting", + "check on save", + "clippy", + "preview" + ], + "view": { + "function": "settings.view" + } + }, + { + "id": "cargo", + "page": { + "buildSystemID": "cargo" + }, + "keywords": [ + "cargo executable", + "toolchain", + "lookup order", + "rustup", + "rust-toolchain.toml", + "CARGO_HOME", + "PATH" + ], + "view": { + "function": "settings.view" + } + } + ], "languages": [ { "id": "rust", @@ -119,6 +197,23 @@ "checkOnSave": "${setting:checkOnSave}", "check": { "command": "${setting:checkCommand}" + }, + "procMacro": { + "enable": "${setting:procMacro}" + }, + "cargo": { + "buildScripts": { + "enable": "${setting:buildScripts}" + } + }, + "semanticHighlighting": { + "doc": { + "comment": { + "inject": { + "enable": "${setting:docCommentInject}" + } + } + } } } }