diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e887ce..2979339 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,43 @@ permissions: contents: read jobs: + # The backend that draws the settings regions, built for each archive on the + # system that links it: a universal binary on macOS, x64 and ARM64 (cross-built + # with the MSVC ARM64 tools) on Windows. + backend: + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - platform: darwin + os: macos-latest + targets: aarch64-apple-darwin x86_64-apple-darwin + - platform: windows-x64 + os: windows-latest + targets: x86_64-pc-windows-msvc + - platform: windows-arm64 + os: windows-latest + targets: aarch64-pc-windows-msvc + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Install the Rust targets + shell: bash + run: rustup target add ${{ matrix.targets }} + - name: Build the backend + run: node scripts/build-backend.mjs ${{ matrix.platform }} + - uses: actions/upload-artifact@v4 + with: + name: backend-${{ matrix.platform }} + path: .artifacts/backend-${{ matrix.platform }} + if-no-files-found: error + package: + needs: backend runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -17,15 +53,19 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - name: Check manifest and build the archive + - uses: actions/download-artifact@v4 + with: + pattern: backend-* + path: .artifacts + - name: Check manifest and build the archives run: node scripts/package.mjs - name: Verify release archives run: node --test --test-timeout=60000 scripts/package/*.test.mjs - - name: Hand the Windows archive to the command jobs + - name: Hand the Windows archives to the command jobs uses: actions/upload-artifact@v4 with: name: go-support-windows - path: dist/go-support-*-windows.zip + path: dist/go-support-*-windows-*.zip if-no-files-found: error - name: Validate against Lithe Store rules run: | @@ -45,8 +85,8 @@ jobs: " # The declared commands with the real go, gopls and dlv, on each platform the - # packages serve. Windows runs the Windows archive, unpacked under a path with - # a space the way Lithe installs it. + # packages serve. Windows runs the Windows archive of its architecture, + # unpacked under a path with a space the way Lithe installs it. commands: needs: package runs-on: ${{ matrix.os }} @@ -73,7 +113,8 @@ jobs: if: runner.os == 'Windows' shell: pwsh run: | - $archive = Get-ChildItem "$env:RUNNER_TEMP\archive\go-support-*-windows.zip" | Select-Object -First 1 + $arch = if ($env:RUNNER_ARCH -eq 'ARM64') { 'arm64' } else { 'x64' } + $archive = Get-ChildItem "$env:RUNNER_TEMP\archive\go-support-*-windows-$arch.zip" | Select-Object -First 1 $plugins = Join-Path $env:RUNNER_TEMP "Lithe Plugins" Expand-Archive -Path $archive.FullName -DestinationPath $plugins "LITHE_TEST_PLUGIN_DIR=$plugins\io.github.lithe-idea.go-support" | Out-File $env:GITHUB_ENV -Append -Encoding utf8 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index de355ec..b7e36bb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,42 @@ permissions: contents: write jobs: + # The settings regions' backend for each archive, built as CI builds it. + backend: + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + permissions: + contents: read + strategy: + matrix: + include: + - platform: darwin + os: macos-latest + targets: aarch64-apple-darwin x86_64-apple-darwin + - platform: windows-x64 + os: windows-latest + targets: x86_64-pc-windows-msvc + - platform: windows-arm64 + os: windows-latest + targets: aarch64-pc-windows-msvc + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Install the Rust targets + shell: bash + run: rustup target add ${{ matrix.targets }} + - name: Build the backend + run: node scripts/build-backend.mjs ${{ matrix.platform }} + - uses: actions/upload-artifact@v4 + with: + name: backend-${{ matrix.platform }} + path: .artifacts/backend-${{ matrix.platform }} + if-no-files-found: error + release: + needs: backend runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -21,6 +56,10 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 + - uses: actions/download-artifact@v4 + with: + pattern: backend-* + path: .artifacts - name: Build archives run: | set -o pipefail @@ -43,7 +82,11 @@ jobs: # Lithe-core-rust#94), which desktop 0.8.6 is the first release to ship. # It is published as a stable release so the Store tracker lists it; the # Store index records its requires and keeps older hosts on 1.0.1. - PRERELEASE_TAGS: v0.0.1 v1.0.0 v1.2.0 + # v1.3.0 adds a backend that draws the settings regions (settingRegions, + # requires backend 0 and ui 0), which needs the host's plugin views + # (1lck/Lithe-IDEA#2183, pinning Lithe-core-rust#104) that no desktop + # release has yet. + PRERELEASE_TAGS: v0.0.1 v1.0.0 v1.2.0 v1.3.0 run: | prerelease=false for tag in $PRERELEASE_TAGS; do diff --git a/.gitignore b/.gitignore index f15e086..579a7d4 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ dist/ .cache/ .DS_Store .artifacts/ +backend/target/ diff --git a/README.md b/README.md index a25bcbb..de139e4 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,14 @@ 用声明式构建系统接口(`buildSystems`)识别 Go 模块,在构建窗口里列出包,运行 `go build`、`go vet`、 `go test` 和 `go run`,查看模块依赖;在「运行/调试配置」里新建 Go 构建和 Go 测试配置;用你电脑上的 Delve(`dlv`)调试, 在「新建项目」里创建 Go 模块。 -这是一个**社区插件**,按插件契约 v0 编写。插件只有一份 `plugin.json` 和几份项目模板,不附带任何可执行文件, -也没有后端进程。 +这是一个**社区插件**,按插件契约 v0 编写。插件包含一份 `plugin.json`、几份项目模板,和一个只画设置页预览的小后端(Rust 编写); +gopls、go 和 dlv 仍然用你电脑上的。 > English: Go support for Lithe — code intelligence through your own `gopls`, the Go Modules build system > (package model, build, vet, test, run and the module list) through the declarative `buildSystems` contract, > Go Build and Go Test run configurations, debugging through your own Delve, and a Go module entry in New Project. -> The plugin is a `plugin.json` and a few project templates, with no executables and no backend process. +> The plugin is a `plugin.json`, a few project templates and a small Rust backend that only draws the settings +> previews; gopls, go and dlv stay your own. > **兼容性**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,只能装进新版 Lithe 桌面端 > (`desktop-v*` 预发布),旧版 macOS Lithe 无法安装。1.0.0 的调试需要宿主支持 `tcpAnnounced` 调试适配器 @@ -26,6 +27,10 @@ > 1.1.0 作为正式版本发布并收录到 Lithe Store;Store 按版本的 `requires` 给更早的桌面端继续提供 1.0.1。 > 1.2.0 的 Go 构建和 Go 测试类型图标需要能读取插件包图标的桌面端([1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169)), > 作为预发布版本发布;桌面端 0.8.6 也能安装它,只是显示通用图标。 +> 1.3.0 在 Go 语言设置页和 Go 构建系统页加了插件自己画的预览区域(`settingRegions`),需要支持插件视图的桌面端 +> ([1lck/Lithe-IDEA#2183](https://github.com/1lck/Lithe-IDEA/pull/2183),固定了 +> [Lithe-core-rust#104](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/104) 的 Core),还没有桌面端版本包含它, +> 所以作为预发布版本发布、不进 Store。 ## 功能 @@ -43,6 +48,7 @@ | 调试 | 「调试」窗口里选 Go (Delve),调试当前打开的 `.go` 文件所在的包:断点、单步、调用栈、变量和表达式求值,程序输出显示在调试控制台 | | 新建项目 | 「新建项目」里的 Go:选择 GOROOT,生成 `go.mod`、`.gitignore`,可选生成示例 `main.go`;模块路径默认是小写的项目名,Go 版本默认是所选 Go 的版本 | | 工具链 | 在常见位置找到电脑上的 Go 安装;项目可以固定用其中一个构建和运行 | +| 设置预览 | Go 语言设置页顶部的预览画出悬停文档、参数占位符、gofumpt 格式化和 Staticcheck 分析在编辑器里的效果;Go 构建系统页画出 Lithe 查找 go 的顺序和当前用的是哪一步。改了还没应用的选项会先在预览里显示,并标出“含未应用的修改” | ## 设置和构建选项 @@ -176,7 +182,7 @@ go install github.com/go-delve/delve/cmd/dlv@latest ## 安装 1. 从 [Releases](https://github.com/Lithe-IDEA/lithe-plugin-go/releases) 下载对应平台的包:macOS 用 `go-support-<版本>-darwin.zip`, - Windows 用 `go-support-<版本>-windows.zip`。 + Windows x64 用 `go-support-<版本>-windows-x64.zip`,Windows ARM64 用 `go-support-<版本>-windows-arm64.zip`。 2. 在 Lithe 中打开 **设置 → 插件**,点击页面标题栏右侧的 **从文件安装…**,选中这个 zip,核对 SHA-256 和权限后确认。 3. 打开含 `go.mod` 的项目。构建窗口会出现 Go Modules,打开 `.go` 文件时启动 gopls。 @@ -215,17 +221,20 @@ Delve 也由 Lithe 启动:每次调试的适配器启动结果(解析、启 ## 本地打包 -需要 Node.js 22+ 和 `zip`(在 macOS 或 Linux 上打包): +先构建画设置预览的后端,需要 Rust 工具链和对应的 target(`rustup target add`):macOS 上构建 darwin(Apple Silicon 和 Intel +合成一个通用二进制并做 ad-hoc 签名),Windows 上构建 windows-x64 和 windows-arm64。再用 Node.js 22+ 和 `zip`(macOS 或 Linux)打包: ```bash -node scripts/package.mjs +node scripts/build-backend.mjs darwin # 写到 .artifacts/backend-darwin/ +node scripts/package.mjs --platforms darwin # CI 和发布时三个平台都打 ``` -输出 `dist/go-support-<版本>-darwin.zip`、字节相同的 `dist/go-support-<版本>-windows.zip` 和它们的 SHA-256。本地开发时,用 **设置 → 插件 → 从文件安装…** +输出 `dist/go-support-<版本>-<平台>.zip` 和它们的 SHA-256。每个包带 `bin/backend`(Windows 是 `bin/backend.exe`, +包里的 `plugin.json` 相应改写启动路径)和列出后端所用 crate 许可证的 `THIRD_PARTY_LICENSES.txt`。本地开发时,用 **设置 → 插件 → 从文件安装…** 选择这个 zip 安装。 ```bash -node --test scripts/package/*.test.mjs # 核对 Windows 包 +node --test scripts/package/*.test.mjs # 核对 dist/ 里的每个包 node scripts/test.mjs # 用真实的 go、gopls、dlv 跑清单里的命令 ``` @@ -249,8 +258,9 @@ CI 在 macOS、Windows x64 和 Windows ARM64 上跑这个脚本,Windows 上测 需要 Node.js 22+、Go、Rust 工具链(构建宿主固定的 Rust Core)、`git`,以及测试要用的 `go`、`gopls` 和 `dlv`: ```bash -node scripts/package.mjs -LITHE_TEST_GO_PLUGIN_ARCHIVE="$PWD/dist/go-support-1.1.0-darwin.zip" node scripts/e2e-host.mjs +node scripts/build-backend.mjs darwin +node scripts/package.mjs --platforms darwin +LITHE_TEST_GO_PLUGIN_ARCHIVE="$PWD/dist/go-support-1.3.0-darwin.zip" node scripts/e2e-host.mjs ``` 插件包路径要写绝对路径。脚本把固定版本的宿主(只取 `desktop/` 和 `scripts/`)检出到 `.artifacts/lithe-host`, @@ -276,7 +286,7 @@ Lithe 主仓库的功能矩阵不收录插件能力,改动插件行为时在 3. `Release` 工作流会核对标签与版本一致、打包并发布 Release(说明里附 SHA-256 和 `docs/releases/v<版本>.md`)。`release.yml` 里 `PRERELEASE_TAGS` 列出的版本会标为预发布版本: - 目前是只能装进新版桌面端的 `v0.0.1`、依赖宿主 #1954、#1964、#1971 的 `v1.0.0` 和图标依赖宿主 #2169 的 `v1.2.0`; + 目前是只能装进新版桌面端的 `v0.0.1`、依赖宿主 #1954、#1964、#1971 的 `v1.0.0` 、图标依赖宿主 #2169 的 `v1.2.0` 和设置预览依赖宿主 #2183 的 `v1.3.0`; `v1.0.1` 和 `v1.1.0` 是正式版本。 4. Lithe Store 的自动追踪会发现稳定版本并开合并请求,合并后用户即可在 Lithe 中更新。自动追踪会跳过预发布版本; 需要收录时在 Store 中手工提交条目,并使用已发布 ZIP 的实际 SHA-256。 diff --git a/backend/Cargo.lock b/backend/Cargo.lock new file mode 100644 index 0000000..9a21662 --- /dev/null +++ b/backend/Cargo.lock @@ -0,0 +1,121 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "go-support-backend" +version = "1.3.0" +dependencies = [ + "lithe-plugin-sdk", + "serde_json", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "lithe-plugin-sdk" +version = "0.4.0" +source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust?rev=545ca11fb971795a9937f0f60bcc29afebe3b8be#545ca11fb971795a9937f0f60bcc29afebe3b8be" +dependencies = [ + "base64", + "serde_json", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/backend/Cargo.toml b/backend/Cargo.toml new file mode 100644 index 0000000..ae402f3 --- /dev/null +++ b/backend/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "go-support-backend" +description = "The Go Support plugin's backend: the previews its settings regions draw." +# Kept equal to the plugin's version; scripts/package.mjs refuses a mismatch. +version = "1.3.0" +edition = "2021" +license = "Apache-2.0" +rust-version = "1.87" +publish = false + +[[bin]] +name = "backend" +path = "src/main.rs" + +[dependencies] +# The Rust plugin SDK has no release tag yet; this is Lithe-core-rust main with +# the plugin views contract (Lithe-core-rust#104), the Core that host +# 1lck/Lithe-IDEA#2183 pins. +lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", rev = "545ca11fb971795a9937f0f60bcc29afebe3b8be" } +serde_json = "1" + +[profile.release] +strip = true +lto = true +codegen-units = 1 +opt-level = "s" diff --git a/backend/src/language.rs b/backend/src/language.rs new file mode 100644 index 0000000..4038e35 --- /dev/null +++ b/backend/src/language.rs @@ -0,0 +1,494 @@ +//! The Go language page's preview: what each gopls option does to a piece of +//! code, in four cards that follow the rows below them. +//! +//! The scene is drawn for the region's width in the smallest settings +//! window, 613 points as measured in the host, so a unit is a point there. +//! 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 crate::scene::{ + code, column, group, pair, path, pill, rect, runs, squiggle, text, token, Node, + MONO_ADVANCE, +}; +use crate::settings::{Hover, Settings}; +use crate::words::Words; +use serde_json::{json, Value}; + +pub const CANVAS_ID: &str = "gopls-preview"; + +/// The settings the cards show; a draft of any of them marks the preview. +pub const SETTINGS: [&str; 4] = ["hoverKind", "usePlaceholders", "gofumpt", "staticcheck"]; + +pub const WIDTH: f64 = 610.0; +const HEADER: f64 = 28.0; +const GAP: f64 = 10.0; +const CARD_W: f64 = (WIDTH - GAP) / 2.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; +const BOX_W: f64 = CARD_W - 2.0 * BOX_X; +/// The box heights of the first row (hover, completion) and the second +/// (gofumpt, Staticcheck): the hover's full documentation 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]; +pub const HEIGHT: f64 = HEADER + CARD_H[0] + GAP + 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 plain() -> Value { + token("$text") +} +fn editor() -> Value { + pair("#FFFFFF", "#1E1F22") +} +fn popup() -> Value { + pair("#F7F8FA", "#2B2D30") +} + +/// 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 the value is a draft not applied yet. + changed: bool, + preview: Vec, +} + +pub fn canvas(settings: &Settings, words: &Words) -> Value { + let changed = settings.any_changed(&SETTINGS); + let mut nodes = vec![ + text(0.0, 17.0, words.preview_title, "strong"), + text( + WIDTH, + 17.0, + if changed { + words.includes_draft + } else { + words.follows_options + }, + "caption", + ) + .align("end") + .color(token(if changed { "$accent" } else { "$textMuted" })), + ]; + let hover = Hover::ALL + .iter() + .position(|hover| *hover == settings.hover) + .expect("every hover kind has words"); + let switch = |on: bool, note_on: &'static str, note_off: &'static str| { + ( + if on { words.on } else { words.off }, + if on { note_on } else { note_off }, + ) + }; + let (placeholders, placeholders_note) = + switch(settings.placeholders, words.placeholders_on, words.placeholders_off); + let (gofumpt, gofumpt_note) = switch(settings.gofumpt, words.gofumpt_on, words.gofumpt_off); + let (staticcheck, staticcheck_note) = + switch(settings.staticcheck, words.staticcheck_on, words.staticcheck_off); + let cards = [ + Card { + title: words.hover_title, + value: words.hover_options[hover], + lit: true, + note: words.hover_notes[hover], + changed: settings.is_changed("hoverKind"), + preview: hover_preview(settings.hover), + }, + Card { + title: words.completion_title, + value: placeholders, + lit: settings.placeholders, + note: placeholders_note, + changed: settings.is_changed("usePlaceholders"), + preview: completion_preview(settings.placeholders, words), + }, + Card { + title: words.format_title, + value: gofumpt, + lit: settings.gofumpt, + note: gofumpt_note, + changed: settings.is_changed("gofumpt"), + preview: format_preview(settings.gofumpt), + }, + Card { + title: words.staticcheck_title, + value: staticcheck, + lit: settings.staticcheck, + note: staticcheck_note, + changed: settings.is_changed("staticcheck"), + preview: staticcheck_preview(settings.staticcheck), + }, + ]; + for (index, card) in cards.into_iter().enumerate() { + let row = index / 2; + let x = (index % 2) as f64 * (CARD_W + GAP); + let y = HEADER + row as f64 * (CARD_H[0] + GAP); + nodes.push(group(x, y, draw(card, row))); + } + json!({ + "type": "canvas", + "id": CANVAS_ID, + "label": words.preview_label, + "height": HEIGHT.ceil() as u64, + "viewBox": [0, 0, WIDTH, HEIGHT], + "nodes": nodes.into_iter().map(Value::from).collect::>(), + }) +} + +/// A card in row `row`: 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. +fn draw(card: Card, row: usize) -> Vec { + let (fill, ink) = if card.lit { + (token("$selection"), token("$accent")) + } 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[row]) + .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, BOX_W, BOX_H[row]) + .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 +} + +/// A hover over `strings.Split`, with as much documentation as `hover` shows. +/// The documentation is Go's own, which gopls shows as it is, wrapped to the +/// popup. +fn hover_preview(hover: Hover) -> Vec { + const POPUP_X: f64 = 4.0; + const POPUP_W: f64 = BOX_W - 2.0 * POPUP_X; + const INSET: f64 = 9.0; + const TEXT_W: f64 = POPUP_W - 2.0 * INSET; + let code_x = 10.0; + let signature = || { + runs( + INSET, + 15.0, + &[ + ("func ", keyword()), + ("Split", function()), + ("(s, sep ", plain()), + ("string", keyword()), + (") []", plain()), + ("string", keyword()), + ], + "monoSmall", + ) + }; + let doc = |y: f64, line: &str| { + text(INSET, y, line, "caption") + .color(token("$textSecondary")) + .max_width(TEXT_W) + }; + let divider = || rect(INSET, 21.0, TEXT_W, 1.0).fill(token("$line")); + let synopsis = || { + [ + doc(34.0, "Split slices s into all substrings separated"), + doc(47.0, "by sep and returns a slice of the substrings"), + doc(60.0, "between those separators."), + ] + }; + let (height, mut body) = match hover { + Hover::Full => { + let mut body = vec![signature(), divider()]; + body.extend(synopsis()); + body.push(doc(73.0, "If s does not contain sep and sep is not…")); + body.push( + text(INSET, 87.0, "pkg.go.dev/strings#Split", "caption").color(token("$accent")), + ); + (94.0, body) + } + Hover::Synopsis => { + let mut body = vec![signature(), divider()]; + body.extend(synopsis()); + (68.0, body) + } + Hover::SingleLine => ( + 22.0, + vec![text( + INSET, + 15.0, + "func strings.Split(s string, sep string) []string", + "caption", + ) + .max_width(TEXT_W)], + ), + Hover::Signature => (22.0, vec![signature()]), + }; + let mut frame = vec![rect(0.0, 0.0, POPUP_W, height) + .radius(6.0) + .fill(popup()) + .stroke(token("$line"), 1.0) + .set("shadow", 1)]; + frame.append(&mut body); + let mut nodes = vec![rect(column(code_x, 17) - 1.0, 6.0, 5.0 * MONO_ADVANCE + 2.0, 15.0) + .radius(2.0) + .fill(token("$selection"))]; + nodes.extend(code( + code_x, + 17.0, + &[ + ("parts := strings.", plain()), + ("Split", function()), + ("(line, ", plain()), + ("\",\"", string()), + (")", plain()), + ], + )); + nodes.push(group(POPUP_X, 24.0, frame)); + nodes +} + +/// Completing `strings.Spl`, with and without parameter placeholders. +fn completion_preview(placeholders: bool, words: &Words) -> Vec { + let code_x = 10.0; + let label = |y: f64, words: &str| { + text(code_x, y, words, "caption") + .color(token("$textMuted")) + .max_width(BOX_W - 2.0 * code_x) + }; + let caret = |x: f64, y: f64| rect(x, y - 10.5, 1.2, 13.0).fill(plain()); + let list_x = column(code_x, 9); + let list_w = BOX_W - list_x - 10.0; + let mut nodes = vec![label(17.0, words.before)]; + nodes.extend(code(code_x, 35.0, &[("parts := strings.Spl", plain())])); + nodes.extend([ + caret(column(code_x, 20), 35.0), + group( + list_x, + 42.0, + vec![ + rect(0.0, 0.0, list_w, 22.0) + .radius(4.0) + .fill(popup()) + .stroke(token("$line"), 1.0) + .set("shadow", 1), + rect(2.0, 2.0, list_w - 4.0, 18.0) + .radius(3.0) + .fill(token("$selection")), + rect(7.0, 6.0, 10.0, 10.0).radius(2.0).fill(function()), + text(12.0, 14.5, "f", "caption").align("center").color("#FFFFFF"), + runs( + 23.0, + 15.0, + &[("Split", plain()), ("(s, sep string)", token("$textMuted"))], + "monoSmall", + ) + .max_width(list_w - 30.0), + ], + ), + label(86.0, words.after), + ]); + if placeholders { + // The placeholders are boxed as the editor boxes a snippet's fields; + // the first one is selected. + for (start, length, selected) in [(23, 1, true), (26, 3, false)] { + let mut field = rect( + column(code_x, start) - 1.0, + 92.0, + length as f64 * MONO_ADVANCE + 2.0, + 16.0, + ) + .radius(3.0) + .stroke(token("$accent"), 1.0); + if selected { + field = field.fill(token("$selection")); + } + nodes.push(field); + } + nodes.extend(code( + code_x, + 104.0, + &[ + ("parts := strings.", plain()), + ("Split", function()), + ("(s, sep)", plain()), + ], + )); + } else { + nodes.extend(code( + code_x, + 104.0, + &[ + ("parts := strings.", plain()), + ("Split", function()), + ("()", plain()), + ], + )); + nodes.push(caret(column(code_x, 23), 104.0)); + } + nodes +} + +/// The first code line's baseline in the gofumpt and Staticcheck 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 +} + +/// The same function as gofmt and as gofumpt format it; what gofumpt changes +/// is tinted. +fn format_preview(gofumpt: bool) -> Vec { + let signature = vec![ + ("func ", keyword()), + ("save", function()), + ("(p ", plain()), + ("string", keyword()), + (") ", plain()), + ("error", keyword()), + (" {", plain()), + ]; + let body = |mode: &'static str| { + vec![ + (" ", plain()), + ("return ", keyword()), + ("os.Chmod(p, ", plain()), + (mode, number()), + (")", plain()), + ] + }; + let close = vec![("}", plain())]; + if !gofumpt { + return numbered(vec![signature, vec![], body("0644"), close]); + } + let mut nodes = vec![ + // The line the blank one closed up into, and the new octal literal. + rect(0.0, CODE_TOP + LINE - 12.0, BOX_W, LINE) + .fill(token("$success")) + .opacity(0.08), + rect(column(CODE_X, 23) - 2.0, CODE_TOP + LINE - 12.0, 5.0 * MONO_ADVANCE + 4.0, LINE) + .radius(3.0) + .fill(token("$success")) + .opacity(0.2), + ]; + nodes.extend(numbered(vec![signature, body("0o644"), close])); + nodes +} + +/// A comparison staticcheck's SA6005 reports and gopls's default analyses +/// do not. The message is staticcheck's own. +fn staticcheck_preview(staticcheck: bool) -> Vec { + let mut nodes = numbered(vec![ + vec![ + ("func ", keyword()), + ("same", function()), + ("(a, b ", plain()), + ("string", keyword()), + (") ", plain()), + ("bool", keyword()), + (" {", plain()), + ], + vec![ + (" ", plain()), + ("return ", keyword()), + ("strings.", plain()), + ("ToLower", function()), + ("(a) ==", plain()), + ], + vec![ + (" strings.", plain()), + ("ToLower", function()), + ("(b)", plain()), + ], + vec![("}", plain())], + ]); + if !staticcheck { + return nodes; + } + for (line, start, end) in [(1.0, 11, 32), (2.0, 8, 26)] { + nodes.push( + path(squiggle( + column(CODE_X, start), + column(CODE_X, end), + CODE_TOP + line * LINE + 3.0, + )) + .stroke(token("$warning"), 1.0), + ); + } + let bar_w = BOX_W - 12.0; + nodes.push(group( + 6.0, + CODE_TOP + 3.0 * LINE + 10.0, + vec![ + rect(0.0, 0.0, bar_w, 22.0) + .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"), + runs( + 25.0, + 15.0, + &[ + ("SA6005", token("$text")), + (": should use strings.EqualFold instead", token("$textSecondary")), + ], + "caption", + ) + .max_width(bar_w - 31.0), + ], + )); + nodes +} diff --git a/backend/src/main.rs b/backend/src/main.rs new file mode 100644 index 0000000..168b69d --- /dev/null +++ b/backend/src/main.rs @@ -0,0 +1,353 @@ +//! The Go Support plugin's backend. It draws 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. It reads +//! settings only; gopls, go 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}; +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 Go language page and the one on the Go 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 TOOLCHAIN_REGION: &str = "toolchain"; + +fn main() { + let mut backend = Backend::new("go-support").version(env!("CARGO_PKG_VERSION")); + let registered = backend.view(VIEW, view).and_then(|backend| { + // A view answers every keystroke in the settings window; its failures + // and degradations are still logged. + backend.suppress_success_diagnostics(VIEW) + }); + if registered.is_err() { + std::process::exit(1); + } + std::process::exit(backend.listen()); +} + +fn view(event: ViewEvent, context: &Context) -> Result { + let nodes = match event.kind { + ViewEventKind::Open | ViewEventKind::Settings => render(&event)?, + _ => return Ok(ViewResult::Unchanged), + }; + if nodes.1 > 0 { + context + .diagnostics() + .degraded(VIEW, "setting.unrecognized", Some(nodes.1))?; + } + Ok(ViewResult::View(nodes.0)) +} + +/// The nodes of the event's region, 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 settings = Settings::read(event); + let words = words::for_language(&event.language); + let canvas = match region.as_str() { + LANGUAGE_REGION => language::canvas(&settings, words), + TOOLCHAIN_REGION => resolution::canvas(&settings, words), + _ => return Err(unknown_region()), + }; + Ok((vec![canvas], settings.unrecognized)) +} + +fn unknown_region() -> PluginError { + PluginError::new( + "go.view.unknownRegion", + "This view draws the Go 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 { + ViewEvent::parse(&json!({ + "event": "settings", + "instance": "i1", + "surface": { "settingRegionID": region }, + "language": language, + "settings": { "effective": effective, "draft": draft }, + })) + .unwrap() + } + + fn nodes(region: &str, language: &str, effective: Value, draft: Value) -> Vec { + render(&event(region, language, effective, draft)).unwrap().0 + } + + /// 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![ + (json!({}), json!({})), + ( + json!({ "usePlaceholders": true, "gofumpt": true, "staticcheck": true }), + json!({ "goExecutable": "/Users/someone/sdk/go1.23.4/bin/go" }), + ), + ]; + for hover in settings::Hover::ALL { + cases.push((json!({ "hoverKind": hover.value() }), json!({}))); + } + cases + } + + /// The limits `plugin-ui.schema.json` sets on what the view draws here. + fn check_limits(nodes: &[Value]) { + let canvases: Vec<_> = all(nodes) + .into_iter() + .filter(|node| node["type"] == "canvas") + .collect(); + assert!(!canvases.is_empty() && canvases.len() <= 8); + for canvas in canvases { + let label = canvas["label"].as_str().unwrap(); + assert!(!label.trim().is_empty() && label.chars().count() <= 120); + let height = canvas["height"].as_u64().expect("a whole height"); + assert!((1..=2000).contains(&height)); + let mut scene = Vec::new(); + walk(canvas, &mut scene); + assert!(scene.len() <= 2000); + 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); + } + for color in ["fill", "color", "stroke"] { + if let Some(value) = node.get(color) { + check_color(value); + } + } + } + } + } + + 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, TOOLCHAIN_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), (TOOLCHAIN_REGION, 344.0)]; + + #[test] + fn each_scene_fits_its_region_one_unit_to_a_point() { + for (region, width) in REGION_WIDTHS { + for language in ["en", "zh-Hans"] { + let nodes = nodes(region, language, json!({}), json!({})); + let view_box = nodes[0]["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!( + nodes[0]["height"].as_f64().unwrap(), + view_box[3].as_f64().unwrap().ceil(), + "{region}" + ); + assert!(nodes[0].get("pan").is_none()); + } + } + } + + #[test] + fn each_region_draws_its_own_preview() { + for (region, id) in [ + (LANGUAGE_REGION, language::CANVAS_ID), + (TOOLCHAIN_REGION, resolution::CANVAS_ID), + ] { + let nodes = nodes(region, "en", json!({}), json!({})); + assert_eq!(nodes.len(), 1); + assert_eq!(nodes[0]["type"], "canvas"); + assert_eq!(nodes[0]["id"], id); + } + } + + #[test] + fn the_hover_preview_shows_as_much_documentation_as_the_setting() { + let shown = |hover: &str| { + words_of(&nodes(LANGUAGE_REGION, "en", json!({ "hoverKind": hover }), json!({}))) + }; + let full = shown("FullDocumentation"); + assert!(full.contains("pkg.go.dev/strings#Split")); + let synopsis = shown("SynopsisDocumentation"); + assert!(synopsis.contains("those separators.") && !synopsis.contains("pkg.go.dev")); + let line = shown("SingleLine"); + assert!(line.contains("func strings.Split(s string, sep string) []string")); + assert!(!line.contains("Split slices")); + let signature = shown("NoDocumentation"); + assert!(signature.contains("func Split(s, sep string) []string")); + assert!(!signature.contains("Split slices")); + } + + #[test] + fn a_draft_shows_in_the_preview_before_it_is_applied() { + let saved = words_of(&nodes(LANGUAGE_REGION, "en", json!({ "gofumpt": false }), json!({}))); + assert!(saved.contains("0644") && !saved.contains("0o644")); + assert!(saved.contains("follows the options below")); + let draft = words_of(&nodes( + LANGUAGE_REGION, + "en", + json!({ "gofumpt": false }), + json!({ "gofumpt": true }), + )); + assert!(draft.contains("0o644")); + assert!(draft.contains("Includes changes not applied yet")); + } + + #[test] + fn a_set_go_executable_is_the_only_step_in_use() { + let unset = words_of(&nodes(TOOLCHAIN_REGION, "en", json!({}), json!({}))); + assert!(unset.contains("Skipped") && unset.contains("Tried first")); + assert!(!unset.contains("In use")); + let set = words_of(&nodes( + TOOLCHAIN_REGION, + "en", + json!({ "goExecutable": "/Users/someone/sdk/go1.23.4/bin/go" }), + json!({}), + )); + assert!(set.contains("In use") && set.contains("Not used")); + assert!(set.contains("/bin/go") && !set.contains("Includes changes")); + let draft = words_of(&nodes( + TOOLCHAIN_REGION, + "zh-Hans", + json!({}), + json!({ "goExecutable": "/opt/go/bin/go" }), + )); + assert!(draft.contains("使用中") && draft.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(), "go.view.unknownRegion"); + let window = ViewEvent::parse(&json!({ + "event": "open", + "instance": "i1", + "surface": { "toolWindowID": "go" }, + "language": "en", + "settings": { "effective": Map::new(), "draft": Map::new() }, + })) + .unwrap(); + assert_eq!(render(&window).unwrap_err().code(), "go.view.unknownRegion"); + } + + #[test] + fn a_value_the_preview_cannot_read_is_counted() { + let (_, unrecognized) = render(&event( + LANGUAGE_REGION, + "en", + json!({ "hoverKind": "Structured" }), + json!({ "staticcheck": "yes" }), + )) + .unwrap(); + assert_eq!(unrecognized, 2); + } +} diff --git a/backend/src/resolution.rs b/backend/src/resolution.rs new file mode 100644 index 0000000..6f0ef0d --- /dev/null +++ b/backend/src/resolution.rs @@ -0,0 +1,246 @@ +//! The Go build page's diagram: the order in which Lithe looks for the `go` +//! program, and which step the `Go executable` row below it decides. +//! +//! The steps follow `toolDefinitions[go].invocation.executables` in +//! `plugin.json`: a set `goExecutable` is the only candidate tried, and an +//! unset one leaves the toolchain's Go, then the automatic lookup. The view +//! sees settings only, so it shows the order, not the program 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, and a unit is a point. + +use crate::scene::{group, pair, path, pill, rect, tail, text, text_width, token, Node, CAPTION}; +use crate::settings::Settings; +use crate::words::Words; +use serde_json::{json, Value}; + +pub const CANVAS_ID: &str = "go-resolution"; + +pub const WIDTH: f64 = 340.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_W: f64 = WIDTH - STEP_X; +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 top of the row of what the program is used for. +const USES_Y: f64 = HEADER + 3.0 * (STEP_H + STEP_GAP) + 4.0; +pub const HEIGHT: f64 = USES_Y + 22.0; + +/// How many characters of the set path a step shows; the end, which names +/// the program, is kept. +const PATH_ROOM: usize = 42; + +/// A step's look: the step in force, a step left out, or one in the order. +#[derive(Clone, Copy, PartialEq)] +enum Look { + InUse, + Dimmed, + Plain, +} + +/// A step's chip, by its meaning. +#[derive(Clone, Copy)] +enum Chip { + Success, + Accent, + Neutral, +} + +struct Step<'a> { + number: u8, + title: &'a str, + lines: [Line<'a>; 2], + chip: (&'a str, Chip), + look: Look, +} + +enum Line<'a> { + Words(&'a str, Value), + Path(String), +} + +pub fn canvas(settings: &Settings, words: &Words) -> Value { + let changed = settings.is_changed("goExecutable"); + let set = !settings.go_executable.is_empty(); + let muted = || token("$textMuted"); + let secondary = || token("$textSecondary"); + let steps = [ + Step { + number: 1, + title: words.step_setting, + lines: if set { + [ + Line::Path(tail(&settings.go_executable, PATH_ROOM)), + Line::Words(words.step_setting_strict, secondary()), + ] + } else { + [ + Line::Words(words.step_setting_unset, muted()), + Line::Words(words.step_setting_only, secondary()), + ] + }, + chip: if set { + (words.in_use, Chip::Success) + } else { + (words.skipped, Chip::Neutral) + }, + look: if set { Look::InUse } else { Look::Dimmed }, + }, + Step { + number: 2, + title: words.step_toolchain, + lines: [ + Line::Words(words.step_toolchain_detail[0], secondary()), + Line::Words(words.step_toolchain_detail[1], muted()), + ], + chip: if set { + (words.not_used, Chip::Neutral) + } else { + (words.first, Chip::Accent) + }, + look: if set { Look::Dimmed } else { Look::Plain }, + }, + Step { + number: 3, + title: words.step_automatic, + lines: [ + Line::Words(words.step_automatic_detail[0], secondary()), + Line::Words(words.step_automatic_detail[1], secondary()), + ], + chip: if set { + (words.not_used, Chip::Neutral) + } else { + (words.last, Chip::Neutral) + }, + look: if set { Look::Dimmed } else { Look::Plain }, + }, + ]; + + let mut nodes = vec![text(0.0, 17.0, words.resolution_title, "strong")]; + if changed { + nodes.push( + text(WIDTH, 17.0, words.includes_draft, "caption") + .align("end") + .color(token("$accent")), + ); + } + 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; past a step in force the order stops, + // and the rail into the next step fades with it. + let above = y - STEP_GAP - STEP_H + TITLE_MIDDLE + DOT / 2.0 + 4.0; + let below = y + TITLE_MIDDLE - DOT / 2.0 - 4.0; + let rail = path(format!("M{RAIL} {above} V{below}")) + .stroke(token("$line"), 2.0) + .set("cap", "round"); + nodes.push(if step.look == Look::Dimmed { + rail.opacity(0.5) + } else { + rail + }); + } + nodes.push(draw(y, step)); + } + nodes.extend(uses(words).0); + json!({ + "type": "canvas", + "id": CANVAS_ID, + "label": words.resolution_label, + "height": HEIGHT.ceil() as u64, + "viewBox": [0, 0, WIDTH, HEIGHT], + "nodes": nodes.into_iter().map(Value::from).collect::>(), + }) +} + +/// A step at `y`: its numbered dot on the rail and its card. +fn draw(y: f64, step: &Step) -> Node { + let in_use = step.look == Look::InUse; + let mut frame = rect(0.0, 0.0, STEP_W, STEP_H).radius(8.0); + frame = if in_use { + frame.fill(token("$selection")).stroke(token("$accent"), 1.5) + } else { + frame.fill(token("$surface")).stroke(token("$line"), 1.0) + }; + let (dot, number) = if in_use { + (token("$accent"), Value::from("#FFFFFF")) + } else { + (token("$badge"), token("$textSecondary")) + }; + let (fill, ink) = match step.chip.1 { + Chip::Success => (pair("#E6F4EA", "#253A2B"), token("$success")), + Chip::Accent => (token("$selection"), token("$accent")), + Chip::Neutral => (token("$badge"), token("$textSecondary")), + }; + let (_, chip_w) = pill(0.0, 0.0, step.chip.0, fill.clone(), ink.clone()); + let chip_x = STEP_W - 10.0 - chip_w; + let (chip, _) = pill(chip_x, TITLE_MIDDLE - 10.0, step.chip.0, fill, ink); + let mut card = vec![ + frame, + text(12.0, TITLE_MIDDLE + 4.5, step.title, "strong").max_width(chip_x - 12.0 - 10.0), + chip, + ]; + for (line, y) in step.lines.iter().zip([40.0, 55.0]) { + card.push(match line { + Line::Words(words, color) => text(12.0, y, words, "caption") + .color(color.clone()) + .max_width(STEP_W - 24.0), + Line::Path(value) => text(12.0, y, value, "monoSmall") + .color(token("$text")) + .max_width(STEP_W - 24.0), + }); + } + let step_group = group( + 0.0, + y, + vec![ + rect(RAIL - DOT / 2.0, TITLE_MIDDLE - DOT / 2.0, DOT, DOT) + .radius(DOT / 2.0) + .fill(dot), + text(RAIL, TITLE_MIDDLE + 4.0, &step.number.to_string(), "caption") + .align("center") + .color(number), + group(STEP_X, 0.0, card), + ], + ); + if step.look == Look::Dimmed { + step_group.opacity(0.55) + } else { + step_group + } +} + +/// What Lithe runs the program for, after the steps, 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::words; + + #[test] + fn the_row_of_uses_fits_the_width_in_both_languages() { + for language in ["en", "zh-Hans"] { + let (_, end) = uses(words::for_language(language)); + assert!(end <= WIDTH, "{language}: {end}"); + } + } +} diff --git a/backend/src/scene.rs b/backend/src/scene.rs new file mode 100644 index 0000000..fe2fec4 --- /dev/null +++ b/backend/src/scene.rs @@ -0,0 +1,271 @@ +//! 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 its region has in +//! the smallest settings window and is as tall as its view box, so one unit +//! is one point there, and a wider window shows it whole at the same size. + +use serde_json::{json, Map, Value}; + +/// The pixel size of the host's `caption` text style at scale 1. +pub const CAPTION: f64 = 11.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) + } +} + +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() +} + +/// The end of `value` in at most `room` characters, with an ellipsis in +/// front when it is cut: for a path, the end names the program. +pub fn tail(value: &str, room: usize) -> String { + let count = value.chars().count(); + if count <= room { + return value.to_string(); + } + let kept: String = value.chars().skip(count - room + 1).collect(); + format!("…{kept}") +} + +#[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 a_long_path_keeps_its_end() { + assert_eq!(tail("/usr/local/go/bin/go", 30), "/usr/local/go/bin/go"); + let cut = tail("/Users/someone/sdk/go1.23.4/bin/go", 12); + assert_eq!(cut.chars().count(), 12); + assert!(cut.starts_with('…') && cut.ends_with("/bin/go")); + } + + #[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_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/settings.rs b/backend/src/settings.rs new file mode 100644 index 0000000..fc3c2ed --- /dev/null +++ b/backend/src/settings.rs @@ -0,0 +1,194 @@ +//! 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; + +/// How much documentation a gopls hover shows: the `hoverKind` setting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hover { + Full, + Synopsis, + SingleLine, + Signature, +} + +impl Hover { + pub const ALL: [Hover; 4] = [ + Hover::Full, + Hover::Synopsis, + Hover::SingleLine, + Hover::Signature, + ]; + + fn parse(value: &str) -> Option { + Some(match value { + "FullDocumentation" => Hover::Full, + "SynopsisDocumentation" => Hover::Synopsis, + "SingleLine" => Hover::SingleLine, + "NoDocumentation" => Hover::Signature, + _ => return None, + }) + } + + pub fn value(self) -> &'static str { + match self { + Hover::Full => "FullDocumentation", + Hover::Synopsis => "SynopsisDocumentation", + Hover::SingleLine => "SingleLine", + Hover::Signature => "NoDocumentation", + } + } +} + +/// The plugin's settings as the settings window holds them now. +#[derive(Debug)] +pub struct Settings { + pub hover: Hover, + pub placeholders: bool, + pub gofumpt: bool, + pub staticcheck: bool, + /// The `goExecutable` path; empty when it is not set. + pub go_executable: String, + /// 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 hover = reader.read("hoverKind", Value::from("FullDocumentation"), |value| { + value.as_str().and_then(Hover::parse) + }); + let placeholders = reader.boolean("usePlaceholders"); + let gofumpt = reader.boolean("gofumpt"); + let staticcheck = reader.boolean("staticcheck"); + let go_executable = reader.read("goExecutable", Value::from(""), |value| { + value.as_str().map(|path| path.trim().to_string()) + }); + Self { + hover, + placeholders, + gofumpt, + staticcheck, + go_executable, + changed: reader.changed, + unrecognized: reader.unrecognized, + } + } + + /// 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) -> bool { + self.read(id, Value::Bool(false), Value::as_bool) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + pub 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_default() { + let settings = Settings::read(&event(json!({}), json!({}))); + assert_eq!(settings.hover, Hover::Full); + assert!(!settings.placeholders && !settings.gofumpt && !settings.staticcheck); + assert_eq!(settings.go_executable, ""); + assert_eq!(settings.unrecognized, 0); + assert!(!settings.any_changed(&["hoverKind", "gofumpt", "goExecutable"])); + } + + #[test] + fn the_draft_wins_over_the_saved_value_and_counts_as_a_change() { + let settings = Settings::read(&event( + json!({ "gofumpt": true, "hoverKind": "SingleLine", "staticcheck": true }), + json!({ "gofumpt": false, "staticcheck": true, "goExecutable": " /opt/go/bin/go " }), + )); + assert!(!settings.gofumpt); + assert_eq!(settings.hover, Hover::SingleLine); + assert_eq!(settings.go_executable, "/opt/go/bin/go"); + assert!(settings.is_changed("gofumpt")); + assert!(settings.is_changed("goExecutable")); + // A draft equal to the value in force changes nothing. + assert!(!settings.is_changed("staticcheck")); + assert!(!settings.is_changed("hoverKind")); + } + + #[test] + fn a_value_outside_the_declaration_shows_the_default_and_is_counted() { + let settings = Settings::read(&event( + json!({ "hoverKind": "Structured", "gofumpt": "yes" }), + json!({}), + )); + assert_eq!(settings.hover, Hover::Full); + assert!(!settings.gofumpt); + assert_eq!(settings.unrecognized, 2); + } + + #[test] + fn every_hover_kind_reads_back_from_its_value() { + for hover in Hover::ALL { + let settings = Settings::read(&event(json!({ "hoverKind": hover.value() }), json!({}))); + assert_eq!(settings.hover, hover); + } + } +} diff --git a/backend/src/words.rs b/backend/src/words.rs new file mode 100644 index 0000000..ef75263 --- /dev/null +++ b/backend/src/words.rs @@ -0,0 +1,178 @@ +//! 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`), so a card names the row +//! that changes it. +//! +//! Go code and gopls's own output, such as documentation and 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 hover_title: &'static str, + pub hover_options: [&'static str; 4], + /// What each hover option shows, in the order of `hover_options`. + pub hover_notes: [&'static str; 4], + + pub completion_title: &'static str, + pub before: &'static str, + pub after: &'static str, + pub placeholders_on: &'static str, + pub placeholders_off: &'static str, + + pub format_title: &'static str, + pub gofumpt_on: &'static str, + pub gofumpt_off: &'static str, + + pub staticcheck_title: &'static str, + pub staticcheck_on: &'static str, + pub staticcheck_off: &'static str, + + pub resolution_title: &'static str, + pub resolution_label: &'static str, + pub step_setting: &'static str, + pub step_setting_unset: &'static str, + pub step_setting_only: &'static str, + pub step_setting_strict: &'static str, + pub step_toolchain: &'static str, + pub step_toolchain_detail: [&'static str; 2], + pub step_automatic: &'static str, + pub step_automatic_detail: [&'static str; 2], + pub in_use: &'static str, + pub skipped: &'static str, + pub not_used: &'static str, + pub first: &'static str, + pub last: &'static str, + pub used_for: &'static str, + pub uses: [&'static str; 5], +} + +const ZH: Words = Words { + preview_title: "效果预览", + preview_label: "gopls 选项的效果预览", + follows_options: "示例代码,随下方选项即时变化", + includes_draft: "含未应用的修改", + on: "开", + off: "关", + + hover_title: "悬停文档", + hover_options: ["完整文档", "第一句", "一行", "只显示签名"], + hover_notes: [ + "签名、完整文档和文档链接", + "签名和文档的第一句", + "带包名的一行签名,不显示文档", + "只显示签名,不显示文档", + ], + + completion_title: "参数占位符", + before: "补全前", + after: "补全后", + placeholders_on: "补全时填好参数名,按 Tab 跳到下一个", + placeholders_off: "只补全函数名,参数自己填", + + format_title: "gofumpt 格式化", + gofumpt_on: "去掉块首空行,八进制写成 0o", + gofumpt_off: "标准 gofmt 格式", + + staticcheck_title: "Staticcheck 分析", + staticcheck_on: "另外报告 Staticcheck 发现的问题", + staticcheck_off: "只报告编译错误和 gopls 默认检查", + + resolution_title: "Lithe 按这个顺序找 go", + resolution_label: "Lithe 查找 go 程序的顺序", + step_setting: "本页「Go 程序」", + step_setting_unset: "未填写", + step_setting_only: "填写后只用这一个", + step_setting_strict: "不可用时报错,不往下找", + step_toolchain: "工具链里的 Go", + step_toolchain_detail: ["项目选的 Go,其次全局默认", "在「工具链」页选择"], + step_automatic: "自动查找", + step_automatic_detail: ["GOROOT → PATH 中的 go", "→ 常见安装位置"], + in_use: "使用中", + skipped: "跳过", + not_used: "不使用", + first: "先找这里", + last: "最后", + used_for: "用于", + uses: ["读取模块", "构建", "检查", "测试", "运行"], +}; + +const EN: Words = Words { + preview_title: "Preview", + preview_label: "Preview of the gopls options", + follows_options: "Sample code; follows the options below", + includes_draft: "Includes changes not applied yet", + on: "On", + off: "Off", + + hover_title: "Hover documentation", + hover_options: ["Full documentation", "First sentence", "One line", "Signature only"], + hover_notes: [ + "Signature, the whole doc and a link to it", + "Signature and the doc's first sentence", + "One line with the package; no documentation", + "The signature alone; no documentation", + ], + + completion_title: "Parameter placeholders", + before: "Typed", + after: "Completed", + placeholders_on: "Fills in parameter names; Tab moves to the next", + placeholders_off: "Completes the name; you type the arguments", + + format_title: "gofumpt formatting", + gofumpt_on: "No blank line opening a block; octal as 0o", + gofumpt_off: "Standard gofmt formatting", + + staticcheck_title: "Staticcheck analyses", + staticcheck_on: "Also reports what Staticcheck finds", + staticcheck_off: "Only compile errors and gopls's default checks", + + resolution_title: "How Lithe finds go", + resolution_label: "The order in which Lithe looks for the go program", + step_setting: "Go executable, below", + step_setting_unset: "Not set", + step_setting_only: "When set, only this one", + step_setting_strict: "If it fails, Lithe stops here", + step_toolchain: "Go in Toolchains", + step_toolchain_detail: ["The project's Go, then the default", "Chosen on the Toolchains page"], + step_automatic: "Automatic", + step_automatic_detail: ["GOROOT → go on PATH", "→ usual install folders"], + in_use: "In use", + skipped: "Skipped", + not_used: "Not used", + first: "Tried first", + last: "Tried last", + used_for: "Used to", + uses: ["read the module", "build", "vet", "test", "run"], +}; + +/// 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/language-en-default-light.png b/docs/assets/settings-previews/language-en-default-light.png new file mode 100644 index 0000000..0ee9b89 Binary files /dev/null and b/docs/assets/settings-previews/language-en-default-light.png differ diff --git a/docs/assets/settings-previews/language-zh-Hans-on-dark.png b/docs/assets/settings-previews/language-zh-Hans-on-dark.png new file mode 100644 index 0000000..bbb9041 Binary files /dev/null and b/docs/assets/settings-previews/language-zh-Hans-on-dark.png differ diff --git a/docs/assets/settings-previews/toolchain-en-on-light.png b/docs/assets/settings-previews/toolchain-en-on-light.png new file mode 100644 index 0000000..2bb6a12 Binary files /dev/null and b/docs/assets/settings-previews/toolchain-en-on-light.png differ diff --git a/docs/assets/settings-previews/toolchain-zh-Hans-on-dark.png b/docs/assets/settings-previews/toolchain-zh-Hans-on-dark.png new file mode 100644 index 0000000..3509b5e Binary files /dev/null and b/docs/assets/settings-previews/toolchain-zh-Hans-on-dark.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 91857c8..1922a5c 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -23,6 +23,7 @@ | `go-support-plugin` | gopls 代码智能、Go Modules 构建、运行与 `go test` | implemented / pending | implemented / pending | 2026-11-15 macOS 宿主端到端测试通过;Windows ARM64、x64 [原生 CI 通过](https://github.com/Lithe-IDEA/lithe-plugin-go/actions/runs/43728078241) | | `go-debug-delve` | 用用户的 Delve 调试 Go 包 | implemented / pending | partial / pending | 2026-11-15 macOS 宿主端到端测试通过;Windows x64 [原生 CI 通过](https://github.com/Lithe-IDEA/lithe-plugin-go/actions/runs/43728078241);Windows ARM64 上 Delve 不支持 | | `go-run-configuration-types` | 「运行/调试配置」里的 Go 构建和 Go 测试 | implemented / pending | implemented / pending | 2026-11-18 macOS 宿主端到端测试通过(宿主 a8797ae);Windows 只有命令层面的 `scripts/test.mjs` | +| `go-settings-previews` | Go 语言设置页和 Go 构建系统页里插件自己画的预览 | implemented / pending | implemented / pending | 2026-11-19 macOS 宿主端到端测试通过(宿主 34afcaf11,1lck/Lithe-IDEA#2183);Windows 后端只在 CI 构建,没有在 Windows 版 Lithe 里运行过 | | `go-project-generator` | 「新建项目」里的 Go 模块,GOROOT 选择和 Go 版本默认值 | implemented / pending | implemented / pending | 2026-11-15 macOS 宿主集成测试通过;Windows ARM64、x64 [原生 CI 通过](https://github.com/Lithe-IDEA/lithe-plugin-go/actions/runs/43728078241)(模板生成的模块能构建和测试) | ## go-support-plugin @@ -36,7 +37,7 @@ | 平台 | 实现 | 验证 | 说明 | | --- | --- | --- | --- | | macOS | implemented | pending | 发布包同时支持 Apple Silicon 和 Intel Mac | -| Windows | implemented | pending | `-windows.zip` 与 darwin 包字节相同,同时用于 ARM64 和 x64:GOROOT 里解析 `bin/go.exe`,gopls 按 PATHEXT 找到 `gopls.exe`。见下文“Windows 安装包” | +| Windows | implemented | pending | `-windows-x64.zip` 和 `-windows-arm64.zip` 只在设置预览后端上与 darwin 包不同:GOROOT 里解析 `bin/go.exe`,gopls 按 PATHEXT 找到 `gopls.exe`。见下文“Windows 安装包” | **证据**: @@ -245,15 +246,56 @@ Core 6477e9a),Homebrew 的 Go 1.27.4。在宿主检出里运行 `internal/pr `go.mod` 的 `go` 行是这个值。 6. 电脑上没有 Go(或只有低于 1.21 的 Go)时 GOROOT 留空,高级选项自动展开并提示填写 Go 版本,填写后可以创建。 +## go-settings-previews + +**能力**:插件后端(`bin/backend`,Rust)实现 `settings.view` 视图函数,给两个 `settingRegions` 画画布: + +- `language`(Go 语言设置页):四张卡片分别画悬停文档(按 `hoverKind` 显示完整、摘要、单行或只有签名)、参数占位符(`usePlaceholders`)、 + gofumpt 格式化(`gofumpt` 开关前后的代码对比)和 Staticcheck 分析(`staticcheck` 开启后多出的问题)在编辑器里的样子。 +- `toolchain`(Go 构建系统页):Lithe 查找 go 的顺序(设置的 `go` 路径、项目固定、全局默认、`GOROOT`、`PATH`、常见位置), + 设置了 `go` 路径时只有这一步“使用中”,其余“不使用”。 + +两个区域都读设置窗口里还没应用的草稿,草稿和已保存的值不同时预览先变、并标出“含未应用的修改”。画面中英文跟随设置窗口的语言, +浅色和深色外观用宿主的颜色标记或成对颜色。后端只读设置,不启动 gopls、go 或 dlv,也不写插件目录。 + +**证据**: + +- `io.github.lithe-idea.go-support/plugin.json`:`settingRegions` 的 `language`、`toolchain`,`backend.launch`,`requires` 的 `backend: 0`、`ui: 0`, + 权限 `backend.launch`、`ui.contribute`。 +- `backend/src/`:视图函数和场景;`cargo test --locked` 检查每个场景在两种语言下都在契约限制内、宽度与区域一致, + 以及各设置对预览的影响。CI 不跑 `cargo test`,只构建后端。 +- `e2e/host/desktop/internal/workbench/official_go_plugin_settings_view_e2e_test.go`:经设置窗口自己的设置来源启动安装包里的后端, + 用中英文打开两个区域并发草稿事件,由 Core 校验每次回答。 + +**依赖的宿主能力**:插件视图和设置区域(1lck/Lithe-IDEA#2183,Core Lithe-core-rust#104)。画布不写 `pan` 时宿主按 +`min(宽/viewBox 宽, 高/viewBox 高)` 从左上角缩放(#2183 的 34afcaf11);场景按设置窗口最窄时区域的宽度画(语言页 610、构建系统页 340), +宽窗口里原样显示。 + +**限制**:代码按 SF Mono 的 7pt 字宽一个字符一个节点排版,选区、光标、输入框和波浪线才能对准字符;Windows 上 Consolas 的字更窄, +代码间距会比宿主自己画的略宽。 + +**最近验证**:2026-11-19,macOS(Apple Silicon),`go-support-1.3.0-darwin.zip`,宿主 `34afcaf11`(1lck/Lithe-IDEA#2183 的分支提交)。 +`TestOfficialGoPluginDrawsItsSettingsRegions` 通过:后端由宿主启动,两个区域在中英文下各画出一张画布,viewBox 宽度分别是 610 和 340, +标题和标签是对应语言,草稿让预览标出未应用的修改、让构建系统页的 `go` 路径一步变成“使用中”,安装目录的文件不变。 +另用宿主无头界面在最小宽度(900)和较宽窗口(1300)下截了中英文、浅色和深色、默认值和全部开启的 32 张图检查排版。没有做手工验收。 + +**验证方法**(macOS): + +1. 安装插件包,打开「设置 › 语言 › Go」:顶部出现四张预览卡片,浅色和深色外观下文字和代码都清楚,窗口拉宽时不被裁掉。 +2. 改悬停文档、参数占位符、gofumpt、Staticcheck,先不点应用:对应卡片立刻变化,标出“含未应用的修改”;点应用后标记消失。 +3. 打开「设置 › 构建、执行、部署 › 构建工具 › Go」:预览列出查找 go 的顺序;填 `go` 路径后这一步变成“使用中”,其余“不使用”。 +4. 界面语言换成中文,两个预览都显示中文。 + ## Windows 安装包 | 能力 | Windows ARM64 | Windows x64 | 验证入口 | | --- | --- | --- | --- | -| 安装包 | 已实现(与 darwin 包同一份字节) | 已实现(同一份包) | `scripts/package/windows.test.mjs`:摘要相同,`go.exe` 布局,条目名在 Windows 上可解压 | +| 安装包 | 已实现(`-windows-arm64.zip`,带 ARM64 的 `bin/backend.exe`) | 已实现(`-windows-x64.zip`,带 x64 的 `bin/backend.exe`) | `scripts/package/archives.test.mjs`:清单只改了后端启动路径,后端是该架构的 PE 程序并带许可证清单,`go.exe` 布局,条目名在 Windows 上可解压 | +| 设置预览后端 | CI 在 `windows-latest` 上用 MSVC ARM64 工具交叉编译 | CI 在 `windows-latest` 上编译 | `.github/workflows/ci.yml` 的 `backend` 任务;还没有在 Windows 版 Lithe 里打开过设置预览 | | 真实 go、gopls 流程 | [已通过原生 CI](https://github.com/Lithe-IDEA/lithe-plugin-go/actions/runs/43728078241)(`windows-11-arm`) | [已通过原生 CI](https://github.com/Lithe-IDEA/lithe-plugin-go/actions/runs/43728078241)(`windows-latest`) | `.github/workflows/ci.yml` 的 `commands` 任务跑 `scripts/test.mjs`,`LITHE_TEST_PLUGIN_DIR` 指向解压到带空格路径的 Windows 包 | | Delve 调试 | 不支持:Delve 上游没有 windows/arm64 后端,`scripts/test.mjs` 把 dlv 检查记为跳过 | [已通过原生 CI](https://github.com/Lithe-IDEA/lithe-plugin-go/actions/runs/43728078241)(托管安装和 `dlv dap` 端点公告) | 同上 | -包里只有声明资源(清单、模板、图标),ARM64 与 x64 的差别只在用户自己的 Go、gopls 和 dlv,所以两种架构用同一份包。 +包里除了声明资源(清单、模板、图标),只有画设置预览的后端,所以 ARM64 与 x64 各有一份包,只有 `bin/backend.exe` 不同;Go、gopls 和 dlv 仍是用户自己的。 Delve 目前不能在 Windows ARM64 上构建,所以那里没有调试;Delve 加入支持后,同一份包不改就能用,测试也会自动改为实际检查。 `scripts/test.mjs` 按清单逐条运行版本探测、模型和依赖命令、构建、vet、过滤后的测试、`go env` 目录、gopls 和 dlv 的托管安装、 gopls 的校验参数和 `dlv dap` 的端点公告。这些只是命令层面的自动化测试,不能代替 Lithe 里的验收,验证列保持 `pending`。 diff --git a/docs/releases/v1.3.0.md b/docs/releases/v1.3.0.md new file mode 100644 index 0000000..3b321ff --- /dev/null +++ b/docs/releases/v1.3.0.md @@ -0,0 +1,21 @@ +1.3.0 给 Go 的两个设置页加上插件自己画的预览,改设置时直接看到效果。这个版本以预发布版本发布。 + +功能: +- 「设置 › 语言 › Go」顶部有四张预览卡片:悬停文档显示多少内容、补全是否填参数占位符、gofumpt 格式化前后的代码、Staticcheck 多查出的问题。 +- 「构建工具 › Go」页画出 Lithe 查找 go 程序的顺序;设置了 go 路径时只有这一步“使用中”。 +- 改了还没应用的选项会先在预览里显示,并标出“含未应用的修改”。预览跟随界面语言和浅色、深色外观。 + +已知限制: +- 需要支持插件视图的桌面端(1lck/Lithe-IDEA#2183)。更早的桌面端不认识 `settingRegions`,无法安装这个版本,Store 继续提供 1.1.0。 +- Windows 上代码的字距比 Lithe 自己画的略宽:预览按 SF Mono 的字宽排版代码,选区和波浪线才能对准字符。 + +验证: +- 在 macOS 上用 1lck/Lithe-IDEA#2183 的桌面端跑宿主端到端测试:后端由宿主启动,两个预览在中英文下都画出、通过 Core 校验,草稿会改变预览,插件安装目录不被写入;原有的构建、调试、运行配置和新建项目测试也都通过。 +- 用宿主无头界面截图检查了最小和较宽窗口、中英文、浅色和深色外观。 +- Windows 包的后端只在 CI 里构建,还没有在 Windows 版 Lithe 里打开过;状态见 `docs/feature-matrix.md`。 + +权限:新增 `backend.launch`(启动包里的预览后端)和 `ui.contribute`(在设置页显示预览)。 + +兼容性: +- 发布包按平台分开:`-darwin.zip`(Apple Silicon 和 Intel 通用)、`-windows-x64.zip`、`-windows-arm64.zip`。原来的 `-windows.zip` 不再提供。 +- 后端用到的第三方 crate 和许可证见包里的 `THIRD_PARTY_LICENSES.txt`。 diff --git a/e2e/host/desktop/internal/workbench/official_go_plugin_settings_view_e2e_test.go b/e2e/host/desktop/internal/workbench/official_go_plugin_settings_view_e2e_test.go new file mode 100644 index 0000000..a3feb87 --- /dev/null +++ b/e2e/host/desktop/internal/workbench/official_go_plugin_settings_view_e2e_test.go @@ -0,0 +1,174 @@ +package workbench + +import ( + "context" + "encoding/json" + "os" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +// This opt-in integration test installs the released Go 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. It needs neither go nor gopls, since the backend reads settings only. + +// goRegion is one of the plugin's settings regions, the width its scene is drawn for and the +// words of its title and label in each language. +type goRegion struct { + id string + width float64 + words map[i18n.Language][]string +} + +var goRegions = []goRegion{ + {id: "language", width: 610, words: map[i18n.Language][]string{ + i18n.English: {"Preview", "Preview of the gopls options", "Hover documentation", "gofumpt formatting"}, + i18n.Chinese: {"效果预览", "gopls 选项的效果预览", "悬停文档", "gofumpt 格式化"}, + }}, + {id: "toolchain", width: 340, words: map[i18n.Language][]string{ + i18n.English: {"How Lithe finds go", "The order in which Lithe looks for the go program"}, + i18n.Chinese: {"Lithe 按这个顺序找 go", "Lithe 查找 go 程序的顺序"}, + }}, +} + +// drawnCanvas is the one node a region's view answers with, as Core checked it. +type drawnCanvas 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"` + Nodes []json.RawMessage `json:"nodes"` +} + +// sceneWords 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 sceneWords(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") +} + +// drawRegion sends one view event to region and returns the canvas it drew. +func drawRegion(t *testing.T, ctx context.Context, sources pluginSettingsSources, editor pluginservice.SettingsEditor, region string, event map[string]any) drawnCanvas { + t.Helper() + encoded, err := json.Marshal(event) + if err != nil { + t.Fatal(err) + } + drawn, changed, err := sources.View(ctx, editor, region, "settings.view", encoded, nil, false) + if err != nil { + t.Fatalf("%s region, %s event: %v", region, event["event"], err) + } + if !changed { + t.Fatalf("%s region, %s event: the view drew nothing new", region, event["event"]) + } + var nodes []drawnCanvas + if err := json.Unmarshal(drawn, &nodes); err != nil { + t.Fatalf("%s region: Core returned %s: %v", region, drawn, err) + } + if len(nodes) != 1 || nodes[0].Type != "canvas" { + t.Fatalf("%s region: want one canvas, got %s", region, drawn) + } + return nodes[0] +} + +func TestOfficialGoPluginDrawsItsSettingsRegions(t *testing.T) { + archive := os.Getenv("LITHE_TEST_GO_PLUGIN_ARCHIVE") + if archive == "" { + t.Skip("set LITHE_TEST_GO_PLUGIN_ARCHIVE to a go-support--darwin.zip") + } + const id = "io.github.lithe-idea.go-support" + h := newHarness(t, &testKernel{Client: core.NewClient()}) + installed := installOfficialPluginArchive(t, h, archive, id) + t.Cleanup(h.app.plugins.Host.StopAll) + before := packageDigest(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, id, language) + if err != nil { + t.Fatalf("load the settings page in %s: %v", language.Code(), err) + } + for _, region := range goRegions { + 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 := drawRegion(t, ctx, sources, editor, region.id, map[string]any{ + "event": "open", "instance": "e2e-" + strconv.Itoa(instance), "language": language.Code(), + }) + if len(opened.ViewBox) != 4 || opened.ViewBox[2] != region.width || opened.ViewBox[3] < 1 { + t.Fatalf("%s region: view box %v, want one %g wide", region.id, opened.ViewBox, region.width) + } + if opened.Height < opened.ViewBox[3] || len(opened.Pan) > 0 { + t.Fatalf("%s region: height %g, pan %s; the scene must show whole at one unit to a point", region.id, opened.Height, opened.Pan) + } + words := sceneWords(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) + } + } + draftNote := map[i18n.Language]string{i18n.English: "Includes changes not applied yet", i18n.Chinese: "含未应用的修改"}[language] + if strings.Contains(words, draftNote) { + t.Fatalf("%s region: the saved settings are drawn as a draft", region.id) + } + + // A draft row of the window shows in the preview before it is applied. + draft := map[string]any{"gofumpt": true} + if region.id == "toolchain" { + draft = map[string]any{"goExecutable": "/opt/go/bin/go"} + } + drafted := drawRegion(t, ctx, sources, editor, region.id, map[string]any{ + "event": "settings", "instance": "e2e-" + strconv.Itoa(instance), "language": language.Code(), + "settings": map[string]any{"effective": map[string]any{}, "draft": draft}, + }) + draftWords := sceneWords(t, drafted.Nodes) + if !strings.Contains(draftWords, draftNote) { + t.Fatalf("%s region in %s: the draft %v is not marked; the scene says:\n%s", region.id, language.Code(), draft, draftWords) + } + inUse := map[i18n.Language]string{i18n.English: "In use", i18n.Chinese: "使用中"}[language] + if region.id == "toolchain" && (strings.Contains(words, inUse) || !strings.Contains(draftWords, inUse)) { + t.Fatalf("toolchain region in %s: only a set go executable is in use; saved:\n%s\ndrafted:\n%s", language.Code(), words, draftWords) + } + } + } + if h.app.plugins.Host.Running(id) == nil { + t.Fatal("the backend is not running after drawing the regions") + } + h.app.plugins.Host.StopAll() + assertPackageUnchanged(t, installed, before) +} diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index 50240db..4894ab2 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,12 +1,12 @@ { "repository": "https://github.com/1lck/Lithe-IDEA.git", - "revision": "a8797ae9aa40d10cbaa6460b48b213c87fe8ad48", + "revision": "34afcaf11016c052b739ee2b9f09eaa26e21ba0a", "packages": { "./internal/projectgen": "^TestGoPlugin", - "./internal/workbench": "^TestOfficialGoPlugin(BuildsAndServesAModule|DebugsEachProjectOfAWorkspaceWithDelve|RunsGoBuildAndGoTestConfigurations)$" + "./internal/workbench": "^TestOfficialGoPlugin(BuildsAndServesAModule|DebugsEachProjectOfAWorkspaceWithDelve|RunsGoBuildAndGoTestConfigurations|DrawsItsSettingsRegions)$" }, "requiredEnvironment": { - "LITHE_TEST_GO_PLUGIN_ARCHIVE": "go-support--darwin.zip to install, for example dist/go-support-1.2.0-darwin.zip" + "LITHE_TEST_GO_PLUGIN_ARCHIVE": "go-support--darwin.zip to install, for example dist/go-support-1.3.0-darwin.zip" }, "repositoryEnvironment": { "LITHE_PLUGIN_GO_DIR": "io.github.lithe-idea.go-support" diff --git a/io.github.lithe-idea.go-support/l10n/zh-Hans.json b/io.github.lithe-idea.go-support/l10n/zh-Hans.json index 755f520..0f16f40 100644 --- a/io.github.lithe-idea.go-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.go-support/l10n/zh-Hans.json @@ -32,6 +32,14 @@ "sections": { "Go toolchain": "Go 工具链" }, + "settingRegions": { + "language": { + "keywords": ["悬停", "补全", "参数占位符", "格式化", "静态检查", "效果预览"] + }, + "toolchain": { + "keywords": ["Go 程序", "工具链", "查找顺序"] + } + }, "runConfigurationTypes": { "go": { "build": { diff --git a/io.github.lithe-idea.go-support/plugin.json b/io.github.lithe-idea.go-support/plugin.json index 5e5ef74..b535a9b 100644 --- a/io.github.lithe-idea.go-support/plugin.json +++ b/io.github.lithe-idea.go-support/plugin.json @@ -2,9 +2,10 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.go-support", "displayName": "Go Support", - "version": "1.2.0", + "version": "1.3.0", "pluginAPIVersion": 0, "requires": { + "backend": 0, "buildSystems": 0, "commandInstallers": 0, "debugAdapters": 0, @@ -13,7 +14,8 @@ "projectGenerators": 0, "runConfigurationTypes": 0, "settings": 0, - "toolDefinitions": 0 + "toolDefinitions": 0, + "ui": 0 }, "requiresTools": [ "go" @@ -24,11 +26,13 @@ "signatureRequirement": "none" }, "permissions": [ + "backend.launch", "commands.install", "debug.launch", "languageServer.launch", "process.build", - "project.generate" + "project.generate", + "ui.contribute" ], "activationEvents": [ "onBuildSystem:go", @@ -116,6 +120,43 @@ ] } ], + "settingRegions": [ + { + "id": "language", + "page": { + "languageID": "go" + }, + "keywords": [ + "gopls", + "hover", + "completion", + "placeholders", + "gofumpt", + "formatting", + "staticcheck", + "preview" + ], + "view": { + "function": "settings.view" + } + }, + { + "id": "toolchain", + "page": { + "buildSystemID": "go" + }, + "keywords": [ + "go executable", + "toolchain", + "lookup order", + "PATH", + "GOROOT" + ], + "view": { + "function": "settings.view" + } + } + ], "languages": [ { "id": "go", @@ -1016,5 +1057,11 @@ } } } - ] + ], + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/backend" + } + } } diff --git a/scripts/build-backend.mjs b/scripts/build-backend.mjs new file mode 100644 index 0000000..ad11ceb --- /dev/null +++ b/scripts/build-backend.mjs @@ -0,0 +1,136 @@ +#!/usr/bin/env node +// Builds the plugin's backend, the Rust program in backend/ that draws the +// settings regions, for one platform into .artifacts/backend-/, where +// scripts/package.mjs takes it from: +// +// darwin backend, a universal binary of aarch64- and x86_64-apple-darwin +// joined with lipo and signed ad hoc, which Apple Silicon needs +// to run it. macOS only. +// windows-x64 backend.exe for x86_64-pc-windows-msvc. Windows only. +// windows-arm64 backend.exe for aarch64-pc-windows-msvc, cross-built on x64 +// Windows with the MSVC ARM64 tools. Windows only. +// +// Next to the program it writes THIRD_PARTY_LICENSES.txt: every crate linked +// into that platform's build, its license, and the license files it ships, read +// from `cargo metadata`. The targets must be installed (`rustup target add`). +// +// Usage: node scripts/build-backend.mjs + +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; + +const PLATFORMS = { + darwin: { host: "darwin", targets: ["aarch64-apple-darwin", "x86_64-apple-darwin"], program: "backend" }, + "windows-x64": { host: "win32", targets: ["x86_64-pc-windows-msvc"], program: "backend.exe" }, + "windows-arm64": { host: "win32", targets: ["aarch64-pc-windows-msvc"], program: "backend.exe" }, +}; +const BACKEND = resolve("backend"); +const CARGO_TIMEOUT_MS = 20 * 60_000; + +const platform = process.argv[2]; +const spec = PLATFORMS[platform]; +if (!spec) { + console.error(`usage: node scripts/build-backend.mjs <${Object.keys(PLATFORMS).join("|")}>`); + process.exit(2); +} +if (process.platform !== spec.host) { + console.error(`✗ ${platform} builds on ${spec.host}, this is ${process.platform}`); + process.exit(1); +} + +const output = resolve(".artifacts", `backend-${platform}`); +rmSync(output, { recursive: true, force: true }); +mkdirSync(output, { recursive: true }); + +const built = spec.targets.map((target) => { + execFileSync("cargo", ["build", "--release", "--locked", "--target", target], { + cwd: BACKEND, stdio: "inherit", timeout: CARGO_TIMEOUT_MS, + }); + return join(BACKEND, "target", target, "release", spec.program); +}); +const program = join(output, spec.program); +if (built.length === 1) { + copyFileSync(built[0], program); +} else { + execFileSync("lipo", ["-create", ...built, "-output", program], { stdio: "inherit", timeout: 60_000 }); + // The linker signs only the arm64 slice. An ad-hoc signature without a + // timestamp covers both and is the same for the same bytes. + execFileSync("codesign", ["--sign", "-", "--force", "--timestamp=none", program], { stdio: "inherit", timeout: 60_000 }); + execFileSync("codesign", ["--verify", "--strict", program], { stdio: "inherit", timeout: 60_000 }); +} + +writeFileSync(join(output, "THIRD_PARTY_LICENSES.txt"), notices(spec.targets)); +const sha256 = createHash("sha256").update(readFileSync(program)).digest("hex"); +console.log(`.artifacts/backend-${platform}/${spec.program} ${sha256}`); + +/** + * The license notices of every crate a build for `targets` links, the backend + * itself left out. A crate that ships no license file, such as the plugin SDK, + * whose repository keeps none, is covered by the Apache License 2.0 text at + * the end, which is this repository's LICENSE. + */ +function notices(targets) { + const crates = new Map(); + for (const target of targets) { + const metadata = JSON.parse(execFileSync("cargo", [ + "metadata", "--format-version", "1", "--locked", "--filter-platform", target, + ], { cwd: BACKEND, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 5 * 60_000 })); + const packages = new Map(metadata.packages.map((entry) => [entry.id, entry])); + const root = metadata.resolve.root; + for (const node of metadata.resolve.nodes) { + if (node.id === root) continue; + const entry = packages.get(node.id); + crates.set(`${entry.name} ${entry.version}`, entry); + } + } + const sorted = [...crates.values()].sort((a, b) => a.name.localeCompare(b.name)); + const lines = [ + "Third-party software in the Go Support backend", + "", + "The backend program links these crates. Each line gives the crate, its", + "version, its license and its source; the license files the crates ship follow.", + "", + ]; + let needsApache = false; + for (const entry of sorted) { + const source = entry.repository ?? (entry.source ?? "").replace(/^git\+/, "").replace(/[?#].*$/, ""); + lines.push(`${entry.name} ${entry.version} (${entry.license}) ${source}`); + } + const seen = new Map(); + for (const entry of sorted) { + const directory = dirname(entry.manifest_path); + const files = readdirSync(directory).filter((name) => /^(licen[cs]e|copying|notice)/i.test(name)).sort(); + if (files.length === 0) { + if (!/\bApache-2\.0\b/.test(entry.license ?? "")) { + throw new Error(`${entry.name} ${entry.version} ships no license file and is not Apache-2.0: ${entry.license}`); + } + needsApache = true; + lines.push("", `==== ${entry.name} ${entry.version} ====`, "", "Ships no license file; Apache License 2.0, text below."); + continue; + } + for (const file of files) { + const text = lf(readFileSync(join(directory, file), "utf8")).trimEnd(); + const digest = createHash("sha256").update(text).digest("hex"); + lines.push("", `==== ${entry.name} ${entry.version}: ${file} ====`, ""); + if (seen.has(digest)) { + lines.push(`The same text as ${seen.get(digest)} above.`); + } else { + seen.set(digest, `${entry.name} ${entry.version}: ${file}`); + lines.push(text); + } + } + } + if (needsApache) { + const license = resolve("LICENSE"); + if (!existsSync(license)) throw new Error("LICENSE, the Apache License 2.0 text, is missing"); + lines.push("", "==== Apache License 2.0 ====", "", lf(readFileSync(license, "utf8")).trimEnd()); + } + return `${lines.join("\n")}\n`; +} + +/** `text` with LF line ends, which a Windows checkout's CRLF files lack. */ +function lf(text) { + return text.replace(/\r\n/g, "\n"); +} diff --git a/scripts/package.mjs b/scripts/package.mjs index e83f589..f83f25b 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -1,36 +1,72 @@ #!/usr/bin/env node -// Packages the plugin into dist/--darwin.zip, the asset name -// Lithe Store's release tracker recognizes (docs/publishing.md there). +// Packages the plugin into one archive per platform, under the asset names +// Lithe Store's release tracker recognizes (docs/publishing.md there): // -// Go Support only declares how Lithe launches the user's own gopls and go, so -// the package is architecture-neutral: one archive serves Apple Silicon and -// Intel Macs, and the same bytes are copied as -windows.zip for Windows ARM64 -// and x64 (plugin.json declares bin/go.exe and resolves gopls and dlv through -// PATHEXT). Nothing is downloaded at build or install time. Packaging needs -// POSIX zip, so it runs on macOS or Linux. +// dist/go-support--darwin.zip Apple Silicon and Intel Macs +// dist/go-support--windows-x64.zip Windows x64 +// dist/go-support--windows-arm64.zip Windows ARM64 // -// Usage: node scripts/package.mjs [--expect-tag ] +// Each holds the package directory and the backend that draws its settings +// regions, built beforehand by scripts/build-backend.mjs into +// .artifacts/backend-/: bin/backend, a universal binary, on macOS and +// bin/backend.exe on Windows, with THIRD_PARTY_LICENSES.txt next to plugin.json. +// The Windows archives' plugin.json names bin/backend.exe as the backend; all +// three declare the same version, pluginAPIVersion and requires, as the Store +// requires. Everything else, Lithe launching the user's own go, gopls and dlv, +// is the same on every platform. Nothing is downloaded at build or install +// time. Packaging needs POSIX zip, so it runs on macOS or Linux. +// +// Usage: node scripts/package.mjs [--expect-tag ] [--platforms darwin,windows-x64,windows-arm64] import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; -import { copyFileSync, mkdirSync, readFileSync, rmSync } from "node:fs"; -import { resolve } from "node:path"; +import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { parseArgs } from "node:util"; const PACKAGE_DIR = "io.github.lithe-idea.go-support"; const ASSET_PREFIX = "go-support"; -const PLATFORM = "darwin"; +const BACKEND_PATH = "bin/backend"; +const PLATFORMS = { + darwin: { program: "backend", builtOn: "macOS" }, + "windows-x64": { program: "backend.exe", builtOn: "Windows" }, + "windows-arm64": { program: "backend.exe", builtOn: "Windows" }, +}; + +const { values } = parseArgs({ + options: { + "expect-tag": { type: "string" }, + platforms: { type: "string", default: Object.keys(PLATFORMS).join(",") }, + }, +}); +const platforms = values.platforms.split(",").filter(Boolean); -const manifest = JSON.parse(readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8")); +const source = readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8"); +const manifest = JSON.parse(source); const problems = []; if (manifest.id !== PACKAGE_DIR) problems.push(`plugin.json id ${manifest.id} must equal the directory ${PACKAGE_DIR}`); if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(manifest.version)) problems.push(`version ${manifest.version} is not MAJOR.MINOR.PATCH`); if (manifest.vendor?.signatureRequirement !== "none") problems.push('vendor.signatureRequirement must be "none"'); if (manifest.id === "dev.lithe" || manifest.id.startsWith("dev.lithe.")) problems.push("dev.lithe.* is reserved for official plugins"); - -const tagFlag = process.argv.indexOf("--expect-tag"); -if (tagFlag >= 0) { - const tag = process.argv[tagFlag + 1]; - if (tag !== `v${manifest.version}`) problems.push(`tag ${tag} does not match plugin.json version ${manifest.version} (expected v${manifest.version})`); +if (manifest.backend?.launch?.kind !== "packaged" || manifest.backend.launch.path !== BACKEND_PATH) { + problems.push(`plugin.json backend.launch must be {"kind": "packaged", "path": "${BACKEND_PATH}"}`); +} +const cargoVersion = /^\[package\][^[]*?^version = "([^"]+)"/ms.exec(readFileSync("backend/Cargo.toml", "utf8"))?.[1]; +if (cargoVersion !== manifest.version) problems.push(`backend/Cargo.toml version ${cargoVersion} must equal plugin.json version ${manifest.version}`); +if (values["expect-tag"] !== undefined && values["expect-tag"] !== `v${manifest.version}`) { + problems.push(`tag ${values["expect-tag"]} does not match plugin.json version ${manifest.version} (expected v${manifest.version})`); +} +for (const platform of platforms) { + const spec = PLATFORMS[platform]; + if (!spec) { + problems.push(`unknown platform ${platform}; use ${Object.keys(PLATFORMS).join(", ")}`); + continue; + } + for (const file of [spec.program, "THIRD_PARTY_LICENSES.txt"]) { + if (!existsSync(join(".artifacts", `backend-${platform}`, file))) { + problems.push(`.artifacts/backend-${platform}/${file} is missing: run node scripts/build-backend.mjs ${platform} on ${spec.builtOn}`); + } + } } if (problems.length > 0) { for (const problem of problems) console.error(`✗ ${problem}`); @@ -39,12 +75,28 @@ if (problems.length > 0) { rmSync("dist", { recursive: true, force: true }); mkdirSync("dist", { recursive: true }); -const asset = resolve("dist", `${ASSET_PREFIX}-${manifest.version}-${PLATFORM}.zip`); -// -X drops extra file attributes; -y stores a symbolic link as a link so -// Lithe refuses it instead of the archive silently carrying its target. -execFileSync("zip", ["-qrXy", asset, PACKAGE_DIR, "-x", "*.DS_Store"]); -const sha256 = createHash("sha256").update(readFileSync(asset)).digest("hex"); -console.log(`dist/${ASSET_PREFIX}-${manifest.version}-${PLATFORM}.zip ${sha256}`); -const windowsAsset = resolve("dist", `${ASSET_PREFIX}-${manifest.version}-windows.zip`); -copyFileSync(asset, windowsAsset); -console.log(`dist/${ASSET_PREFIX}-${manifest.version}-windows.zip ${sha256}`); +const staging = resolve(".artifacts", "package"); +for (const platform of platforms) { + const { program } = PLATFORMS[platform]; + const built = join(".artifacts", `backend-${platform}`); + rmSync(staging, { recursive: true, force: true }); + const root = join(staging, PACKAGE_DIR); + cpSync(PACKAGE_DIR, root, { recursive: true, filter: (path) => !path.endsWith(".DS_Store") }); + mkdirSync(join(root, "bin"), { recursive: true }); + cpSync(join(built, program), join(root, "bin", program)); + // A downloaded build artifact loses its mode, and the archive keeps this one. + chmodSync(join(root, "bin", program), 0o755); + cpSync(join(built, "THIRD_PARTY_LICENSES.txt"), join(root, "THIRD_PARTY_LICENSES.txt")); + if (program !== "backend") { + const forPlatform = JSON.parse(source); + forPlatform.backend.launch.path = `bin/${program}`; + writeFileSync(join(root, "plugin.json"), `${JSON.stringify(forPlatform, null, 2)}\n`); + } + const name = `${ASSET_PREFIX}-${manifest.version}-${platform}.zip`; + // -X drops extra file attributes; -y stores a symbolic link as a link so + // Lithe refuses it instead of the archive silently carrying its target. + execFileSync("zip", ["-qrXy", resolve("dist", name), PACKAGE_DIR], { cwd: staging, timeout: 60_000 }); + const sha256 = createHash("sha256").update(readFileSync(resolve("dist", name))).digest("hex"); + console.log(`dist/${name} ${sha256}`); +} +rmSync(staging, { recursive: true, force: true }); diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs new file mode 100644 index 0000000..fec0041 --- /dev/null +++ b/scripts/package/archives.test.mjs @@ -0,0 +1,80 @@ +// Integration checks of the release archives, after scripts/package.mjs. They +// check every archive dist/ holds, so a local run that packaged only darwin +// checks that one; CI and the release package all three. +import test from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const id = "io.github.lithe-idea.go-support"; +const source = JSON.parse(readFileSync(`${id}/plugin.json`, "utf8")); +const version = source.version; +const UNIVERSAL = 0xcafebabe; +const CPU_X86_64 = 0x01000007; +const CPU_ARM64 = 0x0100000c; +const archives = [ + { platform: "darwin", program: "bin/backend" }, + { platform: "windows-x64", program: "bin/backend.exe", machine: 0x8664 }, + { platform: "windows-arm64", program: "bin/backend.exe", machine: 0xaa64 }, +] + .map((archive) => ({ ...archive, path: resolve(`dist/go-support-${version}-${archive.platform}.zip`) })) + .filter((archive) => existsSync(archive.path)); + +const unzip = (archive, args) => execFileSync("unzip", [...args, archive.path], { timeout: 10_000, maxBuffer: 16 * 1024 * 1024 }); +const read = (archive, path) => execFileSync("unzip", ["-p", archive.path, `${id}/${path}`], { timeout: 10_000, maxBuffer: 16 * 1024 * 1024 }); +const entries = (archive) => unzip(archive, ["-Z1"]).toString("utf8").trim().split("\n"); + +test("dist holds an archive to check", () => { + assert.ok(archives.length > 0, `no dist/go-support-${version}-*.zip; run node scripts/package.mjs`); +}); + +for (const archive of archives) { + test(`${archive.platform}: plugin.json is the source one, launching ${archive.program}`, () => { + const manifest = JSON.parse(read(archive, "plugin.json")); + assert.equal(manifest.backend.launch.path, archive.program); + assert.deepEqual({ ...manifest, backend: { ...manifest.backend, launch: { ...manifest.backend.launch, path: source.backend.launch.path } } }, source); + }); + + test(`${archive.platform}: the backend is an executable for the platform, with its notices`, () => { + const listing = execFileSync("unzip", ["-Z", archive.path, `${id}/${archive.program}`], { encoding: "utf8", timeout: 10_000 }); + assert.match(listing, /^-rwxr-xr-x/, "the archive keeps the program's mode"); + const program = read(archive, archive.program); + if (archive.machine === undefined) { + assert.equal(program.readUInt32BE(0), UNIVERSAL, "a universal Mach-O binary"); + const count = program.readUInt32BE(4); + const cpus = Array.from({ length: count }, (_, index) => program.readUInt32BE(8 + index * 20)).sort(); + assert.deepEqual(cpus, [CPU_X86_64, CPU_ARM64].sort(), "slices for Intel and Apple Silicon"); + } else { + assert.equal(program.toString("latin1", 0, 2), "MZ"); + const header = program.readUInt32LE(0x3c); + assert.equal(program.toString("latin1", header, header + 4), "PE\0\0"); + assert.equal(program.readUInt16LE(header + 4), archive.machine, "the PE machine of the platform"); + } + assert.match(read(archive, "THIRD_PARTY_LICENSES.txt").toString("utf8"), /^lithe-plugin-sdk .* \(Apache-2\.0\)/m); + assert.ok(!entries(archive).some((entry) => entry.includes("backend/") || entry.endsWith(".rs")), "no backend sources"); + }); +} + +for (const archive of archives.filter((entry) => entry.platform.startsWith("windows"))) { + test(`${archive.platform}: GOROOT resolves go.exe`, () => { + const manifest = JSON.parse(read(archive, "plugin.json")); + const go = manifest.toolDefinitions.find((tool) => tool.id === "go"); + const forWindows = (list) => list.filter((entry) => entry.platforms?.includes("windows")).map((entry) => entry.path); + assert.deepEqual(forWindows(go.executableLayouts), ["bin/go.exe"]); + assert.deepEqual(forWindows(go.executables), ["bin/go.exe"]); + }); + + test(`${archive.platform}: every archive entry can be extracted on Windows`, () => { + const seen = new Set(); + for (const entry of entries(archive)) { + for (const part of entry.replace(/\/$/, "").split("/")) { + assert.doesNotMatch(part, /[<>:"\\|?*\x00-\x1f]|[. ]$/, `${entry} has a name Windows refuses`); + assert.doesNotMatch(part, /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i, `${entry} uses a reserved Windows name`); + } + const folded = entry.toLowerCase(); + assert.ok(!seen.has(folded), `${entry} differs from another entry only in case`); + seen.add(folded); + } + }); +} diff --git a/scripts/package/windows.test.mjs b/scripts/package/windows.test.mjs deleted file mode 100644 index b1a361e..0000000 --- a/scripts/package/windows.test.mjs +++ /dev/null @@ -1,37 +0,0 @@ -// Integration checks of the release archives, after scripts/package.mjs. -import test from "node:test"; -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import { createHash } from "node:crypto"; - -const id = "io.github.lithe-idea.go-support"; -const version = JSON.parse(readFileSync(`${id}/plugin.json`, "utf8")).version; -const windows = resolve(`dist/go-support-${version}-windows.zip`); -const digest = (path) => createHash("sha256").update(readFileSync(path)).digest("hex"); -const read = (path) => execFileSync("unzip", ["-p", windows, `${id}/${path}`], { timeout: 10_000, maxBuffer: 16 * 1024 * 1024 }); - -test("Windows ARM64 and x64 use the portable archive", () => { - assert.equal(digest(windows), digest(`dist/go-support-${version}-darwin.zip`)); - const manifest = JSON.parse(read("plugin.json")); - assert.equal(manifest.version, version); - const go = manifest.toolDefinitions.find((tool) => tool.id === "go"); - const forWindows = (entries) => entries.filter((entry) => entry.platforms?.includes("windows")).map((entry) => entry.path); - assert.deepEqual(forWindows(go.executableLayouts), ["bin/go.exe"]); - assert.deepEqual(forWindows(go.executables), ["bin/go.exe"], "GOROOT resolves go.exe on Windows"); -}); - -test("every archive entry can be extracted on Windows", () => { - const entries = execFileSync("unzip", ["-Z1", windows], { encoding: "utf8", timeout: 10_000 }).trim().split("\n"); - const seen = new Set(); - for (const entry of entries) { - for (const part of entry.replace(/\/$/, "").split("/")) { - assert.doesNotMatch(part, /[<>:"\\|?*\x00-\x1f]|[. ]$/, `${entry} has a name Windows refuses`); - assert.doesNotMatch(part, /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i, `${entry} uses a reserved Windows name`); - } - const folded = entry.toLowerCase(); - assert.ok(!seen.has(folded), `${entry} differs from another entry only in case`); - seen.add(folded); - } -});